hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
78123188b58a4238f015ed2a33afc5360fdef54c | 1,268 | cc | C++ | ports/www/chromium-legacy/newport/files/patch-base_threading_platform__thread__linux.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2022-02-08T02:24:08.000Z | 2022-02-08T02:24:08.000Z | ports/www/chromium-legacy/newport/files/patch-base_threading_platform__thread__linux.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/www/chromium-legacy/newport/files/patch-base_threading_platform__thread__linux.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | --- base/threading/platform_thread_linux.cc.orig 2019-03-11 22:00:51 UTC
+++ base/threading/platform_thread_linux.cc
@@ -18,7 +18,9 @@
#if !defined(OS_NACL) && !defined(OS_AIX)
#include <pthread.h>
+#if !defined(OS_BSD)
#include <sys/prctl.h>
+#endif
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
@@ -99,7 +101,7 @@ const ThreadPriorityToNiceValuePair kThreadPriorityToN
Optional<bool> CanIncreaseCurrentThreadPriorityForPlatform(
ThreadPriority priority) {
-#if !defined(OS_NACL)
+#if !defined(OS_NACL) && !defined(OS_BSD)
// A non-zero soft-limit on RLIMIT_RTPRIO is required to be allowed to invoke
// pthread_setschedparam in SetCurrentThreadPriorityForPlatform().
struct rlimit rlim;
@@ -141,7 +143,7 @@ Optional<ThreadPriority> GetCurrentThreadPriorityForPl
void PlatformThread::SetName(const std::string& name) {
ThreadIdNameManager::GetInstance()->SetName(name);
-#if !defined(OS_NACL) && !defined(OS_AIX)
+#if !defined(OS_NACL) && !defined(OS_AIX) && !defined(OS_BSD)
// On linux we can get the thread names to show up in the debugger by setting
// the process name for the LWP. We don't want to do this for the main
// thread because that would rename the process, causing tools like killall
| 40.903226 | 80 | 0.733438 | danielfojt |
78138a58ead6d55c434b76ade30cee7a1b049cfb | 6,615 | cpp | C++ | apps/devApps/ofSynthFloatiesExample/src/FloatingSine.cpp | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | 1 | 2015-12-05T04:53:15.000Z | 2015-12-05T04:53:15.000Z | apps/devApps/ofSynthFloatiesExample/src/FloatingSine.cpp | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | null | null | null | apps/devApps/ofSynthFloatiesExample/src/FloatingSine.cpp | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | null | null | null | /*
* FloatingSine.cpp
* ofSynth
*
* Created by damian on 12/01/11.
* Copyright 2011 frey damian@frey.co.nz. All rights reserved.
*
*/
#include "FloatingSine.h"
static const float RADIUS = 30.0f;
// pentatonic
static const int SCALE_STEPS_PENTATONIC = 5;
static const float SCALE_PENTATONIC[SCALE_STEPS_PENTATONIC] = { 0, 2, 5, 7, 10 };
// lydian Tone, tone, semitone, tone, tone, tone, semitone
static const int SCALE_STEPS_LYDIAN = 8;
static const float SCALE_LYDIAN[SCALE_STEPS_LYDIAN] = { 0, 2, 3, 5, 7, 9, 10 };
static const float BASE_MIDI_NOTE = 62.0f;
float midiToFrequency( float midiNote )
{
return 440.0f*powf(2.0f,(midiNote-60.0f)/12.0f);
}
void FloatingSine::setup( ofSoundMixer* mixer, vector<FloatingSine*> * n, ofImage* particleImage )
{
neighbours = n;
particle = particleImage;
setScale( 0 );
setBaseMidiNote( BASE_MIDI_NOTE );
// setup the sound
//
// we have a chain like this:
// [tone generator]---->[volume control]------>[mixer]
//
// the mixer is shared amongst all objects
//
int whichScaleNote = ofRandom( 0, 0.99999f*scaleSteps );
float midiNote = baseMidiNote + scale[whichScaleNote];
frequency = midiToFrequency( midiNote );
octaveOffset = ofRandom( -2.99f, 0.99f );
tone.setFrequency( frequency );
// tone goes through volume control
volume.addInputFrom( &tone );
volume.setVolume( 1.0f/(n->size()) );
// we add the volume control to the mixer
mixer->addInputFrom( &volume );
sawtooth = false;
bBackgroundAuto = false;
velocity = 0;
// colours for sine and sawtooth waveforms
sineColour.setHsb( 255.0f*(ofRandom( -10, 10 ) + 221.0f)/360.0f,
255.0f*(ofRandom( -0.1f, 0.1f ) + 0.79),
255.0f*(ofRandom( -0.1f, 0.1f ) + 0.66f), 200.0f );
sawColour.setHsb( 255.0f*(ofRandom( -10, 10 ) + 33.0f)/360.0f,
255.0f*(ofRandom( -0.1f, 0.1f ) + 0.79),
255.0f*(ofRandom( -0.1f, 0.1f ) + 0.66f), 200.0f );
// setup motion behaviour
// each dot has a 'buddy' that it tries to maintain a fixed multiple of shellDistance away from
// each dot also has an 'enemy' that it tries to run away from
shellDistance = ofRandom( 100.0f, 200.0f );
position.set( ofRandom( 3.0f*ofGetWidth()/8, 5.0f*ofGetWidth()/8 ), ofRandom( 3.0f*ofGetHeight()/8, 5.0f*ofGetHeight()/8 ) );
if ( neighbours->size() >= 3 )
{
buddy = ofRandomuf()*0.99999f*neighbours->size();
// avoid selecting ourselves as the buddy
while ( n->at( buddy ) == this )
{
buddy = (buddy+1)%neighbours->size();
}
enemy = ofRandomuf()*0.99999f*neighbours->size();
// avoid selecting ourselves as the buddy
while ( n->at( enemy ) == this || buddy == enemy )
{
enemy = (enemy+1)%neighbours->size();
}
}
else
{
buddy = 0;
enemy = 0;
}
}
void FloatingSine::setScale( int which )
{
which = min(max(0,which),1);
if ( which == 0 )
{
scale = SCALE_PENTATONIC;
scaleSteps = SCALE_STEPS_PENTATONIC;
}
else {
scale = SCALE_LYDIAN;
scaleSteps = SCALE_STEPS_LYDIAN;
}
}
void FloatingSine::toggleWaveform() {
setWaveform ( !sawtooth );
}
void FloatingSine::setWaveform( bool toSawtooth ) {
sawtooth = toSawtooth;
if ( sawtooth ) {
tone.setSawtoothWaveform();
} else {
tone.setSineWaveform();
}
}
void FloatingSine::update( )
{
// update the position
position += velocity*ofGetLastFrameTime();
// damp the velocity
velocity *= powf(0.99f,ofGetLastFrameTime());
ofVec2f delta = neighbours->at( buddy )->position - position;
float distance = delta.length();
ofVec2f deltaNorm = delta/distance;
distanceUnits = distance/shellDistance;
// calculate distance in terms of shellDistance
int whichScaleNote = distanceUnits;
float remainder = distanceUnits - whichScaleNote;
if ( remainder > 0.5f ) {
// round
distanceUnits += 1.0f;
whichScaleNote += 1.0f;
remainder = 1.0f-remainder;
}
// update frequency
float midiNote = baseMidiNote;
while ( whichScaleNote>=scaleSteps ) {
midiNote += 12;
whichScaleNote -= scaleSteps;
}
// convert scale steps to actual scale notes
float scaleNote = scale[whichScaleNote%scaleSteps];
float nextScaleNote = scale[(whichScaleNote+1)%scaleSteps];
float prevScaleNote = scale[(whichScaleNote+4)%scaleSteps];
if ( prevScaleNote>nextScaleNote) {
// wrap
nextScaleNote += 12.0f;
}
// set the actual frequency, adding on a detune calculated from remainder
tone.setFrequency( midiToFrequency( float(octaveOffset*12) + midiNote + scaleNote + remainder*0.1f /* (remainder>0.0f?1.0f:-1.0f)*remainder*remainder*/ ) );
// set volume
float vol = 1.0f-min(1.0f,(distance/ofGetWidth()));
volume.setVolume( 1.0f*vol/(neighbours->size()) );
// calculate forces
static const float BUDDY_FORCE_MUL = 1000.0f;
static const float ENEMY_FORCE_MUL = 100.0f;
static const float CENTRE_FORCE_MUL = 0.3f;
// move towards the nearest shell out from our buddy
ofVec2f dv = ((remainder>0.0f)&&(distanceUnits>1.0f)>0.0f?-1.0f:1.0f)*
remainder*remainder*deltaNorm*ofGetLastFrameTime()*BUDDY_FORCE_MUL;
velocity += dv*0.5f;
neighbours->at(buddy)->velocity -= dv*0.5f;
// run away from enemy
ofVec2f enemyDelta = neighbours->at( enemy )->position - position;
float enemyDistance = enemyDelta.length();
ofVec2f enemyDeltaNorm = enemyDelta/enemyDistance;
dv = enemyDeltaNorm*(1.0f/enemyDistance)*ofGetLastFrameTime()*ENEMY_FORCE_MUL;
velocity -= dv*0.5f;
neighbours->at( enemy )->velocity += dv*0.5f;
// don't get too far away from the centre of the screen
ofVec2f centreDelta = ofVec2f(ofGetWidth()/2,ofGetHeight()/2)-position;
velocity += centreDelta*ofGetLastFrameTime()*CENTRE_FORCE_MUL;
}
void FloatingSine::draw(){
float vol = volume.getVolume();
float volSq = vol*vol;
float alpha = fabsf(2.0f*(distanceUnits-int(distanceUnits)-0.5f));
// select colour based on waveform
ofColor colour = sawtooth?sawColour:sineColour;
// draw the particle
float particleAlpha = (bBackgroundAuto?1.0f:0.2f)*(128+128.0f*alpha);
ofSetColor( colour.r, colour.g, colour.b, particleAlpha );
ofFill();
particle->setAnchorPercent(0.5,0.5);
ofCircle( position.x, position.y, RADIUS*(0.4f+0.6f*alpha*volume.getVolume()*neighbours->size()) );
// draw the connecting lines and shell lines
float lineAlpha = (bBackgroundAuto?1.0f:0.2f)*(255.0f*alpha);
ofSetColor( colour.r, colour.g, colour.b, lineAlpha );
ofNoFill();
ofVec2f buddyPosition = neighbours->at(buddy)->position;
ofLine( position.x, position.y, buddyPosition.x, buddyPosition.y );
ofCircle( buddyPosition.x, buddyPosition.y, distanceUnits*shellDistance );
}
void FloatingSine::setBackgroundAuto( bool bAuto )
{
bBackgroundAuto = bAuto;
}
| 28.269231 | 158 | 0.694785 | HellicarAndLewis |
78179b1dfad2bcae017ef85816dee3cda955c733 | 75,794 | cpp | C++ | dev/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_Core.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 2 | 2020-12-22T01:02:01.000Z | 2020-12-22T01:02:05.000Z | dev/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_Core.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_Core.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright EntityRef license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <Source/Framework/ScriptCanvasTestFixture.h>
#include <Source/Framework/ScriptCanvasTestUtilities.h>
#include <Source/Framework/ScriptCanvasTestNodes.h>
#include <AzCore/Serialization/IdUtils.h>
#include <ScriptCanvas/Asset/RuntimeAsset.h>
#include <ScriptCanvas/Asset/RuntimeAssetHandler.h>
#include <ScriptCanvas/Execution/RuntimeComponent.h>
#include <ScriptCanvas/Variable/GraphVariableManagerComponent.h>
using namespace ScriptCanvasTests;
using namespace TestNodes;
TEST_F(ScriptCanvasTestFixture, CoreNodeFunction_OwningGraphCheck)
{
using namespace ScriptCanvas;
Graph* graph = CreateGraph();
ConfigurableUnitTestNode* groupedNode = CreateConfigurableNode();
EXPECT_EQ(graph, groupedNode->GetGraph());
}
TEST_F(ScriptCanvasTestFixture, AddRemoveSlot)
{
RegisterComponentDescriptor<AddNodeWithRemoveSlot>();
using namespace ScriptCanvas;
using namespace Nodes;
AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("RemoveSlotGraph");
graphEntity->Init();
Graph* graph{};
SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get());
AZ::EntityId graphUniqueId = graph->GetUniqueId();
AZ::EntityId outID;
auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID);
auto numberAddNode = CreateTestNode<AddNodeWithRemoveSlot>(graphUniqueId, outID);
auto number1Node = CreateDataNode<Data::NumberType>(graphUniqueId, 1.0, outID);
auto number2Node = CreateDataNode<Data::NumberType>(graphUniqueId, 2.0, outID);
auto number3Node = CreateDataNode<Data::NumberType>(graphUniqueId, 4.0, outID);
auto numberResultNode = CreateDataNode<Data::NumberType>(graphUniqueId, 0.0, outID);
// data
EXPECT_TRUE(Connect(*graph, number1Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "A"));
EXPECT_TRUE(Connect(*graph, number2Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "B"));
EXPECT_TRUE(Connect(*graph, number3Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "C"));
EXPECT_TRUE(Connect(*graph, numberAddNode->GetEntityId(), "Result", numberResultNode->GetEntityId(), "Set"));
// logic
EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", numberAddNode->GetEntityId(), "In"));
// execute pre remove
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
SC_EXPECT_DOUBLE_EQ(7.0, *result);
}
else
{
ADD_FAILURE();
}
// Remove the second number slot from the AddNodeWithRemoveSlot node(the one that contains value = 2.0)
numberAddNode->RemoveSlot(numberAddNode->GetSlotId("B"));
EXPECT_FALSE(numberAddNode->GetSlotId("B").IsValid());
// execute post-remove
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
SC_EXPECT_DOUBLE_EQ(5.0, *result);
}
else
{
ADD_FAILURE();
}
// Add two more slots and set there values to 8.0 and 16.0
EXPECT_TRUE(numberAddNode->AddSlot("D").IsValid());
EXPECT_TRUE(numberAddNode->AddSlot("B").IsValid());
auto number4Node = CreateDataNode<Data::NumberType>(graphUniqueId, 8.0, outID);
auto number5Node = CreateDataNode<Data::NumberType>(graphUniqueId, 16.0, outID);
EXPECT_TRUE(Connect(*graph, number4Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "D"));
EXPECT_TRUE(Connect(*graph, number5Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "B"));
// execute post-add of slot "D" and re-add of slot "A"
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
SC_EXPECT_DOUBLE_EQ(1.0 + 4.0 + 8.0 + 16.0, *result);
}
else
{
ADD_FAILURE();
}
// Remove the first number slot from the AddNodeWithRemoveSlot node(the one that contains value = 1.0
numberAddNode->RemoveSlot(numberAddNode->GetSlotId("A"));
EXPECT_FALSE(numberAddNode->GetSlotId("A").IsValid());
// execute post-remove of "A" slot
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
SC_EXPECT_DOUBLE_EQ(4.0 + 8.0 + 16.0, *result);
}
else
{
ADD_FAILURE();
}
graphEntity.reset();
}
TEST_F(ScriptCanvasTestFixture, AddRemoveSlotNotifications)
{
RegisterComponentDescriptor<AddNodeWithRemoveSlot>();
using namespace ScriptCanvas;
using namespace Nodes;
AZStd::unique_ptr<AZ::Entity> numberAddEntity = AZStd::make_unique<AZ::Entity>("numberAddEntity");
auto numberAddNode = numberAddEntity->CreateComponent<AddNodeWithRemoveSlot>();
numberAddEntity->Init();
ScriptUnitTestNodeNotificationHandler nodeNotifications(numberAddNode->GetEntityId());
SlotId testSlotId = numberAddNode->AddSlot("test");
EXPECT_EQ(1U, nodeNotifications.GetSlotsAdded());
numberAddNode->RemoveSlot(testSlotId);
EXPECT_EQ(1U, nodeNotifications.GetSlotsRemoved());
testSlotId = numberAddNode->AddSlot("duplicate");
EXPECT_EQ(2U, nodeNotifications.GetSlotsAdded());
// This should not signal the NodeNotification::OnSlotAdded event as the slot already exist on the node
SlotId duplicateSlotId = numberAddNode->AddSlot("duplicate");
EXPECT_EQ(2U, nodeNotifications.GetSlotsAdded());
EXPECT_EQ(testSlotId, duplicateSlotId);
numberAddNode->RemoveSlot(testSlotId);
EXPECT_EQ(2U, nodeNotifications.GetSlotsRemoved());
// This should not signal the NodeNotification::OnSlotRemoved event as the slot no longer exist on the node
numberAddNode->RemoveSlot(testSlotId);
EXPECT_EQ(2U, nodeNotifications.GetSlotsRemoved());
numberAddEntity.reset();
}
TEST_F(ScriptCanvasTestFixture, InsertSlot)
{
RegisterComponentDescriptor<InsertSlotConcatNode>();
using namespace ScriptCanvas;
using namespace Nodes;
AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("RemoveSlotGraph");
graphEntity->Init();
SystemRequestBus::Broadcast(&SystemRequests::CreateEngineComponentsOnEntity, graphEntity.get());
Graph* graph = AZ::EntityUtils::FindFirstDerivedComponent<Graph>(graphEntity.get());
AZ::EntityId graphUniqueId = graph->GetUniqueId();
AZ::EntityId outId;
auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outId);
auto insertSlotConcatNode = CreateTestNode<InsertSlotConcatNode>(graphUniqueId, outId);
auto setVariableNode = CreateTestNode<Nodes::Core::SetVariableNode>(graphUniqueId, outId);
VariableId resultVarId = CreateVariable(graphUniqueId, Data::StringType(), "result");
VariableId middleValueVarId = CreateVariable(graphUniqueId, Data::StringType(" Ice Cream"), "middleValue");
setVariableNode->SetId(resultVarId);
EXPECT_TRUE(setVariableNode->GetDataInSlotId().IsValid());
//logic connections
EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", insertSlotConcatNode->GetEntityId(), "In"));
EXPECT_TRUE(Connect(*graph, insertSlotConcatNode->GetEntityId(), "Out", setVariableNode->GetEntityId(), "In"));
// insert slots
auto concatSlotId = insertSlotConcatNode->InsertSlot(-1, "A");
auto slotAId = concatSlotId;
insertSlotConcatNode->SetInput_UNIT_TEST(concatSlotId, Data::StringType("Hello"));
concatSlotId = insertSlotConcatNode->InsertSlot(-1, "B");
auto slotBId = concatSlotId;
insertSlotConcatNode->SetInput_UNIT_TEST(concatSlotId, Data::StringType(" World"));
// data connections
EXPECT_TRUE(graph->Connect(insertSlotConcatNode->GetEntityId(), insertSlotConcatNode->GetSlotId("Result"), setVariableNode->GetEntityId(), setVariableNode->GetDataInSlotId()));
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
const VariableDatum* resultDatum{};
VariableRequestBus::EventResult(resultDatum, resultVarId, &VariableRequests::GetVariableDatumConst);
ASSERT_NE(nullptr, resultDatum);
EXPECT_EQ("Hello World", resultDatum->GetData().ToString());
// insert additional slot between A and B
auto slotIndexOutcome = insertSlotConcatNode->FindSlotIndex(slotBId);
EXPECT_TRUE(slotIndexOutcome);
concatSlotId = insertSlotConcatNode->InsertSlot(slotIndexOutcome.GetValue(), "Alpha");
NodeRequestBus::Event(insertSlotConcatNode->GetEntityId(), &NodeRequests::SetSlotVariableId, concatSlotId, middleValueVarId);
// re-execute the graph
graphEntity->Activate();
ReportErrors(graph);
graphEntity->Deactivate();
// the new concatenated string should be in the middle
EXPECT_EQ("Hello Ice Cream World", resultDatum->GetData().ToString());
graphEntity.reset();
}
TEST_F(ScriptCanvasTestFixture, NativeProperties)
{
using namespace ScriptCanvas;
using namespace Nodes;
AZ::Entity* graphEntity = aznew AZ::Entity("Graph");
graphEntity->Init();
SystemRequestBus::Broadcast(&SystemRequests::CreateGraphOnEntity, graphEntity);
auto graph = graphEntity->FindComponent<Graph>();
EXPECT_NE(nullptr, graph);
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId addId;
CreateTestNode<Vector3Nodes::AddNode>(graphUniqueId, addId);
AZ::EntityId vector3IdA, vector3IdB, vector3IdC;
auto vector3NodeA = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdA);
auto vector3NodeB = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdB);
auto vector3NodeC = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdC);
AZ::EntityId number1Id, number2Id, number3Id, number4Id, number5Id, number6Id, number7Id, number8Id, number9Id;
Node* number1Node = CreateDataNode<Data::NumberType>(graphUniqueId, 1, number1Id);
Node* number2Node = CreateDataNode<Data::NumberType>(graphUniqueId, 2, number2Id);
Node* number3Node = CreateDataNode<Data::NumberType>(graphUniqueId, 3, number3Id);
Node* number4Node = CreateDataNode<Data::NumberType>(graphUniqueId, 4, number4Id);
Node* number5Node = CreateDataNode<Data::NumberType>(graphUniqueId, 5, number5Id);
Node* number6Node = CreateDataNode<Data::NumberType>(graphUniqueId, 6, number6Id);
Node* number7Node = CreateDataNode<Data::NumberType>(graphUniqueId, 7, number7Id);
Node* number8Node = CreateDataNode<Data::NumberType>(graphUniqueId, 8, number8Id);
Node* number9Node = CreateDataNode<Data::NumberType>(graphUniqueId, 0, number9Id);
// data
EXPECT_TRUE(Connect(*graph, number1Id, "Get", vector3IdA, "Number: x"));
EXPECT_TRUE(Connect(*graph, number2Id, "Get", vector3IdA, "Number: y"));
EXPECT_TRUE(Connect(*graph, number3Id, "Get", vector3IdA, "Number: z"));
EXPECT_TRUE(Connect(*graph, number4Id, "Get", vector3IdB, "Number: x"));
EXPECT_TRUE(Connect(*graph, number5Id, "Get", vector3IdB, "Number: y"));
EXPECT_TRUE(Connect(*graph, number6Id, "Get", vector3IdB, "Number: z"));
EXPECT_TRUE(Connect(*graph, vector3IdA, "Get", addId, "Vector3: A"));
EXPECT_TRUE(Connect(*graph, vector3IdB, "Get", addId, "Vector3: B"));
EXPECT_TRUE(Connect(*graph, addId, "Result: Vector3", vector3IdC, "Set"));
EXPECT_TRUE(Connect(*graph, vector3IdC, "x: Number", number7Id, "Set"));
EXPECT_TRUE(Connect(*graph, vector3IdC, "y: Number", number8Id, "Set"));
EXPECT_TRUE(Connect(*graph, vector3IdC, "z: Number", number9Id, "Set"));
// code
EXPECT_TRUE(Connect(*graph, startID, "Out", addId, "In"));
graphEntity->Activate();
ReportErrors(graph);
if (auto result = vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set"))
{
EXPECT_EQ(AZ::Vector3(5, 7, 9), *result);
}
else
{
ADD_FAILURE();
}
if (auto result = number7Node->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
EXPECT_EQ(5, *result);
}
else
{
ADD_FAILURE();
}
if (auto result = number8Node->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
EXPECT_EQ(7, *result);
}
else
{
ADD_FAILURE();
}
if (auto result = number9Node->GetInput_UNIT_TEST<Data::NumberType>("Set"))
{
EXPECT_EQ(9, *result);
}
else
{
ADD_FAILURE();
}
graphEntity->Deactivate();
delete graphEntity;
}
TEST_F(ScriptCanvasTestFixture, ExtractPropertiesNativeType)
{
// TODO: Add Extract test for all Native Types
using namespace ScriptCanvas;
using namespace Nodes;
AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("PropertyGraph");
Graph* graph{};
SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get());
ASSERT_NE(nullptr, graph);
AZ::EntityId propertyEntityId = graphEntity->GetId();
AZ::EntityId graphUniqueId = graph->GetUniqueId();
graphEntity->Init();
// Create Extract Property Node
AZ::EntityId outID;
auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID);
auto extractPropertyNode = CreateTestNode<Nodes::Core::ExtractProperty>(graphUniqueId, outID);
auto printNode = CreateTestNode<TestResult>(graphUniqueId, outID);
// Test Native Vector3 Properties
auto vector3Node = CreateDataNode(graphUniqueId, Data::Vector3Type(10.0f, 23.3f, 77.45f), outID);
auto numberResultNode1 = CreateDataNode(graphUniqueId, 0.0f, outID);
auto numberResultNode2 = CreateDataNode(graphUniqueId, 0.0f, outID);
auto numberResultNode3 = CreateDataNode(graphUniqueId, 0.0f, outID);
// data
EXPECT_EQ(0, extractPropertyNode->GetPropertyFields().size());
EXPECT_FALSE(extractPropertyNode->GetSourceSlotDataType().IsValid());
EXPECT_TRUE(Connect(*graph, vector3Node->GetEntityId(), "Get", extractPropertyNode->GetEntityId(), "Source"));
auto propertyFields = extractPropertyNode->GetPropertyFields();
EXPECT_EQ(3, propertyFields.size());
EXPECT_TRUE(extractPropertyNode->GetSourceSlotDataType().IS_A(Data::Type::Vector3()));
// Vector3::x
auto propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "x";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode1->GetEntityId(), numberResultNode1->GetSlotId("Set")));
// Vector3::y
propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "y";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode2->GetEntityId(), numberResultNode2->GetSlotId("Set")));
// Vector3::z
propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "z";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode3->GetEntityId(), numberResultNode3->GetSlotId("Set")));
// Print the z value to console
EXPECT_TRUE(graph->Connect(numberResultNode3->GetEntityId(), numberResultNode3->GetSlotId("Get"), printNode->GetEntityId(), printNode->GetSlotId("Value")));
// logic
EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", extractPropertyNode->GetEntityId(), "In"));
EXPECT_TRUE(Connect(*graph, extractPropertyNode->GetEntityId(), "Out", printNode->GetEntityId(), "In"));
// execute
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graphEntity->Activate();
}
ReportErrors(graph);
graphEntity->Deactivate();
AZ::Entity* connectionEntity{};
EXPECT_TRUE(graph->FindConnection(connectionEntity, { vector3Node->GetEntityId(), vector3Node->GetSlotId("Get") }, { extractPropertyNode->GetEntityId(), extractPropertyNode->GetSlotId("Source") }));
EXPECT_TRUE(graph->DisconnectById(connectionEntity->GetId()));
const float tolerance = 0.001f;
// x result
auto vectorElementResult = numberResultNode1->GetInput_UNIT_TEST<Data::NumberType>("Set");
ASSERT_NE(nullptr, vectorElementResult);
EXPECT_NEAR(10.0f, *vectorElementResult, tolerance);
// y result
vectorElementResult = numberResultNode2->GetInput_UNIT_TEST<Data::NumberType>("Set");
ASSERT_NE(nullptr, vectorElementResult);
EXPECT_NEAR(23.3f, *vectorElementResult, tolerance);
// z result
vectorElementResult = numberResultNode3->GetInput_UNIT_TEST<Data::NumberType>("Set");
ASSERT_NE(nullptr, vectorElementResult);
EXPECT_NEAR(77.45f, *vectorElementResult, tolerance);
graphEntity.reset();
}
TEST_F(ScriptCanvasTestFixture, ExtractPropertiesBehaviorType)
{
TestBehaviorContextProperties::Reflect(m_serializeContext);
TestBehaviorContextProperties::Reflect(m_behaviorContext);
using namespace ScriptCanvas;
using namespace Nodes;
AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("PropertyGraph");
Graph* graph{};
SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get());
ASSERT_NE(nullptr, graph);
AZ::EntityId propertyEntityId = graphEntity->GetId();
AZ::EntityId graphUniqueId = graph->GetUniqueId();
graphEntity->Init();
// Create Extract Property Node
AZ::EntityId outID;
auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID);
auto extractPropertyNode = CreateTestNode<Nodes::Core::ExtractProperty>(graphUniqueId, outID);
auto printNode = CreateTestNode<TestResult>(graphUniqueId, outID);
// Test BehaviorContext Properties
TestBehaviorContextProperties behaviorContextProperties;
behaviorContextProperties.m_booleanProp = true;
behaviorContextProperties.m_numberProp = 11.90f;
behaviorContextProperties.m_stringProp = "String Property";
auto behaviorContextPropertyNode = CreateDataNode(graphUniqueId, behaviorContextProperties, outID);
auto booleanResultNode = CreateDataNode(graphUniqueId, false, outID);
auto numberResultNode = CreateDataNode(graphUniqueId, 0.0f, outID);
auto stringResultNode = CreateDataNode(graphUniqueId, Data::StringType("Uninitialized"), outID);
// data
EXPECT_EQ(0, extractPropertyNode->GetPropertyFields().size());
EXPECT_FALSE(extractPropertyNode->GetSourceSlotDataType().IsValid());
EXPECT_TRUE(Connect(*graph, behaviorContextPropertyNode->GetEntityId(), "Get", extractPropertyNode->GetEntityId(), "Source"));
auto propertyFields = extractPropertyNode->GetPropertyFields();
EXPECT_EQ(4, propertyFields.size());
EXPECT_TRUE(extractPropertyNode->GetSourceSlotDataType().IS_A(Data::FromAZType<TestBehaviorContextProperties>()));
// TestBehaviorContextProperties::boolean
auto propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "boolean";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, booleanResultNode->GetEntityId(), booleanResultNode->GetSlotId("Set")));
// TestBehaviorContextProperties::number
propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "number";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode->GetEntityId(), numberResultNode->GetSlotId("Set")));
// TestBehaviorContextProperties::string
propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField)
{
return propertyField.first == "string";
});
ASSERT_NE(propIt, propertyFields.end());
EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, stringResultNode->GetEntityId(), stringResultNode->GetSlotId("Set")));
// Print the string value to console
EXPECT_TRUE(graph->Connect(stringResultNode->GetEntityId(), stringResultNode->GetSlotId("Get"), printNode->GetEntityId(), printNode->GetSlotId("Value")));
// logic
EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", extractPropertyNode->GetEntityId(), "In"));
EXPECT_TRUE(Connect(*graph, extractPropertyNode->GetEntityId(), "Out", printNode->GetEntityId(), "In"));
// execute
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graphEntity->Activate();
}
ReportErrors(graph);
graphEntity->Deactivate();
AZ::Entity* connectionEntity{};
EXPECT_TRUE(graph->FindConnection(connectionEntity, { behaviorContextPropertyNode->GetEntityId(), behaviorContextPropertyNode->GetSlotId("Get") }, { extractPropertyNode->GetEntityId(), extractPropertyNode->GetSlotId("Source") }));
EXPECT_TRUE(graph->DisconnectById(connectionEntity->GetId()));
// boolean result
auto booleanResult = booleanResultNode->GetInput_UNIT_TEST<Data::BooleanType>("Set");
ASSERT_NE(nullptr, booleanResult);
EXPECT_TRUE(booleanResult);
// number result
const float tolerance = 0.001f;
auto numberResult = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set");
ASSERT_NE(nullptr, numberResult);
EXPECT_NEAR(11.90f, *numberResult, tolerance);
// string result
auto stringResult = stringResultNode->GetInput_UNIT_TEST<Data::StringType>("Set");
ASSERT_NE(nullptr, stringResult);
EXPECT_EQ("String Property", *stringResult);
graphEntity.reset();
m_serializeContext->EnableRemoveReflection();
TestBehaviorContextProperties::Reflect(m_serializeContext);
m_serializeContext->DisableRemoveReflection();
m_behaviorContext->EnableRemoveReflection();
TestBehaviorContextProperties::Reflect(m_behaviorContext);
m_behaviorContext->DisableRemoveReflection();
}
TEST_F(ScriptCanvasTestFixture, IsNullCheck)
{
using namespace ScriptCanvas;
EventTestHandler::Reflect(m_serializeContext);
EventTestHandler::Reflect(m_behaviorContext);
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
Graph* graph(nullptr);
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityID = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId isNullFalseID;
CreateTestNode<Nodes::Logic::IsNull>(graphUniqueId, isNullFalseID);
AZ::EntityId isNullTrueID;
CreateTestNode<Nodes::Logic::IsNull>(graphUniqueId, isNullTrueID);
AZ::EntityId isNullResultFalseID;
auto isNullResultFalse = CreateDataNode(graphUniqueId, true, isNullResultFalseID);
AZ::EntityId isNullResultTrueID;
auto isNullResultTrue = CreateDataNode(graphUniqueId, false, isNullResultTrueID);
AZ::EntityId normalizeID;
Nodes::Core::Method* normalize = CreateTestNode<Nodes::Core::Method>(graphUniqueId, normalizeID);
Namespaces empty;
normalize->InitializeClass(empty, "TestBehaviorContextObject", "Normalize");
AZ::EntityId vectorID;
Nodes::Core::BehaviorContextObjectNode* vector = CreateTestNode<Nodes::Core::BehaviorContextObjectNode>(graphUniqueId, vectorID);
const AZStd::string vector3("TestBehaviorContextObject");
vector->InitializeObject(vector3);
if (auto vector3 = vector->ModInput_UNIT_TEST<TestBehaviorContextObject>("Set"))
{
EXPECT_FALSE(vector3->IsNormalized());
}
else
{
ADD_FAILURE();
}
// test the reference type contract
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
EXPECT_FALSE(Connect(*graph, isNullResultFalseID, "Get", isNullTrueID, "Reference"));
}
// data
EXPECT_TRUE(Connect(*graph, vectorID, "Get", normalizeID, "TestBehaviorContextObject: 0"));
EXPECT_TRUE(Connect(*graph, vectorID, "Get", isNullFalseID, "Reference"));
EXPECT_TRUE(Connect(*graph, isNullTrueID, "Is Null", isNullResultTrueID, "Set"));
EXPECT_TRUE(Connect(*graph, isNullFalseID, "Is Null", isNullResultFalseID, "Set"));
// execution
EXPECT_TRUE(Connect(*graph, startID, "Out", isNullTrueID, "In"));
EXPECT_TRUE(Connect(*graph, isNullTrueID, "True", isNullFalseID, "In"));
EXPECT_TRUE(Connect(*graph, isNullFalseID, "False", normalizeID, "In"));
AZ::Entity* graphEntity = graph->GetEntity();
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graphEntity->Activate();
}
ReportErrors(graph);
if (auto vector3 = vector->GetInput_UNIT_TEST<TestBehaviorContextObject>("Set"))
{
EXPECT_TRUE(vector3->IsNormalized());
}
else
{
ADD_FAILURE();
}
if (auto shouldBeFalse = isNullResultFalse->GetInput_UNIT_TEST<bool>("Set"))
{
EXPECT_FALSE(*shouldBeFalse);
}
else
{
ADD_FAILURE();
}
if (auto shouldBeTrue = isNullResultTrue->GetInput_UNIT_TEST<bool>("Set"))
{
EXPECT_TRUE(*shouldBeTrue);
}
else
{
ADD_FAILURE();
}
graphEntity->Deactivate();
delete graphEntity;
m_serializeContext->EnableRemoveReflection();
m_behaviorContext->EnableRemoveReflection();
EventTestHandler::Reflect(m_serializeContext);
EventTestHandler::Reflect(m_behaviorContext);
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
m_serializeContext->DisableRemoveReflection();
m_behaviorContext->DisableRemoveReflection();
}
TEST_F(ScriptCanvasTestFixture, NullThisPointerDoesNotCrash)
{
using namespace ScriptCanvas;
EventTestHandler::Reflect(m_serializeContext);
EventTestHandler::Reflect(m_behaviorContext);
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
Graph* graph(nullptr);
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityID = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId normalizeID;
Nodes::Core::Method* normalize = CreateTestNode<Nodes::Core::Method>(graphUniqueId, normalizeID);
Namespaces empty;
normalize->InitializeClass(empty, "TestBehaviorContextObject", "Normalize");
EXPECT_TRUE(Connect(*graph, startID, "Out", normalizeID, "In"));
AZ::Entity* graphEntity = graph->GetEntity();
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graphEntity->Activate();
}
// just don't crash, but be in error
const bool expectError = true;
const bool expectIrrecoverableError = true;
ReportErrors(graph, expectError, expectIrrecoverableError);
graphEntity->Deactivate();
delete graphEntity;
m_serializeContext->EnableRemoveReflection();
m_behaviorContext->EnableRemoveReflection();
EventTestHandler::Reflect(m_serializeContext);
EventTestHandler::Reflect(m_behaviorContext);
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
m_serializeContext->DisableRemoveReflection();
m_behaviorContext->DisableRemoveReflection();
}
TEST_F(ScriptCanvasTestFixture, ValueTypes)
{
using namespace ScriptCanvas;
Datum number0(Datum(0));
int number0Value = *number0.GetAs<int>();
Datum number1(Datum(1));
int number1Value = *number1.GetAs<int>();
Datum numberFloat(Datum(2.f));
float numberFloatValue = *numberFloat.GetAs<float>();
Datum numberDouble(Datum(3.0));
double numberDoubleValue = *numberDouble.GetAs<double>();
Datum numberHex(Datum(0xff));
int numberHexValue = *numberHex.GetAs<int>();
Datum numberPi(Datum(3.14f));
float numberPiValue = *numberPi.GetAs<float>();
Datum numberSigned(Datum(-100));
int numberSignedValue = *numberSigned.GetAs<int>();
Datum numberUnsigned(Datum(100u));
unsigned int numberUnsignedValue = *numberUnsigned.GetAs<unsigned int>();
Datum numberDoublePi(Datum(6.28));
double numberDoublePiValue = *numberDoublePi.GetAs<double>();
EXPECT_EQ(number0Value, 0);
EXPECT_EQ(number1Value, 1);
EXPECT_TRUE(AZ::IsClose(numberFloatValue, 2.f, std::numeric_limits<float>::epsilon()));
EXPECT_TRUE(AZ::IsClose(numberDoubleValue, 3.0, std::numeric_limits<double>::epsilon()));
EXPECT_NE(number0Value, number1Value);
SC_EXPECT_FLOAT_EQ(numberPiValue, 3.14f);
EXPECT_NE(number0Value, numberPiValue);
EXPECT_NE(numberPiValue, numberDoublePiValue);
Datum boolTrue(Datum(true));
EXPECT_TRUE(*boolTrue.GetAs<bool>());
Datum boolFalse(Datum(false));
EXPECT_FALSE(*boolFalse.GetAs<bool>());
boolFalse = boolTrue;
EXPECT_TRUE(*boolFalse.GetAs<bool>());
Datum boolFalse2(Datum(false));
boolTrue = boolFalse2;
EXPECT_FALSE(*boolTrue.GetAs<bool>());
{
const int k_count(10000);
AZStd::vector<Datum> objects;
for (int i = 0; i < k_count; ++i)
{
objects.push_back(Datum("Vector3", Datum::eOriginality::Original));
}
}
GTEST_SUCCEED();
}
namespace
{
using namespace ScriptCanvas;
using namespace ScriptCanvas::Nodes;
bool GraphHasVectorWithValue(const Graph& graph, const AZ::Vector3& vector)
{
for (auto nodeId : graph.GetNodes())
{
AZ::Entity* entity{};
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId);
if (entity)
{
if (auto node = AZ::EntityUtils::FindFirstDerivedComponent<Core::BehaviorContextObjectNode>(entity))
{
if (auto candidate = node->GetInput_UNIT_TEST<AZ::Vector3>("Set"))
{
if (*candidate == vector)
{
return true;
}
}
}
}
}
return false;
}
}
TEST_F(ScriptCanvasTestFixture, SerializationSaveTest)
{
using namespace ScriptCanvas;
using namespace ScriptCanvas::Nodes;
//////////////////////////////////////////////////////////////////////////
// Make the graph.
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
// Make the nodes.
// Start
AZ::Entity* startEntity{ aznew AZ::Entity };
startEntity->Init();
AZ::EntityId startNode{ startEntity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, startNode, graphUniqueId, Nodes::Core::Start::TYPEINFO_Uuid());
// Constant 0
AZ::Entity* constant0Entity{ aznew AZ::Entity };
constant0Entity->Init();
AZ::EntityId constant0Node{ constant0Entity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, constant0Node, graphUniqueId, Nodes::Math::Number::TYPEINFO_Uuid());
// Get the node and set the value
Nodes::Math::Number* constant0NodePtr = nullptr;
SystemRequestBus::BroadcastResult(constant0NodePtr, &SystemRequests::GetNode<Nodes::Math::Number>, constant0Node);
EXPECT_TRUE(constant0NodePtr != nullptr);
if (constant0NodePtr)
{
constant0NodePtr->SetInput_UNIT_TEST("Set", 4);
}
// Constant 1
AZ::Entity* constant1Entity{ aznew AZ::Entity };
constant1Entity->Init();
AZ::EntityId constant1Node{ constant1Entity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, constant1Node, graphUniqueId, Nodes::Math::Number::TYPEINFO_Uuid());
// Get the node and set the value
Nodes::Math::Number* constant1NodePtr = nullptr;
SystemRequestBus::BroadcastResult(constant1NodePtr, &SystemRequests::GetNode<Nodes::Math::Number>, constant1Node);
EXPECT_TRUE(constant1NodePtr != nullptr);
if (constant1NodePtr)
{
constant1NodePtr->SetInput_UNIT_TEST("Set", 12);
}
// Sum
AZ::Entity* sumEntity{ aznew AZ::Entity };
sumEntity->Init();
AZ::EntityId sumNode{ sumEntity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, sumNode, graphUniqueId, Nodes::Math::Sum::TYPEINFO_Uuid());
AZ::EntityId printID;
auto printNode = CreateTestNode<TestResult>(graphUniqueId, printID);
// Connect, disconnect and reconnect to validate disconnection
graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get"));
graph->Disconnect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get"));
graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get"));
{
auto* sumNodePtr = AZ::EntityUtils::FindFirstDerivedComponent<Nodes::Math::Sum>(sumEntity);
EXPECT_NE(nullptr, sumNodePtr);
EXPECT_EQ(1, graph->GetConnectedEndpoints({ sumNode, sumNodePtr->GetSlotId(BinaryOperator::k_lhsName) }).size());
}
graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_rhsName), constant1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant1Entity)->GetSlotId("Get"));
EXPECT_TRUE(Connect(*graph, sumNode, "Result", printID, "Value"));
EXPECT_TRUE(Connect(*graph, startNode, "Out", sumNode, Nodes::BinaryOperator::k_evaluateName));
EXPECT_TRUE(Connect(*graph, sumNode, Nodes::BinaryOperator::k_outName, printID, "In"));
AZ::EntityId vector3IdA, vector3IdB, vector3IdC;
const AZ::Vector3 allOne(1, 1, 1);
const AZ::Vector3 allTwo(2, 2, 2);
const AZ::Vector3 allThree(3, 3, 3);
const AZ::Vector3 allFour(4, 4, 4);
Core::BehaviorContextObjectNode* vector3NodeA = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdA);
vector3NodeA->InitializeObject(azrtti_typeid<AZ::Vector3>());
*vector3NodeA->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allOne;
Core::BehaviorContextObjectNode* vector3NodeB = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdB);
vector3NodeB->InitializeObject(azrtti_typeid<AZ::Vector3>());
*vector3NodeB->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allTwo;
Core::BehaviorContextObjectNode* vector3NodeC = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdC);
vector3NodeC->InitializeObject(azrtti_typeid<AZ::Vector3>());
*vector3NodeC->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allFour;
AZ::EntityId add3IdA;
CreateTestNode<Vector3Nodes::AddNode>(graphUniqueId, add3IdA);
EXPECT_TRUE(Connect(*graph, printID, "Out", add3IdA, "In"));
EXPECT_TRUE(Connect(*graph, vector3IdA, "Get", add3IdA, "Vector3: A"));
EXPECT_TRUE(Connect(*graph, vector3IdB, "Get", add3IdA, "Vector3: B"));
EXPECT_TRUE(Connect(*graph, vector3IdC, "Set", add3IdA, "Result: Vector3"));
AZStd::unique_ptr<AZ::Entity> graphEntity{ graph->GetEntity() };
EXPECT_EQ(allOne, *vector3NodeA->GetInput_UNIT_TEST<AZ::Vector3>("Set"));
EXPECT_EQ(allTwo, *vector3NodeB->GetInput_UNIT_TEST<AZ::Vector3>("Set"));
auto vector3C = *vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set");
EXPECT_EQ(allFour, vector3C);
auto nodeIDs = graph->GetNodes();
EXPECT_EQ(9, nodeIDs.size());
ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, true);
graphEntity->Activate();
ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, false);
ReportErrors(graph);
vector3C = *vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set");
EXPECT_EQ(allThree, vector3C);
if (auto result = printNode->GetInput_UNIT_TEST<float>("Value"))
{
SC_EXPECT_FLOAT_EQ(*result, 16.0f);
}
else
{
ADD_FAILURE();
}
graphEntity->Deactivate();
auto* fileIO = AZ::IO::LocalFileIO::GetInstance();
EXPECT_TRUE(fileIO != nullptr);
auto pathResult = fileIO->CreatePath(k_tempCoreAssetDir);;
EXPECT_EQ(pathResult.GetResultCode(), AZ::IO::ResultCode::Success) << "Path failed to create";
// Save it
bool result = false;
AZ::IO::FileIOStream outFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeWrite);
if (outFileStream.IsOpen())
{
RuntimeAssetHandler runtimeAssetHandler;
AZ::Data::Asset<RuntimeAsset> runtimeAsset = CreateRuntimeAsset(graph);
EXPECT_TRUE(runtimeAssetHandler.SaveAssetData(runtimeAsset, &outFileStream)) << "Asset failed to save";
auto* fileIO = AZ::IO::LocalFileIO::GetInstance();
EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath));
}
else
{
ADD_FAILURE() << "File stream not open";
}
outFileStream.Close();
}
TEST_F(ScriptCanvasTestFixture, SerializationLoadTest_Graph)
{
using namespace ScriptCanvas;
//////////////////////////////////////////////////////////////////////////
// Make the graph.
Graph* graph = nullptr;
AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("Loaded Graph");
SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get());
auto* fileIO = AZ::IO::LocalFileIO::GetInstance();
ASSERT_NE(nullptr, fileIO);
EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath));
// Load it
AZ::IO::FileIOStream inFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeRead);
if (inFileStream.IsOpen())
{
// Serialize the graph entity back in.
RuntimeAssetHandler runtimeAssetHandler;
AZ::Data::Asset<RuntimeAsset> runtimeAsset;
runtimeAsset.Create(AZ::Uuid::CreateRandom());
EXPECT_TRUE(runtimeAssetHandler.LoadAssetData(runtimeAsset, &inFileStream, {}));
GraphData& assetGraphData = runtimeAsset.Get()->GetData().m_graphData;
AZStd::unordered_map<AZ::EntityId, AZ::EntityId> idRemap;
AZ::IdUtils::Remapper<AZ::EntityId>::GenerateNewIdsAndFixRefs(&assetGraphData, idRemap, m_serializeContext);
graph->AddGraphData(assetGraphData);
// Clear GraphData on asset to prevent it from deleting the graph data, the Graph component takes care of cleaning it up
assetGraphData.Clear();
// Close the file
inFileStream.Close();
// Initialize the entity
graphEntity->Init();
ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, true);
graphEntity->Activate();
ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, false);
// Run the graph component
graph = graphEntity->FindComponent<Graph>();
EXPECT_TRUE(graph != nullptr); // "Graph entity did not have the graph component.");
ReportErrors(graph);
const AZ::Vector3 allOne(1, 1, 1);
const AZ::Vector3 allTwo(2, 2, 2);
const AZ::Vector3 allThree(3, 3, 3);
const AZ::Vector3 allFour(4, 4, 4);
auto nodeIDs = graph->GetNodes();
EXPECT_EQ(9, nodeIDs.size());
// Graph result should be still 16
// Serialized graph has new remapped entity ids
auto nodes = graph->GetNodes();
auto sumNodeIt = AZStd::find_if(nodes.begin(), nodes.end(), [](const AZ::EntityId& nodeId) -> bool
{
AZ::Entity* entity{};
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId);
return entity ? AZ::EntityUtils::FindFirstDerivedComponent<TestResult>(entity) ? true : false : false;
});
EXPECT_NE(nodes.end(), sumNodeIt);
TestResult* printNode = nullptr;
SystemRequestBus::BroadcastResult(printNode, &SystemRequests::GetNode<TestResult>, *sumNodeIt);
EXPECT_TRUE(printNode != nullptr);
if (auto result = printNode->GetInput_UNIT_TEST<float>("Value"))
{
SC_EXPECT_FLOAT_EQ(*result, 16.0f);
}
else
{
ADD_FAILURE();
}
EXPECT_TRUE(GraphHasVectorWithValue(*graph, allOne));
EXPECT_TRUE(GraphHasVectorWithValue(*graph, allTwo));
EXPECT_TRUE(GraphHasVectorWithValue(*graph, allThree));
EXPECT_FALSE(GraphHasVectorWithValue(*graph, allFour));
}
else
{
ADD_FAILURE() << "in stream did not open";
}
}
TEST_F(ScriptCanvasTestFixture, SerializationLoadTest_RuntimeComponent)
{
using namespace ScriptCanvas;
//////////////////////////////////////////////////////////////////////////
// Make the graph.
AZStd::unique_ptr<AZ::Entity> executionEntity = AZStd::make_unique<AZ::Entity>("Loaded Graph");
auto executionComponent = executionEntity->CreateComponent<ScriptCanvas::RuntimeComponent>();
auto* fileIO = AZ::IO::LocalFileIO::GetInstance();
EXPECT_NE(nullptr, fileIO);
EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath));
// Load it
AZ::IO::FileIOStream inFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeRead);
if (inFileStream.IsOpen())
{
// Serialize the runtime asset back in.
RuntimeAssetHandler runtimeAssetHandler;
AZ::Data::Asset<ScriptCanvas::RuntimeAsset> runtimeAsset;
runtimeAsset.Create(AZ::Uuid::CreateRandom());
EXPECT_TRUE(runtimeAssetHandler.LoadAssetData(runtimeAsset, &inFileStream, {}));
runtimeAssetHandler.InitAsset(runtimeAsset, true, false);
// Close the file
inFileStream.Close();
// Initialize the entity
executionComponent->SetRuntimeAsset(runtimeAsset);
executionEntity->Init();
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
executionEntity->Activate();
// Dispatch the AssetBus events to force onAssetReady event
AZ::Data::AssetManager::Instance().DispatchEvents();
}
EXPECT_FALSE(executionComponent->IsInErrorState());
const AZ::Vector3 allOne(1, 1, 1);
const AZ::Vector3 allTwo(2, 2, 2);
const AZ::Vector3 allThree(3, 3, 3);
const AZ::Vector3 allFour(4, 4, 4);
auto nodeIds = executionComponent->GetNodes();
EXPECT_EQ(9, nodeIds.size());
// Graph result should be still 16
// Serialized graph has new remapped entity ids
auto sumNodeIt = AZStd::find_if(nodeIds.begin(), nodeIds.end(), [](const AZ::EntityId& nodeId) -> bool
{
AZ::Entity* entity{};
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId);
return entity ? AZ::EntityUtils::FindFirstDerivedComponent<TestResult>(entity) ? true : false : false;
});
EXPECT_NE(nodeIds.end(), sumNodeIt);
TestResult* printNode = nullptr;
SystemRequestBus::BroadcastResult(printNode, &SystemRequests::GetNode<TestResult>, *sumNodeIt);
EXPECT_TRUE(printNode != nullptr);
if (auto result = printNode->GetInput_UNIT_TEST<float>("Value"))
{
SC_EXPECT_FLOAT_EQ(*result, 16.0f);
}
else
{
ADD_FAILURE();
}
AZStd::vector<AZ::Vector3> vector3Results;
for (auto nodeId : nodeIds)
{
AZ::Entity* entity{};
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId);
auto behaviorContextNode = entity ? AZ::EntityUtils::FindFirstDerivedComponent<Core::BehaviorContextObjectNode>(entity) : nullptr;
auto rawVector3 = behaviorContextNode ? behaviorContextNode->GetInput_UNIT_TEST<AZ::Vector3>(PureData::k_setThis) : nullptr;
if (rawVector3)
{
vector3Results.push_back(*rawVector3);
}
}
auto allOneFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allOne](const AZ::Vector3& vector3Result)
{
return allOne == vector3Result;
});
auto allTwoFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allTwo](const AZ::Vector3& vector3Result)
{
return allTwo == vector3Result;
});
auto allThreeFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allThree](const AZ::Vector3& vector3Result)
{
return allThree == vector3Result;
});
auto allFourFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allFour](const AZ::Vector3& vector3Result)
{
return allFour == vector3Result;
});
EXPECT_TRUE(allOneFound);
EXPECT_TRUE(allTwoFound);
EXPECT_TRUE(allThreeFound);
EXPECT_FALSE(allFourFound);
}
}
TEST_F(ScriptCanvasTestFixture, Contracts)
{
using namespace ScriptCanvas;
RegisterComponentDescriptor<ContractNode>();
//////////////////////////////////////////////////////////////////////////
// Make the graph.
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
// Make the nodes.
// Start
AZ::Entity* startEntity{ aznew AZ::Entity("Start") };
startEntity->Init();
AZ::EntityId startNode{ startEntity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, startNode, graphUniqueId, Nodes::Core::Start::TYPEINFO_Uuid());
// ContractNode 0
AZ::Entity* contract0Entity{ aznew AZ::Entity("Contract 0") };
contract0Entity->Init();
AZ::EntityId contract0Node{ contract0Entity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, contract0Node, graphUniqueId, ContractNode::TYPEINFO_Uuid());
// ContractNode 1
AZ::Entity* contract1Entity{ aznew AZ::Entity("Contract 1") };
contract1Entity->Init();
AZ::EntityId contract1Node{ contract1Entity->GetId() };
SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, contract1Node, graphUniqueId, ContractNode::TYPEINFO_Uuid());
// invalid
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Out")));
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In")));
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Get String")));
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Get String")));
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String")));
EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String")));
EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set String")));
EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set Number")));
EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get Number")));
EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set String")));
EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In")));
}
// valid
EXPECT_TRUE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In")));
EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get String")));
EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Out")));
EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set Number"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get Number")));
// Execute it
graph->GetEntity()->Activate();
ReportErrors(graph);
graph->GetEntity()->Deactivate();
delete graph->GetEntity();
}
#if defined (SCRIPTCANVAS_ERRORS_ENABLED)
TEST_F(ScriptCanvasTestFixture, Error)
{
using namespace ScriptCanvas;
RegisterComponentDescriptor<UnitTestErrorNode>();
RegisterComponentDescriptor<InfiniteLoopNode>();
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZStd::string description = "Unit test error!";
AZ::EntityId stringNodeID;
CreateDataNode(graphUniqueId, description, stringNodeID);
AZStd::string sideFX1 = "Side FX 1";
AZ::EntityId sideFX1NodeID;
CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID);
AZ::EntityId errorNodeID;
CreateTestNode<UnitTestErrorNode>(graphUniqueId, errorNodeID);
AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0"));
EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In"));
EXPECT_TRUE(Connect(*graph, errorNodeID, "Out", sideEffectID, "In"));
// test to make sure the graph received an error
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graph->GetEntity()->Activate();
}
const bool expectErrors = true;
const bool expectIrrecoverableErrors = true;
ReportErrors(graph, expectErrors, expectIrrecoverableErrors);
EXPECT_EQ(description, graph->GetLastErrorDescription());
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 0);
graph->GetEntity()->Deactivate();
delete graph->GetEntity();
}
TEST_F(ScriptCanvasTestFixture, ErrorHandled)
{
using namespace ScriptCanvas;
RegisterComponentDescriptor<UnitTestErrorNode>();
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZStd::string description = "Unit test error!";
AZ::EntityId stringNodeID;
CreateDataNode(graphUniqueId, description, stringNodeID);
AZStd::string sideFX1 = "Side FX 1";
AZ::EntityId sideFX1NodeID;
CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID);
AZStd::string sideFX2 = "Side FX 2";
AZ::EntityId sideFX2NodeID;
CreateDataNode(graphUniqueId, sideFX2, sideFX2NodeID);
AZ::EntityId errorNodeID;
CreateTestNode<UnitTestErrorNode>(graphUniqueId, errorNodeID);
AZ::EntityId sideEffectID1 = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
AZ::EntityId sideEffectID2 = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
AZ::EntityId errorHandlerID;
CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID);
EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID1, "String: 0"));
EXPECT_TRUE(Connect(*graph, sideFX2NodeID, "Get", sideEffectID2, "String: 0"));
EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In"));
EXPECT_TRUE(Connect(*graph, errorNodeID, "Out", sideEffectID1, "In"));
EXPECT_TRUE(Connect(*graph, errorHandlerID, "Source", errorNodeID, "This"));
EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectID2, "In"));
{
ScriptCanvasEditor::ScopedOutputSuppression supressOutput; // temporarily suppress the output, since we don't fully support error handling correction, yet
graph->GetEntity()->Activate();
}
ReportErrors(graph);
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 0);
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX2), 1);
delete graph->GetEntity();
}
TEST_F(ScriptCanvasTestFixture, ErrorNode)
{
using namespace ScriptCanvas;
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
// Start
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZStd::string description = "Test Error Report";
AZ::EntityId stringNodeID;
CreateDataNode(graphUniqueId, description, stringNodeID);
AZStd::string sideFX1 = "Side FX 1";
AZ::EntityId sideFX1NodeID;
CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID);
AZ::EntityId errorNodeID;
CreateTestNode<Nodes::Core::Error>(graphUniqueId, errorNodeID);
AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
EXPECT_TRUE(Connect(*graph, startID, "Out", sideEffectID, "In"));
EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0"));
EXPECT_TRUE(Connect(*graph, sideEffectID, "Out", errorNodeID, "In"));
EXPECT_TRUE(Connect(*graph, stringNodeID, "Get", errorNodeID, "Description"));
// test to make sure the graph received an error
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graph->GetEntity()->Activate();
}
const bool expectErrors = true;
const bool expectIrrecoverableErrors = true;
ReportErrors(graph, expectErrors, expectIrrecoverableErrors);
EXPECT_EQ(description, graph->GetLastErrorDescription());
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1);
graph->GetEntity()->Deactivate();
// test to make sure the graph did to retry execution
graph->GetEntity()->Activate();
ReportErrors(graph, expectErrors, expectIrrecoverableErrors);
// if the graph was allowed to execute, the side effect counter should be higher
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1);
delete graph->GetEntity();
}
TEST_F(ScriptCanvasTestFixture, ErrorNodeHandled)
{
using namespace ScriptCanvas;
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
AZStd::string description = "Test Error Report";
AZ::EntityId stringNodeID;
CreateDataNode(graphUniqueId, description, stringNodeID);
AZStd::string sideFX1 = "Side FX 1";
AZ::EntityId sideFX1NodeID;
CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID);
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId errorNodeID;
CreateTestNode<Nodes::Core::Error>(graphUniqueId, errorNodeID);
AZ::EntityId errorHandlerID;
CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID);
AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In"));
EXPECT_TRUE(Connect(*graph, errorHandlerID, "Source", errorNodeID, "This"));
EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectID, "In"));
EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0"));
{
ScriptCanvasEditor::ScopedOutputSuppression supressOutput; // temporarily suppress the output, since we don't fully support error handling correction, yet
graph->GetEntity()->Activate();
}
ReportErrors(graph);
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1);
graph->GetEntity()->Deactivate();
graph->GetEntity()->Activate();
ReportErrors(graph);
EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 2);
delete graph->GetEntity();
}
TEST_F(ScriptCanvasTestFixture, InfiniteLoopDetected)
{
using namespace ScriptCanvas;
RegisterComponentDescriptor<InfiniteLoopNode>();
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
UnitTestEventsHandler unitTestHandler;
unitTestHandler.BusConnect();
AZStd::string sideFXpass = "Side FX Infinite Loop Error Handled";
AZ::EntityId sideFXpassNodeID;
CreateDataNode(graphUniqueId, sideFXpass, sideFXpassNodeID);
AZStd::string sideFXfail = "Side FX Infinite Loop Node Failed";
AZ::EntityId sideFXfailNodeID;
CreateDataNode(graphUniqueId, sideFXfail, sideFXfailNodeID);
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId infiniteLoopNodeID;
CreateTestNode<InfiniteLoopNode>(graphUniqueId, infiniteLoopNodeID);
AZ::EntityId errorHandlerID;
CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID);
AZ::EntityId sideEffectPassID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
AZ::EntityId sideEffectFailID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect");
EXPECT_TRUE(Connect(*graph, sideFXpassNodeID, "Get", sideEffectPassID, "String: 0"));
EXPECT_TRUE(Connect(*graph, sideFXfailNodeID, "Get", sideEffectFailID, "String: 0"));
EXPECT_TRUE(Connect(*graph, startID, "Out", infiniteLoopNodeID, "In"));
EXPECT_TRUE(Connect(*graph, infiniteLoopNodeID, "In", infiniteLoopNodeID, "Before Infinity"));
EXPECT_TRUE(Connect(*graph, infiniteLoopNodeID, "After Infinity", sideEffectFailID, "In"));
EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectPassID, "In"));
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graph->GetEntity()->Activate();
}
const bool expectError = true;
const bool expectIrrecoverableError = true;
ReportErrors(graph, expectError, expectIrrecoverableError);
EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXpass));
EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXfail));
graph->GetEntity()->Deactivate();
graph->GetEntity()->Activate();
ReportErrors(graph, expectError, expectIrrecoverableError);
EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXpass));
EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXfail));
delete graph->GetEntity();
}
#endif // SCRIPTCANAS_ERRORS_ENABLED
TEST_F(ScriptCanvasTestFixture, BinaryOperationTest)
{
using namespace ScriptCanvas::Nodes;
using namespace ScriptCanvas::Nodes::Comparison;
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
BinaryOpTest<EqualTo>(1, 1, true);
BinaryOpTest<EqualTo>(1, 0, false);
BinaryOpTest<EqualTo>(0, 1, false);
BinaryOpTest<EqualTo>(0, 0, true);
BinaryOpTest<NotEqualTo>(1, 1, false);
BinaryOpTest<NotEqualTo>(1, 0, true);
BinaryOpTest<NotEqualTo>(0, 1, true);
BinaryOpTest<NotEqualTo>(0, 0, false);
BinaryOpTest<Greater>(1, 1, false);
BinaryOpTest<Greater>(1, 0, true);
BinaryOpTest<Greater>(0, 1, false);
BinaryOpTest<Greater>(0, 0, false);
BinaryOpTest<GreaterEqual>(1, 1, true);
BinaryOpTest<GreaterEqual>(1, 0, true);
BinaryOpTest<GreaterEqual>(0, 1, false);
BinaryOpTest<GreaterEqual>(0, 0, true);
BinaryOpTest<Less>(1, 1, false);
BinaryOpTest<Less>(1, 0, false);
BinaryOpTest<Less>(0, 1, true);
BinaryOpTest<Less>(0, 0, false);
BinaryOpTest<LessEqual>(1, 1, true);
BinaryOpTest<LessEqual>(1, 0, false);
BinaryOpTest<LessEqual>(0, 1, true);
BinaryOpTest<LessEqual>(0, 0, true);
BinaryOpTest<EqualTo>(true, true, true);
BinaryOpTest<EqualTo>(true, false, false);
BinaryOpTest<EqualTo>(false, true, false);
BinaryOpTest<EqualTo>(false, false, true);
BinaryOpTest<NotEqualTo>(true, true, false);
BinaryOpTest<NotEqualTo>(true, false, true);
BinaryOpTest<NotEqualTo>(false, true, true);
BinaryOpTest<NotEqualTo>(false, false, false);
AZStd::string string0("a string");
AZStd::string string1("b string");
BinaryOpTest<EqualTo>(string1, string1, true);
BinaryOpTest<EqualTo>(string1, string0, false);
BinaryOpTest<EqualTo>(string0, string1, false);
BinaryOpTest<EqualTo>(string0, string0, true);
BinaryOpTest<NotEqualTo>(string1, string1, false);
BinaryOpTest<NotEqualTo>(string1, string0, true);
BinaryOpTest<NotEqualTo>(string0, string1, true);
BinaryOpTest<NotEqualTo>(string0, string0, false);
BinaryOpTest<Greater>(string1, string1, false);
BinaryOpTest<Greater>(string1, string0, true);
BinaryOpTest<Greater>(string0, string1, false);
BinaryOpTest<Greater>(string0, string0, false);
BinaryOpTest<GreaterEqual>(string1, string1, true);
BinaryOpTest<GreaterEqual>(string1, string0, true);
BinaryOpTest<GreaterEqual>(string0, string1, false);
BinaryOpTest<GreaterEqual>(string0, string0, true);
BinaryOpTest<Less>(string1, string1, false);
BinaryOpTest<Less>(string1, string0, false);
BinaryOpTest<Less>(string0, string1, true);
BinaryOpTest<Less>(string0, string0, false);
BinaryOpTest<LessEqual>(string1, string1, true);
BinaryOpTest<LessEqual>(string1, string0, false);
BinaryOpTest<LessEqual>(string0, string1, true);
BinaryOpTest<LessEqual>(string0, string0, true);
const AZ::Vector3 vectorOne(1.0f, 1.0f, 1.0f);
const AZ::Vector3 vectorZero(0.0f, 0.0f, 0.0f);
BinaryOpTest<EqualTo>(vectorOne, vectorOne, true);
BinaryOpTest<EqualTo>(vectorOne, vectorZero, false);
BinaryOpTest<EqualTo>(vectorZero, vectorOne, false);
BinaryOpTest<EqualTo>(vectorZero, vectorZero, true);
BinaryOpTest<NotEqualTo>(vectorOne, vectorOne, false);
BinaryOpTest<NotEqualTo>(vectorOne, vectorZero, true);
BinaryOpTest<NotEqualTo>(vectorZero, vectorOne, true);
BinaryOpTest<NotEqualTo>(vectorZero, vectorZero, false);
const TestBehaviorContextObject zero(0);
const TestBehaviorContextObject one(1);
const TestBehaviorContextObject otherOne(1);
BinaryOpTest<EqualTo>(one, one, true);
BinaryOpTest<EqualTo>(one, zero, false);
BinaryOpTest<EqualTo>(zero, one, false);
BinaryOpTest<EqualTo>(zero, zero, true);
BinaryOpTest<NotEqualTo>(one, one, false);
BinaryOpTest<NotEqualTo>(one, zero, true);
BinaryOpTest<NotEqualTo>(zero, one, true);
BinaryOpTest<NotEqualTo>(zero, zero, false);
BinaryOpTest<Greater>(one, one, false);
BinaryOpTest<Greater>(one, zero, true);
BinaryOpTest<Greater>(zero, one, false);
BinaryOpTest<Greater>(zero, zero, false);
BinaryOpTest<GreaterEqual>(one, one, true);
BinaryOpTest<GreaterEqual>(one, zero, true);
BinaryOpTest<GreaterEqual>(zero, one, false);
BinaryOpTest<GreaterEqual>(zero, zero, true);
BinaryOpTest<Less>(one, one, false);
BinaryOpTest<Less>(one, zero, false);
BinaryOpTest<Less>(zero, one, true);
BinaryOpTest<Less>(zero, zero, false);
BinaryOpTest<LessEqual>(one, one, true);
BinaryOpTest<LessEqual>(one, zero, false);
BinaryOpTest<LessEqual>(zero, one, true);
BinaryOpTest<LessEqual>(zero, zero, true);
BinaryOpTest<EqualTo>(one, otherOne, true);
BinaryOpTest<EqualTo>(otherOne, one, true);
BinaryOpTest<NotEqualTo>(one, otherOne, false);
BinaryOpTest<NotEqualTo>(otherOne, one, false);
BinaryOpTest<Greater>(one, otherOne, false);
BinaryOpTest<Greater>(otherOne, one, false);
BinaryOpTest<GreaterEqual>(one, otherOne, true);
BinaryOpTest<GreaterEqual>(otherOne, one, true);
BinaryOpTest<Less>(one, otherOne, false);
BinaryOpTest<Less>(otherOne, one, false);
BinaryOpTest<LessEqual>(one, otherOne, true);
BinaryOpTest<LessEqual>(otherOne, one, true);
// force failures, to verify crash proofiness
BinaryOpTest<EqualTo>(one, zero, false, true);
BinaryOpTest<NotEqualTo>(one, zero, true, true);
BinaryOpTest<Greater>(one, zero, true, true);
BinaryOpTest<GreaterEqual>(one, zero, true, true);
BinaryOpTest<Less>(one, zero, false, true);
BinaryOpTest<LessEqual>(one, zero, false, true);
m_serializeContext->EnableRemoveReflection();
m_behaviorContext->EnableRemoveReflection();
TestBehaviorContextObject::Reflect(m_serializeContext);
TestBehaviorContextObject::Reflect(m_behaviorContext);
m_serializeContext->DisableRemoveReflection();
m_behaviorContext->DisableRemoveReflection();
}
TEST_F(ScriptCanvasTestFixture, EntityRefTest)
{
using namespace ScriptCanvas;
using namespace ScriptCanvas::Nodes;
// Fake "world" entities
AZ::Entity first("First");
first.CreateComponent<ScriptCanvasTests::TestComponent>();
first.Init();
first.Activate();
AZ::Entity second("Second");
second.CreateComponent<ScriptCanvasTests::TestComponent>();
second.Init();
second.Activate();
// Script Canvas Graph
Graph* graph = nullptr;
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
m_entityContext.AddEntity(first.GetId());
m_entityContext.AddEntity(second.GetId());
m_entityContext.AddEntity(graph->GetEntityId());
graph->GetEntity()->SetName("Graph Owner Entity");
graph->GetEntity()->CreateComponent<ScriptCanvasTests::TestComponent>();
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityId = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
// EntityRef node to some specific entity #1
AZ::EntityId selfEntityIdNode;
auto selfEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, selfEntityIdNode);
selfEntityRef->SetEntityRef(first.GetId());
// EntityRef node to some specific entity #2
AZ::EntityId otherEntityIdNode;
auto otherEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, otherEntityIdNode);
otherEntityRef->SetEntityRef(second.GetId());
// Explicitly set an EntityRef node with this graph's entity Id.
AZ::EntityId graphEntityIdNode;
auto graphEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, graphEntityIdNode);
graphEntityRef->SetEntityRef(graph->GetEntity()->GetId());
// First test: directly set an entity Id on the EntityID: 0 slot
AZ::EntityId eventAid;
Nodes::Core::Method* nodeA = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventAid);
nodeA->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent");
if (auto entityId = nodeA->ModInput_UNIT_TEST<AZ::EntityId>("EntityID: 0"))
{
*entityId = first.GetId();
}
// Second test: Will connect the slot to an EntityRef node
AZ::EntityId eventBid;
Nodes::Core::Method* nodeB = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventBid);
nodeB->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent");
// Third test: Set the slot's EntityId: 0 to GraphOwnerId, this should result in the same Id as graph->GetEntityId()
AZ::EntityId eventCid;
Nodes::Core::Method* nodeC = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventCid);
nodeC->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent");
if (auto entityId = nodeC->ModInput_UNIT_TEST<AZ::EntityId>("EntityID: 0"))
{
*entityId = ScriptCanvas::GraphOwnerId;
}
// True
AZ::EntityId trueNodeId;
CreateDataNode<Data::BooleanType>(graphUniqueId, true, trueNodeId);
// False
AZ::EntityId falseNodeId;
CreateDataNode<Data::BooleanType>(graphUniqueId, false, falseNodeId);
// Start -> TestEvent
// O EntityId: 0 (not connected, it was set directly on the slot)
// EntityRef: first -O EntityId: 1
// False -O Boolean: 2
EXPECT_TRUE(Connect(*graph, startID, "Out", eventAid, "In"));
EXPECT_TRUE(Connect(*graph, eventAid, "EntityID: 1", selfEntityIdNode, "Get"));
EXPECT_TRUE(Connect(*graph, eventAid, "Boolean: 2", falseNodeId, "Get"));
// Start -> TestEvent
// EntityRef: second -O EntityId: 0
// EntityRef: second -O EntityId: 1
// False -O Boolean: 2
EXPECT_TRUE(Connect(*graph, startID, "Out", eventBid, "In"));
EXPECT_TRUE(Connect(*graph, eventBid, "EntityID: 0", otherEntityIdNode, "Get"));
EXPECT_TRUE(Connect(*graph, eventBid, "EntityID: 1", otherEntityIdNode, "Get"));
EXPECT_TRUE(Connect(*graph, eventBid, "Boolean: 2", falseNodeId, "Get"));
// Start -> TestEvent
// -O EntityId: 0 (not connected, slot is set to GraphOwnerId)
// graphEntityIdNode -O EntityId: 1
// True -O Boolean: 2
EXPECT_TRUE(Connect(*graph, startID, "Out", eventCid, "In"));
EXPECT_TRUE(Connect(*graph, eventCid, "EntityID: 1", graphEntityIdNode, "Get"));
EXPECT_TRUE(Connect(*graph, eventCid, "Boolean: 2", trueNodeId, "Get"));
// Execute the graph
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graph->GetEntity()->Activate();
}
ReportErrors(graph);
delete graph->GetEntity();
}
const int k_executionCount = 998;
TEST_F(ScriptCanvasTestFixture, ExecutionLength)
{
using namespace ScriptCanvas;
Graph* graph(nullptr);
SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph);
EXPECT_TRUE(graph != nullptr);
graph->GetEntity()->Init();
const AZ::EntityId& graphEntityID = graph->GetEntityId();
const AZ::EntityId& graphUniqueId = graph->GetUniqueId();
AZ::EntityId startID;
CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID);
AZ::EntityId previousID = startID;
for (int i = 0; i < k_executionCount; ++i)
{
AZ::EntityId printNodeID;
TestResult* printNode = CreateTestNode<TestResult>(graphUniqueId, printNodeID);
printNode->SetInput_UNIT_TEST<int>("Value", i);
EXPECT_TRUE(Connect(*graph, previousID, "Out", printNodeID, "In"));
previousID = printNodeID;
}
AZ::Entity* graphEntity = graph->GetEntity();
{
ScriptCanvasEditor::ScopedOutputSuppression suppressOutput;
graphEntity->Activate();
}
ReportErrors(graph);
graphEntity->Deactivate();
delete graphEntity;
}
TEST_F(ScriptCanvasTestFixture, AnyNode)
{
RunUnitTestGraph("LY_SC_UnitTest_Any");
}
| 40.166402 | 251 | 0.705636 | jeikabu |
7818f610f9d012020338ac08ac054864afd454c0 | 565 | cpp | C++ | codeforces/contests/round/646-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/contests/round/646-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/contests/round/646-div2/c.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n, x;
cin >> n >> x;
int cnt = 0;
for(int i=1; i<n; ++i){
int a, b;
cin >> a >> b;
if(a == x or b == x)
cnt++;
}
if(cnt <= 1)
cout << "Ayush" << endl;
else{
int till = n-2;
if(till%2)
cout << "Ashish" << endl;
else
cout << "Ayush" << endl;
}
}
return 0;
}
| 19.482759 | 41 | 0.316814 | tysm |
781969a6b52dc866a1f04fd36357081fcd7d0d5b | 7,030 | cpp | C++ | cpp/open3d/visualization/gui/Button.cpp | Dudulle/Open3D | ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab | [
"MIT"
] | 1 | 2021-05-10T04:23:24.000Z | 2021-05-10T04:23:24.000Z | cpp/open3d/visualization/gui/Button.cpp | Dudulle/Open3D | ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab | [
"MIT"
] | null | null | null | cpp/open3d/visualization/gui/Button.cpp | Dudulle/Open3D | ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab | [
"MIT"
] | 1 | 2021-11-05T01:16:13.000Z | 2021-11-05T01:16:13.000Z | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2021 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "open3d/visualization/gui/Button.h"
#include <imgui.h>
#include <cmath>
#include <string>
#include "open3d/visualization/gui/Theme.h"
#include "open3d/visualization/gui/Util.h"
namespace open3d {
namespace visualization {
namespace gui {
namespace {
static int g_next_button_id = 1;
} // namespace
struct Button::Impl {
std::string id_;
std::string title_;
std::shared_ptr<UIImage> image_;
float padding_horizontal_em_ = 0.5f;
float padding_vertical_em_ = 0.5f;
bool is_toggleable_ = false;
bool is_on_ = false;
std::function<void()> on_clicked_;
};
Button::Button(const char* title) : impl_(new Button::Impl()) {
impl_->id_ = std::string("##button") + std::to_string(g_next_button_id++);
impl_->title_ = title;
}
Button::Button(std::shared_ptr<UIImage> image) : impl_(new Button::Impl()) {
impl_->image_ = image;
}
Button::~Button() {}
const char* Button::GetText() const { return impl_->title_.c_str(); }
void Button::SetText(const char* text) { impl_->title_ = text; }
float Button::GetHorizontalPaddingEm() const {
return impl_->padding_horizontal_em_;
}
float Button::GetVerticalPaddingEm() const {
return impl_->padding_vertical_em_;
}
void Button::SetPaddingEm(float horiz_ems, float vert_ems) {
impl_->padding_horizontal_em_ = horiz_ems;
impl_->padding_vertical_em_ = vert_ems;
}
bool Button::GetIsToggleable() const { return impl_->is_toggleable_; }
void Button::SetToggleable(bool toggles) { impl_->is_toggleable_ = toggles; }
bool Button::GetIsOn() const { return impl_->is_on_; }
void Button::SetOn(bool is_on) {
if (impl_->is_toggleable_) {
impl_->is_on_ = is_on;
}
}
void Button::SetOnClicked(std::function<void()> on_clicked) {
impl_->on_clicked_ = on_clicked;
}
Size Button::CalcPreferredSize(const LayoutContext& context,
const Constraints& constraints) const {
auto em = float(context.theme.font_size);
auto padding_horiz = int(std::ceil(impl_->padding_horizontal_em_ * em));
auto padding_vert = int(std::ceil(impl_->padding_vertical_em_ * em));
if (impl_->image_) {
auto size = impl_->image_->CalcPreferredSize(context, constraints);
return Size(size.width + 2 * padding_horiz,
size.height + 2 * padding_vert);
} else {
auto font = ImGui::GetFont();
auto imguiVertPadding = ImGui::GetTextLineHeightWithSpacing() -
ImGui::GetTextLineHeight();
auto size = font->CalcTextSizeA(float(context.theme.font_size),
float(constraints.width), 10000,
impl_->title_.c_str());
// When ImGUI draws text, it draws text in a box of height
// font_size + spacing. The padding on the bottom is essentially the
// descender height, and the box height ends up giving a visual padding
// of descender_height on the top and bottom. So while we only need to
// 1 * imguiVertPadding on the bottom, we need to add 2x on the sides.
// Note that padding of 0 doesn't actually produce a padding of zero,
// because that would look horrible. (And also because if we do that,
// ImGUI will position the text so that the descender is cut off,
// because it is assuming that it gets a little extra on the bottom.
// This looks really bad...)
return Size(
int(std::ceil(size.x + 2.0f + imguiVertPadding)) +
2 * padding_horiz,
int(std::ceil(ImGui::GetTextLineHeight() + imguiVertPadding)) +
2 * padding_vert);
}
}
Widget::DrawResult Button::Draw(const DrawContext& context) {
auto& frame = GetFrame();
auto result = Widget::DrawResult::NONE;
ImGui::SetCursorScreenPos(ImVec2(float(frame.x), float(frame.y)));
bool was_on = impl_->is_on_;
if (was_on) {
ImGui::PushStyleColor(ImGuiCol_Text,
colorToImgui(context.theme.button_on_text_color));
ImGui::PushStyleColor(ImGuiCol_Button,
colorToImgui(context.theme.button_on_color));
ImGui::PushStyleColor(
ImGuiCol_ButtonHovered,
colorToImgui(context.theme.button_on_hover_color));
ImGui::PushStyleColor(
ImGuiCol_ButtonActive,
colorToImgui(context.theme.button_on_active_color));
}
DrawImGuiPushEnabledState();
bool pressed = false;
if (impl_->image_) {
auto params = impl_->image_->CalcDrawParams(context.renderer, frame);
ImTextureID image_id =
reinterpret_cast<ImTextureID>(params.texture.GetId());
pressed = ImGui::ImageButton(
image_id, ImVec2(params.width, params.height),
ImVec2(params.u0, params.v0), ImVec2(params.u1, params.v1));
} else {
pressed = ImGui::Button(
(impl_->title_ + impl_->id_).c_str(),
ImVec2(float(GetFrame().width), float(GetFrame().height)));
}
if (pressed) {
if (impl_->is_toggleable_) {
impl_->is_on_ = !impl_->is_on_;
}
if (impl_->on_clicked_) {
impl_->on_clicked_();
}
result = Widget::DrawResult::REDRAW;
}
DrawImGuiPopEnabledState();
DrawImGuiTooltip();
if (was_on) {
ImGui::PopStyleColor(4);
}
return result;
}
} // namespace gui
} // namespace visualization
} // namespace open3d
| 37.393617 | 80 | 0.624609 | Dudulle |
781b076387a86f0610600e89ede7e4e78c99712f | 370 | cpp | C++ | Symboltable/src/SymtabEntry.cpp | SystemOfAProg/SysProgTotallyNotTheSolution | 0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9 | [
"MIT"
] | null | null | null | Symboltable/src/SymtabEntry.cpp | SystemOfAProg/SysProgTotallyNotTheSolution | 0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9 | [
"MIT"
] | null | null | null | Symboltable/src/SymtabEntry.cpp | SystemOfAProg/SysProgTotallyNotTheSolution | 0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9 | [
"MIT"
] | null | null | null | #include "../includes/SymtabEntry.h"
#include <cstring>
SymtabEntry::SymtabEntry(Information* info) {
this->info = info;
this->next = NULL;
}
SymtabEntry::~SymtabEntry() {
}
SymtabEntry* SymtabEntry::getNext() {
return this->next;
}
void SymtabEntry::setNext(SymtabEntry* next) {
this->next = next;
}
Information* SymtabEntry::getInfo() {
return this->info;
}
| 16.086957 | 46 | 0.7 | SystemOfAProg |
781e455ed73908ed72b4682a72adeb0c9ad4993a | 4,625 | hpp | C++ | OptimExplorer/core/utils.hpp | MarkTuddenham/OptimExplorer | 1fb724bb80b099ade76d9f8d6179cb561dedb9bd | [
"MIT"
] | 1 | 2020-08-18T20:55:26.000Z | 2020-08-18T20:55:26.000Z | OptimExplorer/core/utils.hpp | MarkTuddenham/OptimExplorer | 1fb724bb80b099ade76d9f8d6179cb561dedb9bd | [
"MIT"
] | 4 | 2020-10-11T12:57:29.000Z | 2020-10-11T14:06:17.000Z | OptimExplorer/core/utils.hpp | MarkTuddenham/OptimExplorer | 1fb724bb80b099ade76d9f8d6179cb561dedb9bd | [
"MIT"
] | null | null | null | #if defined(_MSC_VER) && !defined(NDEBUG)
#define DISABLE_WARNING_PUSH __pragma(warning(push))
#define DISABLE_WARNING_PUSH_ALL __pragma(warning(push, 0))
#define DISABLE_WARNING_POP __pragma(warning(pop))
#define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber))
#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(4100)
#define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505)
#define DISABLE_WARNING_PRAGMAS
#define DISABLE_WARNING_SIGN_CONVERSION
#define DISABLE_WARNING_OLD_STYLE_CAST
#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION
#define DISABLE_WARNING_SHORTEN_64_TO_32
#define DISABLE_WARNING_MISSING_PROTOTYPES
#define DISABLE_WARNING_SHADOW
#define DISABLE_WARNING_ENUM_ENUM_CONVERSION
#define DISABLE_WARNING_USELESS_CAST
#define DISABLE_WARNING_PEDANTIC
#define DISABLE_WARNING_IGNORED_QUALIFIERS
#define DISABLE_WARNING_REORDER
#define DISABLE_WARNING_NON_VIRTUAL_DTOR
#elif (defined(__GNUC__) || defined(__clang__)) && !defined(NDEBUG)
#define DO_PRAGMA(X) _Pragma(#X)
#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push)
#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop)
#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName)
#define DISABLE_WARNING_PRAGMAS DISABLE_WARNING(-Wpragmas)
#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(-Wunused-parameter)
#define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function)
#define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING(-Wsign-conversion)
#define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING(-Wold-style-cast)
#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING(-Wimplicit-int-conversion)
#define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING(-Wshorten-64-to-32)
#define DISABLE_WARNING_MISSING_PROTOTYPES DISABLE_WARNING(-Wmissing-prototypes)
#define DISABLE_WARNING_SHADOW DISABLE_WARNING(-Wshadow)
#define DISABLE_WARNING_ENUM_ENUM_CONVERSION DISABLE_WARNING(-Wenum-enum-conversion)
#define DISABLE_WARNING_USELESS_CAST DISABLE_WARNING(-Wuseless-cast)
#define DISABLE_WARNING_PEDANTIC DISABLE_WARNING(-Wpedantic)
#define DISABLE_WARNING_IGNORED_QUALIFIERS DISABLE_WARNING(-Wignored-qualifiers)
#define DISABLE_WARNING_REORDER DISABLE_WARNING(-Wreorder)
#define DISABLE_WARNING_NON_VIRTUAL_DTOR DISABLE_WARNING(-Wnon-virtual-dtor)
#define DISABLE_WARNING_PUSH_ALL \
DISABLE_WARNING_PRAGMAS \
DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER \
DISABLE_WARNING_UNREFERENCED_FUNCTION \
DISABLE_WARNING_SIGN_CONVERSION \
DISABLE_WARNING_OLD_STYLE_CAST \
DISABLE_WARNING_IMPLICIT_INT_CONVERSION \
DISABLE_WARNING_SHORTEN_64_TO_32 \
DISABLE_WARNING_MISSING_PROTOTYPES \
DISABLE_WARNING_SHADOW \
DISABLE_WARNING_ENUM_ENUM_CONVERSION \
DISABLE_WARNING_USELESS_CAST \
DISABLE_WARNING_PEDANTIC \
DISABLE_WARNING_IGNORED_QUALIFIERS \
DISABLE_WARNING_REORDER \
DISABLE_WARNING_NON_VIRTUAL_DTOR
#else
#define DISABLE_WARNING_PUSH_ALL
#define DISABLE_WARNING_PUSH
#define DISABLE_WARNING_POP
#define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER
#define DISABLE_WARNING_UNREFERENCED_FUNCTION
#define DISABLE_WARNING_PRAGMAS
#define DISABLE_WARNING_SIGN_CONVERSION
#define DISABLE_WARNING_OLD_STYLE_CAST
#define DISABLE_WARNING_IMPLICIT_INT_CONVERSION
#define DISABLE_WARNING_SHORTEN_64_TO_32
#define DISABLE_WARNING_MISSING_PROTOTYPES
#define DISABLE_WARNING_SHADOW
#define DISABLE_WARNING_ENUM_ENUM_CONVERSION
#define DISABLE_WARNING_USELESS_CAST
#define DISABLE_WARNING_PEDANTIC
#define DISABLE_WARNING_IGNORED_QUALIFIERS
#define DISABLE_WARNING_REORDER
#define DISABLE_WARNING_NON_VIRTUAL_DTOR
#endif | 56.402439 | 92 | 0.697297 | MarkTuddenham |
781eb578aa62046cf3cd83874e434580b0264997 | 934 | hh | C++ | src/utils/matrix/MatrixOperations.hh | LeoRya/py-orbit | 340b14b6fd041ed8ec2cc25b0821b85742aabe0c | [
"MIT"
] | 17 | 2018-02-09T23:39:06.000Z | 2022-03-04T16:27:04.000Z | src/utils/matrix/MatrixOperations.hh | LeoRya/py-orbit | 340b14b6fd041ed8ec2cc25b0821b85742aabe0c | [
"MIT"
] | 22 | 2017-05-31T19:40:14.000Z | 2021-09-24T22:07:47.000Z | src/utils/matrix/MatrixOperations.hh | LeoRya/py-orbit | 340b14b6fd041ed8ec2cc25b0821b85742aabe0c | [
"MIT"
] | 37 | 2016-12-08T19:39:35.000Z | 2022-02-11T19:59:34.000Z | #ifndef __MATRIX_OPERATIONS_H_
#define __MATRIX_OPERATIONS_H_
#include "Matrix.hh"
#include "PhaseVector.hh"
#include "Bunch.hh"
namespace OrbitUtils{
/**
The collection of the static methods for matrices.
*/
class MatrixOperations{
public:
/** Inverts the 2D array as a matrix. */
static int invert(double **a, int n);
/** Inversts the matrix in place. */
static int invert(Matrix* matrix);
/** Multiplies a vector with the transposed matrix. */
static int mult(PhaseVector* v, Matrix* mtrx, PhaseVector* v_res);
/** Multiplies a vector with the matrix. */
static int mult(Matrix* mtrx, PhaseVector* v, PhaseVector* v_res);
/** Calculates determinant of the matrix. */
static int det(Matrix* mtrx_in, double& det);
/**
Tracks the bunch through the transport matrix.
The matrix should be 6x6 or 7x7.
*/
static void track(Bunch* bunch,Matrix* mtrx);
};
};
#endif
| 22.780488 | 68 | 0.683084 | LeoRya |
781f5650f19507eb6ec43720d07c306bb91080af | 11,669 | cpp | C++ | src/mame/audio/nl_kidniki.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/audio/nl_kidniki.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/audio/nl_kidniki.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Andrew Gardner, Couriersud
#include "netlist/devices/net_lib.h"
#ifdef NLBASE_H_
#error Somehow nl_base.h made it into the include chain.
#endif
#define USE_FRONTIERS 1
/* if we use frontiers, use fixed STV for smaller matrix sizes */
#if (USE_FRONTIERS)
#define USE_FIXED_STV 1
#else
#define USE_FIXED_STV 0
#endif
/*
* Schematic errors:
*
* The kungfu master schematics differ from the kidnik schematics in wiring
* D4, D5 and Q4 with other components. The manual corrections to the
* kungfu master schematics make sense and thus are used here.
*
* opamp XU1.B according to schematics has no feedback loop between output and
* inputs. The arrangement of components in the schematic however indicate that
* this is not the case and indeed a connection exists. This results in sounds
* at output XU1.14 to contain more detail.
*
* You can observe sounds at XU1.14 by doing
*
* NL_LOGS=XU1.14 ./mame kidniki
* nlwav -o x.wav log_XU1.14.log
* play x.wav
*
* VERIFICATION NEEDED: Are D4 and D5 Cathodes connected?
*
* This has quite some impact on the drums.
*
*/
#define FIX_SCHEMATIC_ERRORS (1)
#define D4_AND_D5_CONNECTED (1)
/* On M62 boards with pcb pictures available
* D6 is missing, although the pcb print exists.
* We are replacing this with a 10m Resistor.
*/
#define D6_EXISTS (0)
/*
* J4 connects channel C either to sound_ic or sound.
*
* 1: Connect C to channel to sound_ic
*
*/
#define J4 (1)
/* ----------------------------------------------------------------------------
* Library section header START
* ---------------------------------------------------------------------------*/
#ifndef __PLIB_PREPROCESSOR__
#endif
/* ----------------------------------------------------------------------------
* Library section header END
* ---------------------------------------------------------------------------*/
/* ----------------------------------------------------------------------------
* Kidniki schematics
* ---------------------------------------------------------------------------*/
static NETLIST_START(kidniki_schematics)
// EESCHEMA NETLIST VERSION 1.1 (SPICE FORMAT) CREATION DATE: SAT 06 JUN 2015 01:06:26 PM CEST
// TO EXCLUDE A COMPONENT FROM THE SPICE NETLIST ADD [SPICE_NETLIST_ENABLED] USER FIELD SET TO: N
// TO REORDER THE COMPONENT SPICE NODE SEQUENCE ADD [SPICE_NODE_SEQUENCE] USER FIELD AND DEFINE SEQUENCE: 2,1,0
// SHEET NAME:/
// IGNORED O_AUDIO0: O_AUDIO0 49 0
// .END
#if FIX_SCHEMATIC_ERRORS
NET_C(XU1.7, C40.1)
#endif
CAP(C200, CAP_N(100))
CAP(C28, CAP_U(1))
CAP(C31, CAP_N(470))
CAP(C32, CAP_N(3.3))
CAP(C33, CAP_U(1))
CAP(C34, CAP_N(1))
CAP(C35, CAP_N(1))
CAP(C36, CAP_N(6.8))
CAP(C37, CAP_N(22))
CAP(C38, CAP_N(1))
CAP(C39, CAP_N(1))
CAP(C40, CAP_P(12))
CAP(C41, CAP_U(1))
CAP(C42, CAP_N(1.2))
CAP(C43, CAP_N(1.2))
CAP(C44, CAP_U(1))
CAP(C45, CAP_N(22))
CAP(C47, CAP_U(1))
CAP(C48, CAP_N(470))
CAP(C49, CAP_N(3.3))
CAP(C50, CAP_N(22))
CAP(C51, CAP_N(22))
CAP(C52, CAP_N(27))
CAP(C53, CAP_N(27))
CAP(C56, CAP_N(6.8))
CAP(C57, CAP_N(6.8))
CAP(C59, CAP_N(6.8))
CAP(C60, CAP_N(22))
CAP(C61, CAP_N(22))
CAP(C62, CAP_N(6.8))
CAP(C63, CAP_N(1))
CAP(C64, CAP_N(68))
CAP(C65, CAP_N(68))
CAP(C66, CAP_N(68))
CAP(C67, CAP_N(15))
CAP(C68, CAP_N(15))
CAP(C69, CAP_N(10))
CAP(C70, CAP_N(22))
CAP(C72, CAP_N(12))
CAP(C73, CAP_N(10))
CAP(C76, CAP_N(68))
CAP(C77, CAP_N(12))
DIODE(D3, "1S1588")
DIODE(D4, "1S1588")
DIODE(D5, "1S1588")
POT(RV1, RES_K(50))
QBJT_EB(Q10, "2SC945")
QBJT_EB(Q3, "2SC945")
QBJT_EB(Q4, "2SC945")
QBJT_EB(Q5, "2SC945")
QBJT_EB(Q6, "2SC945")
QBJT_EB(Q7, "2SC945")
QBJT_EB(Q9, "2SC945")
LM2902_DIP(XU1)
LM358_DIP(XU2)
MC14584B_DIP(XU3)
RES(R100, RES_K(560))
RES(R101, RES_K(150))
RES(R102, RES_K(150))
RES(R103, RES_K(470))
RES(R104, RES_K(22))
RES(R105, RES_K(470))
RES(R106, RES_K(150))
RES(R107, RES_K(150))
RES(R108, RES_K(560))
RES(R119, RES_K(22))
RES(R200, RES_K(100))
RES(R201, RES_K(100))
RES(R27, RES_K(6.8))
RES(R28, RES_K(150))
RES(R29, RES_K(2.7))
RES(R30, RES_K(10))
RES(R31, RES_K(5.1))
RES(R32, RES_K(4.7))
RES(R34, RES_K(100))
RES(R35, RES_K(100))
RES(R36, RES_K(100))
RES(R37, RES_K(47))
RES(R38, 820)
RES(R39, RES_K(22))
RES(R40, RES_K(10))
RES(R41, RES_K(10))
RES(R42, RES_K(150))
RES(R43, 470)
RES(R44, RES_K(100))
RES(R45, RES_K(1))
RES(R46, RES_K(12))
RES(R48, 470)
RES(R48_2, RES_K(100))
RES(R49, RES_K(10))
RES(R50, RES_K(2.2))
RES(R51, RES_K(150))
RES(R52, RES_K(100))
RES(R53, RES_K(100))
RES(R54, 680)
RES(R55, RES_K(510))
RES(R57, 560)
RES(R58, RES_K(39))
RES(R59, 560)
RES(R60, RES_K(39))
RES(R61, RES_K(100))
RES(R62, RES_K(100))
RES(R63, RES_K(1))
RES(R65, RES_K(1))
RES(R65_1, RES_K(27))
RES(R66, RES_M(1))
RES(R67, RES_K(100))
RES(R68, RES_K(100))
RES(R69, RES_K(1))
RES(R70, RES_K(10))
RES(R71, RES_K(100))
RES(R72, RES_K(100))
RES(R73, RES_K(10))
RES(R74, RES_K(10))
RES(R75, RES_K(10))
RES(R76, RES_K(47))
RES(R81, 220)
RES(R82, RES_M(2.2))
RES(R83, RES_K(12))
RES(R84, RES_K(1))
RES(R85, RES_M(2.2))
RES(R86, RES_K(10))
RES(R87, RES_K(68))
RES(R89, RES_K(22))
RES(R90, RES_K(390))
RES(R91, RES_K(100))
RES(R92, RES_K(22))
RES(R93, RES_K(1))
RES(R94, RES_K(22))
RES(R95, RES_K(330))
RES(R96, RES_K(150))
RES(R97, RES_K(150))
RES(R98, RES_K(680))
#if USE_FIXED_STV
ANALOG_INPUT(STV, 2)
#else
RES(R78, RES_K(3.3))
RES(R77, RES_K(2.2))
CAP(C58, CAP_U(47))
NET_C(R77.2, C58.1, I_V0.Q)
NET_C(R78.1, I_V5.Q)
#endif
NET_C(R95.1, XU3.2, R96.2)
NET_C(R95.2, XU3.1, C69.1)
NET_C(XU3.3, R103.2, C73.1)
NET_C(XU3.4, R103.1, R102.2)
NET_C(XU3.5, R105.2, C72.1)
NET_C(XU3.6, R105.1, R106.2)
NET_C(XU3.7, C69.2, C73.2, C72.2, C77.2, C67.2, C68.2, R65.2, R38.2, XU1.11, R54.2, Q4.E, R63.2, C47.2, R72.2, R67.2, R71.2, R68.2, C48.2, R46.2, C28.1, C32.1, R43.2, XU2.4, C56.1, C52.1, R48.2, R93.2, R94.2, R119.2, R104.2, R53.2, R34.2, R81.2, R92.2, R89.2, C33.1, R37.2, R36.1, R91.1, I_V0.Q, RV1.3)
NET_C(XU3.8, R108.1, R107.2)
NET_C(XU3.9, R108.2, C77.1)
NET_C(XU3.10, R100.1, R101.2)
NET_C(XU3.11, R100.2, C67.1)
NET_C(XU3.12, R98.1, R97.2)
NET_C(XU3.13, R98.2, C68.1)
NET_C(XU3.14, XU1.4, R66.1, R70.1, Q6.C, Q5.C, XU2.8, R86.1, R83.1, Q3.C, I_V5.Q)
NET_C(R96.1, R102.1, R106.1, R107.1, R101.1, R97.1, R65.1, C63.2)
NET_C(C63.1, R65_1.2)
NET_C(R65_1.1, R44.2, C38.2, C40.2, XU1.6)
#if USE_FIXED_STV
NET_C(R30.1, R41.1, R40.1, R76.2, /* R78.2, R77.1, C58.2*/ STV)
#else
NET_C(R30.1, R41.1, R40.1, R76.2, R78.2, R77.1, C58.2)
#endif
NET_C(R30.2, XU1.5)
NET_C(R44.1, C39.1, C40.1, R48_2.2)
NET_C(C38.1, C39.2, R38.1)
NET_C(XU1.1, XU1.2, R39.1, R32.2)
NET_C(XU1.3, C34.1, R41.2)
NET_C(XU1.7, R45.2)
NET_C(XU1.8, XU1.9, R31.2, C36.2)
NET_C(XU1.10, R42.1, C32.2)
NET_C(XU1.12, C49.1, C31.1, R40.2, C61.1, C60.1)
NET_C(XU1.13, R27.1, R28.2)
NET_C(XU1.14, R28.1, R29.2, I_SINH0)
NET_C(R48_2.1, C45.2, R54.1)
NET_C(C45.1, R55.1, Q7.B)
NET_C(R55.2, R90.2, C33.2, R37.1, Q3.E)
NET_C(R45.1, C44.2)
NET_C(C44.1, R66.2, Q4.B)
#if FIX_SCHEMATIC_ERRORS
#if D4_AND_D5_CONNECTED
/* needs verification */
NET_C(Q4.C, D4.K, D5.K)
NET_C(C42.1, C43.1, R46.1, C35.2)
#else
NET_C(Q4.C, D5.K)
NET_C(C42.1, C43.1, R46.1, C35.2, D4.K)
#endif
#else
NET_C(Q4.C, C42.1, C43.1, R46.1, C35.2, D4.K, D5.K)
#endif
NET_C(R70.2, R69.2, Q7.C)
NET_C(R63.1, Q7.E)
NET_C(R69.1, C49.2)
NET_C(C42.2, R58.1, D5.A)
NET_C(R58.2, R57.1, C47.1)
NET_C(R57.2, Q6.E)
NET_C(Q6.B, R61.1)
NET_C(C50.1, R67.1, R61.2)
NET_C(C50.2, R72.1, I_OH0.Q)
NET_C(C51.1, R68.1, R62.2)
NET_C(C51.2, R71.1, I_CH0.Q)
NET_C(R62.1, Q5.B)
NET_C(Q5.E, R59.2)
NET_C(R60.1, C43.2, D4.A)
NET_C(R60.2, R59.1, C48.1)
NET_C(C35.1, C34.2, R39.2)
NET_C(R32.1, C31.2)
NET_C(R27.2, C28.2)
NET_C(R29.1, R31.1, R50.2, R49.1, RV1.1)
NET_C(R42.2, R51.1, C36.1)
NET_C(R51.2, C41.1)
NET_C(C41.2, R43.1, I_SOUNDIC0)
NET_C(XU2.1, XU2.2, R73.1)
NET_C(XU2.3, R76.1, C200.2)
NET_C(XU2.5, C56.2, R75.1)
NET_C(XU2.6, XU2.7, R50.1, C53.2)
NET_C(R75.2, R74.1, C53.1)
NET_C(R74.2, C52.2, R73.2)
NET_C(R49.2, R48.1, I_SOUND0)
NET_C(Q9.E, R81.1)
NET_C(Q9.C, R84.2, R83.2, R82.1, C59.1)
NET_C(Q9.B, R82.2, C62.1)
NET_C(Q10.E, R93.1)
NET_C(Q10.C, R87.2, R86.2, R85.1, C76.1)
NET_C(Q10.B, R85.2, C64.1)
NET_C(R84.1, C61.2)
NET_C(C60.2, R87.1)
NET_C(C64.2, C65.1, R94.1, D3.K)
NET_C(C65.2, C66.1, R119.1)
NET_C(C66.2, C76.2, R104.1)
NET_C(R53.1, R52.2, C37.1)
NET_C(R34.1, C37.2, I_BD0.Q)
NET_C(R52.1, D3.A)
NET_C(R92.1, C62.2, C57.1)
NET_C(R89.1, C57.2, C59.2, R90.1)
NET_C(Q3.B, R35.1)
NET_C(R35.2, R36.2, C70.1)
NET_C(R91.2, C70.2, I_SD0.Q)
NET_C(I_MSM3K0.Q, R200.2)
NET_C(I_MSM2K0.Q, R201.2)
NET_C(R200.1, R201.1, C200.1)
/* Amplifier stage */
CAP(C26, CAP_U(1))
RES(R25, 560)
RES(R26, RES_K(47))
CAP(C29, CAP_U(0.01))
NET_C(RV1.2, C26.1)
NET_C(C26.2, R25.1)
NET_C(R25.2, R26.1, C29.1)
NET_C(R26.2, C29.2, GND)
NETLIST_END()
/* ----------------------------------------------------------------------------
* Kidniki audio
* ---------------------------------------------------------------------------*/
NETLIST_START(kidniki)
#if (1 || USE_FRONTIERS)
SOLVER(Solver, 48000)
PARAM(Solver.ACCURACY, 1e-7)
PARAM(Solver.NR_LOOPS, 300)
PARAM(Solver.GS_LOOPS, 10)
//PARAM(Solver.METHOD, "SOR")
PARAM(Solver.METHOD, "MAT_CR")
PARAM(Solver.FPTYPE, "DOUBLE")
//PARAM(Solver.METHOD, "MAT")
//PARAM(Solver.PIVOT, 1)
//PARAM(Solver.Solver_0.METHOD, "GMRES")
PARAM(Solver.SOR_FACTOR, 1.313)
PARAM(Solver.DYNAMIC_TS, 0)
PARAM(Solver.DYNAMIC_LTE, 5e-4)
PARAM(Solver.DYNAMIC_MIN_TIMESTEP, 20e-6)
PARAM(Solver.SORT_TYPE, "PREFER_IDENTITY_TOP_LEFT")
//PARAM(Solver.SORT_TYPE, "PREFER_BAND_MATRIX")
#else
//PARAM(Solver.SORT_TYPE, "PREFER_BAND_MATRIX")
SOLVER(Solver, 48000)
PARAM(Solver.ACCURACY, 1e-7)
PARAM(Solver.NR_LOOPS, 10000)
PARAM(Solver.GS_LOOPS, 100)
//PARAM(Solver.METHOD, "MAT_CR")
PARAM(Solver.METHOD, "GMRES")
#endif
#if (USE_FRONTIERS)
PARAM(Solver.PARALLEL, 2) // More does not help
#else
PARAM(Solver.PARALLEL, 0)
#endif
LOCAL_SOURCE(kidniki_schematics)
ANALOG_INPUT(I_V5, 5)
//ANALOG_INPUT(I_V0, 0)
ALIAS(I_V0.Q, GND)
/* AY 8910 internal resistors */
RES(R_AY45L_A, 1000)
RES(R_AY45L_B, 1000)
RES(R_AY45L_C, 1000)
RES(R_AY45M_A, 1000)
RES(R_AY45M_B, 1000)
RES(R_AY45M_C, 1000)
NET_C(I_V5, R_AY45L_A.1, R_AY45L_B.1, R_AY45L_C.1, R_AY45M_A.1, R_AY45M_B.1, R_AY45M_C.1)
NET_C(R_AY45L_A.2, R_AY45L_B.2, R_AY45M_A.2, R_AY45M_B.2, R_AY45M_C.2)
#if (J4)
ALIAS(I_SOUNDIC0, R_AY45L_C.2)
#else
NET_C(R_AY45L_A.2, R_AY45L_C.2)
ALIAS(I_SOUNDIC0, I_V0.Q)
#endif
ALIAS(I_SOUND0, R_AY45L_A.2)
TTL_INPUT(SINH, 1)
#if (D6_EXISTS)
DIODE(D6, "1N914")
NET_C(D6.K, SINH)
ALIAS(I_SINH0, D6.A)
#else
RES(SINH_DUMMY, RES_M(10))
NET_C(SINH_DUMMY.1, SINH)
ALIAS(I_SINH0, SINH_DUMMY.2)
#endif
NET_MODEL("AY8910PORT FAMILY(TYPE=NMOS OVL=0.05 OVH=0.05 ORL=100.0 ORH=0.5k)")
LOGIC_INPUT(I_SD0, 1, "AY8910PORT")
LOGIC_INPUT(I_BD0, 1, "AY8910PORT")
LOGIC_INPUT(I_CH0, 1, "AY8910PORT")
LOGIC_INPUT(I_OH0, 1, "AY8910PORT")
NET_C(I_V5, I_SD0.VCC, I_BD0.VCC, I_CH0.VCC, I_OH0.VCC, SINH.VCC)
NET_C(GND, I_SD0.GND, I_BD0.GND, I_CH0.GND, I_OH0.GND, SINH.GND)
ANALOG_INPUT(I_MSM2K0, 0)
ANALOG_INPUT(I_MSM3K0, 0)
INCLUDE(kidniki_schematics)
#if (USE_FRONTIERS)
OPTIMIZE_FRONTIER(C63.2, RES_K(27), RES_K(1))
OPTIMIZE_FRONTIER(R31.2, RES_K(5.1), 50)
OPTIMIZE_FRONTIER(R29.2, RES_K(2.7), 50)
OPTIMIZE_FRONTIER(R87.2, RES_K(68), 50)
OPTIMIZE_FRONTIER(R50.1, RES_K(2.2), 50)
OPTIMIZE_FRONTIER(R55.2, RES_K(1000), 50)
OPTIMIZE_FRONTIER(R84.2, RES_K(50), RES_K(5))
#endif
NETLIST_END()
| 25.367391 | 303 | 0.629788 | Robbbert |
781fbeaa2b4f0bff4d81099f43017283c50ddd3a | 7,936 | cpp | C++ | source/modules/examples/roles/roles.cpp | noglass/FarageBot | f8fbb3a70275230719916fb5083757e8fcf5753b | [
"MIT"
] | null | null | null | source/modules/examples/roles/roles.cpp | noglass/FarageBot | f8fbb3a70275230719916fb5083757e8fcf5753b | [
"MIT"
] | null | null | null | source/modules/examples/roles/roles.cpp | noglass/FarageBot | f8fbb3a70275230719916fb5083757e8fcf5753b | [
"MIT"
] | null | null | null | #include "api/farage.h"
#include <unordered_map>
#include <unordered_set>
#include <fstream>
using namespace Farage;
#define VERSION "v0.0.4"
extern "C" Info Module
{
"User Roles",
"Madison",
"User Role Granting System",
VERSION,
"http://farage.justca.me/",
FARAGE_API_VERSION
};
namespace role
{
std::unordered_map<std::string,std::unordered_set<std::string>> roles;
}
int addroleCmd(Handle&,int,const std::string[],const Message&);
int delroleCmd(Handle&,int,const std::string[],const Message&);
int giveroleCmd(Handle&,int,const std::string[],const Message&);
extern "C" int onModuleStart(Handle &handle, Global *global)
{
recallGlobal(global);
handle.createGlobVar("roles_version",VERSION,"User Roles Version",GVAR_CONSTANT);
handle.regChatCmd("addrole",&addroleCmd,ROLE,"Allow an already existing role to the roster.");
handle.regChatCmd("delrole",&delroleCmd,ROLE,"Remove a role from the roster.");
handle.regChatCmd("role",&giveroleCmd,NOFLAG,"Grant a role for yourself.");
return 0;
}
extern "C" int onReady(Handle &handle, Event event, void *data, void *nil, void *foo, void *bar)
{
Ready* readyData = (Ready*)data;
for (auto it = readyData->guilds.begin(), ite = readyData->guilds.end();it != ite;++it)
{
std::unordered_set<std::string> r;
std::ifstream file ("roles/" + *it);
if (file.is_open())
{
std::string line;
while (std::getline(file,line))
r.emplace(line);
file.close();
}
role::roles.emplace(*it,std::move(r));
}
return PLUGIN_CONTINUE;
}
int addroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message)
{
Global *global = recallGlobal();
auto server = getGuildCache(message.guild_id);
auto roles = role::roles.find(message.guild_id);
if (roles == role::roles.end())
{
role::roles.emplace(message.guild_id,std::unordered_set<std::string>());
roles = role::roles.find(message.guild_id);
}
if (argc < 2)
{
sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`");
return PLUGIN_HANDLED;
}
std::string role = argv[1];
for (int i = 2;i < argc;++i)
role.append(1,' ').append(argv[i]);
if ((role.substr(0,3) == "<@&") && (role.back() == '>'))
role = role.substr(3,role.size()-4);
std::string name = strlower(role);
if ((name.front() == '"') && (name.back() == '"'))
name = name.substr(1,name.size()-2);
bool found = false;
for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it)
{
if ((strlower(it->name) == name) || (it->id == role))
{
role = it->id;
name = it->name;
found = true;
break;
}
}
if ((found) && (roles->second.find(role) == roles->second.end()))
{
roles->second.emplace(role);
std::ofstream file ("roles/" + message.guild_id);
if (file.is_open())
{
for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it)
file<<*it<<std::endl;
file.close();
}
sendMessage(message.channel_id,"Added the role: `" + name + "`!");
}
else if (found)
sendMessage(message.channel_id,"Role is already registered: `" + name + "`!");
else
sendMessage(message.channel_id,"Not a valid role: `" + role + "`!");
return PLUGIN_HANDLED;
}
int delroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message)
{
Global *global = recallGlobal();
auto server = getGuildCache(message.guild_id);
auto roles = role::roles.find(message.guild_id);
if (argc < 2)
{
sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`");
return PLUGIN_HANDLED;
}
if ((roles == role::roles.end()) || (roles->second.size() == 0))
{
sendMessage(message.channel_id,"There are no registered roles!");
return PLUGIN_HANDLED;
}
std::string role = argv[1];
for (int i = 2;i < argc;++i)
role.append(1,' ').append(argv[i]);
if ((role.substr(0,3) == "<@&") && (role.back() == '>'))
role = role.substr(3,role.size()-4);
std::string name = strlower(role);
if ((name.front() == '"') && (name.back() == '"'))
name = name.substr(1,name.size()-2);
for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it)
{
if ((strlower(it->name) == name) || (it->id == role))
{
role = it->id;
name = it->name;
break;
}
}
auto r = roles->second.find(role);
if (r == roles->second.end())
{
sendMessage(message.channel_id,"Not a valid role: `" + role + "`!");
return PLUGIN_HANDLED;
}
roles->second.erase(r);
std::ofstream file ("roles/" + message.guild_id);
if (file.is_open())
{
for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it)
file<<*it<<std::endl;
file.close();
}
sendMessage(message.channel_id,"Removed the role: `" + name + "`!");
return PLUGIN_HANDLED;
}
int giveroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message)
{
Global *global = recallGlobal();
auto server = getGuildCache(message.guild_id);
auto roles = role::roles.find(message.guild_id);
if ((roles == role::roles.end()) || (roles->second.size() == 0))
{
sendMessage(message.channel_id,"There are no registered roles!");
return PLUGIN_HANDLED;
}
if (argc < 2)
{
Embed out;
out.color = 11614177;
out.title = "Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>` to give yourself a role.";
for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it)
for (auto sit = server.roles.begin(), site = server.roles.end();sit != site;++sit)
if (sit->id == *it)
out.description.append(1,'\n').append(sit->name);
sendEmbed(message.channel_id,out);
return PLUGIN_HANDLED;
}
std::string role = argv[1];
for (int i = 2;i < argc;++i)
role.append(1,' ').append(argv[i]);
std::string name = strlower(role);
if ((role.substr(0,3) == "<@&") && (role.back() == '>'))
role = role.substr(3,role.size()-4);
else
{
if ((name.front() == '"') && (name.back() == '"'))
name = name.substr(1,name.size()-2);
for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it)
{
if (strlower(it->name) == name)
{
role = it->id;
name = it->name;
break;
}
}
}
if (roles->second.find(role) == roles->second.end())
{
sendMessage(message.channel_id,"Not a valid role: `" + role + "`!");
return PLUGIN_HANDLED;
}
else
{
auto mroles = message.member.roles;
for (auto it = mroles.begin(), ite = mroles.end();it != ite;++it)
{
if (*it == role)
{
mroles.erase(it);
editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles);
sendMessage(message.channel_id,"You have left the `" + name + "` role.");
return PLUGIN_HANDLED;
}
}
mroles.push_back(role);
editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles);
sendMessage(message.channel_id,"You have joined the `" + name + "` role.");
}
return PLUGIN_HANDLED;
}
| 34.960352 | 151 | 0.559098 | noglass |
7820c1e7c5124e6c2a55bd2ad7ea73d0c4e3ae88 | 1,125 | cpp | C++ | libc/test/src/string/strdup_test.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | libc/test/src/string/strdup_test.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | libc/test/src/string/strdup_test.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | //===-- Unittests for strdup ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "src/string/strdup.h"
#include "utils/UnitTest/Test.h"
#include <stdlib.h>
TEST(LlvmLibcStrDupTest, EmptyString) {
const char *empty = "";
char *result = __llvm_libc::strdup(empty);
ASSERT_NE(result, static_cast<char *>(nullptr));
ASSERT_NE(empty, const_cast<const char *>(result));
ASSERT_STREQ(empty, result);
::free(result);
}
TEST(LlvmLibcStrDupTest, AnyString) {
const char *abc = "abc";
char *result = __llvm_libc::strdup(abc);
ASSERT_NE(result, static_cast<char *>(nullptr));
ASSERT_NE(abc, const_cast<const char *>(result));
ASSERT_STREQ(abc, result);
::free(result);
}
TEST(LlvmLibcStrDupTest, NullPtr) {
char *result = __llvm_libc::strdup(nullptr);
ASSERT_EQ(result, static_cast<char *>(nullptr));
}
| 28.125 | 80 | 0.624889 | mkinsner |
7822532491068056bccda67af9935be670d60aa6 | 2,312 | cpp | C++ | collector/src/main_win32.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 194 | 2015-07-27T09:54:24.000Z | 2022-03-21T20:50:22.000Z | collector/src/main_win32.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 63 | 2015-08-19T16:42:33.000Z | 2022-02-22T20:30:49.000Z | collector/src/main_win32.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 33 | 2015-08-21T17:48:03.000Z | 2022-02-23T03:54:17.000Z | // Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <crtdbg.h>
#include "detour.h"
#include "main.h"
#include <tchar.h>
#include <windows.h>
using namespace std;
namespace micro_profiler
{
namespace
{
collector_app_instance *g_instance_singleton = nullptr;
shared_ptr<void> *g_exit_process_detour = nullptr;
void WINAPI ExitProcessHooked(UINT exit_code)
{
if (g_exit_process_detour)
g_exit_process_detour->reset();
g_instance_singleton->terminate();
::ExitProcess(exit_code);
}
}
void collector_app_instance::platform_specific_init()
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
static shared_ptr<void> exit_process_detour;
g_instance_singleton = this;
g_exit_process_detour = &exit_process_detour;
HMODULE hmodule;
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, _T("kernel32"), &hmodule);
const auto exit_process = ::GetProcAddress(hmodule, "ExitProcess");
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
reinterpret_cast<LPCTSTR>(&ExitProcessHooked), &hmodule);
exit_process_detour = detour(exit_process, &ExitProcessHooked);
}
}
| 34.507463 | 101 | 0.773356 | tyoma |
7822a8e6784939bc2e3f32e0ac89b7080553b9aa | 68 | cpp | C++ | BrowserPivotingIE/HTTPProxy/payload.cpp | ZwCreatePhoton/BrowserPivotingIE | 5cc0b8f46b29ec7559de164bc8677457b70607e9 | [
"MIT"
] | null | null | null | BrowserPivotingIE/HTTPProxy/payload.cpp | ZwCreatePhoton/BrowserPivotingIE | 5cc0b8f46b29ec7559de164bc8677457b70607e9 | [
"MIT"
] | null | null | null | BrowserPivotingIE/HTTPProxy/payload.cpp | ZwCreatePhoton/BrowserPivotingIE | 5cc0b8f46b29ec7559de164bc8677457b70607e9 | [
"MIT"
] | null | null | null | #include "HTTPProxy.h"
void Payload()
{
run(DEFAULT_PROXY_PORT);
} | 11.333333 | 25 | 0.720588 | ZwCreatePhoton |
7825c118fddfb25686acd603cadb9fb07bf4b437 | 4,568 | cpp | C++ | engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 58 | 2018-05-10T17:06:42.000Z | 2019-01-24T13:42:22.000Z | engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp | blab-liuliang/echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 290 | 2018-01-24T16:29:42.000Z | 2019-01-24T07:11:16.000Z | engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 9 | 2018-08-26T04:06:21.000Z | 2019-01-14T03:47:39.000Z | #include "opendrive_dynamic_mesh.h"
#include "engine/core/log/log.h"
#include "engine/core/scene/node_tree.h"
#include "base/renderer.h"
#include "base/shader/shader_program.h"
#include "engine/core/main/Engine.h"
namespace Echo
{
OpenDriveDynamicMesh::OpenDriveDynamicMesh()
: Render()
{
setRenderType("3d");
}
OpenDriveDynamicMesh::~OpenDriveDynamicMesh()
{
reset();
}
void OpenDriveDynamicMesh::bindMethods()
{
CLASS_BIND_METHOD(OpenDriveDynamicMesh, getStepLength);
CLASS_BIND_METHOD(OpenDriveDynamicMesh, setStepLength);
CLASS_BIND_METHOD(OpenDriveDynamicMesh, getMaterial);
CLASS_BIND_METHOD(OpenDriveDynamicMesh, setMaterial);
CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "StepLength", Variant::Type::Real, getStepLength, setStepLength);
CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "Material", Variant::Type::Object, getMaterial, setMaterial);
CLASS_REGISTER_PROPERTY_HINT(OpenDriveDynamicMesh, "Material", PropertyHintType::ObjectType, "Material");
}
void OpenDriveDynamicMesh::reset()
{
m_controlPoints.clear();
m_renderable.reset();
m_mesh.reset();
}
void OpenDriveDynamicMesh::add(const Vector3& position, const Vector3& forward, const Vector3& up, float width, const Color& color, bool separator)
{
ControlPoint controlPoint;
controlPoint.m_position = position;
controlPoint.m_forward = forward;
controlPoint.m_up = up;
controlPoint.m_width = width;
controlPoint.m_length = m_controlPoints.empty() ? 0.f : m_controlPoints.back().m_length + (m_controlPoints.back().m_position - position).len();
controlPoint.m_color = color;
controlPoint.m_separator = separator;
m_controlPoints.emplace_back(controlPoint);
m_isRenderableDirty = true;
}
void OpenDriveDynamicMesh::setStepLength(float stepLength)
{
if (m_stepLength != stepLength)
{
m_stepLength = stepLength;
m_isRenderableDirty = true;
}
}
void OpenDriveDynamicMesh::setMaterial(Object* material)
{
m_material = (Material*)material;
m_isRenderableDirty = true;
}
void OpenDriveDynamicMesh::buildRenderable()
{
if (m_isRenderableDirty)
{
if (!m_material)
{
StringArray macros = { "HAS_NORMALS" };
ShaderProgramPtr shader = ShaderProgram::getDefault3D(macros);
m_material = ECHO_CREATE_RES(Material);
m_material->setShaderPath(shader->getPath());
}
// mesh
updateMeshBuffer();
// create render able
m_renderable = RenderProxy::create(m_mesh, m_material, this, true);
m_isRenderableDirty = false;
}
}
void OpenDriveDynamicMesh::updateInternal(float elapsedTime)
{
if (isNeedRender())
buildRenderable();
if (m_renderable)
m_renderable->setSubmitToRenderQueue(isNeedRender());
}
void OpenDriveDynamicMesh::updateMeshBuffer()
{
if (!m_mesh)
{
if (m_controlPoints.size()>1)
m_mesh = Mesh::create(true, true);
}
if (m_mesh)
{
IndiceArray indices;
VertexArray vertices;
for (size_t i = 0; i < m_controlPoints.size(); i++)
{
const ControlPoint& controlPoint = m_controlPoints[i];
Vector3 halfRightDir = controlPoint.m_forward.cross(controlPoint.m_up) * controlPoint.m_width * 0.5f;
// Update Vertices
VertexFormat v0;
v0.m_position = controlPoint.m_position + halfRightDir;
v0.m_normal = controlPoint.m_up;
//v0.m_color = controlPoint.Color;
v0.m_uv = Vector2(0.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale;
VertexFormat v1;
v1.m_position = controlPoint.m_position - halfRightDir;
v1.m_normal = controlPoint.m_up;
//v1.Color = controlPoint.Color;
v1.m_uv = Vector2(1.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale;
vertices.push_back(v0);
vertices.push_back(v1);
// Update Indices
if (i != 0 && !controlPoint.m_separator)
{
i32 base = vertices.size() - 4;
indices.push_back(base);
indices.push_back(base + 3);
indices.push_back(base + 2);
indices.push_back(base);
indices.push_back(base + 1);
indices.push_back(base + 3);
}
}
// format
MeshVertexFormat define;
define.m_isUseNormal = true;
define.m_isUseUV = true;
m_mesh->updateIndices(static_cast<ui32>(indices.size()), sizeof(ui32), indices.data());
m_mesh->updateVertexs(define, static_cast<ui32>(vertices.size()), (const Byte*)vertices.data());
m_localAABB = m_mesh->getLocalBox();
}
}
void* OpenDriveDynamicMesh::getGlobalUniformValue(const String& name)
{
if (name == "u_WorldMatrix")
return (void*)(&Matrix4::IDENTITY);
return Render::getGlobalUniformValue(name);
}
}
| 26.252874 | 148 | 0.721103 | blab-liuliang |
782734aaf28fea2fbf28536efde825f2d7d9af08 | 34,650 | cpp | C++ | marxan.cpp | hotzevzl/marxan | 23ba3a0ada90e721c745b922363458bece3477dc | [
"MIT"
] | 5 | 2021-02-16T07:50:47.000Z | 2021-09-14T00:17:13.000Z | marxan.cpp | hotzevzl/marxan | 23ba3a0ada90e721c745b922363458bece3477dc | [
"MIT"
] | 7 | 2021-02-17T00:03:09.000Z | 2021-10-05T14:46:22.000Z | marxan.cpp | hotzevzl/marxan | 23ba3a0ada90e721c745b922363458bece3477dc | [
"MIT"
] | 2 | 2020-10-02T18:08:17.000Z | 2021-06-18T09:03:01.000Z | // C++ code for Marxan
// version 2.3 introduced multiple connectivity files and their associated weighting file
// version 2.4.3 introduced 1D and 2D probability
// version 3.0.0 is refactoring of code in 2019
#include <algorithm>
#include <chrono>
#include <ctime>
#include <cfloat>
#include <iostream>
#include <omp.h>
#include <chrono>
// load the required function definition modules
#include "utils.hpp"
#include "algorithms.hpp"
#include "computation.hpp"
#include "clumping.hpp"
#include "anneal.hpp"
#include "heuristics.hpp"
#include "probability.hpp"
#include "input.hpp"
#include "output.hpp"
#include "score_change.hpp"
#include "iterative_improvement.hpp"
#include "quantum_annealing.hpp"
#include "thermal_annealing.hpp"
#include "hill_climbing.hpp"
#include "marxan.hpp"
#include "defines.hpp"
namespace marxan {
using namespace algorithms;
using namespace utils;
// Initialize global constants
double delta;
long int RandSeed1;
int iMemoryUsed = 0;
int fSpecPROPLoaded = 0;
int iProbFieldPresent = 0;
int iOptimisationCalcPenalties = 1;
int savelog;
int verbosity = 0;
int asymmetricconnectivity = 0;
string sVersionString = "Marxan v 4.0.6";
string sMarxanWebSite = "https://marxansolutions.org/";
string sTraceFileName;
string sApplicationPathName;
string savelogname;
FILE* fsavelog;
// init global structures
sanneal anneal_global;
vector<sconnections> connections;
sfname fnames;
vector<spu> SMGlobal;
vector<spusporder> SMsporder;
vector<spustuff> pu;
map<int, int> PULookup, SPLookup;
vector<sspecies> specGlobal, bestSpec;
chrono::high_resolution_clock::time_point startTime;
double rProbabilityWeighting = 1;
double rStartDecThresh = 0.7, rEndDecThresh = 0.3, rStartDecMult = 3, rEndDecMult = 1;
int fProb2D = 0, fProb1D = 0, fUserPenalties = 0;
int fOptimiseConnectivityIn = 0;
// number of the best solution
int bestRun = 1;
// score of the best solution
double bestScore;
// R vector of planning unit status for the best solution
vector<int> bestR;
// is marxan being called by another program?
int marxanIsSecondary = 0;
// runs the loop for each "solution" marxan is generating
void executeRunLoop(long int repeats, int puno, int spno, double cm, int aggexist, double prop, int clumptype, double misslevel,
string savename, double costthresh, double tpf1, double tpf2, int heurotype, srunoptions& runoptions,
int itimptype, vector<int>& sumsoln, rng_engine& rngEngineGlobal)
{
string bestRunString;
vector<string> summaries(repeats); // stores individual summaries for each run
bestR.resize(puno);
bestScore = DBL_MAX;
bestSpec.resize(spno); // best species config
// Locks for bestR and bestScore as it will be read/written by multiple threads
omp_lock_t bestR_write_lock;
omp_init_lock(&bestR_write_lock);
// Locks for solution matrix append
omp_lock_t solution_matrix_append_lock;
omp_init_lock(&solution_matrix_append_lock);
// Locks for sumsoln
omp_lock_t solution_sum_lock;
omp_init_lock(&solution_sum_lock);
// for each repeat run
int maxThreads = omp_get_max_threads();
printf("Running multithreaded over number of threads: %d\n", maxThreads);
displayProgress1("Running multithreaded over number of threads: " + to_string(maxThreads) + "\n");
displayProgress1("Runs will be printed as they complete, and may not be in order due to parallelisation.\n");
//create seeds for local rng engines
vector<unsigned int> seeds(repeats);
for (int run_id = 1; run_id <= repeats; run_id++)
seeds[run_id - 1] = rngEngineGlobal();
bool quitting_loop = false;
#pragma omp parallel for schedule(dynamic)
for (int run_id = 1; run_id <= repeats; run_id++)
{
if(quitting_loop)
continue; //skipping iterations. It is not allowed to break or throw out omp for loop.
// Create run specific structures
int thread = omp_get_thread_num();
rng_engine rngEngine(seeds[run_id - 1]);
string tempname2;
stringstream appendLogBuffer; // stores the trace file log
stringstream runConsoleOutput; // stores the console message for the run. This is needed for more organized printing output due to multithreading.
sanneal anneal = anneal_global;
scost reserve;
scost change;
vector<int> R(puno);
vector<sspecies> spec = specGlobal; // make local copy of original spec
vector<spu_out> SM_out; // make local copy output part of SMGlobal.
//if (aggexist)
SM_out.resize(SMGlobal.size());
appendLogBuffer << "\n Start run loop run " << run_id << endl;
try {
if (runoptions.ThermalAnnealingOn)
{
// Annealing Setup
if (anneal.type == 2)
{
appendLogBuffer << "before initialiseConnollyAnnealing run " << run_id << endl;
initialiseConnollyAnnealing(puno, spno, pu, connections, spec, SMGlobal, SM_out, cm, anneal, aggexist, R, prop, clumptype, run_id, appendLogBuffer, rngEngine);
appendLogBuffer << "after initialiseConnollyAnnealing run " << run_id << endl;
}
if (anneal.type == 3)
{
appendLogBuffer << "before initialiseAdaptiveAnnealing run " << run_id << endl;
initialiseAdaptiveAnnealing(puno, spno, prop, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, anneal, clumptype, appendLogBuffer, rngEngine);
appendLogBuffer << "after initialiseAdaptiveAnnealing run " << run_id << endl;
}
if (verbosity > 1) runConsoleOutput << "\nRun " << run_id << ": Using Calculated Tinit = " << anneal.Tinit << " Tcool = " << anneal.Tcool << "\n";
anneal.temp = anneal.Tinit;
}
appendLogBuffer << "before computeReserveValue run " << run_id << endl;
initialiseReserve(prop, pu, R, rngEngine); // Create Initial Reserve
SpeciesAmounts(spno, puno, spec, pu, SMGlobal, R, clumptype); // Re-added this from v2.4 because spec amounts need to be refreshed when initializing
if (aggexist)
ClearClumps(spno, spec, pu, SMGlobal, SM_out);
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
appendLogBuffer << "after computeReserveValue run " << run_id << endl;
if (verbosity > 1)
{
runConsoleOutput << "Run " << run_id << " Init: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
if (verbosity > 5)
{
displayTimePassed(startTime);
}
if (runoptions.ThermalAnnealingOn)
{
appendLogBuffer << "before thermalAnnealing run " << run_id << endl;
thermalAnnealing(spno, puno, connections, R, cm, spec, pu, SMGlobal, SM_out, reserve,
repeats, run_id, savename, misslevel,
aggexist, costthresh, tpf1, tpf2, clumptype, anneal, appendLogBuffer, rngEngine);
if (verbosity > 1)
{
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
runConsoleOutput << "Run " << run_id << " ThermalAnnealing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
appendLogBuffer << "after thermalAnnealing run " << run_id << endl;
}
if (runoptions.HillClimbingOn)
{
appendLogBuffer << "before hill climbing run " << run_id << endl;
hill_climbing( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2,
clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine);
if (verbosity > 1)
{
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
runConsoleOutput << "Run " << run_id << " Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
appendLogBuffer << "after hill climbing run " << run_id << endl;
}
if (runoptions.TwoStepHillClimbingOn)
{
appendLogBuffer << "before two step hill climbing run " << run_id << endl;
hill_climbing_two_steps( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2,
clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine);
if (verbosity > 1)
{
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
runConsoleOutput << "Run " << run_id << " Two Step Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
appendLogBuffer << "after hill climbing run " << run_id << endl;
}
if (runoptions.HeuristicOn)
{
appendLogBuffer << "before Heuristics run " << run_id << endl;
Heuristics(spno, puno, pu, connections, R, cm, spec, SMGlobal, SM_out, reserve,
costthresh, tpf1, tpf2, heurotype, clumptype, appendLogBuffer, rngEngine);
if (verbosity > 1)
{
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
runConsoleOutput << "Run " << run_id << " Heuristic: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
appendLogBuffer << "after Heuristics run " << run_id << endl;
}
if (runoptions.ItImpOn)
{
appendLogBuffer << "before iterativeImprovement run " << run_id << endl;
iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm,
reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine);
if (itimptype == 3)
iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm,
reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine);
appendLogBuffer << "after iterativeImprovement run " << run_id << endl;
if (aggexist)
ClearClumps(spno, spec, pu, SMGlobal, SM_out);
if (verbosity > 1)
{
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer);
runConsoleOutput << "Run " << run_id << " Iterative Improvement: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str();
}
} // Activate Iterative Improvement
appendLogBuffer << "before file output run " << run_id << endl;
string fileNumber = utils::intToPaddedString(run_id, 5);
if (fnames.saverun)
{
tempname2 = savename + "_r" + fileNumber + getFileNameSuffix(fnames.saverun);
writeSolution(puno, R, pu, tempname2, fnames.saverun, fnames);
}
if (fnames.savespecies && fnames.saverun)
{
tempname2 = savename + "_mv" + fileNumber + getFileNameSuffix(fnames.savespecies);
writeSpecies(spno, spec, tempname2, fnames.savespecies, misslevel);
}
if (fnames.savesum)
{ // summaries get stored and aggregated to prevent race conditions.
summaries[run_id - 1] = computeSummary(puno, spno, R, spec, reserve, run_id, misslevel, fnames.savesum);
}
// Print results from run.
displayProgress1(runConsoleOutput.str());
// compute and store objective function score for this reserve system
computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, change, clumptype, appendLogBuffer);
// remember the bestScore and bestRun
if (change.total < bestScore)
{
omp_set_lock(&bestR_write_lock);
// After locking, do another check in case bestScore has changed
if (change.total < bestScore) {
// this is best run so far
bestScore = change.total;
bestRun = run_id;
// store bestR
bestR = R;
bestRunString = runConsoleOutput.str();
bestSpec = spec; // make a copy of best spec.
}
omp_unset_lock(&bestR_write_lock);
}
if (fnames.savesolutionsmatrix)
{
appendLogBuffer << "before appendSolutionsMatrix savename " << run_id << endl;
tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix);
omp_set_lock(&solution_matrix_append_lock);
appendSolutionsMatrix(run_id, puno, R, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
omp_unset_lock(&solution_matrix_append_lock);
appendLogBuffer << "after appendSolutionsMatrix savename " << run_id << endl;
}
// Save solution sum
if (fnames.savesumsoln) {
omp_set_lock(&solution_sum_lock);
for (int k = 0; k < puno; k++) {
if (R[k] == 1 || R[k] == 2) {
sumsoln[k]++;
}
}
omp_unset_lock(&solution_sum_lock);
}
if (aggexist)
ClearClumps(spno, spec, pu, SMGlobal, SM_out);
}
catch (const exception& e) {
// On exceptions, append exception to log file in addition to existing buffer.
displayProgress1(runConsoleOutput.str());
appendLogBuffer << "Exception occurred on run " << run_id << ": " << e.what() << endl;
displayProgress1(appendLogBuffer.str());
appendTraceFile(appendLogBuffer.str());
//cannot throw or break out of omp loop
quitting_loop = true;
continue;
}
appendLogBuffer << "after file output run " << run_id << endl;
appendLogBuffer << "end run " << run_id << endl;
appendTraceFile(appendLogBuffer.str());
if (marxanIsSecondary == 1)
writeSecondarySyncFileRun(run_id);
if (verbosity > 1)
{
stringstream done_message;
done_message << "Run " << run_id << " is finished (out of " << repeats << "). ";
#pragma omp critical
{
displayProgress1(done_message.str());
displayTimePassed(startTime);
}
}
}
if(quitting_loop)
{
displayProgress1("\nRuns were aborted due to error.\n");
throw runtime_error("Runs were aborted due to error.\n");
}
// Write all summaries for each run.
if (fnames.savesum)
{
string tempname2 = savename + "_sum" + getFileNameSuffix(fnames.savesum);
writeSummary(tempname2, summaries, fnames.saverun);
}
stringstream bestOut;
bestOut << "\nBest run: " << bestRun << " Best score: " << bestScore << "\n" << bestRunString;
cout << bestOut.str();
displayProgress1(bestOut.str());
} // executeRunLoop
int executeMarxan(string sInputFileName)
{
long int repeats;
int puno, spno, gspno;
double cm, prop;
int heurotype, clumptype, itimptype;
string savename, tempname2;
double misslevel;
int iseed = time(NULL), seedinit;
int aggexist = 0, sepexist = 0;
vector<int> R_CalcPenalties;
vector<int> sumsoln;
double costthresh, tpf1, tpf2;
long int itemp;
int isp;
int maxThreads = omp_get_max_threads();
srunoptions runoptions;
displayStartupMessage();
startTime = chrono::high_resolution_clock::now(); // set program start time.
readInputOptions(cm, prop, anneal_global,
iseed, repeats, savename, fnames, sInputFileName,
runoptions, misslevel, heurotype, clumptype, itimptype, verbosity,
costthresh, tpf1, tpf2);
sTraceFileName = savename + "_TraceFile.txt";
createTraceFile();
appendTraceFile("%s begin execution\n\n", sVersionString.c_str());
appendTraceFile("LoadOptions\n");
#ifdef DEBUGCHECKCHANGE
createDebugFile("debug_MarOpt_CheckChange.csv", "ipu,puid,R,total,cost,connection,penalty,threshpen,probability\n", fnames);
#endif
#ifdef DEBUGCHANGEPEN
createDebugFile("debug_MarOpt_ChangePen.csv", "ipu,puid,isp,spid,penalty,target,targetocc,occurrence,sepnum,amount,newamount,fractionAmount\n", fnames);
#endif
#ifdef DEBUGCALCPENALTIES
createDebugFile("debug_MarZone_CalcPenalties.csv", "\n", fnames);
#endif
if (fnames.savelog)
{
tempname2 = savename + "_log.dat";
createLogFile(fnames.savelog, tempname2);
}
delta = 1e-14; // This would more elegantly be done as a constant
// init rng engine
rng_engine rngEngine(iseed);
RandSeed1 = iseed;
seedinit = iseed;
appendTraceFile("RandSeed iseed %i RandSeed1 %li\n", iseed, RandSeed1);
// read the data files
displayProgress1("\nEntering in the data files \n");
displayProgress3(" Reading in the Planning Unit names \n");
appendTraceFile("before readPlanningUnits\n");
itemp = readPlanningUnits(puno, pu, fnames);
appendTraceFile("after readPlanningUnits\n");
if (iProbFieldPresent == 1)
appendTraceFile("prob field present\n");
else
appendTraceFile("prob field not present\n");
#ifdef DEBUG_PROB1D
if (iProbFieldPresent == 1)
writeProbData(puno, pu, fnames);
#endif
displayProgress1(" There are %i Planning units.\n %i Planning Unit names read in \n", puno, itemp);
displayProgress3(" Reading in the species file \n");
appendTraceFile("before readSpecies\n");
itemp = readSpecies(spno, specGlobal, fnames);
appendTraceFile("after readSpecies\n");
displayProgress1(" %i species read in \n", itemp);
appendTraceFile("before build search arrays\n");
// create the fast lookup tables for planning units and species names
populateLookupTables(puno, spno, pu, specGlobal, PULookup, SPLookup);
appendTraceFile("after build search arrays\n");
if (fnames.savesumsoln)
sumsoln.resize(puno);
connections.resize(puno);
displayProgress3(" Reading in the Connection file :\n");
itemp = 0;
if (!fnames.connectionname.empty())
{
appendTraceFile("before readConnections\n");
if (!fnames.connectionfilesname.empty())
writeWeightedConnectivityFile(fnames);
itemp = readConnections(puno, connections, pu, PULookup, fnames);
appendTraceFile("after readConnections\n");
if (asymmetricconnectivity)
{
appendTraceFile("Asymmetric connectivity is on.\n");
writeAsymmetricConnectionFile(puno, connections, pu, fnames);
}
if (fOptimiseConnectivityIn)
appendTraceFile("Optimising 'Connectivity In'.\n");
}
displayProgress1(" %i connections entered \n", itemp);
if (asymmetricconnectivity)
displayProgress1(" Asymmetric connectivity is on.\n");
if (fOptimiseConnectivityIn)
displayProgress1(" Optimising 'Connectivity In'.\n");
displayProgress3(" Reading in the Planning Unit versus Species File \n");
appendTraceFile("before readSparseMatrix\n");
readSparseMatrix(SMGlobal, puno, spno, pu, PULookup, SPLookup, fnames);
appendTraceFile("after readSparseMatrix\n");
if (fProb2D == 1)
appendTraceFile("Prob2D is on\n");
else
appendTraceFile("Prob2D is off\n");
#ifdef DEBUG_PROB2D
writeSparseMatrix(iSparseMatrixFileLength, puno, pu, spec, SM, fnames);
#endif
if (fnames.saverichness)
{
tempname2 = savename + "_richness" + getFileNameSuffix(fnames.saverichness);
writeRichness(puno, pu, tempname2, fnames.saverichness);
}
if (!fnames.matrixspordername.empty())
{
appendTraceFile("before readSparseMatrixSpOrder\n");
displayWarningMessage("input.dat option: MATRIXSPORDERNAME is no longer needed, however the supplied file will still be read and processed. Please refer to the version 4 feature changelog.md.");
readSparseMatrixSpOrder(SMsporder, puno, spno, PULookup, SPLookup, specGlobal, fnames);
appendTraceFile("after readSparseMatrixSpOrder\n");
}
appendTraceFile("before process block definitions\n");
if (!fnames.blockdefname.empty())
{
displayProgress1(" Reading in the Block Definition File \n");
vector<sgenspec> gspec; // declare within this scope of usage
readSpeciesBlockDefinition(gspno, gspec, fnames);
setBlockDefinitions(gspno, spno, puno, gspec, specGlobal, pu, SMGlobal);
}
setDefaultTargets(specGlobal);
appendTraceFile("after process block definitions\n");
appendTraceFile("before computeTotalAreas\n");
computeTotalAreas(puno, spno, pu, specGlobal, SMGlobal);
appendTraceFile("after computeTotalAreas\n");
if (fnames.savetotalareas)
{
tempname2 = savename + "totalareas" + getFileNameSuffix(fnames.savetotalareas);
writeTotalAreas(puno, spno, pu, specGlobal, SMGlobal, tempname2, fnames.savepenalty);
}
if (fSpecPROPLoaded > 0)
{
appendTraceFile("before computeSpecProp\n");
// species have prop value specified
computeSpecProp(spno, specGlobal, puno, pu, SMGlobal);
appendTraceFile("after computeSpecProp\n");
}
displayProgress2("Checking to see if there are aggregating or separating species.\n");
for (isp = 0; isp < spno; isp++)
{
if (specGlobal[isp].target2 > 0)
aggexist = 1;
if (specGlobal[isp].sepdistance > 0)
sepexist = 1;
}
if (fnames.savesen)
{
appendTraceFile("before writeScenario\n");
tempname2 = savename + "_sen.dat";
writeScenario(puno, spno, prop, cm, anneal_global, seedinit, repeats, clumptype,
runoptions, heurotype, costthresh, tpf1, tpf2, tempname2);
appendTraceFile("after writeScenario\n");
}
if (verbosity > 1)
displayTimePassed(startTime);
// ******* Pre-processing ************
displayProgress1("\nPre-processing Section. \n");
displayProgress2(" Calculating all the penalties \n");
R_CalcPenalties.resize(puno);
// load penalties from file if they are present
if (!fnames.penaltyname.empty())
{
fUserPenalties = 1;
appendTraceFile("before readPenalties\n");
readPenalties(specGlobal, spno, fnames, SPLookup);
appendTraceFile("after readPenalties\n");
}
if (runoptions.CalcPenaltiesOn == 0)
{
// if penalties have not been loaded, then stop error message
if (fUserPenalties == 0)
{
appendTraceFile("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n");
displayProgress1("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n");
exit(EXIT_FAILURE);
}
// transfer loaded penalties to correct data structrure
applyUserPenalties(specGlobal);
}
else
{
vector<spu_out> SM_out; // make local copy output part of SMGlobal.
//if (aggexist)
SM_out.resize(SMGlobal.size());
// we are computing penalties
if (fnames.matrixspordername.empty())
{
appendTraceFile("before CalcPenalties\n");
// we don't have sporder matrix available, so use slow CalcPenalties method
itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine);
appendTraceFile("after CalcPenalties\n");
}
else
{
// we have sporder matrix available, so use optimised CalcPenalties method
if (iOptimisationCalcPenalties == 1)
{
appendTraceFile("before CalcPenaltiesOptimise\n");
itemp = computePenaltiesOptimise(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, SMsporder, R_CalcPenalties, aggexist, cm, clumptype, rngEngine);
appendTraceFile("after CalcPenaltiesOptimise\n");
}
else
{
appendTraceFile("before CalcPenalties\n");
// we have optimise calc penalties switched off, so use slow CalcPenalties method
itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine);
appendTraceFile("after CalcPenalties\n");
}
}
}
if (itemp > 0)
displayProgress("%d species cannot meet target%c.\n", itemp, itemp == 1 ? ' ' : 's');
if (runoptions.ThermalAnnealingOn)
{
displayProgress2(" Calculating temperatures.\n");
if (!anneal_global.Titns)
displayErrorMessage("Initial Temperature is set to zero. Fatal Error \n");
anneal_global.Tlen = anneal_global.iterations / anneal_global.Titns;
displayProgress2(" Temperature length %ld \n", anneal_global.Tlen);
displayProgress2(" iterations %lld, repeats %ld \n", anneal_global.iterations, repeats);
} // Annealing Preprocessing. Should be moved to SetAnnealingOptions
if (fnames.savepenalty)
{
tempname2 = savename + "_penalty" + getFileNameSuffix(fnames.savepenalty);
writePenalty(spno, specGlobal, tempname2, fnames.savepenalty);
tempname2 = savename + "_penalty_planning_units" + getFileNameSuffix(fnames.savepenalty);
writePenaltyPlanningUnits(puno, pu, R_CalcPenalties, tempname2, fnames.savepenalty);
}
//free(R_CalcPenalties);
if (fnames.savespec)
{
tempname2 = savename + "_spec.csv";
writeSpec(spno, specGlobal, tempname2);
}
if (fnames.savepu)
{
tempname2 = savename + "_pu.csv";
writePu(puno, pu, tempname2);
}
// If we are in a runmode with only CalcPenalties, we stop/exit here gracefully because we are finished.
if (runoptions.HeuristicOn == 0 && runoptions.ThermalAnnealingOn == 0 && runoptions.HillClimbingOn == 0 && runoptions.ItImpOn == 0 && runoptions.TwoStepHillClimbingOn == 0)
{
appendTraceFile("end final file output\n");
appendTraceFile("\nMarxan end execution\n");
displayShutdownMessage(startTime);
if (marxanIsSecondary == 1)
secondaryExit();
exit(EXIT_FAILURE);
}
if (fnames.savesolutionsmatrix)
{
tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix);
#ifdef DEBUG_CLUSTERANALYSIS
appendTraceFile("before createSolutionsMatrix savename %s\n", savename);
#endif
createSolutionsMatrix(puno, pu, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
#ifdef DEBUG_CLUSTERANALYSIS
appendTraceFile("after createSolutionsMatrix savename %s\n", savename);
#endif
}
if (fProb1D == 1)
{
tempname2 = savename + "_ComputeP_AllPUsSelected_1D.csv";
ComputeP_AllPUsSelected_1D(tempname2, puno, spno, pu, SMGlobal, specGlobal);
}
if (fProb2D == 1)
{
tempname2 = savename + "_ComputeP_AllPUsSelected_2D.csv";
ComputeP_AllPUsSelected_2D(tempname2, puno, spno, pu, SMGlobal, specGlobal);
}
try
{
executeRunLoop(repeats, puno, spno, cm, aggexist, prop, clumptype, misslevel,
savename, costthresh, tpf1, tpf2, heurotype, runoptions,
itimptype, sumsoln, rngEngine);
}
catch (const exception& e)
{
appendTraceFile("Error during main loop.\n");
exit(EXIT_FAILURE);
}
appendTraceFile("before final file output\n");
if (fnames.savebest)
{
tempname2 = savename + "_best" + getFileNameSuffix(fnames.savebest);
writeSolution(puno, bestR, pu, tempname2, fnames.savebest, fnames);
appendTraceFile("Best solution is run %i\n", bestRun);
displayProgress1("\nBest solution is run %i\n", bestRun);
}
if (fnames.savespecies && fnames.savebest)
{
tempname2 = savename + "_mvbest" + getFileNameSuffix(fnames.savespecies);
// TODO ADBAI - need to write best spec, NOT spec_global
writeSpecies(spno, bestSpec, tempname2, fnames.savespecies, misslevel);
}
if (fnames.savesumsoln)
{
tempname2 = savename + "_ssoln" + getFileNameSuffix(fnames.savesumsoln);
writeSumSoln(puno, sumsoln, pu, tempname2, fnames.savesumsoln);
}
if (fnames.savesolutionsmatrix)
{
if (fnames.rexecutescript)
{
if (marxanIsSecondary == 1)
secondaryExit();
}
}
displayShutdownMessage(startTime);
appendTraceFile("end final file output\n");
appendTraceFile("\nMarxan end execution. Press any key to continue\n");
return 0;
} // executeMarxan
// handle command line parameters for the marxan executable
void handleOptions(int argc, char* argv[], string& sInputFileName, int& marxanIsSecondary)
{
if (argc > 4)
{ // if more than one commandline argument then exit
displayUsage(argv[0]);
exit(1);
}
for (int i = 1; i < argc; i++)
{ // Deal with all arguments
if (argv[i][0] == '/' || argv[i][0] == '-')
{
switch (argv[i][1])
{
case 'C':
case 'c':
case 'S':
case 's':
marxanIsSecondary = 1;
break;
default:
fprintf(stderr, "unknown option %s\n", argv[i]);
break;
}
}
else {
sInputFileName = argv[i]; /* If not a -option then must be input.dat name */
}
}
}
// marxan is running as a secondary process and has finished. create a sync file so the calling software will know marxan has finished creating the output files
// secondaryExit does not deliver a message prior to exiting, but creates a file so C-Plan/Zonae Cogito/etc knows marxan has exited
void secondaryExit(void)
{
writeSecondarySyncFile();
}
} // namespace marxan
// main needs to be defined outside of namespace
int main(int argc, char* argv[]) {
std::string sInputFileName = "input.dat";
// store application name
marxan::sApplicationPathName = argv[0];
if (argc > 1)
{
// handle the program options
marxan::handleOptions(argc, argv, sInputFileName, marxan::marxanIsSecondary);
}
try
{
if (marxan::executeMarxan(sInputFileName)) // Calls the main annealing unit
{
if (marxan::marxanIsSecondary == 1)
{
marxan::secondaryExit();
}
return 1;
} // Abnormal Exit
}
catch(const std::exception& e)
{
std::cerr << "Error during Marxan execution." << '\n';
exit(EXIT_FAILURE);
}
if (marxan::marxanIsSecondary == 1)
{
marxan::secondaryExit();
}
return 0;
} | 38.715084 | 206 | 0.579711 | hotzevzl |
782899f9988943c76c8561801486af2b8d52e4d9 | 854 | cc | C++ | src/bluetooth/bluetooth_extension.cc | izaman/tizen-extensions-crosswalk | e1373788f4e4e271e39b0fee66c26210e40dd86f | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2015-01-16T16:14:35.000Z | 2018-12-25T16:01:43.000Z | src/bluetooth/bluetooth_extension.cc | liyingzh/tizen-extensions-crosswalk | 5957945effafff02a507c35a4b7b4d5ee6ca14c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 35 | 2015-01-04T02:11:22.000Z | 2015-09-22T08:43:45.000Z | src/bluetooth/bluetooth_extension.cc | liyingzh/tizen-extensions-crosswalk | 5957945effafff02a507c35a4b7b4d5ee6ca14c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 14 | 2015-02-03T04:38:19.000Z | 2022-01-20T10:38:01.000Z | // Copyright (c) 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "bluetooth/bluetooth_extension.h"
#if defined(TIZEN_CAPI_BT)
#include "bluetooth/bluetooth_instance_capi.h"
#else
#include "bluetooth/bluetooth_instance.h"
#endif
common::Extension* CreateExtension() {
return new BluetoothExtension;
}
// This will be generated from bluetooth_api.js.
extern const char kSource_bluetooth_api[];
BluetoothExtension::BluetoothExtension() {
const char* entry_points[] = { NULL };
SetExtraJSEntryPoints(entry_points);
SetExtensionName("tizen.bluetooth");
SetJavaScriptAPI(kSource_bluetooth_api);
}
BluetoothExtension::~BluetoothExtension() {}
common::Instance* BluetoothExtension::CreateInstance() {
return new BluetoothInstance;
}
| 26.6875 | 73 | 0.779859 | izaman |
7829431a53fb619a77d9d90b26c090cf99083836 | 8,699 | cpp | C++ | HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp | HoverWings/IOTCommunicationTechnologyLabs | 376866db63086ddce39aae0d492cc6e95f3df1c1 | [
"MIT"
] | 1 | 2019-01-13T06:35:06.000Z | 2019-01-13T06:35:06.000Z | HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp | HoverWings/IOTCommunicationTechnologyLabs | 376866db63086ddce39aae0d492cc6e95f3df1c1 | [
"MIT"
] | null | null | null | HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp | HoverWings/IOTCommunicationTechnologyLabs | 376866db63086ddce39aae0d492cc6e95f3df1c1 | [
"MIT"
] | 1 | 2019-11-29T14:04:22.000Z | 2019-11-29T14:04:22.000Z | /* FileName: myping.cpp
* Author: Hover
* E-Mail: hover@hust.edu.cn
* GitHub: HoverWings
* Description: the Hover's impletation of ping
* Attention: you may need sudo to run this code
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
using namespace std;
#define MAX_WAIT_TIME 5
#define PACKET_SIZE 4096
int max_no_packets=5;
int interval=1;
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
pid_t pid;
int sockfd;
int datalen = 56;
int nsend = 0;
int nreceived = 0;
struct sockaddr_in dest_addr;
struct sockaddr_in from_addr;
struct timeval tvrecv;
vector<double> rtt_vec;
void statistics(int signo);
unsigned short cal_chksum(unsigned short *addr,int len);
int pack(int pack_no);
void send_packet(void);
void recv_packet(void);
int unpack(char *buf,int len);
void timediff(struct timeval *out,struct timeval *in);
bool opt_t = false; // set ttl
bool opt_i = false; // interval
void Stop(int signo)
{
statistics(signo);
_exit(0);
}
int main(int argc,char *argv[])
{
signal(SIGINT, Stop); //set exit function
char opt;
int option_index = 0;
static struct option long_options[] =
{
{"help", no_argument, NULL, 'h'}
};
char str[256];
strcpy(str,argv[1]);
while ((opt = getopt_long(argc, argv, "t:i:h", long_options, &option_index)) != -1)
{
//printf("%c",opt);
//cout<<argv[optind - 1];
switch (opt)
{
case 't':
max_no_packets=atoi(argv[optind - 1]);
opt_t = true;
break;
case 'i':
interval==atoi(argv[optind - 1]);
opt_i = true;
break;
case 'h':
opt_i = true;
break;
}
}
struct hostent *host; //host entry
struct protoent *protocol;
unsigned long inaddr = 0l;
int size = 50*1024; //50k
if(argc < 2)
{
printf("use : %s hostname/IP address \n", argv[0]);
exit(1);
}
if((protocol = getprotobyname("icmp")) == NULL)
{
perror("getprotobyname");
exit(1);
}
// setuid(getpid());
// need root to create socket
if((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0){
perror("socket error");
exit(1);
}
setuid(getuid()); // recycle root privilage
// case: broadcast address then there will be a lot of reply
// so the buf need enough size
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size) );
bzero(&dest_addr, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
// domain or address judge
printf("%s",str);
if((inaddr=inet_addr(str)) == INADDR_NONE)
{
if((host = gethostbyname(str)) == NULL)
{
perror("gethostbyname error");
exit(1);
}
memcpy((char*)&dest_addr.sin_addr, host->h_addr, host->h_length);
}
else
{
memcpy((char*)&dest_addr.sin_addr, (char*)&inaddr, sizeof(inaddr));
}
pid = getpid();
printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr), datalen);
send_packet();
statistics(SIGALRM);
return 0;
}
void statistics(int signo)
{
printf("\n--------------------PING statistics-------------------\n");
printf("%d packets transmitted, %d received , %%%d lost\n",nsend, nreceived, (nsend-nreceived)/nsend*100);
printf("rtt min/avg/max/mdev = ");
sort(rtt_vec.begin(), rtt_vec.end());
double min=rtt_vec.front();
double max=rtt_vec[rtt_vec.size()-1];
double total;
for(vector<double>::iterator iter=rtt_vec.begin();iter!=rtt_vec.end();iter++)
{
// cout << (*iter) << endl;
total+=*iter;
}
double avg=total/nsend;
double mdev=max-min;
cout<<fixed<<setprecision(3) <<min<<"/"<<avg<<"/"<<max<<"/"<<mdev<<"ms"<<endl;
close(sockfd);
exit(1);
}
/*
I: addr: check data buffer
check data len(byte)
*/
unsigned short cal_chksum(unsigned short *addr,int len)
{
int sum=0;
int nleft = len;
unsigned short *w = addr;
unsigned short answer = 0;
while(nleft > 1)
{
sum += *w++;
nleft -= 2;
}
//if the ICMP head len is odd, then the final data is high bit and add it
if(nleft == 1)
{
*(unsigned char *)(&answer) = *(unsigned char *)w;
sum += answer; //transfer answer to int
}
sum = (sum >> 16) + (sum & 0xffff); // add high bit and low bit
sum += (sum >> 16); // add overflow
answer = ~sum; // 16 bit checksum
return answer;
}
/*
I: icmp struct
sequence
O: packed icmp
*/
int pack(int pack_no)
{
int packsize;
struct icmp *icmp;
struct timeval *tval;
icmp = (struct icmp*)sendpacket;
icmp->icmp_type = ICMP_ECHO; // type of service
icmp->icmp_code = 0;
icmp->icmp_cksum = 0;
icmp->icmp_seq = pack_no;
icmp->icmp_id = pid;
packsize = 8 + datalen; //64=8(head)+56
tval = (struct timeval *)icmp->icmp_data; // 获得icmp结构中最后的数据部分的指针
gettimeofday(tval, NULL); // 将发送的时间填入icmp结构中最后的数据部分
icmp->icmp_cksum = cal_chksum((unsigned short *)icmp, packsize);/*填充发送方的校验和*/
return packsize;
}
void send_packet()
{
int packetsize;
while(nsend < max_no_packets)
{
nsend++;
packetsize = pack(nsend); // set ICMP message head
if(sendto(sockfd, sendpacket, packetsize, 0,(struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0)
{
perror("sendto error");
continue;
}
recv_packet();
sleep((uint)interval);
}
}
void recv_packet()
{
int n;
extern int errno;
signal(SIGALRM,statistics);
int from_len = sizeof(from_addr);
while(nreceived < nsend)
{
alarm(MAX_WAIT_TIME);
if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0,(struct sockaddr *)&from_addr, (socklen_t *)&from_len)) < 0)
{
if(errno == EINTR)
{
continue;
}
perror("recvfrom error");
continue;
}
gettimeofday(&tvrecv, NULL); // get receive time
if(unpack(recvpacket, n) == -1)
continue;
nreceived++;
}
}
/*
I:buf IP buf
len IP message len
addr ICMP dest address
O:error code
*/
int unpack(char *buf, int len)
{
int iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip = (struct ip *)buf;
iphdrlen = ip->ip_hl << 2; //ip head len
icmp = (struct icmp *)(buf + iphdrlen); // seek to IP message
len -= iphdrlen;
if(len < 8) // less than ICMP head len
{
printf("ICMP packets\'s length is less than 8\n");
return -1;
}
// check ICMP reply
if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == pid))
{
tvsend = (struct timeval *)icmp->icmp_data;
timediff(&tvrecv, tvsend);
rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0;
rtt_vec.push_back(rtt);
printf("%d byte from %s: icmp_seq=%u ttl=%d time=%.3f ms\n",
len, // total message len
inet_ntoa(from_addr.sin_addr),
icmp->icmp_seq,
ip->ip_ttl,
rtt); //ms rtt
return 0;
}
else
return -1;
}
/*
I:begin_time
endtime
O:ms diff
*/
void timediff(struct timeval *recv, struct timeval *send)
{
if((recv->tv_usec -= send->tv_usec) < 0)
{
--recv->tv_sec;
recv->tv_usec += 1000000;
}
recv->tv_sec -= send->tv_sec;
} | 26.440729 | 127 | 0.528911 | HoverWings |
782c86339a22a2846f37801e2431396073f7b918 | 1,279 | cpp | C++ | aws-cpp-sdk-lakeformation/source/model/DatabaseResource.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-lakeformation/source/model/DatabaseResource.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-lakeformation/source/model/DatabaseResource.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lakeformation/model/DatabaseResource.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LakeFormation
{
namespace Model
{
DatabaseResource::DatabaseResource() :
m_catalogIdHasBeenSet(false),
m_nameHasBeenSet(false)
{
}
DatabaseResource::DatabaseResource(JsonView jsonValue) :
m_catalogIdHasBeenSet(false),
m_nameHasBeenSet(false)
{
*this = jsonValue;
}
DatabaseResource& DatabaseResource::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("CatalogId"))
{
m_catalogId = jsonValue.GetString("CatalogId");
m_catalogIdHasBeenSet = true;
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
return *this;
}
JsonValue DatabaseResource::Jsonize() const
{
JsonValue payload;
if(m_catalogIdHasBeenSet)
{
payload.WithString("CatalogId", m_catalogId);
}
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
return payload;
}
} // namespace Model
} // namespace LakeFormation
} // namespace Aws
| 17.053333 | 69 | 0.716966 | Neusoft-Technology-Solutions |
782cd72175b8921fa2cb51cff5fb26574814e471 | 748 | hpp | C++ | src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp | pedrohsreis/boulos | a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e | [
"MIT"
] | 3 | 2018-09-18T18:05:05.000Z | 2019-10-23T17:47:07.000Z | src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp | pedrohsreis/boulos | a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e | [
"MIT"
] | 1 | 2020-06-08T18:48:32.000Z | 2020-06-19T21:41:16.000Z | src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp | pedrohsreis/boulos | a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e | [
"MIT"
] | 9 | 2018-09-11T17:19:16.000Z | 2019-07-30T16:43:56.000Z | #pragma once
#include "motion/generator/Generator.hpp"
class ClippedGenerator : Generator {
public:
explicit ClippedGenerator(Generator* g);
~ClippedGenerator();
virtual JointValues makeJoints(ActionCommand::All* request,
Odometry* odometry,
const SensorValues &sensors,
BodyModel &bodyModel,
float ballX,
float ballY);
virtual bool isActive();
void reset();
void readOptions(const boost::program_options::variables_map &config);
private:
Generator* generator;
JointValues old_j;
bool old_exists;
};
| 31.166667 | 76 | 0.536096 | pedrohsreis |
782d226c5d26f8f1df931900d2cc9c874fc226bb | 318 | cpp | C++ | Diameter Of Binary Tree .cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 2 | 2021-10-01T04:20:04.000Z | 2021-10-01T04:20:06.000Z | Diameter Of Binary Tree .cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 1 | 2021-10-01T18:00:09.000Z | 2021-10-01T18:00:09.000Z | Diameter Of Binary Tree .cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 8 | 2021-10-01T04:20:38.000Z | 2022-03-19T17:05:05.000Z | int diameterOfBinaryTree(TreeNode* root) {
int d=0;
rec(root, d);
return d;
}
int rec(TreeNode* root, int &d) {
if(root == NULL) return 0;
int ld = rec(root->left, d);
int rd = rec(root->right, d);
d=max(d,ld+rd);
return max(ld,rd)+1;
}
| 22.714286 | 42 | 0.477987 | Subhash3 |
782d63ef335a860c41b2b6f0ba060154c0ab87d0 | 3,456 | cpp | C++ | src/maiken/app.cpp | PhilipDeegan/mkn | 399dd01990e130c4deeb0c2800204836d3875ae9 | [
"BSD-3-Clause"
] | 3 | 2019-02-07T20:50:36.000Z | 2019-08-05T19:22:59.000Z | src/maiken/app.cpp | mkn/mkn | a05b542497270def02200df6620804b89429259b | [
"BSD-3-Clause"
] | null | null | null | src/maiken/app.cpp | mkn/mkn | a05b542497270def02200df6620804b89429259b | [
"BSD-3-Clause"
] | null | null | null | /**
Copyright (c) 2017, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiken/app.hpp"
#include "maiken/env.hpp"
maiken::Application* maiken::Applications::getOrCreate(maiken::Project const& proj,
std::string const& _profile, bool setup)
KTHROW(mkn::kul::Exception) {
std::string pDir(proj.dir().real());
std::string profile = _profile.empty() ? "@" : _profile;
if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) {
auto app = std::make_unique<Application>(proj, _profile);
auto pp = app.get();
m_appPs.push_back(std::move(app));
m_apps[pDir][profile] = pp;
if (setup) {
mkn::kul::os::PushDir pushd(proj.dir());
pp->setup();
}
}
return m_apps[pDir][profile];
}
maiken::Application* maiken::Applications::getOrCreateRoot(maiken::Project const& proj,
std::string const& _profile, bool setup)
KTHROW(mkn::kul::Exception) {
std::string pDir(proj.dir().real());
std::string profile = _profile.empty() ? "@" : _profile;
if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) {
auto* pp = getOrCreate(proj, _profile, /*setup = */ false);
pp->ro = 1;
if (setup) {
mkn::kul::os::PushDir pushd(proj.dir());
pp->setup();
}
}
return m_apps[pDir][profile];
}
maiken::Application* maiken::Applications::getOrNullptr(std::string const& project) {
uint32_t count = 0;
Application* app = nullptr;
for (auto const& p1 : m_apps)
for (auto const& p2 : p1.second) {
if (p2.second->project().root()[STR_NAME].Scalar() == project) {
count++;
app = p2.second;
}
}
if (count > 1) {
KEXIT(1, "Cannot deduce project version as")
<< " there are multiple versions in the dependency tree";
}
return app;
}
mkn::kul::cli::EnvVar maiken::Application::PARSE_ENV_NODE(YAML::Node const& n, Application const& app) {
return maiken::PARSE_ENV_NODE(n, app, app.project().file());
}
| 37.978022 | 104 | 0.688079 | PhilipDeegan |
782e5d07868a1bc4f1ef192aa6941837cf8123f8 | 114 | hpp | C++ | Music/OnMei/Pitch/OnDo/a_Alias.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Music/OnMei/Pitch/OnDo/a_Alias.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Music/OnMei/Pitch/OnDo/a_Alias.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Music/OnMei/Pitch/OnDo/a_Alias.hpp
#pragma once
using DoSuu = uint;
| 19 | 74 | 0.72807 | p-adic |
78316209795bf380740a4363ff6af1e88b0566b0 | 102,696 | cpp | C++ | genrollups/genrollups.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | genrollups/genrollups.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | genrollups/genrollups.cpp | rsuchecki/biokanga | ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e | [
"MIT"
] | null | null | null | // genrollups.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if _WIN32
#include "../libbiokanga/commhdrs.h"
#else
#include "../libbiokanga/commhdrs.h"
#endif
const unsigned int cProgVer = 304; // increment with each release
const int cRUmaxSpecies = 50; // max number of species handled
// Caution: check genhyperconserved before changing the following....
const int cMaxNumRangeClasses = 28; // max number of range classes
const int cMaxMatchDistSegments = 100; // max match distribution profile segments (applies if eProcModeOutspecies)
const int cMaxNumIdentityClasses = 101; // 0-100% identity classes
CStopWatch gStopWatch;
CDiagnostics gDiagnostics; // for writing diagnostics messages to log file
char gszProcName[_MAX_FNAME]; // process name
// user selects one of following bin class range sets with '-c<rangeclass>'
typedef enum eRCClass {
eRCCFull = 0, // 20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+
eRCCReduced, // 20-49,50-99,100-149,150-199,200-249,250-299,300+
eRCCMinimal, // 20-49,50-99,100-199,200-299,300+
eRCCMinimalA, // 20-99,100-199,200+
eRCCMinimalB, // 20-49,50-99,100+
eRCCMinimalC // 100+
} etRCClass;
// user selects one of following processing modes with '-m<mode>'
typedef enum eRPMode {
eRPMTotals = 0,
eRPMRegional,
eRPMLociBases,
eRPMLociRegional,
eRPMOutspeciesSummary
} etRPMode;
// user selects one of following generated results layout with '-l<layout>'
// only applies if processing mode is eRPMOutspeciesSummary
typedef enum eRPRsltLayout {
eRPRsltStandard = 0,
eRPRsltTable,
eRPRsltSegDistRows,
eRPRsltSegDistTables,
eRPRsltSegDistCols,
eRPRsltIdentDistCols,
eRPRsltRegionTableA,
eRPRsltRegionTable
} etRPRsltLayout;
// processing parameters passsed between functions
typedef struct TAG_sProcParams
{
etRPMode Mode; // processing mode
teFuncRegion Region; // genomic functional region to filter on
bool bSegsExcludeMatch; // true if cores which 100% match outspecies are to be excluded from segment distributions
etRCClass RangeClass; // into which range class characterisation
bool bPercentages; // output as percentages
int hRsltsFile; // results file handle
char *pszRsltsFile; // results file name
bool bHeaderOut; // true if results header has been written
etRPRsltLayout RsltsLayout; // layout format to use if processing eRPMOutspeciesSummary
int NumDistSegs; // number of distribution segments
int NumSpecies; // number of species in szSpecies following
char szSpecies[cRUmaxSpecies][cMaxDatasetSpeciesChrom]; // species names of interest
int Align2Core; // must be at least this number of bases in alignment to count as aligned to a core
double PCAlign2Core; // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 0%)");
double IDAlign2Core; // minimum identity (1..100) aligned to core to count as as aligned to core (default is 0%)");
double IDOSIdentity; // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)");
} tsProcParams;
int InitRangeClasses(etRCClass RangeClass);
char *RangeClass2Txt(etRCClass RangeClass);
int Process(etRPMode Mode, // processing mode
etRPRsltLayout RsltsLayout, // table layout to generate results into
bool bSegsExcludeMatch, // true if cores which 100% match outspecies are to be excluded from segment distributions
etRCClass RangeClass, // length range class
teFuncRegion Region, // process this genomic functional region
bool bPercentages, // results as percentages instead of counts
int Align2Core, // must be at least this number of bases in alignment to count as aligned to a core
double PCAlign2Core, // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 1%)");
double IDAlign2Core, // minimum identity (1..100) aligned to core to count as as aligned to core (default is 1%)");
double dIDOSIdentity, // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)");
char *pszInputFiles, // process from this/these inputfiles - can contain wildcards
char *pszOutputFile); // results into this file
bool ProcessThisFile(char *pszFile,void *pParams); // will be ptr to tsProcParams
int WriteRsltsHeader(tsProcParams *pParams);
int ParseFileNameSpecies(char *pszFile, // filename to parse for ref+rel species
char *pszClass, // user supplied buffer to hold element class (NULL allowed)
char *pszRefSpecies, // user supplied buffer to hold ref species name
char *pszRelSpecies, // user supplied buffer to hold rel species names
char *pszType); // user supplied buffer to hold element type (NULL allowed)
char *Mode2Text(etRPMode Mode);
char *Region2Text(int Region);
int ProcessLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams);
int ProcessLociLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams);
int ProcessRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams);
int ProcessLociRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams);
int ProcessOutspeciesSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams);
#ifdef _WIN32
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel; // level of screen diagnostics
int iFileLogLevel; // level of file diagnostics
char szLogFile[_MAX_PATH]; // write diagnostics to this file
int Rslt;
char szOutputFile[_MAX_PATH];
char szInputFile[_MAX_PATH];
etRPMode iMode;
int iRegion;
bool bPercentages;
etRCClass RangeClass;
bool bSegsExcludeMatch;
etRPRsltLayout iRsltsLayout; // out species processing file format to generate
int iAlign2Core; // at least this many bases aligned in outspecies for it to count as aligned to core
double dPCAlign2Core; // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 1%)");
double dIDAlign2Core; // minimum identity (1..100) aligned to core to count as as aligned to core (default is 1%)");
double dIDOSIdentity; // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)");
// command line args
struct arg_lit *help = arg_lit0("hH","help", "print this help and exit");
struct arg_lit *version = arg_lit0("v","version,ver", "print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_int *ScreenLogLevel=arg_int0("S", "ScreenLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>", "diagnostics log file");
struct arg_file *InFile = arg_file1("i",NULL,"<file>", "input from .csv files");
struct arg_file *OutFile = arg_file1("o",NULL,"<file>", "output to rollup statistics file as CSV");
struct arg_int *Mode = arg_int0("m","mode","<int>", "processing mode - 0:Totals,1:Regional,2:Loci bases Totals, 3: Loci bases Regional, 4: Outspecies totals");
struct arg_int *Region = arg_int0("r","region","<int>", "which region, 0:IG,1:5'US,2:5'UTR,3:CDS,4:Intronic,5:3'UTR,6:3'DS,7:All (default is 7:All)");
struct arg_lit *SegsExcludeMatch = arg_lit0("s","segsmatchprof","exclude 100% match cores in segment distribution profiles");
struct arg_lit *Percentages = arg_lit0("p","percent", "generate results as percentages");
struct arg_int *Range = arg_int0("c","binclass","<int>", "range bin class characterisation - 0: full, 1: reduced, 2: minimal, 3: UCSCUltra 200+");
struct arg_int *RsltsLayout = arg_int0("l","layout","<int>", "File layout for results if out species processing - 0: row values, 1: column values, 2: Segment Distribution rows, 3: Segment Distribution tables, 4: Segment Distribution columns, 5: core identity columns, 6: regions");
struct arg_int *Align2Core = arg_int0("a","align2core","<int>","minimum bases in outspecies for alignment to count as aligned to core (default is 1)");
struct arg_dbl *PCAlign2Core = arg_dbl0("P","pcalign2core","<dbl>","minimum percentage bases aligned to core to count as as aligned to core (default is 0%)");
struct arg_dbl *IDAlign2Core = arg_dbl0("A","idalign2core","<dbl>","minimum identity to count as as aligned to core (default is 0%)");
struct arg_dbl *IDOSIdentity = arg_dbl0("k","osidentity","<dbl>","minimum outspecies identity ,matches/(matches+mismatches), to count as as aligned to core (default is 0%)");
struct arg_end *end = arg_end(20);
void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile,
InFile,OutFile,
Mode,Region,SegsExcludeMatch,Percentages,Range,RsltsLayout,
Align2Core,PCAlign2Core,IDAlign2Core,IDOSIdentity,
end};
char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
argerrors = arg_parse(argerrors,pAllArgs,argtable);
/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
{
printf("\n%s ", gszProcName);
arg_print_syntax(stdout,argtable,"\n");
arg_print_glossary(stdout,argtable," %-25s %s\n");
printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
printf("\n To invoke this parameter file then precede its name with '@'");
printf("\n e.g. %s @myparams.txt\n\n",gszProcName);
exit(1);
}
/* special case: '--version' takes precedence error reporting */
if (version->count > 0)
{
printf("\n%s Version %d.%2.2d",gszProcName,cProgVer/100,cProgVer%100);
exit(1);
}
if (!argerrors)
{
iScreenLogLevel = ScreenLogLevel->count ? ScreenLogLevel->ival[0] : eDLInfo;
if(iScreenLogLevel < eDLNone || iScreenLogLevel > eDLDebug)
{
printf("\nError: ScreenLogLevel '-S%d' specified outside of range %d..%d",iScreenLogLevel,eDLNone,eDLDebug);
exit(1);
}
if(FileLogLevel->count && !LogFile->count)
{
printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
exit(1);
}
iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
{
printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
exit(1);
}
if(LogFile->count)
{
strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
szLogFile[_MAX_PATH-1] = '\0';
}
else
{
iFileLogLevel = eDLNone;
szLogFile[0] = '\0';
}
iMode = (etRPMode)(Mode->count ? Mode->ival[0] : eRPMTotals);
if(iMode < eRPMTotals || iMode > eRPMOutspeciesSummary)
{
printf("\nError: Processing mode '-m%d' is not supported\n",(int)iMode);
exit(1);
}
if(iMode == eRPMRegional || iMode == eRPMLociRegional)
{
iRegion = Region->count ? Region->ival[0] : eFRAuto;
if(iRegion < eFRIntergenic || iRegion > eFRAuto)
{
printf("\nError: Region '-r%d' is not supported\n",iRegion);
exit(1);
}
}
else
iRegion = eFRAuto;
if(iMode == eRPMOutspeciesSummary)
{
iRsltsLayout = RsltsLayout->count ? (etRPRsltLayout)RsltsLayout->ival[0] : eRPRsltStandard;
if(iRsltsLayout < eRPRsltStandard || iRsltsLayout > eRPRsltRegionTable)
{
printf("\nError: Results layout format '-x%d' is not supported\n",iRsltsLayout);
exit(1);
}
iAlign2Core = Align2Core->count ? Align2Core->ival[0] : 1;
if(iAlign2Core < 1)
{
printf("\nError: Aligned bases to core '-a%d' must be >= 1",iAlign2Core);
exit(1);
}
dPCAlign2Core = PCAlign2Core->count ? PCAlign2Core->dval[0] : 0.0;
if(dPCAlign2Core < 0.0 || dPCAlign2Core > 100.0)
{
printf("\nError: Minimum percentage aligned bases to core '-P%f' must be in range 0.0 to 100.0",dPCAlign2Core);
exit(1);
}
dIDAlign2Core = IDAlign2Core->count ? IDAlign2Core->dval[0] : 0.0;
if(dIDAlign2Core < 0.0 || dIDAlign2Core > 100.0)
{
printf("\nError: Minimum identity to core '-A%f' must be in range 0.0 to 100.0",dIDAlign2Core);
exit(1);
}
dIDOSIdentity = IDOSIdentity->count ? IDOSIdentity->dval[0] : 0.0;
if(dIDOSIdentity < 0.0 || dIDOSIdentity > 100.0)
{
printf("\nError: Minimum outspecies identity '-k%f' must be in range 0.0 to 100.0",dIDOSIdentity);
exit(1);
}
}
else
{
iRsltsLayout = eRPRsltStandard;
iAlign2Core = 1;
dIDAlign2Core = 0.0;
dPCAlign2Core = 0.0;
dIDOSIdentity = 0.0;
}
bSegsExcludeMatch = SegsExcludeMatch->count ? true : false;
RangeClass = Range->count ? (etRCClass)Range->ival[0] : eRCCFull;
if(RangeClass < eRCCFull || RangeClass > eRCCMinimalC)
{
printf("\nError: Range class characterisation '-c%d' is not supported\n",RangeClass);
exit(1);
}
if(!InFile->count)
{
printf("\nError: Input files to process '-i<inputfilespec>' is not specified\n");
exit(1);
}
strcpy(szInputFile,InFile->filename[0]);
if(!OutFile->count)
{
printf("\nError: Output file to generate '-o<outputfilespec>' is not specified\n");
exit(1);
}
strcpy(szOutputFile,OutFile->filename[0]);
bPercentages = Percentages->count ? true : false;
// now that command parameters have been parsed then initialise diagnostics log system
if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
{
printf("\nError: Unable to start diagnostics subsystem.");
if(szLogFile[0] != '\0')
printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
exit(1);
}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %d.%2.2d Processing parameters:",cProgVer/100,cProgVer%100);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing Mode: '%s'",Mode2Text(iMode));
if(iMode == eRPMOutspeciesSummary)
{
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Segment distribution profiles to exclude 100%% identity cores: %s",
bSegsExcludeMatch ? "yes" : "no");
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Generated processed results layout format: %d",iRsltsLayout);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Alignments must have at least : %d bases",iAlign2Core);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum percentage bases must be least : %1.2f%% ",dPCAlign2Core);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum identity at least : %1.2f%%",dIDAlign2Core);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum outspecies identity at least : %1.2f%%",dIDOSIdentity);
}
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Range Classes: %s",RangeClass2Txt(RangeClass));
if(iMode == eRPMRegional || iMode == eRPMLociRegional)
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Region: %d - '%s'",iMode,Region2Text(iRegion));
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Results as percentages: '%s'",bPercentages ? "yes" : "no");
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input filespec: '%s'",szInputFile);
gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output file: '%s'",szOutputFile);
gStopWatch.Start();
#ifdef _WIN32
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
Rslt = Process(iMode,iRsltsLayout,bSegsExcludeMatch,RangeClass,(teFuncRegion)iRegion,bPercentages,iAlign2Core,dPCAlign2Core,dIDAlign2Core,dIDOSIdentity,szInputFile,szOutputFile);
gStopWatch.Stop();
Rslt = Rslt < 0 ? 1 : 0;
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit Code: %d Total processing time: %s",Rslt,gStopWatch.Read());
exit(Rslt);
}
else
{
arg_print_errors(stdout,end,gszProcName);
arg_print_syntax(stdout,argtable,"\nend of help\n");
exit(1);
}
}
char *
RangeClass2Txt(etRCClass RangeClass)
{
switch(RangeClass) {
case eRCCFull: return((char *)"20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+");
case eRCCReduced: return((char *)"20-49,50-99,100-149,150-199,200-249,250-299,300+");
case eRCCMinimal: return((char *)"20-49,50-99,100-199,200-299,300+");
case eRCCMinimalA: return((char *)"20-99,100-199,200+");
case eRCCMinimalB: return((char *)"20-49,50-99,100+");
case eRCCMinimalC: return((char *)"100+");
default: return((char *)"Undefined");
}
}
int Process(etRPMode Mode, // processing mode
etRPRsltLayout RsltsLayout, // table layout to generate results into
bool bSegsExcludeMatch, // true if cores which 100% match outspecies are to be excluded from segment distributions
etRCClass RangeClass, // length range class
teFuncRegion Region, // process this genomic functional region
bool bPercentages, // results as percentages instead of counts
int Align2Core, // must be at least this many bases in alignment to count as an alignment
double PCAlign2Core, // minimum percentage (0..100) aligned to core to count as as aligned to core (default is 0%)");
double IDAlign2Core, // minimum identity (0..100) aligned to core to count as as aligned to core (default is 0%)");
double IDOSIdentity, // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 0%)");
char *pszInputFiles, // process from this/these inputfiles - can contain wildcards
char *pszOutputFile) // results into this file
{
int Rslt;
char szDirPath[_MAX_PATH];
char szFileSpec[_MAX_PATH];
#ifndef _WIN32
struct stat FileStat;
#endif
tsProcParams ProcParams;
memset(&ProcParams,0,sizeof(tsProcParams));
ProcParams.Mode = Mode;
ProcParams.RsltsLayout = RsltsLayout;
ProcParams.bSegsExcludeMatch = bSegsExcludeMatch;
ProcParams.RangeClass = RangeClass;
ProcParams.pszRsltsFile = pszOutputFile;
ProcParams.bPercentages = bPercentages;
ProcParams.Align2Core = Align2Core;
ProcParams.PCAlign2Core = PCAlign2Core;
ProcParams.IDAlign2Core= IDAlign2Core;
ProcParams.IDOSIdentity = IDOSIdentity;
#ifdef _WIN32
char szDrive[_MAX_DRIVE];
char szDir[_MAX_DIR];
char szFname[_MAX_FNAME];
char szExt[_MAX_EXT];
_splitpath(pszInputFiles,szDrive,szDir,szFname,szExt);
_makepath(szDirPath,szDrive,szDir,"","");
if(!szFname[0])
strcpy(szFname,"*");
if(!szExt[0])
strcpy(szExt,".*");
sprintf(szFileSpec,"%s%s",szFname,szExt);
#else
CUtility::splitpath(pszInputFiles,szDirPath,szFileSpec);
if(!szFileSpec[0])
strcpy(szFileSpec,"*");
#endif
#ifdef _WIN32
if((ProcParams.hRsltsFile = open(pszOutputFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1)
#else
if((ProcParams.hRsltsFile = open(pszOutputFile,O_RDWR | O_CREAT |O_TRUNC, S_IREAD | S_IWRITE ))==-1)
#endif
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to create %s - %s",pszOutputFile,strerror(errno));
return(eBSFerrCreateFile);
}
ProcParams.Region = Region;
if((Mode == eRPMRegional || Mode == eRPMLociRegional) && Region == eFRAuto) // process all regions
{
Rslt = eBSFSuccess;
for(int iRegion = eFRIntergenic; iRegion <= eFRDnstream; iRegion++)
{
ProcParams.Region = (teFuncRegion)iRegion;
CSimpleGlob glob(SG_GLOB_FULLSORT);
if (glob.Add(pszInputFiles) >= SG_SUCCESS)
{
for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n)
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Will process in this order: %d '%s", n+1,glob.File(n));
for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n)
Rslt = ProcessThisFile(glob.File(n),&ProcParams);
}
else
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to glob '%s",pszInputFiles);
Rslt = eBSFerrOpnFile; // treat as though unable to open file
}
if(Rslt < eBSFSuccess)
break;
}
}
else
{
Rslt = eBSFSuccess;
CSimpleGlob glob(SG_GLOB_FULLSORT);
if (glob.Add(pszInputFiles) >= SG_SUCCESS)
{
for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n)
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Will process in this order: %d '%s", n+1,glob.File(n));
for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n)
Rslt = ProcessThisFile(glob.File(n),&ProcParams);
}
else
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to glob '%s",pszInputFiles);
Rslt = eBSFerrOpnFile; // treat as though unable to open file
}
}
if(ProcParams.hRsltsFile != -1)
close(ProcParams.hRsltsFile);
return(Rslt);
}
bool
ProcessThisFile(char *pszFile,void *pParams)
{
tsProcParams *pProcParams = (tsProcParams *)pParams;
CCSVFile *pCSV = new CCSVFile;
int Rslt;
InitRangeClasses(pProcParams->RangeClass);
pCSV->SetMaxFields(15 + (cMaxMatchDistSegments*4));
if((Rslt=pCSV->Open(pszFile))!=eBSFSuccess)
{
while(pCSV->NumErrMsgs())
gDiagnostics.DiagOut(eDLFatal,gszProcName,pCSV->GetErrMsg());
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open file: %s",pszFile);
return(false);
}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing File: %s",pszFile);
switch(pProcParams->Mode) {
case eRPMTotals: // process length summary files
Rslt = ProcessLengthSummary(pszFile,pCSV,pProcParams);
break;
case eRPMRegional:
Rslt = ProcessRegionalLengthSummary(pszFile,pCSV,pProcParams);
break;
case eRPMLociBases: // process loci length summary files
Rslt = ProcessLociLengthSummary(pszFile,pCSV,pProcParams);
break;
case eRPMLociRegional:
Rslt = ProcessLociRegionalLengthSummary(pszFile,pCSV,pProcParams);
break;
case eRPMOutspeciesSummary:
Rslt = ProcessOutspeciesSummary(pszFile,pCSV,pProcParams);
break;
}
delete pCSV;
return(Rslt >= eBSFSuccess ? true : false);
}
// ParseFileNameSpecies
// parse filename to determine reference and relative species --- UGH!!!
// Expected filename format is -
// <Class><RefSpecies><RelSpecies>_<Type>*.csv
// <Class> 'L' or 'S' but could be some other single char
// <RefSpecies> species name with the last one or two chars digits e.g. hg17
// <RelSpecies> concatenated species names, last species name is terminated by an underscore '_'
// <Type> currently 'u' for ultra or 'h' for hyper
int
ParseFileNameSpecies(char *pszFile, // filename to parse for ref+rel species
char *pszClass, // user supplied buffer to hold element class
char *pszRefSpecies, // user supplied buffer to hold ref species name
char *pszRelSpecies, // user supplied buffer to hold rel species names
char *pszType) // user supplied buffer to hold element type
{
char *pSrcChr;
char *pDstChr;
char Chr;
bool bParseRef;
bool bParsedRef;
bool bParseRel;
bool bParsedRel;
bool bDigit;
char szFname[256];
char szDir[256];
#ifdef _WIN32
char szDrive[_MAX_DRIVE];
char szExt[_MAX_EXT];
_splitpath(pszFile,szDrive,szDir,szFname,szExt);
#else
CUtility::splitpath(pszFile,szDir,szFname);
#endif
if(pszClass != NULL)
switch(szFname[0]) {
case 's': case 'S':
strcpy(pszClass,"summary");
break;
case 'l': case 'L':
strcpy(pszClass,"loci");
break;
default:
*pszClass = szFname[0];
pszClass[1] = '\0';
break;
}
pSrcChr = &szFname[1];
pDstChr = pszRefSpecies;
bParseRef = true;
bParsedRef = false;
bParseRel = false;
bParsedRel = false;
bDigit = false;
*pszRefSpecies = '\0';
*pszRelSpecies = '\0';
while(Chr = *pSrcChr++)
{
if(Chr == '_')
{
bParsedRel = true;
*pDstChr = '\0';
if(pszType != NULL)
{
if((Chr = *pSrcChr) == '\0')
{
*pszType = '?';
pszType[1] = '\0';
}
else
switch(Chr) {
case 'u': case 'U':
strcpy(pszType,"ultra");
break;
case 'h': case 'H':
strcpy(pszType,"hyper");
break;
default:
*pszType = Chr;
pszType[1] = '\0';
break;
}
}
break;
}
if(bParseRef)
{
if(Chr >= '0' && Chr <= '9')
bDigit = true;
else
{
if(bDigit) // was previously parsing digits but not now then that means rel species starting
{
*pDstChr = '\0';
bParseRef = false;
bParsedRef = true;
bParseRel = true;
pDstChr = pszRelSpecies;
}
}
}
*pDstChr++ = Chr;
}
if(!(bParsedRef && bParsedRel))
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to parse filename '%s' into ref+rel species names",szFname);
return(eBSFerrFileName);
}
return(eBSFSuccess);
}
// ParseNumSpecies
// Initialises pProcParams with parsed species names in space or comma delimited list ptd at by pszSpeciesList
// Returns number of species
int
ParseNumSpecies(char *pszSpeciesList,tsProcParams *pProcParams)
{
// parse out species list
char Chr;
char *pSpecies;
int NumSpecies = 0;
bool InToken = false;
if(pszSpeciesList == NULL || *pszSpeciesList == '\0')
return(0);
while(Chr = *pszSpeciesList++)
{
if(Chr == '"' || Chr == '\'') // change any single or double quotes into spaces
Chr = ' ';
if(isspace(Chr) || Chr==',')
{
if(!InToken) // slough whitespace or ',' if not inside a token parse
continue;
InToken = false;
pszSpeciesList[-1] = '\0';
if(pProcParams != NULL)
{
strncpy(pProcParams->szSpecies[NumSpecies],pSpecies,cMaxDatasetSpeciesChrom);
pProcParams->szSpecies[NumSpecies][cMaxDatasetSpeciesChrom-1] = '\0';
}
pszSpeciesList[-1] = Chr;
NumSpecies++;
if(NumSpecies >= cRUmaxSpecies)
break;
continue;
}
if(!InToken) // if not already inside token then start token
{
pSpecies = pszSpeciesList-1;
InToken = true;
}
}
if(InToken)
{
pszSpeciesList[-1] = '\0';
if(pProcParams != NULL)
{
strncpy(pProcParams->szSpecies[NumSpecies],pSpecies,cMaxDatasetSpeciesChrom);
pProcParams->szSpecies[NumSpecies][cMaxDatasetSpeciesChrom-1] = '\0';
}
pszSpeciesList[-1] = Chr;
NumSpecies++;
}
return(NumSpecies);
}
char *
Mode2Text(etRPMode Mode)
{
switch(Mode) {
case eRPMTotals:
return((char *)"Totals summary");
case eRPMRegional:
return((char *)"Regional summary");
case eRPMLociBases:
return((char *)"Loci bases Totals summary");
case eRPMLociRegional:
return((char *)"Loci bases Regional summary");
case eRPMOutspeciesSummary:
return((char *)"Out species summary");
default:
break;
}
gDiagnostics.DiagOut(eDLInfo,gszProcName,"Unsupported processing mode '%d' requested",(int)Mode);
return((char *)"Unsupported");
}
// Regions can be overlapping
// feature bits - note that features can concurrently overlap multiple gene components
// bit 0 (0x01) part of feature overlaps CDS
// bit 1 (0x02) part of feature overlaps 5'UTR
// bit 2 (0x04) part of feature overlaps 3'UTR
// bit 3 (0x08) part of feature overlaps Intron
// bit 4 (0x10) part of feature overlaps 5'upstream regulatory
// bit 5 (0x20) part of feature overlaps 3'downstream regulatory
// bit 6 (x040) part of feature overlaps intron5'/3'exon splice site
// bit 7 (0x80) part of feature overlaps exon5'/3'intron splice site
// Normalise regions maps regions into a logical index
// Intergenic -> 0
// US -> 1
// 5'UTR -> 2
// CDS -> 3
// INTRON -> 4
// 3'UTR -> 5
// DS -> 6
int
NormaliseRegion(int Region)
{
if(Region & cFeatBitCDS)
return(eFRCDS); // CDS
if(Region & cFeatBit5UTR)
return(eFR5UTR); // 5'UTR
if(Region & cFeatBit3UTR)
return(eFR3UTR); // 3'UTR
if(Region & cFeatBitIntrons)
return(eFRIntronic); // Intron
if(Region & cFeatBitUpstream)
return(eFRUpstream); // 5'US
if(Region & cFeatBitDnstream)
return(eFRDnstream); // 3'DS
return(eFRIntergenic); // IG
}
char *
Region2Text(int Region)
{
switch(Region) {
case 0:
return((char *)"IG");
case 1:
return((char *)"US");
case 2:
return((char *)"5'UTR");
case 3:
return((char *)"CDS");
case 4:
return((char *)"INTRON");
case 5:
return((char *)"3'UTR");
case 6:
return((char *)"DS");
case 7:
return((char *)"ANY");
default:
break;
}
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unsupported region '%d' requested",Region);
return((char *)"Unsupported");
}
int
WriteRsltsHeader(tsProcParams *pParams)
{
char szLineBuff[2048];
int Len;
int SegIdx;
if(pParams->bHeaderOut) // if header already written?
return(eBSFSuccess);
if(pParams->hRsltsFile == -1)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Results file '%s' was closed when called to write headers",pParams->pszRsltsFile);
return(eBSFerrFileClosed);
}
switch(pParams->Mode) {
case eRPMTotals: case eRPMLociBases:
Len = sprintf(szLineBuff,"\"ElType\",\"Ref Species\",\"Rel Species\",\"Total\"");
break;
case eRPMRegional: case eRPMLociRegional:
Len = sprintf(szLineBuff,"\"ElType\",\"Ref Species\",\"Rel Species\",\"Region\",\"Total\"");
break;
case eRPMOutspeciesSummary:
switch(pParams->RsltsLayout) {
case eRPRsltStandard:
Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"Region\",\"Qualifier\",\"Name\",\"Value\"\n");
break;
case eRPRsltTable:
Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"Aligned Core %%\",\"Aligned Bases\",\"Aligned Mismatches\",\"Aligned Identical\",\"Aligned Identity\"\n");
break;
case eRPRsltSegDistRows:
Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\"");
for(SegIdx = 0; SegIdx < pParams->NumDistSegs; SegIdx++)
Len += sprintf(&szLineBuff[Len],",\"Seg%dMatches\",\"Seg%dMismatches\",\"Seg%dInDels\",\"Seg%dUnaligns\"",
SegIdx+1,SegIdx+1,SegIdx+1,SegIdx+1);
Len += sprintf(&szLineBuff[Len],"\n");
break;
case eRPRsltSegDistTables:
Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Category\"");
for(SegIdx = 1; SegIdx <= pParams->NumDistSegs; SegIdx++)
Len += sprintf(&szLineBuff[Len],",\"Segment%d\"",SegIdx);
Len += sprintf(&szLineBuff[Len],"\n");
break;
case eRPRsltSegDistCols:
Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Segment\",\"Matches\",\"Mismatches\",\"InDels\",\"Unaligned\"\n");
break;
case eRPRsltIdentDistCols:
Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Core Instances\",\"OG Instances\",\"Identity\",\"OG Identity Instances\"\n");
break;
case eRPRsltRegionTable:
Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"IG\",\"US\",\"5'UTR\",\"CDS\",\"INTRON\",\"3'UTR\",\"DS\",\"5'ExSplice\",\"3'ExSplice\"\n");
break;
case eRPRsltRegionTableA:
Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"IG\",\"US\",\"5'UTR\",\"CDS\",\"INTRON\",\"3'UTR\",\"DS\",\"5'ExSplice\",\"3'ExSplice\",\"Excl IG\",\"Excl US\",\"Excl 5'UTR\",\"Excl CDS\",\"Excl INTRON\",\"Excl 3'UTR\",\"Excl DS\",\"Splice Sites\"\n");
break;
default:
Len = sprintf(szLineBuff,",\"Illegal Layout\"\n");
break;
}
break;
default:
Len = sprintf(szLineBuff,",\"Illegal Mode\"");
}
if(pParams->Mode != eRPMOutspeciesSummary)
switch(pParams->RangeClass) {
case eRCCFull:
Len += sprintf(&szLineBuff[Len],",\"20-29\",\"30-49\",\"50-74\",\"75-99\",\"100-124\",\"125-149\",\"150-174\",\"175-199\"");
Len += sprintf(&szLineBuff[Len],",\"200-249\",\"250-299\",\"300-349\",\"350-399\",\"400-449\",\"450-499\"");
Len += sprintf(&szLineBuff[Len],",\"500-599\",\"600-699\",\"700-799\",\"800-899\",\"900-999\"");
Len += sprintf(&szLineBuff[Len],",\"1000-1249\",\"1250-1499\",\"1500-1749\",\"1750-1999\",\"2000+\"");
break;
case eRCCReduced:
Len += sprintf(&szLineBuff[Len],",\"20-49\",\"50-99\",\"100-149\",\"150-199\",\"200-249\",\"250-299\",\"300+\"");
break;
case eRCCMinimal:
Len += sprintf(&szLineBuff[Len],",\"20-49\",\"50-99\",\"100-199\",\"200-299\",\"300+\"");
break;
case eRCCMinimalA:
Len += sprintf(&szLineBuff[Len],",\"20-99\",\"100-199\",\"200+\"");
break;
case eRCCMinimalB:
Len += sprintf(&szLineBuff[Len],",\"20-49\",\"59-99\",\"100+\"");
break;
case eRCCMinimalC:
Len += sprintf(&szLineBuff[Len],",\"100+\"");
break;
default:
Len += sprintf(&szLineBuff[Len],",\"Illegal Range Class\"");
break;
}
if(Len && (write(pParams->hRsltsFile,szLineBuff,Len)!=Len))
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
pParams->bHeaderOut = true;
return(eBSFSuccess);
}
int
ProcessLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams)
{
int Rslt;
int NumRows;
int NumFields;
int Len;
char *pszRange;
int RangeCnt;
int Total;
int Totals[cMaxNumRangeClasses]; // to hold all totals
int Idx;
char szLineBuff[2048];
char szRefSpecies[200];
char szRelSpecies[200];
char szElementType[20];
if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess)
return(Rslt);
// Skip first row as that contains titles
if((Rslt=pCSV->NextLine())<12)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 header fields in 1st row of '%s', NextLine returned '%d'",pszFile,Rslt);
return(eBSFerrFieldCnt);
}
// subsequent rows contain fields of interest
memset(Totals,0,sizeof(Totals));
NumRows = 0;
Total = 0;
while((Rslt=pCSV->NextLine()) == 12) // onto next line containing fields
{
if(NumRows == cMaxNumRangeClasses)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected only 28 rows (plus header) in '%s', file has more rows",pszFile);
return(eBSFerrRowCnt);
}
NumFields = pCSV->GetCurFields();
if(NumFields != 12)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 12 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields);
return(eBSFerrFieldCnt);
}
pCSV->GetText(1,&pszRange);
pCSV->GetInt(3,&RangeCnt);
switch(pParams->RangeClass) {
case eRCCFull:
Totals[NumRows] = RangeCnt;
break;
case eRCCReduced:
switch(NumRows) {
case 0: // 0-4
Totals[0] = RangeCnt;
break;
case 1: // 5-9
Totals[0] += RangeCnt;
break;
case 2: // 10-14
Totals[1] = RangeCnt;
break;
case 3: // 15-19
Totals[1] += RangeCnt;
break;
case 4: // 20-29
Totals[2] = RangeCnt;
break;
case 5: // 30-49
Totals[2] += RangeCnt;
break;
case 6: // 50-74
Totals[3] = RangeCnt;
break;
case 7: // 75-99
Totals[3] += RangeCnt;
break;
case 8: // 100-124
Totals[4] = RangeCnt;
break;
case 9: // 125-149
Totals[4] += RangeCnt;
break;
case 10: // 150-174
Totals[5] = RangeCnt;
break;
case 11: // 175-199
Totals[5] += RangeCnt;
break;
case 12: // 200-249
Totals[6] = RangeCnt;
break;
case 13: // 250-300
Totals[7] = RangeCnt;
Totals[8] = 0;
break;
default:
Totals[8] += RangeCnt;
break;
}
break;
case eRCCMinimal:
switch(NumRows) {
case 0: // 0-4
Totals[0] += RangeCnt;
break;
case 1: case 2: case 3: // 5-9, 10-14,15-19
Totals[0] += RangeCnt;
break;
case 4: // 20-29
Totals[1] += RangeCnt;
break;
case 5: // 30-49
Totals[1] += RangeCnt;
break;
case 6: // 50-74
Totals[2] += RangeCnt;
break;
case 7: // 75-99
Totals[2] += RangeCnt;
break;
case 8: // 100-124
Totals[3] += RangeCnt;
break;
case 9: case 10: case 11: // 125-149, 150-174,175-199
Totals[3] += RangeCnt;
break;
case 12: // 200-249
Totals[4] = RangeCnt;
break;
case 13: // 250-300
Totals[4] += RangeCnt;
break;
default:
Totals[5] += RangeCnt;
break;
}
break;
case eRCCMinimalA:
switch(NumRows) {
case 0: case 1: case 2: case 3: // 0-20
Totals[0] += RangeCnt;
break;
case 4: case 5: case 6: case 7: // 20-99
Totals[1] += RangeCnt;
break;
case 8: case 9: case 10: case 11: // 100-199
Totals[2] += RangeCnt;
break;
default:
Totals[3] += RangeCnt;
break;
}
break;
case eRCCMinimalB:
switch(NumRows) {
case 0: case 1: case 2: case 3: // 0-20
Totals[0] += RangeCnt;
break;
case 4: case 5: // 20-49
Totals[1] += RangeCnt;
break;
case 6: case 7: // 50-99
Totals[2] += RangeCnt;
break;
default: // 100+
Totals[3] += RangeCnt;
break;
}
break;
case eRCCMinimalC:
switch(NumRows) {
case 0: case 1: case 2: case 3: // 0-20
case 4: case 5: // 20-49
case 6: case 7: // 50-99
break;
default: // 100+
Totals[0] += RangeCnt;
break;
}
break;
}
NumRows++;
}
if(NumRows != cMaxNumRangeClasses)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 28 rows (plus header) in '%s', only '%d' parsed",pszFile,NumRows);
return(eBSFerrRowCnt);
}
switch(pParams->RangeClass) {
case eRCCFull:
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCReduced:
for(Idx = 2; Idx < 9; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 2; Idx < 9; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimal:
for(Idx = 1; Idx < 6; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 6; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalA:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalB:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalC:
Total += Totals[0];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]);
break;
default:
Len=sprintf(szLineBuff,",-1");
break;
}
WriteRsltsHeader(pParams);
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
typedef struct TAG_sLenRangeClass {
int ID; // uniquely identifies this range
int Min; // minimum length in this range
int Max; // maximum length in this range
const char *pszDescr; // descriptive text
}tsLenRangeClass;
// length range classes
tsLenRangeClass LenRangeClassesFull[] = {
{1,0,4,"0-4"},
{2,5,9,"5-9"},
{3,10,14,"10-14"},
{4,15,19,"15-19"},
{5,20,29,"20-29"},
{6,30,49,"30-49"},
{7,50,74,"50-74"},
{8,75,99,"75-99"},
{9,100,124,"100-124"},
{10,125,149,"125-149"},
{11,150,174,"150-174"},
{12,175,199,"175-199"},
{13,200,249,"200-249"},
{14,250,299,"250-299"},
{15,300,349,"300-349"},
{16,350,399,"350-399"},
{17,400,449,"400-449"},
{18,450,499,"450-499"},
{19,500,599,"500-599"},
{20,600,699,"600-699"},
{21,700,799,"700-799"},
{22,800,899,"800-899"},
{23,900,999,"900-999"},
{24,1000,1249,"1000-1249"},
{25,1250,1499,"1250-1499"},
{26,1500,1749,"1500-1749"},
{27,1750,1999,"1750-1999"},
{28,2000,INT_MAX,"2000+"}
};
const int cLenRangesFull = sizeof(LenRangeClassesFull)/sizeof(tsLenRangeClass); // number of length range classes
tsLenRangeClass LenRangeClassesReduced[] = {
{1,0,9,"0-9"},
{2,10,19,"10-19"},
{3,20,49,"20-49"},
{4,50,99,"50-99"},
{5,100,149,"100-149"},
{6,150,199,"150-199"},
{7,200,249,"200-249"},
{8,250,299,"250-299"},
{9,300,INT_MAX,"300+"}
};
const int cLenRangesReduced = sizeof(LenRangeClassesReduced)/sizeof(tsLenRangeClass); // number of length range classes
tsLenRangeClass LenRangeClassesMinimal[] = {
{1,0,19,"0-19"},
{2,20,49,"20-49"},
{3,50,99,"50-99"},
{4,100,199,"100-199"},
{5,200,299,"200-299"},
{6,300,INT_MAX,"300+"}
};
const int cLenRangesMinimal = sizeof(LenRangeClassesMinimal)/sizeof(tsLenRangeClass);
tsLenRangeClass LenRangeClassesMinimalA[] = {
{1,0,19,"0-19"},
{2,20,99,"20-99"},
{3,100,199,"100-199"},
{4,200,INT_MAX,"200+"}
};
const int cLenRangesMinimalA = sizeof(LenRangeClassesMinimalA)/sizeof(tsLenRangeClass);
tsLenRangeClass LenRangeClassesMinimalB[] = {
{1,0,19,"0-19"},
{2,20,49,"20-49"},
{3,50,99,"50-99"},
{4,100,INT_MAX,"100+"}
};
const int cLenRangesMinimalB = sizeof(LenRangeClassesMinimalB)/sizeof(tsLenRangeClass);
tsLenRangeClass LenRangeClassesMinimalC[] = {
{1,100,INT_MAX,"100+"}
};
const int cLenRangesMinimalC = sizeof(LenRangeClassesMinimalC)/sizeof(tsLenRangeClass);
tsLenRangeClass *pLenRangeClasses = LenRangeClassesFull;
int NumLenRanges = cLenRangesFull;
int // returns number of ranges
InitRangeClasses(etRCClass RangeClass)
{
switch(RangeClass) {
case eRCCFull: // 20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+
pLenRangeClasses = LenRangeClassesFull;
NumLenRanges = cLenRangesFull;
break;
case eRCCReduced: // 20-49,50-99,100-149,150-199,200-249,250-299,300+
pLenRangeClasses = LenRangeClassesReduced;
NumLenRanges = cLenRangesReduced;
break;
case eRCCMinimal: // 20-49,50-99,100-199,200-299,300+
pLenRangeClasses = LenRangeClassesMinimal;
NumLenRanges = cLenRangesMinimal;
break;
case eRCCMinimalA: // 20-99,100-199,200+
pLenRangeClasses = LenRangeClassesMinimalA;
NumLenRanges = cLenRangesMinimalA;
break;
case eRCCMinimalB: // 20-49,50-99,100+
pLenRangeClasses = LenRangeClassesMinimalB;
NumLenRanges = cLenRangesMinimalB;
break;
case eRCCMinimalC: // 100+
pLenRangeClasses = LenRangeClassesMinimalC;
NumLenRanges = cLenRangesMinimalC;
break;
default:
return(-1);
}
return(NumLenRanges);
}
// GetLengthRangeClass
// Returns ptr to length range class for specified Length, or NULL if can't classify into a range
tsLenRangeClass *GetLengthRangeClass(int Length)
{
int Idx;
tsLenRangeClass *pRange = pLenRangeClasses;
for(Idx = 0; Idx < NumLenRanges; Idx++,pRange++)
if(Length >= pRange->Min && Length <= pRange->Max)
return(pRange);
return(NULL);
}
// Expected CSV format
// ElementID Uniquely identifies this element (1..n)
// CoreType Currently either 'hypercore' or 'ultracore'
// Chromosome Chromosome on reference species
// StartLoci Starting offset (0..n) on Chromosome
// EndLoci Ending offset (StartLoci + length -1) on Chromosome
// Length Element length
// SpeciesList List of all species sharing this element, 1st species is the reference
// Region In which region core is located
//
// There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option)
// Unaligned Count of bases in outspecies not aligned
// Matches Count of bases in outspecies which align and match
// Mismatches Count of bases in outspecies which align but mismatch
// InDels Count of bases in reference or outspecies which are InDels
int
ProcessLociLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams)
{
int Rslt;
int NumRows;
int NumFields;
int Len;
int Total;
int Totals[cMaxNumRangeClasses]; // to hold all totals
int Idx;
char szLineBuff[2048];
char szRefSpecies[200];
char szRelSpecies[200];
char szElementType[20];
tsLenRangeClass *pRangeClass;
int SeqLen;
if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess)
return(Rslt);
// no headers, straight into the rows which are expected to contain 9 fields
NumRows = 0;
Total = 0;
memset(Totals,0,sizeof(Totals));
while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields
{
NumFields = pCSV->GetCurFields();
if(NumFields < 9)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields);
return(eBSFerrFieldCnt);
}
pCSV->GetInt(7,&SeqLen);
pRangeClass = GetLengthRangeClass(SeqLen);
Totals[pRangeClass->ID-1] += SeqLen;
NumRows++;
}
switch(pParams->RangeClass) {
case eRCCFull:
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCReduced:
for(Idx = 2; Idx < 9; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 2; Idx < 9; Idx++)
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimal:
for(Idx = 1; Idx < 6; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 6; Idx++)
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalA:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalB:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalC:
Total += Totals[0];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total);
if(pParams->bPercentages)
{
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0);
}
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]);
break;
default:
Len=sprintf(szLineBuff,",-1");
break;
}
WriteRsltsHeader(pParams);
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
int
ProcessRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams)
{
int Rslt;
int NumRows;
int NumFields;
int Len;
char *pszRange;
int RangeCnt;
int Total;
int Totals[cMaxNumRangeClasses]; // to hold all totals
int Idx;
char szLineBuff[2048];
char szRefSpecies[200];
char szRelSpecies[200];
char szClass[20];
char szElementType[20];
char *pszRegion;
pszRegion = Region2Text(pParams->Region);
if((Rslt=ParseFileNameSpecies(pszFile,szClass,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess)
return(Rslt);
// Skip first row as that contains titles
if((Rslt=pCSV->NextLine())<12)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 header fields in 1st row of '%s', NextLine returned '%d'",pszFile,Rslt);
return(eBSFerrFieldCnt);
}
// subsequent rows contain fields of interest
memset(Totals,0,sizeof(Totals));
NumRows = 0;
Total = 0;
while((Rslt=pCSV->NextLine()) == 12) // onto next line containing fields
{
if(NumRows == cMaxNumRangeClasses)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected only 28 rows (plus header) in '%s', file has more rows",pszFile);
return(eBSFerrRowCnt);
}
NumFields = pCSV->GetCurFields();
if(NumFields < 12)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields);
return(eBSFerrFieldCnt);
}
pCSV->GetText(1,&pszRange);
pCSV->GetInt(pParams->Region+4,&RangeCnt);
switch(pParams->RangeClass) {
case eRCCFull:
Totals[NumRows] = RangeCnt;
break;
case eRCCReduced:
switch(NumRows) {
case 0: // 0-4
Totals[0] = RangeCnt;
break;
case 1: // 5-9
Totals[0] += RangeCnt;
break;
case 2: // 10-14
Totals[1] = RangeCnt;
break;
case 3: // 15-19
Totals[1] += RangeCnt;
break;
case 4: // 20-29
Totals[2] = RangeCnt;
break;
case 5: // 30-49
Totals[2] += RangeCnt;
break;
case 6: // 50-74
Totals[3] = RangeCnt;
break;
case 7: // 75-99
Totals[3] += RangeCnt;
break;
case 8: // 100-124
Totals[4] = RangeCnt;
break;
case 9: // 125-149
Totals[4] += RangeCnt;
break;
case 10: // 150-174
Totals[5] = RangeCnt;
break;
case 11: // 175-199
Totals[5] += RangeCnt;
break;
case 12: // 200-249
Totals[6] = RangeCnt;
break;
case 13: // 250-300
Totals[7] = RangeCnt;
Totals[8] = 0;
break;
default:
Totals[8] += RangeCnt;
break;
}
break;
case eRCCMinimal:
switch(NumRows) {
case 0: // 0-4
Totals[0] = RangeCnt;
break;
case 1: case 2: case 3: // 5-9, 10-14,15-19
Totals[0] += RangeCnt;
break;
case 4: // 20-29
Totals[1] = RangeCnt;
break;
case 5: // 30-49
Totals[1] += RangeCnt;
break;
case 6: // 50-74
Totals[2] = RangeCnt;
break;
case 7: // 75-99
Totals[2] += RangeCnt;
break;
case 8: // 100-124
Totals[3] = RangeCnt;
break;
case 9: case 10: case 11: // 125-149, 150-174,175-199
Totals[3] += RangeCnt;
break;
case 12: // 200-249
Totals[4] = RangeCnt;
break;
case 13: // 250-300
Totals[4] += RangeCnt;
Totals[5] = 0;
break;
default:
Totals[5] += RangeCnt;
break;
}
break;
case eRCCMinimalA:
switch(NumRows) {
case 0: case 1: case 2: case 3: // < 20
Totals[0] += RangeCnt;
break;
case 4: case 5: case 6: case 7: // 20-99
Totals[1] += RangeCnt;
break;
case 8: case 9: case 10: case 11: // 100-199
Totals[2] += RangeCnt;
break;
default:
Totals[3] += RangeCnt;
break;
}
break;
case eRCCMinimalB:
switch(NumRows) {
case 0: case 1: case 2: case 3: // < 20
Totals[0] += RangeCnt;
break;
case 4: case 5: // 20-49
Totals[1] += RangeCnt;
break;
case 6: case 7: // 50-99
Totals[2] += RangeCnt;
break;
default:
Totals[3] += RangeCnt;
break;
}
break;
case eRCCMinimalC:
switch(NumRows) {
case 0: case 1: case 2: case 3: // < 20
break;
case 4: case 5: // 20-49
break;
case 6: case 7: // 50-99
break;
default:
Totals[0] += RangeCnt;
break;
}
break;
}
NumRows++;
}
if(NumRows != cMaxNumRangeClasses)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 28 rows (plus header) in '%s', only '%d' parsed",pszFile,NumRows);
return(eBSFerrRowCnt);
}
switch(pParams->RangeClass) {
case eRCCFull:
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCReduced:
for(Idx = 2; Idx < 9; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 2; Idx < 9; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimal:
for(Idx = 1; Idx < 6; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 6; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalA:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalB:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalC:
Total += Totals[0];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]);
break;
default:
Len=sprintf(szLineBuff,",-1");
break;
}
WriteRsltsHeader(pParams);
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// Expected CSV format
// ElementID Uniquely identifies this element (1..n)
// CoreType Currently either 'hypercore' or 'ultracore'
// Chromosome Chromosome on reference species
// StartLoci Starting offset (0..n) on Chromosome
// EndLoci Ending offset (StartLoci + length -1) on Chromosome
// Length Element length
// SpeciesList List of all species sharing this element, 1st species is the reference
// Region In which region core is located
//
// There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option)
// Unaligned Count of bases in outspecies not aligned
// Matches Count of bases in outspecies which align and match
// Mismatches Count of bases in outspecies which align but mismatch
// InDels Count of bases in reference or outspecies which are InDels
int
ProcessLociRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams)
{
int Rslt;
int NumRows;
int NumFields;
int Len;
int Total;
int Totals[cMaxNumRangeClasses]; // to hold all totals
int Idx;
char szLineBuff[2048];
char szRefSpecies[200];
char szRelSpecies[200];
char szElementType[20];
tsLenRangeClass *pRangeClass;
int SeqLen;
int Region;
int NormRegion;
char *pszRegion;
pszRegion = Region2Text(pParams->Region);
if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess)
return(Rslt);
// no headers, straight into the rows which are expected to contain at least 9 fields
NumRows = 0;
Total = 0;
memset(Totals,0,sizeof(Totals));
while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields
{
NumFields = pCSV->GetCurFields();
if(NumFields < 9)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields);
return(eBSFerrFieldCnt);
}
pCSV->GetInt(9,&Region);
NormRegion = NormaliseRegion(Region);
if(pParams->Region != eFRAuto && pParams->Region != NormRegion)
continue;
pCSV->GetInt(7,&SeqLen);
pRangeClass = GetLengthRangeClass(SeqLen);
Totals[pRangeClass->ID-1] += SeqLen;
NumRows++;
}
switch(pParams->RangeClass) {
case eRCCFull:
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCReduced:
for(Idx = 2; Idx < 9; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 2; Idx < 9; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimal:
for(Idx = 1; Idx < 6; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 6; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalA:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalB:
for(Idx = 1; Idx < 4; Idx++)
Total += Totals[Idx];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
for(Idx = 1; Idx < 4; Idx++)
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]);
break;
case eRCCMinimalC:
Total += Totals[0];
Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total);
if(pParams->bPercentages)
Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0);
else
Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]);
break;
default:
Len=sprintf(szLineBuff,",-1");
break;
}
WriteRsltsHeader(pParams);
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
int
FormatSummaryLine(char *pszBuffer,const char *pszElementType,const char *pszRefSpecies,const char *pszCoreList,const char *pszOutSpecies,const char *pszRegion,const char *pszQual,const char *pszName,int Value)
{
int Len = sprintf(pszBuffer,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%d\n",
pszElementType,pszRefSpecies,pszCoreList,pszOutSpecies,pszRegion,pszQual,pszName,Value);
return(Len);
}
typedef struct TAG_sDistSegCnts {
double Matches; // number of exact matches in this segment
double Mismatches; // number of mismatches
double InDels; // total number of InDel bases
double Unaligned; // number of unaligned bases
} tsDistSegCnts;
typedef struct TAG_sOutSpeciesSummary {
int OGMatchBaseTotal;
int OGMismatchBaseTotal;
int OGInDelBaseTotal;
int OGUnalignedBaseTotal;
int OGUnalignedCoreBaseTotal;
int InstTotal; // total number of core or reference instances
int AlignedInstTotal; // total number of aligned cores
int BaseTotal; // total number of bases over all core or reference instances
int RegionTotals[7]; // genomic region totals
int IntronExonSpliceSiteTotals; // 5' splice site totals
int ExonIntronSpliceSiteTotals; // 3' splice site totals
int InstTotals[cMaxNumRangeClasses]; // to hold total core or reference instance counts
int BaseTotals[cMaxNumRangeClasses]; // total number of bases over all core or reference instances in each length range
int OGUnalignedCores[cMaxNumRangeClasses]; // to hold outspecies number of instances with no alignment to core
int OGUnalignedCoreBases[cMaxNumRangeClasses]; // to hold total number of bases in instances of cores unaligned to out species
int OGMatchBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species matching core
int OGMismatchBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species not matching core
int OGInDelBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species which are InDels
int OGUnalignedBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species which are not aligned
int OGAligned2Cores[cMaxNumRangeClasses]; // total number of alignments of at least MinAlignedBases in outspecies
int OGRegions[cMaxNumRangeClasses][7]; // region counts
int OGIntronExonSpliceSite[cMaxNumRangeClasses]; // 5'splice site
int OGExonIntronSpliceSite[cMaxNumRangeClasses]; // 3'splice site
int OGIntergenicRegion[cMaxNumRangeClasses]; // contained exclusively within intergenic region counts
int OGIntergenicRegionTotals;
int OGUSRegion[cMaxNumRangeClasses]; // contained exclusively within US counts
int OGUSRegionTotals;
int OG5UTRRegion[cMaxNumRangeClasses]; // contained exclusively within 5'UTR counts
int OG5UTRRegionTotals;
int OGCDSRegion[cMaxNumRangeClasses]; // contained exclusively within CDS counts
int OGCDSRegionTotals;
int OGIntronRegion[cMaxNumRangeClasses]; // contained exclusively within Intron counts
int OGIntronRegionTotals;
int OG3UTRRegion[cMaxNumRangeClasses]; // contained exclusively within 3'UTR counts
int OG3UTRRegionTotals;
int OGDSRegion[cMaxNumRangeClasses]; // contained exclusively within DS counts
int OGDSRegionTotals;
int OGSpliceSites[cMaxNumRangeClasses]; // counts of either 5' or 3' splice sites
int OGSpliceSitesTotals;
int OGMatchIdentities[cMaxNumRangeClasses][cMaxNumIdentityClasses]; // number of ref core elements with identities 0..100 in each range class
int OGTotMatchIdentities[cMaxNumIdentityClasses]; // total number of ref core elements with identities 0..100
tsDistSegCnts DistSegCnts[cMaxNumRangeClasses][cMaxMatchDistSegments]; // to hold distribution segment counts for each length range
tsDistSegCnts DistSegCntsTotals[cMaxNumRangeClasses];
int OGUnalignedCoresTotal;
char szRefSpecies[200];
char szOutSpecies[200];
char szCoreList[1024];
char szElementType[120];
tsLenRangeClass *pRangeClass;
char *pszRegion;
int NumDistSegs;
int StartIdx;
int EndIdx;
} tsOutSpeciesSummary;
int
RsltStandard(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
char szSegBuff[128];
int SegIdx;
int Idx;
int Len;
WriteRsltsHeader(pParams);
Len = FormatSummaryLine(szLineBuff,pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Cores",pOSSummary->InstTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Bases in Cores",pOSSummary->BaseTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Cores to OG Unaligned",pOSSummary->OGUnalignedCoresTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Bases in Unaligned Cores",pOSSummary->OGUnalignedCoreBaseTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Matching Bases",pOSSummary->OGMatchBaseTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Missmatch Bases",pOSSummary->OGMismatchBaseTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG InDel Bases",pOSSummary->OGInDelBaseTotal);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Unaligned Bases",pOSSummary->OGUnalignedBaseTotal);
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
sprintf(szSegBuff,"Segment %d",SegIdx+1);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,
pOSSummary->pszRegion,"All Cores (Matches)",szSegBuff,
(int)(pOSSummary->DistSegCntsTotals[SegIdx].Matches + 0.5));
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,
pOSSummary->pszRegion,"All Cores (Mismatches)",szSegBuff,
(int)(pOSSummary->DistSegCntsTotals[SegIdx].Mismatches + 0.5));
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,
pOSSummary->pszRegion,"All Cores (InDels)",szSegBuff,
(int)(pOSSummary->DistSegCntsTotals[SegIdx].InDels + 0.5));
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,
pOSSummary->pszRegion,"All Cores (Unaligned)",szSegBuff,
(int)(pOSSummary->DistSegCntsTotals[SegIdx].Unaligned + 0.5));
}
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr;
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Cores",pOSSummary->InstTotals[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Bases in Cores",pOSSummary->BaseTotals[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Cores to OG Unaligned",pOSSummary->OGUnalignedCores[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Bases in Unaligned Cores",pOSSummary->OGUnalignedCoreBases[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Matching Bases",pOSSummary->OGMatchBaseTotals[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Missmatch Bases",pOSSummary->OGMismatchBaseTotals[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG InDel Bases",pOSSummary->OGInDelBaseTotals[Idx]);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Unaligned Bases",pOSSummary->OGUnalignedBaseTotals[Idx]);
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
sprintf(szSegBuff,"Segment %d (Matches)",SegIdx+1);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff,
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5));
sprintf(szSegBuff,"Segment %d (Mismatches)",SegIdx+1);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff,
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5));
sprintf(szSegBuff,"Segment %d (InDels)",SegIdx+1);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff,
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5));
sprintf(szSegBuff,"Segment %d (Unaligned)",SegIdx+1);
Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,
pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff,
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5));
}
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltTable
// Generates table showing matching base identities for each outspecies
// <refspecies>,<specieslist>,<outspecies>,<region>,<refcorelen>,<numrefcores>,<numoutcores>,<identity1>,<identity2>
// <identity1> Identity as NumMatchingBases/NumBasesInCoresWhichAlignToRefCores
// <identity2> Identity as NumMatchingBases/(NumMatchingBases + NumMissmatchingBases)
int
RsltTable(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int Len;
WriteRsltsHeader(pParams);
char szCoreSet[200];
strcpy(szCoreSet,pOSSummary->szRefSpecies);
strcat(szCoreSet,pOSSummary->szCoreList);
Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d,%2.2f,%d,%d,%d,%2.2f\n",
szCoreSet,pOSSummary->szOutSpecies,"All", // core length range
pOSSummary->InstTotal,
pOSSummary->AlignedInstTotal,
pOSSummary->InstTotal == 0 ? 0.0 : (pOSSummary->AlignedInstTotal*100.0)/pOSSummary->InstTotal,
pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal,
pOSSummary->OGMismatchBaseTotal,
pOSSummary->OGMatchBaseTotal,
(pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal) == 0 ? 0.0 :
(pOSSummary->OGMatchBaseTotal * 100.0) / (pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal));
for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr;
Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d,%2.2f,%d,%d,%d,%2.2f\n",
szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range
pOSSummary->InstTotals[Idx],
pOSSummary->OGAligned2Cores[Idx],
pOSSummary->InstTotals[Idx] == 0 ? 0.0 :
((pOSSummary->InstTotals[Idx] - pOSSummary->OGUnalignedCores[Idx]) * 100.0) /pOSSummary->InstTotals[Idx],
pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx],
pOSSummary->OGMismatchBaseTotals[Idx],
pOSSummary->OGMatchBaseTotals[Idx],
(pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx]) == 0 ? 0.0 :
(pOSSummary->OGMatchBaseTotals[Idx] * 100.0) / (pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx]));
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltSegDistRows
// Output the segment distributions as proportions in rows
int
RsltSegDistRows(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int SegIdx;
int Idx;
double SegTotal;
int Len = 0;
WriteRsltsHeader(pParams);
for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr;
Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",
pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange);
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
if(pParams->bPercentages)
{
SegTotal = pOSSummary->DistSegCnts[Idx][SegIdx].Matches +
pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches +
pOSSummary->DistSegCnts[Idx][SegIdx].InDels +
pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned;
if(SegTotal <= 0.0)
Len += sprintf(&szLineBuff[Len],",0.00000,0.00000,0.00000,0.00000");
else
Len += sprintf(&szLineBuff[Len],",%1.8f,%1.8f,%1.8f,%1.8f",
pOSSummary->DistSegCnts[Idx][SegIdx].Matches/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].InDels/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned/SegTotal);
}
else
Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d",
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5));
}
Len += sprintf(&szLineBuff[Len],"\n");
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltSegDistTables
// Output the segment distributions as a table with segments the columns and rows from matches/mismatches/indels/unaligned
int
RsltSegDistTables(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int SegIdx;
int Idx;
double SegTotals[500];
double CntCatVal;
int Len = 0;
WriteRsltsHeader(pParams);
for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr;
if(pParams->bPercentages)
{
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
SegTotals[SegIdx] = pOSSummary->DistSegCnts[Idx][SegIdx].Matches +
pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches +
pOSSummary->DistSegCnts[Idx][SegIdx].InDels +
pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned;
if(SegTotals[SegIdx] < 0.0)
SegTotals[SegIdx] = 0.0;
}
}
for(int CntCat=0;CntCat<4;CntCat++)
{
Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",
pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange);
switch(CntCat) {
case 0: // matches
Len += sprintf(&szLineBuff[Len],",Matches");
break;
case 1: // mismatches
Len += sprintf(&szLineBuff[Len],",Mismatches");
break;
case 2: // indels
Len += sprintf(&szLineBuff[Len],",InDels");
break;
case 3: // unaligned
Len += sprintf(&szLineBuff[Len],",Unaligned");
break;
}
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
switch(CntCat) {
case 0: // matches
CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Matches;
break;
case 1: // mismatches
CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches;
break;
case 2: // indels
CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].InDels;
break;
case 3: // unaligned
CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned;
break;
}
if(pParams->bPercentages)
{
if(SegTotals[SegIdx] <= 0.0)
Len += sprintf(&szLineBuff[Len],",0.00000");
else
Len += sprintf(&szLineBuff[Len],",%1.8f",CntCatVal/SegTotals[SegIdx]);
}
else
Len += sprintf(&szLineBuff[Len],",%d",(int)(CntCatVal+0.5));
}
Len += sprintf(&szLineBuff[Len],"\n");
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
}
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltSegDistCols
// Output the segment distributions as proportions in columns
int
RsltSegDistCols(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int SegIdx;
int Idx;
double SegTotal;
char *pszRange;
int Len = 0;
WriteRsltsHeader(pParams);
for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr;
Len = 0;
for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++)
{
Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"Segment%d\"",
pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange,SegIdx+1);
if(pParams->bPercentages)
{
SegTotal = pOSSummary->DistSegCnts[Idx][SegIdx].Matches +
pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches +
pOSSummary->DistSegCnts[Idx][SegIdx].InDels +
pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned;
if(SegTotal <= 0.0)
Len += sprintf(&szLineBuff[Len],",0.00000,0.00000,0.00000,0.00000\n");
else
Len += sprintf(&szLineBuff[Len],",%1.8f,%1.8f,%1.8f,%1.8f\n",
pOSSummary->DistSegCnts[Idx][SegIdx].Matches/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].InDels/SegTotal,
pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned/SegTotal);
}
else
Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d\n",
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5),
(int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5));
}
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltIdentDistCols
// Output the identities and number of instances for each length range class in columns
int
RsltIdentDistCols(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x07fff];
int Idx;
char *pszRange;
int Len = 0;
WriteRsltsHeader(pParams);
for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr;
Len = 0;
for(int IdentityIdx = 0; IdentityIdx < cMaxNumIdentityClasses; IdentityIdx++)
{
Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%d,%d,%2.1f,%d\n",
pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange,
pOSSummary->InstTotals[Idx],pOSSummary->InstTotals[Idx] - pOSSummary->OGUnalignedCores[Idx],
(double)IdentityIdx,
pOSSummary->OGMatchIdentities[Idx][IdentityIdx]);
}
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
Len = 0;
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltRegionTable
// Output the regional characterisation by length range
int
RsltRegionTable(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int Len;
WriteRsltsHeader(pParams);
char szCoreSet[200];
strcpy(szCoreSet,pOSSummary->szRefSpecies);
strcat(szCoreSet,pOSSummary->szCoreList);
Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d",
szCoreSet,pOSSummary->szOutSpecies,"All", // core length range
pOSSummary->InstTotal,
pOSSummary->AlignedInstTotal);
for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++)
Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->RegionTotals[RegionIdx]);
Len += sprintf(&szLineBuff[Len],",%d,%d\n",pOSSummary->IntronExonSpliceSiteTotals,pOSSummary->ExonIntronSpliceSiteTotals);
for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr;
Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d",
szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range
pOSSummary->InstTotals[Idx],
pOSSummary->OGAligned2Cores[Idx]);
for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++)
Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->OGRegions[Idx][RegionIdx]);
Len += sprintf(&szLineBuff[Len],",%d,%d\n",pOSSummary->OGIntronExonSpliceSite[Idx],pOSSummary->OGExonIntronSpliceSite[Idx]);
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// RsltRegionTableA
// Output the regional characterisation by length range
int
RsltRegionTableA(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams)
{
char szLineBuff[0x03fff];
int Len;
WriteRsltsHeader(pParams);
char szCoreSet[2048];
strcpy(szCoreSet,pOSSummary->szRefSpecies);
strcat(szCoreSet,pOSSummary->szCoreList);
Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d",
szCoreSet,pOSSummary->szOutSpecies,"All", // core length range
pOSSummary->InstTotal,
pOSSummary->AlignedInstTotal);
for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++)
Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->RegionTotals[RegionIdx]);
Len += sprintf(&szLineBuff[Len],",%d,%d",
pOSSummary->IntronExonSpliceSiteTotals,pOSSummary->ExonIntronSpliceSiteTotals);
Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d,%d,%d,%d,%d\n",
pOSSummary->OGIntergenicRegionTotals,pOSSummary->OGUSRegionTotals,
pOSSummary->OG5UTRRegionTotals,pOSSummary->OGCDSRegionTotals,
pOSSummary->OGIntronRegionTotals,pOSSummary->OG3UTRRegionTotals,
pOSSummary->OGDSRegionTotals,pOSSummary->OGSpliceSitesTotals);
for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++)
{
char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr;
Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d",
szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range
pOSSummary->InstTotals[Idx],
pOSSummary->OGAligned2Cores[Idx]);
for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++)
Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->OGRegions[Idx][RegionIdx]);
Len += sprintf(&szLineBuff[Len],",%d,%d",pOSSummary->OGIntronExonSpliceSite[Idx],pOSSummary->OGExonIntronSpliceSite[Idx]);
Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d,%d,%d,%d,%d\n",
pOSSummary->OGIntergenicRegion[Idx],pOSSummary->OGUSRegion[Idx],
pOSSummary->OG5UTRRegion[Idx],pOSSummary->OGCDSRegion[Idx],
pOSSummary->OGIntronRegion[Idx],pOSSummary->OG3UTRRegion[Idx],
pOSSummary->OGDSRegion[Idx],pOSSummary->OGSpliceSites[Idx]);
}
if(Len)
if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno));
return(eBSFerrWrite);
}
return(eBSFSuccess);
}
// Expected CSV format
// ElementID Uniquely identifies this element (1..n)
// CoreType Currently either 'hypercore' or 'ultracore'
// Chromosome Chromosome on reference species
// StartLoci Starting offset (0..n) on Chromosome
// EndLoci Ending offset (StartLoci + length -1) on Chromosome
// Length Element length
// SpeciesList List of all species sharing this element, 1st species is the reference
// Region In which region core is located
//
// There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option)
// Unaligned Count of bases in outspecies not aligned
// Matches Count of bases in outspecies which align and match
// Mismatches Count of bases in outspecies which align but mismatch
// InDels Count of bases in reference or outspecies which are InDels
int
ProcessOutspeciesSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams)
{
int Rslt;
int NumRows;
int NumFields;
int AlignedBases;
int OGUnalignedBases;
int OGMatchCnt;
int OGMismatchCnt;
int OGInDelCnt;
int SegCnt;
int SegIdx;
char *pszElementType;
char *pszSpeciesList;
char *pszRefSpecies;
int SeqLen;
int Region;
int NormRegion;
tsLenRangeClass *pRangeClass;
tsOutSpeciesSummary OSSummary;
// no headers, straight into the rows which are expected to contain at least 13 fields
NumRows = 0;
memset(&OSSummary,0,sizeof(OSSummary));
OSSummary.pszRegion = Region2Text(pParams->Region);
switch(pParams->RangeClass) {
case eRCCFull:
OSSummary.StartIdx = 4;
OSSummary.EndIdx = cMaxNumRangeClasses;
break;
case eRCCReduced:
OSSummary.StartIdx = 2;
OSSummary.EndIdx = 9;
break;
case eRCCMinimal:
OSSummary.StartIdx = 1;
OSSummary.EndIdx = 6;
break;
case eRCCMinimalA:
OSSummary.StartIdx = 1;
OSSummary.EndIdx = 4;
break;
case eRCCMinimalB:
OSSummary.StartIdx = 1;
OSSummary.EndIdx = 4;
break;
case eRCCMinimalC:
OSSummary.StartIdx = 0;
OSSummary.EndIdx = 1;
break;
}
pParams->NumSpecies = 0;
while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields
{
NumFields = pCSV->GetCurFields();
if(NumFields < 9)
{
gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in outspecies '%s', GetCurFields() returned '%d'",pszFile,NumFields);
return(eBSFerrFieldCnt);
}
pCSV->GetText(2,(char **)&pszElementType);
strncpy(OSSummary.szElementType,pszElementType,sizeof(OSSummary.szElementType));
OSSummary.szElementType[sizeof(OSSummary.szElementType)-1] = '\0';
pCSV->GetText(3,(char **)&pszRefSpecies);
pCSV->GetText(8,(char **)&pszSpeciesList);
if(!pParams->NumSpecies)
{
pParams->NumSpecies = ParseNumSpecies(pszSpeciesList,pParams);
strcpy(OSSummary.szRefSpecies,pParams->szSpecies[0]);
strcpy(OSSummary.szOutSpecies,pParams->szSpecies[pParams->NumSpecies-1]);
OSSummary.szCoreList[0] = '\0';
for(int Idx = 1; Idx < (pParams->NumSpecies-1); Idx++)
{
if(Idx > 1)
strcat(OSSummary.szCoreList,",");
strcat(OSSummary.szCoreList,pParams->szSpecies[Idx]);
}
}
pCSV->GetInt(9,&Region);
NormRegion = NormaliseRegion(Region);
if(pParams->Region != eFRAuto && pParams->Region != NormRegion)
continue;
pCSV->GetInt(7,&SeqLen);
pRangeClass = GetLengthRangeClass(SeqLen);
if(NumFields > 9) // if base alignment detail in file
{
pCSV->GetInt(10,&OGUnalignedBases);
pCSV->GetInt(11,&OGMatchCnt);
pCSV->GetInt(12,&OGMismatchCnt);
pCSV->GetInt(13,&OGInDelCnt);
AlignedBases = OGMatchCnt + OGMismatchCnt;
if((AlignedBases >= pParams->Align2Core || AlignedBases == SeqLen) &&
(((AlignedBases * 100.0) / SeqLen) >= pParams->PCAlign2Core) &&
(((OGMatchCnt * 100.0) / SeqLen) >= pParams->IDAlign2Core) &&
(((OGMatchCnt * 100.0) / (OGMatchCnt + OGMismatchCnt)) >= pParams->IDOSIdentity))
OSSummary.OGAligned2Cores[pRangeClass->ID-1] += 1;
else
{
OGMatchCnt = 0;
OGMismatchCnt = 0;
OGInDelCnt = 0;
OGUnalignedBases = SeqLen;
NormRegion = -1;
Region = -1;
}
}
else
{
OGUnalignedBases = 0;
OGMatchCnt = SeqLen;
OGMismatchCnt = 0;
OGInDelCnt = 0;
}
OSSummary.BaseTotals[pRangeClass->ID-1] += SeqLen;
OSSummary.InstTotals[pRangeClass->ID-1] += 1;
OSSummary.OGMatchBaseTotals[pRangeClass->ID-1] += OGMatchCnt;
OSSummary.OGMismatchBaseTotals[pRangeClass->ID-1] += OGMismatchCnt;
OSSummary.OGInDelBaseTotals[pRangeClass->ID-1] += OGInDelCnt;
if(NormRegion != -1) // if regional mapping in source file
{
if(pParams->RsltsLayout == eRPRsltRegionTableA)
{
// determine exclusive regions (loci exclusive, totally contained, within the region)
if(Region & cFeatBitCDS && !(Region & (cFeatBit5UTR | cFeatBit3UTR)))
{
OSSummary.OGCDSRegion[pRangeClass->ID-1] += 1;
OSSummary.OGCDSRegionTotals += 1;
}
else
if(Region & cFeatBit5UTR && !(Region & (cFeatBitCDS | cFeatBit3UTR)))
{
OSSummary.OG5UTRRegion[pRangeClass->ID-1] += 1;
OSSummary.OG5UTRRegionTotals += 1;
}
else
if(Region & cFeatBit3UTR && !(Region & (cFeatBitCDS | cFeatBit5UTR)))
{
OSSummary.OG3UTRRegion[pRangeClass->ID-1] += 1;
OSSummary.OG3UTRRegionTotals += 1;
}
else
if(Region & cFeatBitIntrons && !(Region & (cFeatBitCDS | cFeatBit5UTR | cFeatBit3UTR)))
{
OSSummary.OGIntronRegion[pRangeClass->ID-1] += 1;
OSSummary.OGIntronRegionTotals += 1;
}
else
if(Region & cFeatBitUpstream && !(Region & (cFeatBitCDS | cFeatBitIntrons | cFeatBit5UTR | cFeatBit3UTR)))
{
OSSummary.OGUSRegion[pRangeClass->ID-1] += 1;
OSSummary.OGUSRegionTotals += 1;
}
else
if(Region & cFeatBitDnstream && !(Region & (cFeatBitCDS | cFeatBitIntrons | cFeatBit5UTR | cFeatBit3UTR)))
{
OSSummary.OGDSRegion[pRangeClass->ID-1] += 1;
OSSummary.OGDSRegionTotals += 1;
}
else
if(!Region)
{
OSSummary.OGIntergenicRegion[pRangeClass->ID-1] += 1;
OSSummary.OGIntergenicRegionTotals += 1;
}
if(Region & (cIntronExonSpliceSite | cExonIntronSpliceSite))
{
OSSummary.OGSpliceSites[pRangeClass->ID-1] += 1;
OSSummary.OGSpliceSitesTotals += 1;
}
// now process region counts with region unnormalised
if(Region & cFeatBitCDS)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFRCDS] += 1;
OSSummary.RegionTotals[eFRCDS] += 1;
}
if(Region & cFeatBit5UTR)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFR5UTR] += 1;
OSSummary.RegionTotals[eFR5UTR] += 1;
}
if(Region & cFeatBit3UTR)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFR3UTR] += 1;
OSSummary.RegionTotals[eFR3UTR] += 1;
}
if(Region & cFeatBitIntrons)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFRIntronic] += 1;
OSSummary.RegionTotals[eFRIntronic] += 1;
}
if(Region & cFeatBitUpstream)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFRUpstream] += 1;
OSSummary.RegionTotals[eFRUpstream] += 1;
}
if(Region & cFeatBitDnstream)
{
OSSummary.OGRegions[pRangeClass->ID-1][NormRegion] += 1;
OSSummary.RegionTotals[eFRDnstream] += 1;
}
if(!Region)
{
OSSummary.OGRegions[pRangeClass->ID-1][eFRIntergenic] += 1;
OSSummary.RegionTotals[eFRIntergenic] += 1;
}
if(Region & cIntronExonSpliceSite)
{
OSSummary.OGIntronExonSpliceSite[pRangeClass->ID-1] += 1;
OSSummary.IntronExonSpliceSiteTotals += 1;
}
if(Region & cExonIntronSpliceSite)
{
OSSummary.OGExonIntronSpliceSite[pRangeClass->ID-1] += 1;
OSSummary.ExonIntronSpliceSiteTotals += 1;
}
}
else
{
// now process region counts where region has been normalised
OSSummary.OGRegions[pRangeClass->ID-1][NormRegion] += 1;
OSSummary.RegionTotals[NormRegion] += 1;
if(Region & cIntronExonSpliceSite)
{
OSSummary.OGIntronExonSpliceSite[pRangeClass->ID-1] += 1;
OSSummary.IntronExonSpliceSiteTotals += 1;
}
if(Region & cExonIntronSpliceSite)
{
OSSummary.OGExonIntronSpliceSite[pRangeClass->ID-1] += 1;
OSSummary.ExonIntronSpliceSiteTotals += 1;
}
}
}
if(NumFields <= 15)
OSSummary.NumDistSegs = 0;
else
OSSummary.NumDistSegs = (NumFields - 15)/4; // 4 fields per segment (matches,mismatches,indels,unaligned)
pParams->NumDistSegs = OSSummary.NumDistSegs;
// need to normalise the counts because the orginal count binning
// was on discrete base boundaries. For example -
// Assume 10 bins, and sequence length was 20
// All 10 bins contain counts for 2 bases per bin (BinWidth = 2)
// Assume sequence length was 21
// The first 9 bins contain counts for 2 bases per bin, but the last bin contains counts for 3 bases
// Assume sequence length now 28
// The first 2 bins contain counts for 2 bases per bin (BinWidth = 2), but the last 8 bins contains counts for 3 bases (BinWidth = 3)
//
// To normalise, scale the bases per bin to be BinCnt *= Sequencelength/(NumberBins*BinWidth)
// Using same examples as above -
// Assume 10 bins, and sequence length was 20
// Scale all 10 bins by 20/(10*2) or 1.0
// Assume sequence length was 21
// Scale first 9 bins by 21/(10*2) or 1.05 , last bin by 21/(10*3) or 0.70
if(OSSummary.NumDistSegs && (!pParams->bSegsExcludeMatch || SeqLen > OGMatchCnt))
{
int BinWidth = SeqLen / OSSummary.NumDistSegs; // intial bin width or number of bases in that bin
int BinWidthChg = OSSummary.NumDistSegs - (SeqLen % OSSummary.NumDistSegs); // bin index at which scaling changes
double CntScale = (double)SeqLen / (OSSummary.NumDistSegs * BinWidth);
for(SegIdx = 0; SegIdx < OSSummary.NumDistSegs; SegIdx++)
{
if(SegIdx == BinWidthChg)
CntScale = (double)SeqLen / (OSSummary.NumDistSegs * (BinWidth+1));
pCSV->GetInt((SegIdx * 4) + 16,&SegCnt);
OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Matches += SegCnt * CntScale;
pCSV->GetInt((SegIdx * 4) + 17,&SegCnt);
OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Mismatches += SegCnt * CntScale;
pCSV->GetInt((SegIdx * 4) + 18,&SegCnt);
OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].InDels += SegCnt * CntScale;
pCSV->GetInt((SegIdx * 4) + 19,&SegCnt);
OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Unaligned += SegCnt * CntScale;
}
}
if(OGUnalignedBases == SeqLen) // if no alignment at all...
{
OSSummary.OGUnalignedCores[pRangeClass->ID-1] += 1;
OSSummary.OGUnalignedCoreBases[pRangeClass->ID-1] += OGUnalignedBases;
}
else // else at least 1 base aligned!
{
OSSummary.OGUnalignedBaseTotals[pRangeClass->ID-1] += OGUnalignedBases;
double MatchPercent = (OGMatchCnt * 100.0) / SeqLen;
int MatchPercentIdx = (int)(MatchPercent + 0.001); // 0.001 added in case of small round down errors in floating points
OSSummary.OGMatchIdentities[pRangeClass->ID-1][MatchPercentIdx] += 1;
}
NumRows++;
}
// all element rows have been processed
OSSummary.InstTotal = 0;
OSSummary.BaseTotal = 0;
for(int Idx = OSSummary.StartIdx; Idx < OSSummary.EndIdx; Idx++)
{
OSSummary.InstTotal += OSSummary.InstTotals[Idx];
OSSummary.BaseTotal += OSSummary.BaseTotals[Idx];
OSSummary.AlignedInstTotal += OSSummary.OGAligned2Cores[Idx];
OSSummary.OGMatchBaseTotal += OSSummary.OGMatchBaseTotals[Idx];
OSSummary.OGMismatchBaseTotal += OSSummary.OGMismatchBaseTotals[Idx];
OSSummary.OGInDelBaseTotal += OSSummary.OGInDelBaseTotals[Idx];
OSSummary.OGUnalignedBaseTotal += OSSummary.OGUnalignedBaseTotals[Idx];
OSSummary.OGUnalignedCoreBaseTotal += OSSummary.OGUnalignedCoreBases[Idx];
OSSummary.OGUnalignedCoresTotal += OSSummary.OGUnalignedCores[Idx];
for(int IdentityIdx = 0; IdentityIdx < cMaxNumIdentityClasses; IdentityIdx++)
OSSummary.OGTotMatchIdentities[IdentityIdx] += OSSummary.OGMatchIdentities[Idx][IdentityIdx];
for(SegIdx = 0; SegIdx < OSSummary.NumDistSegs; SegIdx++)
{
OSSummary.DistSegCntsTotals[SegIdx].Matches += OSSummary.DistSegCnts[Idx][SegIdx].Matches;
OSSummary.DistSegCntsTotals[SegIdx].Mismatches += OSSummary.DistSegCnts[Idx][SegIdx].Mismatches;
OSSummary.DistSegCntsTotals[SegIdx].InDels += OSSummary.DistSegCnts[Idx][SegIdx].InDels;
OSSummary.DistSegCntsTotals[SegIdx].Unaligned += OSSummary.DistSegCnts[Idx][SegIdx].Unaligned;
}
}
OSSummary.pRangeClass = pLenRangeClasses;
switch(pParams->RsltsLayout) {
case eRPRsltStandard:
Rslt = RsltStandard(&OSSummary,pParams);
break;
case eRPRsltTable:
Rslt = RsltTable(&OSSummary,pParams);
break;
case eRPRsltSegDistRows:
Rslt = RsltSegDistRows(&OSSummary,pParams);
break;
case eRPRsltSegDistTables:
Rslt = RsltSegDistTables(&OSSummary,pParams);
break;
case eRPRsltSegDistCols:
Rslt = RsltSegDistCols(&OSSummary,pParams);
break;
case eRPRsltIdentDistCols:
Rslt = RsltIdentDistCols(&OSSummary,pParams);
break;
case eRPRsltRegionTable:
Rslt = RsltRegionTable(&OSSummary,pParams);
break;
case eRPRsltRegionTableA:
Rslt = RsltRegionTableA(&OSSummary,pParams);
break;
}
return(eBSFSuccess);
}
| 35.254377 | 316 | 0.674272 | rsuchecki |
783255735e65bcabcc634f0512064bc0808cbecf | 4,323 | cpp | C++ | src/vecmath/cross_product.cpp | dogesoulseller/weirdlib | 35d3be8a7621890e6870a48f3839f00b87d5ced9 | [
"MIT"
] | null | null | null | src/vecmath/cross_product.cpp | dogesoulseller/weirdlib | 35d3be8a7621890e6870a48f3839f00b87d5ced9 | [
"MIT"
] | null | null | null | src/vecmath/cross_product.cpp | dogesoulseller/weirdlib | 35d3be8a7621890e6870a48f3839f00b87d5ced9 | [
"MIT"
] | null | null | null | #ifdef WEIRDLIB_ENABLE_VECTOR_MATH
#include "../../include/weirdlib_vecmath.hpp"
#include "../../include/cpu_detection.hpp"
#include "../../include/weirdlib_simdhelper.hpp"
#include <array>
namespace wlib::vecmath
{
#if X86_SIMD_LEVEL >= LV_AVX2
static const auto PERM_MASK_CROSSP_LHS = _mm256_set_epi32(0, 0, 1, 0, 2, 0, 2, 1);
static const auto PERM_MASK_CROSSP_RHS = _mm256_set_epi32(0, 0, 0, 2, 1, 1, 0, 2);
static const auto PERM_MASK_CROSSP_SUB = _mm256_set_epi32(0, 0, 5, 2, 4, 1, 3, 0);
#endif
Vector3<float> CrossProduct(const Vector3<float>& lhs, const Vector3<float>& rhs) {
#if X86_SIMD_LEVEL >= LV_AVX2
auto lhs_vec = _mm256_loadu_ps(&lhs.x);
auto rhs_vec = _mm256_loadu_ps(&rhs.x);
auto lhs_yzxzxy = _mm256_permutevar8x32_ps(lhs_vec, PERM_MASK_CROSSP_LHS);
auto rhs_zxyyzx = _mm256_permutevar8x32_ps(rhs_vec, PERM_MASK_CROSSP_RHS);
auto product = _mm256_mul_ps(lhs_yzxzxy, rhs_zxyyzx);
// Set up for subtraction
auto prod_hsub = _mm256_permutevar8x32_ps(product, PERM_MASK_CROSSP_SUB);
auto result = _mm256_hsub_ps(prod_hsub, prod_hsub);
alignas(32) std::array<float, 8> outvec;
_mm256_store_ps(outvec.data(), result);
return Vector3(outvec[0], outvec[1], outvec[4]);
#elif X86_SIMD_LEVEL >= LV_SSE
auto lhs_vec = _mm_loadu_ps(&lhs.x);
auto rhs_vec = _mm_loadu_ps(&rhs.x);
auto lhs_yzx = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 0, 2, 1));
auto lhs_zxy = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 1, 0, 2));
auto rhs_zxy = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 1, 0, 2));
auto rhs_yzx = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 0, 2, 1));
auto left_side = _mm_mul_ps(lhs_yzx, rhs_zxy);
auto right_side = _mm_mul_ps(lhs_zxy, rhs_yzx);
auto result = _mm_sub_ps(left_side, right_side);
alignas(16) std::array<float, 4> outvec;
_mm_store_ps(outvec.data(), result);
return Vector3(outvec[0], outvec[1], outvec[2]);
#else
float x = (lhs.y * rhs.z) - (lhs.z * rhs.y);
float y = (lhs.z * rhs.x) - (lhs.x * rhs.z);
float z = (lhs.x * rhs.y) - (lhs.y * rhs.x);
return Vector3(x, y, z);
#endif
}
Vector3<double> CrossProduct(const Vector3<double>& lhs, const Vector3<double>& rhs) {
#if X86_SIMD_LEVEL >= LV_AVX2
auto lhs_vec = _mm256_loadu_pd(&lhs.x);
auto rhs_vec = _mm256_loadu_pd(&rhs.x);
auto lhs_yzx = _mm256_permute4x64_pd(lhs_vec, 0b00001001);
auto lhs_zxy = _mm256_permute4x64_pd(lhs_vec, 0b00010010);
auto rhs_yzx = _mm256_permute4x64_pd(rhs_vec, 0b00001001);
auto rhs_zxy = _mm256_permute4x64_pd(rhs_vec, 0b00010010);
auto left_side = _mm256_mul_pd(lhs_yzx, rhs_zxy);
auto right_side = _mm256_mul_pd(lhs_zxy, rhs_yzx);
auto result = _mm256_sub_pd(left_side, right_side);
alignas(32) std::array<double, 4> outvec;
_mm256_store_pd(outvec.data(), result);
return Vector3(outvec[0], outvec[1], outvec[2]);
#elif X86_SIMD_LEVEL >= LV_SSE2
auto lhs_vec_xy = _mm_loadu_pd(&lhs.x);
auto lhs_vec_z_ = _mm_loadu_pd(&lhs.z);
auto rhs_vec_xy = _mm_loadu_pd(&rhs.x);
auto rhs_vec_z_ = _mm_loadu_pd(&rhs.z);
auto lhs_yz = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_z_, 0b00000001);
auto lhs_zx = _mm_shuffle_pd(lhs_vec_z_, lhs_vec_xy, 0b00000000);
auto lhs_x_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000000);
auto lhs_y_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000001);
auto rhs_yz = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_z_, 0b00000001);
auto rhs_zx = _mm_shuffle_pd(rhs_vec_z_, rhs_vec_xy, 0b00000000);
auto rhs_x_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000000);
auto rhs_y_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000001);
auto l0 = _mm_mul_pd(lhs_yz, rhs_zx);
auto r0 = _mm_mul_pd(lhs_zx, rhs_yz);
auto l1 = _mm_mul_pd(lhs_x_, rhs_y_);
auto r1 = _mm_mul_pd(lhs_y_, rhs_x_);
auto result0 = _mm_sub_pd(l0, r0);
auto result1 = _mm_sub_pd(l1, r1);
alignas(16) std::array<double, 4> outvec;
_mm_store_pd(outvec.data(), result0);
_mm_store_pd(outvec.data()+2, result1);
return Vector3(outvec[0], outvec[1], outvec[2]);
#else
double x = (lhs.y * rhs.z) - (lhs.z * rhs.y);
double y = (lhs.z * rhs.x) - (lhs.x * rhs.z);
double z = (lhs.x * rhs.y) - (lhs.y * rhs.x);
return Vector3(x, y, z);
#endif
}
} // namespace wlib::vecmath
#endif | 36.025 | 87 | 0.703909 | dogesoulseller |
7833f274716337ee25a7eab223247e96841dfdb7 | 79 | cpp | C++ | test/unit-tests/metafs/mvm/volume/meta_volume_state_test.cpp | so931/poseidonos | 2aa82f26bfbd0d0aee21cd0574779a655634f08c | [
"BSD-3-Clause"
] | 38 | 2021-04-06T03:20:55.000Z | 2022-03-02T09:33:28.000Z | test/unit-tests/metafs/mvm/volume/meta_volume_state_test.cpp | so931/poseidonos | 2aa82f26bfbd0d0aee21cd0574779a655634f08c | [
"BSD-3-Clause"
] | 19 | 2021-04-08T02:27:44.000Z | 2022-03-23T00:59:04.000Z | test/unit-tests/metafs/mvm/volume/meta_volume_state_test.cpp | so931/poseidonos | 2aa82f26bfbd0d0aee21cd0574779a655634f08c | [
"BSD-3-Clause"
] | 28 | 2021-04-08T04:39:18.000Z | 2022-03-24T05:56:00.000Z | #include "src/metafs/mvm/volume/meta_volume_state.h"
#include <gtest/gtest.h>
| 19.75 | 52 | 0.772152 | so931 |
783a5175903571c1c754e056cd78e2084ce1d2d1 | 6,497 | cpp | C++ | Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | // Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// float Health (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UGAB_AthenaDBNO_C::GetInitialHealAmount(float* Health)
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount");
UGAB_AthenaDBNO_C_GetInitialHealAmount_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Health != nullptr)
*Health = params.Health;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGameplayEventData EventHitData (Parm)
void UGAB_AthenaDBNO_C::InitializeDeathHitDirection(const struct FGameplayEventData& EventHitData)
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection");
UGAB_AthenaDBNO_C_InitializeDeathHitDirection_Params params;
params.EventHitData = EventHitData;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnCancelled_F0F6785443BD2E74F5591884CB19F35F()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F");
UGAB_AthenaDBNO_C_OnCancelled_F0F6785443BD2E74F5591884CB19F35F_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnInterrupted_F0F6785443BD2E74F5591884CB19F35F()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F");
UGAB_AthenaDBNO_C_OnInterrupted_F0F6785443BD2E74F5591884CB19F35F_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnBlendOut_F0F6785443BD2E74F5591884CB19F35F()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F");
UGAB_AthenaDBNO_C_OnBlendOut_F0F6785443BD2E74F5591884CB19F35F_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnCompleted_F0F6785443BD2E74F5591884CB19F35F()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F");
UGAB_AthenaDBNO_C_OnCompleted_F0F6785443BD2E74F5591884CB19F35F_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6");
UGAB_AthenaDBNO_C_OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6
// (BlueprintCallable, BlueprintEvent)
void UGAB_AthenaDBNO_C::OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6");
UGAB_AthenaDBNO_C_OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent
// (Event, Protected, HasOutParms, BlueprintEvent)
// Parameters:
// struct FGameplayEventData* EventData (ConstParm, Parm, OutParm, ReferenceParm)
void UGAB_AthenaDBNO_C::K2_ActivateAbilityFromEvent(struct FGameplayEventData* EventData)
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent");
UGAB_AthenaDBNO_C_K2_ActivateAbilityFromEvent_Params params;
params.EventData = EventData;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility
// (Event, Protected, BlueprintEvent)
void UGAB_AthenaDBNO_C::K2_OnEndAbility()
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility");
UGAB_AthenaDBNO_C_K2_OnEndAbility_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UGAB_AthenaDBNO_C::ExecuteUbergraph_GAB_AthenaDBNO(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO");
UGAB_AthenaDBNO_C_ExecuteUbergraph_GAB_AthenaDBNO_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 29.39819 | 145 | 0.785901 | Milxnor |
783d5ddfb3bc1652f3ff5d191f70f471a441a899 | 6,391 | cpp | C++ | third_party/VisEngine/PresetFrameIO.cpp | Narflex/sagetv | 76cb5755e54fd3b01d2bb708a8a72af0aa1533f1 | [
"Apache-2.0"
] | 292 | 2015-08-10T18:34:55.000Z | 2022-01-26T00:38:45.000Z | third_party/VisEngine/PresetFrameIO.cpp | Narflex/sagetv | 76cb5755e54fd3b01d2bb708a8a72af0aa1533f1 | [
"Apache-2.0"
] | 366 | 2015-08-10T18:21:02.000Z | 2022-01-22T20:03:41.000Z | third_party/VisEngine/PresetFrameIO.cpp | Narflex/sagetv | 76cb5755e54fd3b01d2bb708a8a72af0aa1533f1 | [
"Apache-2.0"
] | 227 | 2015-08-10T22:24:29.000Z | 2022-02-25T19:16:21.000Z | #include "PresetFrameIO.hpp"
#include "wipemalloc.h"
#include <math.h>
#include <cassert>
#include <iostream>
PresetInputs::PresetInputs()
{
}
void PresetInputs::Initialize ( int gx, int gy )
{
int x, y;
this->gx =gx;
this->gy= gy;
this->x_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->x_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->y_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->y_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->rad_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->rad_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->theta_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x <gx; x++ )
{
this->theta_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->origtheta= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->origtheta[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->origrad= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->origrad[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->origx= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->origx[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->origy= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->origy[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
for ( x=0;x<gx;x++ )
{
for ( y=0;y<gy;y++ )
{
this->origx[x][y]=mathval(x/ ( float ) ( gx-1 ));
this->origy[x][y]=mathval(- ( ( y/ ( float ) ( gy-1 ) )-1 ));
this->origrad[x][y]=mathval( hypotf ( ( mathtofloat(this->origx[x][y])-.5f ) *2, ( mathtofloat(this->origy[x][y])-.5f ) *2 ) * .7071067f);
this->origtheta[x][y]=mathval(atan2 ( ( ( mathtofloat(this->origy[x][y])-.5f ) *2 ), ( ( mathtofloat(this->origx[x][y])-.5f ) *2 ) ));
}
}
}
PresetOutputs::PresetOutputs()
{}
PresetOutputs::~PresetOutputs()
{
assert(this->gx > 0);
for ( int x = 0; x < this->gx; x++ )
{
free(this->x_mesh[x]);
free(this->y_mesh[x]);
free(this->sx_mesh[x]);
free(this->sy_mesh[x]);
free(this->dy_mesh[x]);
free(this->dx_mesh[x]);
free(this->cy_mesh[x]);
free(this->cx_mesh[x]);
free(this->warp_mesh[x]);
free(this->zoom_mesh[x]);
free(this->zoomexp_mesh[x]);
free(this->rot_mesh[x]);
}
free(this->x_mesh);
free(this->y_mesh);
free(this->sx_mesh);
free(this->sy_mesh);
free(this->dy_mesh);
free(this->dx_mesh);
free(this->cy_mesh);
free(this->cx_mesh);
free(this->warp_mesh);
free(this->zoom_mesh);
free(this->zoomexp_mesh);
free(this->rot_mesh);
}
void PresetOutputs::Initialize ( int gx, int gy )
{
assert(gx > 0);
this->gx = gx;
this->gy= gy;
assert(this->gx > 0);
int x;
this->x_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->x_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->y_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->y_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->sx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->sx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->sy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->sy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->dx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->dx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->dy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->dy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->cx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->cx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->cy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->cy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->zoom_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->zoom_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->zoomexp_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->zoomexp_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->rot_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->rot_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
this->warp_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) );
for ( x = 0; x < gx; x++ )
{
this->warp_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) );
}
}
PresetInputs::~PresetInputs()
{
for ( int x = 0; x < this->gx; x++ )
{
free ( this->origtheta[x] );
free ( this->origrad[x] );
free ( this->origx[x] );
free ( this->origy[x] );
free ( this->x_mesh[x] );
free ( this->y_mesh[x] );
free ( this->rad_mesh[x] );
free ( this->theta_mesh[x] );
}
free ( this->origx );
free ( this->origy );
free ( this->origrad );
free ( this->origtheta );
free ( this->x_mesh );
free ( this->y_mesh );
free ( this->rad_mesh );
free ( this->theta_mesh );
this->origx = NULL;
this->origy = NULL;
this->origtheta = NULL;
this->origrad = NULL;
this->x_mesh = NULL;
this->y_mesh = NULL;
this->rad_mesh = NULL;
this->theta_mesh = NULL;
}
void PresetInputs::ResetMesh()
{
int x,y;
assert ( x_mesh );
assert ( y_mesh );
assert ( rad_mesh );
assert ( theta_mesh );
for ( x=0;x<this->gx;x++ )
{
for ( y=0;y<this->gy;y++ )
{
x_mesh[x][y]=this->origx[x][y];
y_mesh[x][y]=this->origy[x][y];
rad_mesh[x][y]=this->origrad[x][y];
theta_mesh[x][y]=this->origtheta[x][y];
}
}
}
| 25.564 | 141 | 0.558129 | Narflex |
783f9c4301f10f37660fe7c80f60c71f3432b3e1 | 10,196 | cpp | C++ | third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2000 Simon Hausmann (hausmann@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2006, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/html/HTMLFrameElementBase.h"
#include "bindings/core/v8/BindingSecurity.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/ScriptEventListener.h"
#include "core/HTMLNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/RemoteFrame.h"
#include "core/frame/RemoteFrameView.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
namespace blink {
using namespace HTMLNames;
HTMLFrameElementBase::HTMLFrameElementBase(const QualifiedName& tagName,
Document& document)
: HTMLFrameOwnerElement(tagName, document),
m_scrollingMode(ScrollbarAuto),
m_marginWidth(-1),
m_marginHeight(-1) {}
bool HTMLFrameElementBase::isURLAllowed() const {
if (m_URL.isEmpty())
return true;
const KURL& completeURL = document().completeURL(m_URL);
if (contentFrame() && protocolIsJavaScript(completeURL)) {
// Check if the caller can execute script in the context of the content
// frame. NB: This check can be invoked without any JS on the stack for some
// parser operations. In such case, we use the origin of the frame element's
// containing document as the caller context.
v8::Isolate* isolate = toIsolate(&document());
LocalDOMWindow* accessingWindow = isolate->InContext()
? currentDOMWindow(isolate)
: document().domWindow();
if (!BindingSecurity::shouldAllowAccessToFrame(
accessingWindow, contentFrame(),
BindingSecurity::ErrorReportOption::Report))
return false;
}
LocalFrame* parentFrame = document().frame();
if (parentFrame)
return parentFrame->isURLAllowed(completeURL);
return true;
}
void HTMLFrameElementBase::openURL(bool replaceCurrentItem) {
if (!isURLAllowed())
return;
if (m_URL.isEmpty())
m_URL = AtomicString(blankURL().getString());
LocalFrame* parentFrame = document().frame();
if (!parentFrame)
return;
// Support for <frame src="javascript:string">
KURL scriptURL;
KURL url = document().completeURL(m_URL);
if (protocolIsJavaScript(m_URL)) {
// We'll set/execute |scriptURL| iff CSP allows us to execute inline
// JavaScript. If CSP blocks inline JavaScript, then exit early if
// we're trying to execute script in an existing document. If we're
// executing JavaScript to create a new document (e.g.
// '<iframe src="javascript:...">' then continue loading 'about:blank'
// so that the frame is populated with something reasonable.
if (ContentSecurityPolicy::shouldBypassMainWorld(&document()) ||
document().contentSecurityPolicy()->allowJavaScriptURLs(
this, document().url(), OrdinalNumber::first())) {
scriptURL = url;
} else {
if (contentFrame())
return;
}
url = blankURL();
}
if (!loadOrRedirectSubframe(url, m_frameName, replaceCurrentItem))
return;
if (!contentFrame() || scriptURL.isEmpty() || !contentFrame()->isLocalFrame())
return;
if (contentFrame()->owner()->getSandboxFlags() & SandboxOrigin)
return;
toLocalFrame(contentFrame())
->script()
.executeScriptIfJavaScriptURL(scriptURL, this);
}
void HTMLFrameElementBase::frameOwnerPropertiesChanged() {
// Don't notify about updates if contentFrame() is null, for example when
// the subframe hasn't been created yet.
if (contentFrame())
document().frame()->loader().client()->didChangeFrameOwnerProperties(this);
}
void HTMLFrameElementBase::parseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.newValue;
if (name == srcdocAttr) {
if (!value.isNull()) {
setLocation(srcdocURL().getString());
} else {
const AtomicString& srcValue = fastGetAttribute(srcAttr);
if (!srcValue.isNull())
setLocation(stripLeadingAndTrailingHTMLSpaces(srcValue));
}
} else if (name == srcAttr && !fastHasAttribute(srcdocAttr)) {
setLocation(stripLeadingAndTrailingHTMLSpaces(value));
} else if (name == idAttr) {
// Important to call through to base for the id attribute so the hasID bit
// gets set.
HTMLFrameOwnerElement::parseAttribute(params);
m_frameName = value;
} else if (name == nameAttr) {
m_frameName = value;
} else if (name == marginwidthAttr) {
setMarginWidth(value.toInt());
} else if (name == marginheightAttr) {
setMarginHeight(value.toInt());
} else if (name == scrollingAttr) {
// Auto and yes both simply mean "allow scrolling." No means "don't allow
// scrolling."
if (equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "yes"))
setScrollingMode(ScrollbarAuto);
else if (equalIgnoringCase(value, "no"))
setScrollingMode(ScrollbarAlwaysOff);
} else if (name == onbeforeunloadAttr) {
// FIXME: should <frame> elements have beforeunload handlers?
setAttributeEventListener(
EventTypeNames::beforeunload,
createAttributeEventListener(this, name, value, eventParameterName()));
} else {
HTMLFrameOwnerElement::parseAttribute(params);
}
}
void HTMLFrameElementBase::setNameAndOpenURL() {
m_frameName = getNameAttribute();
openURL();
}
Node::InsertionNotificationRequest HTMLFrameElementBase::insertedInto(
ContainerNode* insertionPoint) {
HTMLFrameOwnerElement::insertedInto(insertionPoint);
return InsertionShouldCallDidNotifySubtreeInsertions;
}
void HTMLFrameElementBase::didNotifySubtreeInsertionsToDocument() {
if (!document().frame())
return;
if (!SubframeLoadingDisabler::canLoadFrame(*this))
return;
// We should never have a content frame at the point where we got inserted
// into a tree.
SECURITY_CHECK(!contentFrame());
setNameAndOpenURL();
}
void HTMLFrameElementBase::attachLayoutTree(const AttachContext& context) {
HTMLFrameOwnerElement::attachLayoutTree(context);
if (layoutPart()) {
if (Frame* frame = contentFrame()) {
if (frame->isLocalFrame())
setWidget(toLocalFrame(frame)->view());
else if (frame->isRemoteFrame())
setWidget(toRemoteFrame(frame)->view());
}
}
}
void HTMLFrameElementBase::setLocation(const String& str) {
m_URL = AtomicString(str);
if (isConnected())
openURL(false);
}
bool HTMLFrameElementBase::supportsFocus() const {
return true;
}
void HTMLFrameElementBase::setFocused(bool received) {
HTMLFrameOwnerElement::setFocused(received);
if (Page* page = document().page()) {
if (received) {
page->focusController().setFocusedFrame(contentFrame());
} else if (page->focusController().focusedFrame() == contentFrame()) {
// Focus may have already been given to another frame, don't take it away.
page->focusController().setFocusedFrame(nullptr);
}
}
}
bool HTMLFrameElementBase::isURLAttribute(const Attribute& attribute) const {
return attribute.name() == longdescAttr || attribute.name() == srcAttr ||
HTMLFrameOwnerElement::isURLAttribute(attribute);
}
bool HTMLFrameElementBase::hasLegalLinkAttribute(
const QualifiedName& name) const {
return name == srcAttr || HTMLFrameOwnerElement::hasLegalLinkAttribute(name);
}
bool HTMLFrameElementBase::isHTMLContentAttribute(
const Attribute& attribute) const {
return attribute.name() == srcdocAttr ||
HTMLFrameOwnerElement::isHTMLContentAttribute(attribute);
}
// FIXME: Remove this code once we have input routing in the browser
// process. See http://crbug.com/339659.
void HTMLFrameElementBase::defaultEventHandler(Event* event) {
if (contentFrame() && contentFrame()->isRemoteFrame()) {
toRemoteFrame(contentFrame())->forwardInputEvent(event);
return;
}
HTMLFrameOwnerElement::defaultEventHandler(event);
}
void HTMLFrameElementBase::setScrollingMode(ScrollbarMode scrollbarMode) {
if (m_scrollingMode == scrollbarMode)
return;
if (contentDocument()) {
contentDocument()->willChangeFrameOwnerProperties(
m_marginWidth, m_marginHeight, scrollbarMode);
}
m_scrollingMode = scrollbarMode;
frameOwnerPropertiesChanged();
}
void HTMLFrameElementBase::setMarginWidth(int marginWidth) {
if (m_marginWidth == marginWidth)
return;
if (contentDocument()) {
contentDocument()->willChangeFrameOwnerProperties(
marginWidth, m_marginHeight, m_scrollingMode);
}
m_marginWidth = marginWidth;
frameOwnerPropertiesChanged();
}
void HTMLFrameElementBase::setMarginHeight(int marginHeight) {
if (m_marginHeight == marginHeight)
return;
if (contentDocument()) {
contentDocument()->willChangeFrameOwnerProperties(
m_marginWidth, marginHeight, m_scrollingMode);
}
m_marginHeight = marginHeight;
frameOwnerPropertiesChanged();
}
} // namespace blink
| 34.100334 | 80 | 0.709004 | google-ar |
78421089f5b1f378e97570df420efc819399389d | 2,346 | cpp | C++ | packages/CLPBN/horus/unit_tests/Common.cpp | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 90 | 2015-03-09T01:24:15.000Z | 2022-02-24T13:56:25.000Z | packages/CLPBN/horus/unit_tests/Common.cpp | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 52 | 2016-02-14T08:59:37.000Z | 2022-03-14T16:39:35.000Z | packages/CLPBN/horus/unit_tests/Common.cpp | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 27 | 2015-11-19T02:45:49.000Z | 2021-11-25T19:47:58.000Z | #include <cstdlib>
#include <cmath>
#include <cassert>
#include <numeric>
#include <functional>
#include <iostream>
#include "Common.h"
#include "Util.h"
namespace Horus {
namespace UnitTests {
const std::string modelFile = "../examples/complex.fg" ;
const std::vector<Params> marginalProbs = {
/* marginals x0 = */ {0.5825521, 0.4174479},
/* marginals x1 = */ {0.648528, 0.351472},
{0.03100852, 0.9689915},
{0.04565728, 0.503854, 0.4504888},
{0.7713128, 0.03128429, 0.1974029},
{0.8771822, 0.1228178},
{0.05617282, 0.01509834, 0.9287288},
{0.08224711, 0.5698616, 0.047964, 0.2999273},
{0.1368483, 0.8631517},
/* marginals x9 = */ {0.7529569, 0.2470431}
};
const Params jointProbs = {
/* P(x0=0, x4=0, x6=0) = */ 0.025463399,
/* P(x0=0, x4=0, x6=1) = */ 0.0067233122,
/* P(x0=0, x4=0, x6=2) = */ 0.42069289,
/* P(x0=0, x4=1, x6=0) = */ 0.0010111473,
/* P(x0=0, x4=1, x6=1) = */ 0.00027096982,
/* P(x0=0, x4=1, x6=2) = */ 0.016715682,
/* P(x0=0, x4=2, x6=0) = */ 0.0062433667,
/* P(x0=0, x4=2, x6=1) = */ 0.001828545,
/* P(x0=0, x4=2, x6=2) = */ 0.10360283,
/* P(x0=1, x4=0, x6=0) = */ 0.017910021,
/* P(x0=1, x4=0, x6=1) = */ 0.0046988842,
/* P(x0=1, x4=0, x6=2) = */ 0.29582433,
/* P(x0=1, x4=1, x6=0) = */ 0.00074648444,
/* P(x0=1, x4=1, x6=1) = */ 0.00019991076,
/* P(x0=1, x4=1, x6=2) = */ 0.012340097,
/* P(x0=1, x4=2, x6=0) = */ 0.0047984062,
/* P(x0=1, x4=2, x6=1) = */ 0.0013767189,
/* P(x0=1, x4=2, x6=2) = */ 0.079553004
};
Params
generateRandomParams (Ranges ranges)
{
Params params;
unsigned size = std::accumulate (ranges.begin(), ranges.end(),
1, std::multiplies<unsigned>());
for (unsigned i = 0; i < size; i++) {
params.push_back (rand() / double (RAND_MAX));
}
Horus::LogAware::normalize (params);
return params;
}
bool
similiar (double v1, double v2)
{
const double epsilon = 0.0000001;
return std::fabs (v1 - v2) < epsilon;
}
bool
similiar (const Params& p1, const Params& p2)
{
assert (p1.size() == p2.size());
for (size_t i = 0; i < p1.size(); i++) {
if (! similiar(p1[i], p2[i])) {
return false;
}
}
return true;
}
} // namespace UnitTests
} // namespace Horus;
| 24.4375 | 66 | 0.542626 | ryandesign |
78432ee9cf1d62b320b491645d09370833fcc2f4 | 16,513 | cpp | C++ | src/Parameters.cpp | MikeHeiber/Ising_OPV | 6a108675bdee1847abee0273b7874d9d312b048e | [
"MIT"
] | 8 | 2015-10-26T22:27:51.000Z | 2021-09-01T19:40:29.000Z | src/Parameters.cpp | MikeHeiber/Ising_OPV | 6a108675bdee1847abee0273b7874d9d312b048e | [
"MIT"
] | 13 | 2017-04-14T18:27:26.000Z | 2020-11-27T19:03:22.000Z | src/Parameters.cpp | MikeHeiber/Ising_OPV | 6a108675bdee1847abee0273b7874d9d312b048e | [
"MIT"
] | 5 | 2018-05-22T19:15:10.000Z | 2020-02-27T02:23:31.000Z | // Copyright (c) 2014-2019 Michael C. Heiber
// This source file is part of the Ising_OPV project, which is subject to the MIT License.
// For more information, see the LICENSE file that accompanies this software.
// The Ising_OPV project can be found on Github at https://github.com/MikeHeiber/Ising_OPV
#include "Parameters.h"
using namespace std;
namespace Ising_OPV {
Parameters::Parameters() {
}
bool Parameters::checkParameters() const {
bool Error_found = false;
// Check for valid lattice dimensions
if (Length <= 0 || Width <= 0 || Height <= 0) {
cout << "Parameter error! The input Length, Width, and Height of the lattice must be greater than zero." << endl;
Error_found = true;
}
// Check the input mix fraction
if (Mix_fraction < 0 || Mix_fraction > 1) {
cout << "Parameter error! The input Mix_fraction must be between 0 and 1." << endl;
Error_found = true;
}
// Check the input interaction energies
if (Interaction_energy1 < 0 || Interaction_energy2 < 0) {
cout << "Parameter error! The input Interaction_energy1 and Interaction_energy2 parameters cannot be negative." << endl;
Error_found = true;
}
// Check the input number of Monte Carlo steps
if (MC_steps < 0) {
cout << "Parameter error! The input MC_steps parameter cannot be negative." << endl;
Error_found = true;
}
// Check the smoothing parameters
if (Enable_smoothing && !(Smoothing_threshold > 0)) {
cout << "Parameter error! When performing smoothing, the input Smoothing_threshold must be greater than zero." << endl;
Error_found = true;
}
// Check the lattice resclae parameters
if (Enable_rescale && !(Rescale_factor > 0)) {
cout << "Parameter error! When rescaling the lattice, the input Rescale_factor must be greater than zero." << endl;
Error_found = true;
}
if (Enable_rescale && Enable_shrink && (Length % Rescale_factor != 0 || Width % Rescale_factor != 0 || Height % Rescale_factor != 0)) {
cout << "Parameter error! When shrinking the lattice, the input Rescale_factor must be an integer multiple of the Length, Width, and Height." << endl;
Error_found = true;
}
// Check the interfacial mixing parameters
if (Enable_interfacial_mixing && !(Interface_width > 0)) {
cout << "Parameter error! When performing interfacial mixing, the input Interface_width must be greater than zero." << endl;
Error_found = true;
}
if (Enable_interfacial_mixing && (!(Interface_conc > 0) || !(Interface_conc < 1))) {
cout << "Parameter error! When performing interfacial mixing, the input Interface_conc must be greater than zero and less than 1." << endl;
Error_found = true;
}
// Check the correlation calculation parameters
if (Enable_correlation_calc && !(N_sampling_max > 0)) {
cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl;
Error_found = true;
}
if (Enable_correlation_calc && Enable_mix_frac_method && Enable_e_method) {
cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl;
Error_found = true;
}
if (Enable_correlation_calc && !Enable_mix_frac_method && !Enable_e_method) {
cout << "Parameter error! When performing the correlation calculation, either the mix fraction method or the 1/e method must be enabled." << endl;
Error_found = true;
}
if (Enable_correlation_calc && Enable_extended_correlation_calc && !(Extended_correlation_cutoff_distance > 0)) {
cout << "Parameter error! When performing the extended correlation calculation, Extended_correlation_cutoff_distance must be greater than zero." << endl;
Error_found = true;
}
// Check the growth preference parameters
if (Enable_growth_pref && (Growth_direction < 1 || Growth_direction > 3)) {
cout << "Parameter error! When performing phase separation with a directional growth preference, the input Growth_direction paramter must be 1, 2, or 3." << endl;
Error_found = true;
}
if (Enable_growth_pref && !(Additional_interaction > 0) && !(Additional_interaction < 0)) {
cout << "Parameter error! When performing phase separation with a directional growth preference, the input Additional_interaction parameter must not be zero." << endl;
Error_found = true;
}
// Check tomogram import parameters
if (Enable_import_morphologies && Enable_import_tomogram) {
cout << "Parameter error! The import morphologies and import tomogram options cannot both be enabled." << endl;
Error_found = true;
}
if (Enable_import_tomogram && !(Desired_unit_size > 0)) {
cout << "Parameter error! When importing a tomogram dataset, the input Desired_unit_size must not be zero." << endl;
Error_found = true;
}
if (Enable_import_tomogram && !(Mixed_frac < 1)) {
cout << "Parameter error! When importing a tomogram dataset, the Mixed_frac must be graeter than equal to 0 and less than 1." << endl;
Error_found = true;
}
if (Enable_import_tomogram && (!(Mixed_conc > 0) || !(Mixed_conc < 1))) {
cout << "Parameter error! When importing a tomogram dataset, the Mixed_conc must be greater than zero and less than 1." << endl;
Error_found = true;
}
//if (Enable_import_tomogram && !Enable_cutoff_analysis && !Enable_probability_analysis) {
// cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis or the probability analysis option must be enabled." << endl;
// Error_found = true;
//}
//if (Enable_import_tomogram && Enable_cutoff_analysis && Enable_probability_analysis) {
// cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis and the probability analysis options cannot both be enabled." << endl;
// Error_found = true;
//}
//if (Enable_import_tomogram && Enable_probability_analysis && Probability_scaling_exponent < 0) {
// cout << "Parameter error! When importing a tomogram dataset and using the probability analysis option, the Probability_scaling_exponent must not be negative." << endl;
// Error_found = true;
//}
if (Enable_import_tomogram && N_extracted_segments <= 0) {
cout << "Parameter error! When importing a tomogram dataset, the input N_extracted segments must be greater than zero." << endl;
Error_found = true;
}
if (Enable_import_tomogram && N_variants <= 0) {
cout << "Parameter error! When importing a tomogram dataset, the input N_variants segments must be greater than zero." << endl;
Error_found = true;
}
if (Enable_import_tomogram && N_extracted_segments != intpow((int)floor(sqrt(N_extracted_segments)), 2)) {
cout << "Parameter error! When importing a tomogram dataset, the input value for N_extracted_segments must be 1, 4, 9, 16, 25, 36, 49, 64, 89, 100, 121, 144, 169, or 196 but " << N_extracted_segments << " was entered." << endl;
Error_found = true;
}
// Check other parameter conflicts
if (Enable_analysis_only && !Enable_import_morphologies && !Enable_import_tomogram) {
cout << "Parameter error! The 'analysis only' option can only be used when importing morphologies." << endl;
Error_found = true;
}
if (Error_found) {
return false;
}
return true;
}
bool Parameters::importParameters(ifstream& parameterfile) {
Version min_version("4.0.0-rc.1");
string line;
// Parse header file line
getline(parameterfile, line);
line = line.substr(line.find('v') + 1);
Version file_version;
try {
file_version = Version(line);
}
catch (invalid_argument exception) {
cout << "Error! Unable to load parameter file with version " << line << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl;
return false;
}
if (file_version < min_version) {
cout << "Error! Unable to load parameter file with v" << file_version << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl;
return false;
}
string var;
vector<string> stringvars;
// Read input file line by line.
while (getline(parameterfile, line)) {
// Skip lines designated as section breaks and section headers.
if ((line.substr(0, 2)).compare("--") != 0 && (line.substr(0, 2)).compare("##") != 0) {
// Strip off trailing comments from each line.
var = line.substr(0, line.find("//"));
var = removeWhitespace(var);
// Add parameter value strings to a vector.
stringvars.push_back(var);
}
}
// Check that correct number of parameters have been imported
if ((int)stringvars.size() != 42) {
cout << "Error! Incorrect number of parameters were loaded from the parameter file." << endl;
return false;
}
bool Error_found = false;
int i = 0;
// Convert strings into the correct data type and assign them to their corresponding parameter variable.
// General Parameters
Length = atoi(stringvars[i].c_str());
i++;
Width = atoi(stringvars[i].c_str());
i++;
Height = atoi(stringvars[i].c_str());
i++;
//enable_z_periodic_boundary
try {
Enable_periodic_z = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting z-direction periodic boundary conditions!" << endl;
Error_found = true;
}
i++;
Mix_fraction = atof(stringvars[i].c_str());
i++;
Interaction_energy1 = atof(stringvars[i].c_str());
i++;
Interaction_energy2 = atof(stringvars[i].c_str());
i++;
MC_steps = atoi(stringvars[i].c_str());
i++;
//enable_smoothing
try {
Enable_smoothing = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting morphology smoothing options" << endl;
Error_found = true;
}
i++;
Smoothing_threshold = atof(stringvars[i].c_str());
i++;
//enable_rescale
try {
Enable_rescale = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting morphology rescale options" << endl;
Error_found = true;
}
i++;
Rescale_factor = atoi(stringvars[i].c_str());
i++;
try {
Enable_shrink = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting morphology shrink options" << endl;
Error_found = true;
}
i++;
//enable_interfacial_mixing
try {
Enable_interfacial_mixing = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting interfacial mixing options" << endl;
Error_found = true;
}
i++;
Interface_width = atof(stringvars[i].c_str());
i++;
Interface_conc = atof(stringvars[i].c_str());
i++;
//enable_analysis_only
try {
Enable_analysis_only = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting analysis options" << endl;
Error_found = true;
}
i++;
//enable_correlation_calc
try {
Enable_correlation_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting correlation calculation options" << endl;
Error_found = true;
}
i++;
N_sampling_max = atoi(stringvars[i].c_str());
i++;
//enable_mix_frac_method
try {
Enable_mix_frac_method = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting correlation calculation domain size determination method options" << endl;
Error_found = true;
}
i++;
//enable_e_method
try {
Enable_e_method = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting correlation calculation domain size determination method options" << endl;
Error_found = true;
}
i++;
//enable_extended_correlation_calc
try {
Enable_extended_correlation_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting extended correlation calculation options" << endl;
Error_found = true;
}
i++;
Extended_correlation_cutoff_distance = atoi(stringvars[i].c_str());
i++;
//enable_interfacial_distance_calc
try {
Enable_interfacial_distance_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting interfacial distance calculation options" << endl;
Error_found = true;
}
i++;
//enable_tortuosity_calc
try {
Enable_tortuosity_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting tortuosity calculation options" << endl;
Error_found = true;
}
i++;
//enable_reduced_memory_tortuosity_calc
try {
Enable_reduced_memory_tortuosity_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting reduced memory tortuosity calculation options" << endl;
Error_found = true;
}
i++;
//enable_depth_dependent_cal
try {
Enable_depth_dependent_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting areal mapping calculation options" << endl;
Error_found = true;
}
i++;
//enable_areal_maps_cal
try {
Enable_areal_maps_calc = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting depth dependent calculation options" << endl;
Error_found = true;
}
i++;
//enable_checkerboard_start
try {
Enable_checkerboard_start = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting checkerboard starting condition" << endl;
Error_found = true;
}
i++;
//enable_growth_pref
try {
Enable_growth_pref = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting growth preference conditions" << endl;
Error_found = true;
}
i++;
Growth_direction = atoi(stringvars[i].c_str());
i++;
Additional_interaction = atof(stringvars[i].c_str());
i++;
// Export Morphology Parameters
//Enable_export_compressed_files
try {
Enable_export_compressed_files = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting export options" << endl;
Error_found = true;
}
i++;
//Enable_export_cross_section
try {
Enable_export_cross_section = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting export cross-section options" << endl;
Error_found = true;
}
i++;
// Import Morphology Options
//Enable_import_morphologies
try {
Enable_import_morphologies = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting morphology import option" << endl;
Error_found = true;
}
i++;
// Tomogram Import Options
//Enable_import_tomogram
try {
Enable_import_tomogram = str2bool(stringvars[i]);
}
catch (invalid_argument& exception) {
cout << exception.what() << endl;
cout << "Error setting tomogram import option" << endl;
Error_found = true;
}
i++;
Tomogram_name = stringvars[i];
i++;
Desired_unit_size = atof(stringvars[i].c_str());
i++;
//try {
// Enable_cutoff_analysis = str2bool(stringvars[i]);
//}
//catch (invalid_argument& exception) {
// cout << exception.what() << endl;
// cout << "Error setting tomogram import conditions" << endl;
// Error_found = true;
//}
//i++;
Mixed_frac = atof(stringvars[i].c_str());
i++;
Mixed_conc = atof(stringvars[i].c_str());
i++;
//try {
// Enable_probability_analysis = str2bool(stringvars[i]);
//}
//catch (invalid_argument& exception) {
// cout << exception.what() << endl;
// cout << "Error setting tomogram import conditions" << endl;
// Error_found = true;
//}
//i++;
//Probability_scaling_exponent = atof(stringvars[i].c_str());
//i++;
N_extracted_segments = atoi(stringvars[i].c_str());
i++;
N_variants = atoi(stringvars[i].c_str());
i++;
return !Error_found;
}
}
| 36.212719 | 230 | 0.690002 | MikeHeiber |
7845268ec5d8209992670ff50587909751d8c545 | 2,028 | cc | C++ | libqpdf/Pl_ASCIIHexDecoder.cc | tomty89/qpdf | e0775238b8b011755b9682555a8449b8a71f33eb | [
"Apache-2.0"
] | 1,812 | 2015-01-27T09:07:20.000Z | 2022-03-30T23:03:15.000Z | libqpdf/Pl_ASCIIHexDecoder.cc | tomty89/qpdf | e0775238b8b011755b9682555a8449b8a71f33eb | [
"Apache-2.0"
] | 584 | 2015-01-24T00:31:12.000Z | 2022-03-24T21:42:38.000Z | libqpdf/Pl_ASCIIHexDecoder.cc | tomty89/qpdf | e0775238b8b011755b9682555a8449b8a71f33eb | [
"Apache-2.0"
] | 204 | 2015-04-09T16:28:06.000Z | 2022-03-29T14:29:45.000Z | #include <qpdf/Pl_ASCIIHexDecoder.hh>
#include <qpdf/QTC.hh>
#include <stdexcept>
#include <string.h>
#include <ctype.h>
Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) :
Pipeline(identifier, next),
pos(0),
eod(false)
{
this->inbuf[0] = '0';
this->inbuf[1] = '0';
this->inbuf[2] = '\0';
}
Pl_ASCIIHexDecoder::~Pl_ASCIIHexDecoder()
{
}
void
Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len)
{
if (this->eod)
{
return;
}
for (size_t i = 0; i < len; ++i)
{
char ch = static_cast<char>(toupper(buf[i]));
switch (ch)
{
case ' ':
case '\f':
case '\v':
case '\t':
case '\r':
case '\n':
QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space");
// ignore whitespace
break;
case '>':
this->eod = true;
flush();
break;
default:
if (((ch >= '0') && (ch <= '9')) ||
((ch >= 'A') && (ch <= 'F')))
{
this->inbuf[this->pos++] = ch;
if (this->pos == 2)
{
flush();
}
}
else
{
char t[2];
t[0] = ch;
t[1] = 0;
throw std::runtime_error(
std::string("character out of range"
" during base Hex decode: ") + t);
}
break;
}
if (this->eod)
{
break;
}
}
}
void
Pl_ASCIIHexDecoder::flush()
{
if (this->pos == 0)
{
QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush");
return;
}
int b[2];
for (int i = 0; i < 2; ++i)
{
if (this->inbuf[i] >= 'A')
{
b[i] = this->inbuf[i] - 'A' + 10;
}
else
{
b[i] = this->inbuf[i] - '0';
}
}
unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]);
QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush",
(this->pos == 2) ? 0 : 1);
// Reset before calling getNext()->write in case that throws an
// exception.
this->pos = 0;
this->inbuf[0] = '0';
this->inbuf[1] = '0';
this->inbuf[2] = '\0';
getNext()->write(&ch, 1);
}
void
Pl_ASCIIHexDecoder::finish()
{
flush();
getNext()->finish();
}
| 17.482759 | 80 | 0.52071 | tomty89 |
784bdea7b6ec687d56c4c1e87db04a58522942f5 | 1,875 | cxx | C++ | Modules/Loadable/VolumeRendering/Testing/Cxx/qMRMLVolumePropertyNodeWidgetTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/Loadable/VolumeRendering/Testing/Cxx/qMRMLVolumePropertyNodeWidgetTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/Loadable/VolumeRendering/Testing/Cxx/qMRMLVolumePropertyNodeWidgetTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Julien Finet, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
#include "vtkSlicerConfigure.h" // Slicer_VTK_RENDERING_USE_{OpenGL|OpenGL2}_BACKEND
// Qt includes
#include <QApplication>
#include <QTimer>
// qMRML includes
#include "qMRMLVolumePropertyNodeWidget.h"
// MRML includes
#include <vtkMRMLVolumePropertyNode.h>
// VTK includes
#include <vtkSmartPointer.h>
#include "qMRMLWidget.h"
// this test only works on VTKv6 and later
#include <vtkAutoInit.h>
#if defined(Slicer_VTK_RENDERING_USE_OpenGL2_BACKEND)
VTK_MODULE_INIT(vtkRenderingContextOpenGL2);
#else
VTK_MODULE_INIT(vtkRenderingContextOpenGL);
#endif
// STD includes
int qMRMLVolumePropertyNodeWidgetTest1(int argc, char * argv [] )
{
qMRMLWidget::preInitializeApplication();
QApplication app(argc, argv);
qMRMLWidget::postInitializeApplication();
vtkSmartPointer<vtkMRMLVolumePropertyNode> volumePropertyNode =
vtkSmartPointer<vtkMRMLVolumePropertyNode>::New();
qMRMLVolumePropertyNodeWidget widget;
widget.setMRMLVolumePropertyNode(volumePropertyNode);
widget.show();
if (argc < 2 || QString(argv[1]) != "-I" )
{
QTimer::singleShot(200, &app, SLOT(quit()));
}
return app.exec();
}
| 27.573529 | 84 | 0.702933 | forfullstack |
784e1c675e1798b69faa732596d74064692a0655 | 11,561 | cpp | C++ | FEBioFluid/FEFluidSolutesNaturalFlux.cpp | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 59 | 2020-06-15T12:38:49.000Z | 2022-03-29T19:14:47.000Z | FEBioFluid/FEFluidSolutesNaturalFlux.cpp | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 36 | 2020-06-14T21:10:01.000Z | 2022-03-12T12:03:14.000Z | FEBioFluid/FEFluidSolutesNaturalFlux.cpp | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 26 | 2020-06-25T15:02:13.000Z | 2022-03-10T09:14:03.000Z | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
//For now only allows for one solute at a time, jn=-d0*gradc+c*vf
//Stiffness does not include effect from different solutes
#include "stdafx.h"
#include "FEFluidSolutesNaturalFlux.h"
#include "FEFluidMaterial.h"
#include "FEFluidSolutes.h"
#include "FEBioFluidSolutes.h"
#include <FECore/FELinearSystem.h>
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
//-----------------------------------------------------------------------------
// Parameter block for pressure loads
BEGIN_FECORE_CLASS(FEFluidSolutesNaturalFlux, FESurfaceLoad)
ADD_PARAMETER(m_beta, "beta");
ADD_PARAMETER(m_isol , "solute_id");
END_FECORE_CLASS()
//-----------------------------------------------------------------------------
//! constructor
FEFluidSolutesNaturalFlux::FEFluidSolutesNaturalFlux(FEModel* pfem) : FESurfaceLoad(pfem), m_dofW(pfem), m_dofC(pfem)
{
m_beta = 1.0;
m_isol = 1;
}
//-----------------------------------------------------------------------------
//! initialize
bool FEFluidSolutesNaturalFlux::Init()
{
if (m_isol == -1) return false;
// set up the dof lists
FEModel* fem = GetFEModel();
m_dofC.Clear();
m_dofW.Clear();
m_dofC.AddDof(fem->GetDOFIndex(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::FLUID_CONCENTRATION), m_isol-1));
m_dofW.AddVariable(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::RELATIVE_FLUID_VELOCITY));
m_dof.Clear();
m_dof.AddDofs(m_dofW);
m_dof.AddDofs(m_dofC);
FESurface& surf = GetSurface();
if (FESurfaceLoad::Init() == false) return false;
// get the list of FluidSolutes elements connected to this interface
int NF = surf.Elements();
m_elem.resize(NF);
for (int j = 0; j<NF; ++j)
{
FESurfaceElement& el = surf.Element(j);
// extract the first of two elements on this interface
m_elem[j] = el.m_elem[0];
// get its material and check if FluidSolutes
FEMaterial* pm = fem->GetMaterial(m_elem[j]->GetMatID());
FEFluidSolutes* pfsi = dynamic_cast<FEFluidSolutes*>(pm);
if (pfsi == nullptr) {
pm = fem->GetMaterial(el.m_elem[1]->GetMatID());
pfsi = dynamic_cast<FEFluidSolutes*>(pm);
if (pfsi == nullptr) return false;
m_elem[j] = el.m_elem[1];
}
}
return true;
}
//-----------------------------------------------------------------------------
void FEFluidSolutesNaturalFlux::Serialize(DumpStream& ar)
{
FESurfaceLoad::Serialize(ar);
if (ar.IsShallow() == false)
{
ar & m_dofC & m_dofW;
}
if (ar.IsShallow() == false)
{
if (ar.IsSaving())
{
int NE = (int)m_elem.size();
ar << NE;
for (int i = 0; i < NE; ++i)
{
FEElement* pe = m_elem[i];
int nid = (pe ? pe->GetID() : -1);
ar << nid;
}
}
else
{
FEMesh& mesh = ar.GetFEModel().GetMesh();
int NE, nid;
ar >> NE;
m_elem.resize(NE, nullptr);
for (int i = 0; i < NE; ++i)
{
ar >> nid;
if (nid != -1)
{
FEElement* pe = mesh.FindElementFromID(nid);
assert(pe);
m_elem[i] = pe;
}
}
}
}
}
//-----------------------------------------------------------------------------
void FEFluidSolutesNaturalFlux::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp)
{
m_psurf->LoadStiffness(LS, m_dof, m_dof, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, const FESurfaceDofShape& dof_b, matrix& Kab) {
FESurfaceElement& el = *mp.SurfaceElement();
int iel = el.m_lid;
int neln = el.Nodes();
// get the diffusivity
FEElement* pe = el.m_elem[0];
FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID());
FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm);
double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp);
double d0p = pfsm->GetSolute(m_isol-1)->m_pDiff->Tangent_Free_Diffusivity_Concentration(mp, m_isol-1);
double* N = el.H (mp.m_index);
double* Gr = el.Gr(mp.m_index);
double* Gs = el.Gs(mp.m_index);
// tangent vectors
vec3d rt[FEElement::MAX_NODES];
m_psurf->GetNodalCoordinates(el, tp.alphaf, rt);
vec3d dxr = el.eval_deriv1(rt, mp.m_index);
vec3d dxs = el.eval_deriv2(rt, mp.m_index);
vec3d n = dxr ^ dxs;
//double da = n.unit();
double alpha = tp.alphaf;
vector<vec3d> gradN(neln);
// Fluid velocity
vec3d v = FluidVelocity(mp, tp.alphaf);
double c = EffectiveConcentration(mp, tp.alphaf);
//vec3d v = FluidVelocityElm(mp);
//double c = EffectiveConcentrationElm(mp);
vec3d gradc = EffectiveCGrad(mp);
vec3d gcnt[2], gcntp[2];
m_psurf->ContraBaseVectors(el, mp.m_index, gcnt);
m_psurf->ContraBaseVectorsP(el, mp.m_index, gcntp);
for (int i = 0; i<neln; ++i)
gradN[i] = (gcnt[0] * alpha + gcntp[0] * (1 - alpha))*Gr[i] +
(gcnt[1] * alpha + gcntp[1] * (1 - alpha))*Gs[i];
Kab.zero();
// calculate stiffness component
int i = dof_a.index;
int j = dof_b.index;
vec3d kcw = n*(N[i]*N[j]*c*tp.alphaf);
double kcc = n*((-gradc*d0p+v)*N[j]-gradN[j]*d0)*(tp.alphaf*N[i]);
Kab[3][0] -= kcw.x;
Kab[3][1] -= kcw.y;
Kab[3][2] -= kcw.z;
Kab[3][3] -= kcc;
});
}
//-----------------------------------------------------------------------------
vec3d FEFluidSolutesNaturalFlux::FluidVelocity(FESurfaceMaterialPoint& mp, double alpha)
{
vec3d vt[FEElement::MAX_NODES];
FESurfaceElement& el = *mp.SurfaceElement();
int neln = el.Nodes();
for (int j = 0; j<neln; ++j) {
FENode& node = m_psurf->Node(el.m_lnode[j]);
vt[j] = node.get_vec3d(m_dofW[0], m_dofW[1], m_dofW[2])*alpha + node.get_vec3d_prev(m_dofW[0], m_dofW[1], m_dofW[2])*(1 - alpha);
}
return el.eval(vt, mp.m_index);
}
//-----------------------------------------------------------------------------
double FEFluidSolutesNaturalFlux::EffectiveConcentration(FESurfaceMaterialPoint& mp, double alpha)
{
double c = 0;
FESurfaceElement& el = *mp.SurfaceElement();
double* H = el.H(mp.m_index);
int neln = el.Nodes();
for (int j = 0; j < neln; ++j) {
FENode& node = m_psurf->Node(el.m_lnode[j]);
double cj = node.get(m_dofC[0])*alpha + node.get_prev(m_dofC[0])*(1.0 - alpha);
c += cj*H[j];
}
return c;
}
//-----------------------------------------------------------------------------
vec3d FEFluidSolutesNaturalFlux::EffectiveCGrad(FESurfaceMaterialPoint& pt)
{
FESurfaceElement& face = *pt.SurfaceElement();
int iel = face.m_lid;
// Get the fluid stress from the fluid-FSI element
vec3d gradc(0.0);
FEElement* pe = m_elem[iel];
int nint = pe->GaussPoints();
for (int n = 0; n<nint; ++n)
{
FEMaterialPoint& mp = *pe->GetMaterialPoint(n);
FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>());
gradc += spt.m_gradc[m_isol-1];
}
gradc /= nint;
return gradc;
}
//-----------------------------------------------------------------------------
double FEFluidSolutesNaturalFlux::EffectiveConcentrationElm(FESurfaceMaterialPoint& pt)
{
FESurfaceElement& face = *pt.SurfaceElement();
int iel = face.m_lid;
// Get the fluid stress from the fluid-FSI element
double c = 0.0;
FEElement* pe = m_elem[iel];
int nint = pe->GaussPoints();
for (int n = 0; n<nint; ++n)
{
FEMaterialPoint& mp = *pe->GetMaterialPoint(n);
FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>());
c += spt.m_c[m_isol-1];
}
c /= nint;
return c;
}
//-----------------------------------------------------------------------------
vec3d FEFluidSolutesNaturalFlux::FluidVelocityElm(FESurfaceMaterialPoint& pt)
{
FESurfaceElement& face = *pt.SurfaceElement();
int iel = face.m_lid;
// Get the fluid stress from the fluid-FSI element
vec3d v(0.0);
FEElement* pe = m_elem[iel];
int nint = pe->GaussPoints();
for (int n = 0; n<nint; ++n)
{
FEMaterialPoint& mp = *pe->GetMaterialPoint(n);
FEFluidMaterialPoint& fpt = *(mp.ExtractData<FEFluidMaterialPoint>());
v += fpt.m_vft;
}
v /= nint;
return v;
}
//-----------------------------------------------------------------------------
void FEFluidSolutesNaturalFlux::LoadVector(FEGlobalVector& R, const FETimeInfo& tp)
{
m_psurf->LoadVector(R, m_dofC, false, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, vector<double>& fa) {
FESurfaceElement& el = *mp.SurfaceElement();
// get the diffusivity
FEElement* pe = el.m_elem[0];
FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID());
FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm);
double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp);
// tangent vectors
vec3d rt[FEElement::MAX_NODES];
m_psurf->GetNodalCoordinates(el, tp.alphaf, rt);
vec3d dxr = el.eval_deriv1(rt, mp.m_index);
vec3d dxs = el.eval_deriv2(rt, mp.m_index);
// normal and area element
vec3d n = dxr ^ dxs;
//double da = n.unit();
// fluid velocity
vec3d v = FluidVelocity(mp, tp.alphaf);
double c = EffectiveConcentration(mp, tp.alphaf);
//vec3d v = FluidVelocityElm(mp);
//double c = EffectiveConcentrationElm(mp);
vec3d gradc = EffectiveCGrad(mp);
// force vector (change sign for inflow vs outflow)
double f = n*(-gradc*d0+v*c)*(m_beta);
double H = dof_a.shape;
fa[0] = H * f;
});
}
| 34.927492 | 155 | 0.564398 | AlexandraAllan23 |
784e40066228e00614cbf5ff86b6fe1e99c73de0 | 38,680 | cpp | C++ | Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //EInstruction.cpp
// Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>
// Copyright (c) Querysoft Limited 2012
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Implement an x86 instruction emittable
#include "ArchQOR.h"
#if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
#include "ArchQOR/x86/HLAssembler/Emittables/EInstruction.h"
#include "ArchQOR/x86/HLAssembler/x86HLAContext.h"
#include <assert.h>
//------------------------------------------------------------------------------
namespace nsArch
{
//------------------------------------------------------------------------------
namespace nsx86
{
//------------------------------------------------------------------------------
CEInstruction::CEInstruction( Cx86HLAIntrinsics* c, Cmp_unsigned__int32 code, COperand** operandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW : CEmittable( (nsArch::CHighLevelAssemblerBase*)c, EMITTABLE_INSTRUCTION )
{
m_uiCode = code;
m_uiEmitOptions = c->getEmitOptions();
c->setEmitOptions( 0 );// Each created instruction takes emit options and clears it.
m_pOperands = operandsData;
m_uiOperandsCount = operandsCount;
m_pVariables = 0;
m_uiVariablesCount = 0;
m_pMemOp = 0;
Cmp_unsigned__int32 i;
for( i = 0; i < operandsCount; i++ )
{
if( m_pOperands[ i ]->isMem() )
{
m_pMemOp = dynamic_cast< CMem* >( m_pOperands[ i ] );
break;
}
}
const InstructionDescription* id = &instructionDescription[ m_uiCode ];
m_bIsSpecial = id->isSpecial();
m_bIsFPU = id->isFPU();
m_bIsGPBLoUsed = false;
m_bIsGPBHiUsed = false;
if( m_bIsSpecial )
{
// ${SPECIAL_INSTRUCTION_HANDLING_BEGIN}
switch( m_uiCode )
{
case INST_CPUID:
// Special...
break;
case INST_CBW:
case INST_CDQE:
case INST_CWDE:
// Special...
break;
case INST_CMPXCHG:
case INST_CMPXCHG8B:
# if ( QOR_ARCH_WORDSIZE == 64 )
case INST_CMPXCHG16B:
# endif // ASMJIT_X64
// Special...
break;
# if ( QOR_ARCH_WORDSIZE == 64 )
case INST_DAA:
case INST_DAS:
// Special...
break;
# endif //
case INST_IMUL:
switch (operandsCount)
{
case 2:
// IMUL dst, src is not special instruction.
m_bIsSpecial = false;
break;
case 3:
if( !( m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && m_pOperands[ 2 ]->isVarMem() ) )
{
m_bIsSpecial = false; // Only IMUL dst_lo, dst_hi, reg/mem is special, all others not.
}
break;
}
break;
case INST_MUL:
case INST_IDIV:
case INST_DIV:
// Special...
break;
case INST_MOV_PTR:
// Special...
break;
case INST_LAHF:
case INST_SAHF:
// Special...
break;
case INST_MASKMOVQ:
case INST_MASKMOVDQU:
// Special...
break;
case INST_ENTER:
case INST_LEAVE:
// Special...
break;
case INST_RET:
// Special...
break;
case INST_MONITOR:
case INST_MWAIT:
// Special...
break;
case INST_POP:
case INST_POPAD:
case INST_POPFD:
case INST_POPFQ:
// Special...
break;
case INST_PUSH:
case INST_PUSHAD:
case INST_PUSHFD:
case INST_PUSHFQ:
// Special...
break;
case INST_RCL:
case INST_RCR:
case INST_ROL:
case INST_ROR:
case INST_SAL:
case INST_SAR:
case INST_SHL:
case INST_SHR:
// Rot instruction is special only if last operand is variable (register).
m_bIsSpecial = m_pOperands[ 1 ]->isVar();
break;
case INST_SHLD:
case INST_SHRD:
// Shld/Shrd instruction is special only if last operand is variable (register).
m_bIsSpecial = m_pOperands[ 2 ]->isVar();
break;
case INST_RDTSC:
case INST_RDTSCP:
// Special...
break;
case INST_REP_LODSB:
case INST_REP_LODSD:
case INST_REP_LODSQ:
case INST_REP_LODSW:
case INST_REP_MOVSB:
case INST_REP_MOVSD:
case INST_REP_MOVSQ:
case INST_REP_MOVSW:
case INST_REP_STOSB:
case INST_REP_STOSD:
case INST_REP_STOSQ:
case INST_REP_STOSW:
case INST_REPE_CMPSB:
case INST_REPE_CMPSD:
case INST_REPE_CMPSQ:
case INST_REPE_CMPSW:
case INST_REPE_SCASB:
case INST_REPE_SCASD:
case INST_REPE_SCASQ:
case INST_REPE_SCASW:
case INST_REPNE_CMPSB:
case INST_REPNE_CMPSD:
case INST_REPNE_CMPSQ:
case INST_REPNE_CMPSW:
case INST_REPNE_SCASB:
case INST_REPNE_SCASD:
case INST_REPNE_SCASQ:
case INST_REPNE_SCASW:
// Special...
break;
default:
assert( 0 );
}
// ${SPECIAL_INSTRUCTION_HANDLING_END}
}
}
//------------------------------------------------------------------------------
CEInstruction::~CEInstruction() __QCMP_THROW
{
}
//------------------------------------------------------------------------------
void CEInstruction::getVariable( VarData* _candidate, VarAllocRecord*& cur, VarAllocRecord*& var )
{
for( var = cur; ;)
{
if( var == m_pVariables )
{
var = cur++;
var->vdata = _candidate;
var->vflags = 0;
var->regMask = 0xFFFFFFFF;
break;
}
var--;
if( var->vdata == _candidate )
{
break;
}
}
assert( var != 0 );
}
//------------------------------------------------------------------------------
void CEInstruction::prepare( CHLAssemblerContextBase& hlac ) __QCMP_THROW
{
Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac );
/*
# define __GET_VARIABLE(__vardata__) \
{ \
VarData* _candidate = __vardata__; \
\
for (var = cur; ;) \
{ \
if (var == m_pVariables) \
{ \
var = cur++; \
var->vdata = _candidate; \
var->vflags = 0; \
var->regMask = 0xFFFFFFFF; \
break; \
} \
\
var--; \
\
if (var->vdata == _candidate) \
{ \
break; \
} \
} \
\
assert(var != 0); \
}
*/
m_uiOffset = cc.GetCurrentOffset();
const InstructionDescription* id = &instructionDescription[ m_uiCode ];
Cmp_unsigned__int32 i, len = m_uiOperandsCount;
Cmp_unsigned__int32 variablesCount = 0;
for( i = 0; i < len; i++ )
{
COperand* o = m_pOperands[ i ];
if( o->isVar() )
{
assert( o->getId() != INVALID_VALUE );
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() );
assert( vdata != 0 );
CBaseVar* pVar = dynamic_cast< CBaseVar* >( o );
if( pVar && pVar->isGPVar() )
{
if( pVar->isGPBLo() )
{
m_bIsGPBLoUsed = true;
vdata->registerGPBLoCount++;
};
if( pVar->isGPBHi() )
{
m_bIsGPBHiUsed = true;
vdata->registerGPBHiCount++;
};
}
if( vdata->workOffset != m_uiOffset )
{
if( !cc._isActive( vdata ) )
{
cc._addActive( vdata );
}
vdata->workOffset = m_uiOffset;
variablesCount++;
}
}
else if( o->isMem() )
{
CMem& m( dynamic_cast< CMem& >( *o ) );
if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() );
assert( vdata != 0 );
cc._markMemoryUsed( vdata );
if( vdata->workOffset != m_uiOffset )
{
if( !cc._isActive( vdata ) )
{
cc._addActive( vdata );
}
vdata->workOffset = m_uiOffset;
variablesCount++;
}
}
else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() );
assert( vdata != 0 );
if( vdata->workOffset != m_uiOffset )
{
if( !cc._isActive( vdata ) )
{
cc._addActive( vdata );
}
vdata->workOffset = m_uiOffset;
variablesCount++;
}
}
if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() );
assert( vdata != 0 );
if( vdata->workOffset != m_uiOffset )
{
if( !cc._isActive( vdata ) )
{
cc._addActive( vdata );
}
vdata->workOffset = m_uiOffset;
variablesCount++;
}
}
}
}
if( !variablesCount )
{
cc.IncrementCurrentOffset();
return;
}
m_pVariables = reinterpret_cast< VarAllocRecord* >( ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->getZone().zalloc( sizeof( VarAllocRecord ) * variablesCount ) );
if( !m_pVariables )
{
( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->setError( ERROR_NO_HEAP_MEMORY );
cc.IncrementCurrentOffset();
return;
}
m_uiVariablesCount = variablesCount;
VarAllocRecord* cur = m_pVariables;
VarAllocRecord* var = 0;
bool _isGPBUsed = m_bIsGPBLoUsed || m_bIsGPBHiUsed;
Cmp_unsigned__int32 gpRestrictMask = nsCodeQOR::maskUpToIndex( REG_NUM_GP );
# if ( QOR_ARCH_WORDSIZE == 64 )
if( m_bIsGPBHiUsed )
{
gpRestrictMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EBP ) |
nsCodeQOR::maskFromIndex( REG_INDEX_ESI ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EDI ) ;
}
# endif // ASMJIT_X64
for( i = 0; i < len; i++ )
{
COperand* o = m_pOperands[ i ];
if( o->isVar() )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() );
assert( vdata != 0 );
//__GET_VARIABLE( vdata )
getVariable( vdata, cur, var );
var->vflags |= VARIABLE_ALLOC_REGISTER;
CBaseVar* pVar = dynamic_cast< CBaseVar* >( o );
if( _isGPBUsed )
{
CGPVar* pGPVar = dynamic_cast< CGPVar* >( pVar );
# if ( QOR_ARCH_WORDSIZE == 32 )
if( pGPVar->isGPB() )
{
var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) ;
}
# else
// Restrict all BYTE registers to RAX/RBX/RCX/RDX if HI BYTE register
// is used (REX prefix makes HI BYTE addressing unencodable).
if( m_bIsGPBHiUsed )
{
if( pGPVar->isGPB() )
{
var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) |
nsCodeQOR::maskFromIndex( REG_INDEX_EDX );
}
}
# endif //
}
if( isSpecial() )
{
// ${SPECIAL_INSTRUCTION_HANDLING_BEGIN}
switch( m_uiCode )
{
case INST_CPUID:
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
case 3:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_CBW:
case INST_CDQE:
case INST_CWDE:
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_CMPXCHG:
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE;
break;
case 2:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
break;
default:
assert( 0 );
}
break;
case INST_CMPXCHG8B:
# if ( QOR_ARCH_WORDSIZE == 64 )
case INST_CMPXCHG16B:
# endif // ASMJIT_X64
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
case 3:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
# if ( QOR_ARCH_WORDSIZE == 32 )
case INST_DAA:
case INST_DAS:
assert( i == 0 );
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
# endif // ( QOR_ARCH_WORDSIZE == 32 )
case INST_IMUL:
case INST_MUL:
case INST_IDIV:
case INST_DIV:
switch( i )
{
case 0:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
break;
default:
assert( 0 );
}
break;
case INST_MOV_PTR:
switch( i )
{
case 0:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_LAHF:
assert( i == 0 );
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case INST_SAHF:
assert( i == 0 );
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case INST_MASKMOVQ:
case INST_MASKMOVDQU:
switch( i )
{
case 0:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI );
gpRestrictMask &= ~var->regMask;
break;
case 1:
case 2:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
break;
}
break;
case INST_ENTER:
case INST_LEAVE:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_RET:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_MONITOR:
case INST_MWAIT:
// TODO: MONITOR/MWAIT (COMPILER).
break;
case INST_POP:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_POPAD:
case INST_POPFD:
case INST_POPFQ:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_PUSH:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_PUSHAD:
case INST_PUSHFD:
case INST_PUSHFQ:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_RCL:
case INST_RCR:
case INST_ROL:
case INST_ROR:
case INST_SAL:
case INST_SAR:
case INST_SHL:
case INST_SHR:
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_SHLD:
case INST_SHRD:
switch( i )
{
case 0:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
break;
case 2:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_RDTSC:
case INST_RDTSCP:
switch( i )
{
case 0:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
assert( m_uiCode == INST_RDTSCP );
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_REP_LODSB:
case INST_REP_LODSD:
case INST_REP_LODSQ:
case INST_REP_LODSW:
switch( i )
{
case 0:
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_REP_MOVSB:
case INST_REP_MOVSD:
case INST_REP_MOVSQ:
case INST_REP_MOVSW:
case INST_REPE_CMPSB:
case INST_REPE_CMPSD:
case INST_REPE_CMPSQ:
case INST_REPE_CMPSW:
case INST_REPNE_CMPSB:
case INST_REPNE_CMPSD:
case INST_REPNE_CMPSQ:
case INST_REPNE_CMPSW:
switch( i )
{
case 0:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_REP_STOSB:
case INST_REP_STOSD:
case INST_REP_STOSQ:
case INST_REP_STOSW:
switch( i )
{
case 0:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
case INST_REPE_SCASB:
case INST_REPE_SCASD:
case INST_REPE_SCASQ:
case INST_REPE_SCASW:
case INST_REPNE_SCASB:
case INST_REPNE_SCASD:
case INST_REPNE_SCASQ:
case INST_REPNE_SCASW:
switch( i )
{
case 0:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI );
gpRestrictMask &= ~var->regMask;
break;
case 1:
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX );
gpRestrictMask &= ~var->regMask;
break;
case 2:
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL;
var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX );
gpRestrictMask &= ~var->regMask;
break;
default:
assert( 0 );
}
break;
default:
assert( 0 );
}
// ${SPECIAL_INSTRUCTION_HANDLING_END}
}
else
{
if( i == 0 )
{
// CMP/TEST instruction.
if( id->code == INST_CMP || id->code == INST_TEST )
{
// Read-only case.
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
}
// CVTTSD2SI/CVTTSS2SI instructions.
else if( id->code == INST_CVTTSD2SI || id->code == INST_CVTTSS2SI )
{
// In 32-bit mode the whole destination is replaced. In 64-bit mode
// we need to check whether the destination operand size is 64-bits.
#if ( QOR_ARCH_WORDSIZE == 64 )
if (m_pOperands[0]->isRegType(REG_TYPE_GPQ))
{
#endif // X64
// Write-only case.
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE;
#if ( QOR_ARCH_WORDSIZE == 64 )
}
else
{
// Read/Write.
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE;
}
#endif // ASMJIT_X64
}
// MOV/MOVSS/MOVSD instructions.
//
// If instruction is MOV (source replaces the destination) or
// MOVSS/MOVSD and source operand is memory location then register
// allocator should know that previous destination value is lost
// (write only operation).
else if( ( id->isMov()) || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) /* && _operands[1].isMem() */ ) || ( id->code == INST_IMUL && m_uiOperandsCount == 3 && !isSpecial() ) )
{
// Write-only case.
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE;
}
else if( id->code == INST_LEA )
{
// Write.
vdata->registerWriteCount++;
var->vflags |= VARIABLE_ALLOC_WRITE;
}
else
{
// Read/Write.
vdata->registerRWCount++;
var->vflags |= VARIABLE_ALLOC_READWRITE;
}
}
else
{
// Second, third, ... operands are read-only.
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_READ;
}
if( !m_pMemOp && i < 2 && ( id->oflags[ i ] & InstructionDescription::O_MEM ) != 0 )
{
var->vflags |= VARIABLE_ALLOC_MEMORY;
}
}
// If variable must be in specific register we could add some hint to allocator.
if( var->vflags & VARIABLE_ALLOC_SPECIAL )
{
vdata->prefRegisterMask |= nsCodeQOR::maskFromIndex( var->regMask );
cc._newRegisterHomeIndex( vdata, nsCodeQOR::findFirstBit( var->regMask ) );
}
}
else if( o->isMem() )
{
CMem& m( dynamic_cast< CMem& >( *o ) );
if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() );
assert( vdata != 0 );
//__GET_VARIABLE( vdata )
getVariable( vdata, cur, var );
if( i == 0 )
{
// If variable is MOV instruction type (source replaces the destination)
// or variable is MOVSS/MOVSD instruction then register allocator should
// know that previous destination value is lost (write only operation).
if( id->isMov() || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) ) )
{
// Write only case.
vdata->memoryWriteCount++;
}
else
{
vdata->memoryRWCount++;
}
}
else
{
vdata->memoryReadCount++;
}
}
else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() );
assert( vdata != 0 );
//__GET_VARIABLE( vdata )
getVariable( vdata, cur, var );
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ;
var->regMask &= gpRestrictMask;
}
if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() );
assert( vdata != 0 );
//__GET_VARIABLE( vdata )
getVariable( vdata, cur, var );
vdata->registerReadCount++;
var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ;
var->regMask &= gpRestrictMask;
}
}
}
// Traverse all variables and update firstEmittable / lastEmittable. This
// function is called from iterator that scans emittables using forward
// direction so we can use this knowledge to optimize the process.
// Similar to ECall::prepare().
for( i = 0; i < m_uiVariablesCount; i++ )
{
VarData* v = m_pVariables[ i ].vdata;
// Update GP register allocator restrictions.
if( isVariableInteger( v->type ) )
{
if( m_pVariables[ i ].regMask == 0xFFFFFFFF )
{
m_pVariables[ i ].regMask &= gpRestrictMask;
}
}
// Update first/last emittable (begin of variable scope).
if( v->firstEmittable == 0 )
{
v->firstEmittable = this;
}
v->lastEmittable = this;
}
// There are some instructions that can be used to clear register or to set
// register to some value (ideal case is all zeros or all ones).
//
// xor/pxor reg, reg ; Set all bits in reg to 0.
// sub/psub reg, reg ; Set all bits in reg to 0.
// andn reg, reg ; Set all bits in reg to 0.
// pcmpgt reg, reg ; Set all bits in reg to 0.
// pcmpeq reg, reg ; Set all bits in reg to 1.
if( m_uiVariablesCount == 1 && m_uiOperandsCount > 1 && m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && !m_pMemOp )
{
switch( m_uiCode )
{
// XOR Instructions.
case INST_XOR:
case INST_XORPD:
case INST_XORPS:
case INST_PXOR:
// ANDN Instructions.
case INST_PANDN:
// SUB Instructions.
case INST_SUB:
case INST_PSUBB:
case INST_PSUBW:
case INST_PSUBD:
case INST_PSUBQ:
case INST_PSUBSB:
case INST_PSUBSW:
case INST_PSUBUSB:
case INST_PSUBUSW:
// PCMPEQ Instructions.
case INST_PCMPEQB:
case INST_PCMPEQW:
case INST_PCMPEQD:
case INST_PCMPEQQ:
// PCMPGT Instructions.
case INST_PCMPGTB:
case INST_PCMPGTW:
case INST_PCMPGTD:
case INST_PCMPGTQ:
// Clear the read flag. This prevents variable alloc/spill.
m_pVariables[ 0 ].vflags = VARIABLE_ALLOC_WRITE;
m_pVariables[ 0 ].vdata->registerReadCount--;
break;
}
}
cc.IncrementCurrentOffset();
//# undef __GET_VARIABLE
}
//------------------------------------------------------------------------------
nsArch::CEmittable* CEInstruction::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW
{
Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac );
Cmp_unsigned__int32 i;
Cmp_unsigned__int32 variablesCount = m_uiVariablesCount;
if( variablesCount > 0 )
{
// These variables are used by the instruction and we set current offset
// to their work offsets -> getSpillCandidate never return the variable
// used this instruction.
for( i = 0; i < variablesCount; i++ )
{
m_pVariables->vdata->workOffset = cc.GetCurrentOffset();
}
// Alloc variables used by the instruction (special first).
for( i = 0; i < variablesCount; i++ )
{
VarAllocRecord& r = m_pVariables[ i ];
// Alloc variables with specific register first.
if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) != 0 )
{
cc.allocVar( r.vdata, r.regMask, r.vflags );
}
}
for( i = 0; i < variablesCount; i++ )
{
VarAllocRecord& r = m_pVariables[ i ];
// Alloc variables without specific register last.
if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) == 0 )
{
cc.allocVar( r.vdata, r.regMask, r.vflags );
}
}
cc.translateOperands( m_pOperands, m_uiOperandsCount );
}
if( m_pMemOp && ( m_pMemOp->getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR )
{
VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m_pMemOp->getId() );
assert( vdata != 0 );
switch( vdata->state )
{
case VARIABLE_STATE_UNUSED:
vdata->state = VARIABLE_STATE_MEMORY;
break;
case VARIABLE_STATE_REGISTER:
vdata->changed = false;
cc.unuseVar( vdata, VARIABLE_STATE_MEMORY );
break;
}
}
for( i = 0; i < variablesCount; i++ )
{
cc._unuseVarOnEndOfScope( this, &m_pVariables[ i ] );
}
return translated();
}
//------------------------------------------------------------------------------
void CEInstruction::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW
{
CCPU* pAssembler = dynamic_cast< CCPU* >( ( dynamic_cast< Cx86HLAIntrinsics& >( ab ) ).getAssembler() );
pAssembler->SetComment( m_szComment );
pAssembler->SetEmitOptions( m_uiEmitOptions );
if( isSpecial() )
{
// ${SPECIAL_INSTRUCTION_HANDLING_BEGIN}
switch( m_uiCode )
{
case INST_CPUID:
pAssembler->_emitInstruction( m_uiCode );
return;
case INST_CBW:
case INST_CDQE:
case INST_CWDE:
pAssembler->_emitInstruction( m_uiCode );
return;
case INST_CMPXCHG:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] );
return;
case INST_CMPXCHG8B:
#if ( QOR_ARCH_WORDSIZE == 64 )
case INST_CMPXCHG16B:
#endif // ASMJIT_X64
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 4 ] );
return;
#if ( QOR_ARCH_WORDSIZE == 64 )
case INST_DAA:
case INST_DAS:
pAssembler->_emitInstruction( m_uiCode );
return;
#endif //
case INST_IMUL:
case INST_MUL:
case INST_IDIV:
case INST_DIV:
// INST dst_lo (implicit), dst_hi (implicit), src (explicit)
assert( m_uiOperandsCount == 3 );
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 2 ] );
return;
case INST_MOV_PTR:
break;
case INST_LAHF:
case INST_SAHF:
pAssembler->_emitInstruction( m_uiCode );
return;
case INST_MASKMOVQ:
case INST_MASKMOVDQU:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] );
return;
case INST_ENTER:
case INST_LEAVE:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_RET:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_MONITOR:
case INST_MWAIT:
// TODO: MONITOR/MWAIT (COMPILER).
break;
case INST_POP:
case INST_POPAD:
case INST_POPFD:
case INST_POPFQ:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_PUSH:
case INST_PUSHAD:
case INST_PUSHFD:
case INST_PUSHFQ:
// TODO: SPECIAL INSTRUCTION.
break;
case INST_RCL:
case INST_RCR:
case INST_ROL:
case INST_ROR:
case INST_SAL:
case INST_SAR:
case INST_SHL:
case INST_SHR:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], &Cx86CPUCore::cl );
return;
case INST_SHLD:
case INST_SHRD:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], &Cx86CPUCore::cl );
return;
case INST_RDTSC:
case INST_RDTSCP:
pAssembler->_emitInstruction( m_uiCode );
return;
case INST_REP_LODSB:
case INST_REP_LODSD:
case INST_REP_LODSQ:
case INST_REP_LODSW:
case INST_REP_MOVSB:
case INST_REP_MOVSD:
case INST_REP_MOVSQ:
case INST_REP_MOVSW:
case INST_REP_STOSB:
case INST_REP_STOSD:
case INST_REP_STOSQ:
case INST_REP_STOSW:
case INST_REPE_CMPSB:
case INST_REPE_CMPSD:
case INST_REPE_CMPSQ:
case INST_REPE_CMPSW:
case INST_REPE_SCASB:
case INST_REPE_SCASD:
case INST_REPE_SCASQ:
case INST_REPE_SCASW:
case INST_REPNE_CMPSB:
case INST_REPNE_CMPSD:
case INST_REPNE_CMPSQ:
case INST_REPNE_CMPSW:
case INST_REPNE_SCASB:
case INST_REPNE_SCASD:
case INST_REPNE_SCASQ:
case INST_REPNE_SCASW:
pAssembler->_emitInstruction( m_uiCode );
return;
default:
assert( 0 );
}
// ${SPECIAL_INSTRUCTION_HANDLING_END}
}
switch( m_uiOperandsCount )
{
case 0:
pAssembler->_emitInstruction( m_uiCode );
break;
case 1:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ] );
break;
case 2:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ] );
break;
case 3:
pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], m_pOperands[ 2 ] );
break;
default:
assert( 0 );
break;
}
}
//------------------------------------------------------------------------------
int CEInstruction::getMaxSize() const __QCMP_THROW
{
// TODO: Do something more exact.
return 15;
}
//------------------------------------------------------------------------------
bool CEInstruction::tryUnuseVar( nsArch::CommonVarData* vdata ) __QCMP_THROW
{
VarData* v = reinterpret_cast< VarData* >( vdata );
for( Cmp_unsigned__int32 i = 0; i < m_uiVariablesCount; i++ )
{
if( m_pVariables[ i ].vdata == v )
{
m_pVariables[ i ].vflags |= VARIABLE_ALLOC_UNUSE_AFTER_USE;
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
CETarget* CEInstruction::getJumpTarget() const __QCMP_THROW
{
return 0;
}
}//nsx86
}//nsArch
#endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
| 27.569494 | 228 | 0.594907 | mfaithfull |
7854be80c217f33d28aa45dad4e7ff06fb4cb6d7 | 1,507 | hpp | C++ | src/collection_iterator.hpp | stanislav-podlesny/cpp-driver | be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d | [
"Apache-2.0"
] | null | null | null | src/collection_iterator.hpp | stanislav-podlesny/cpp-driver | be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d | [
"Apache-2.0"
] | null | null | null | src/collection_iterator.hpp | stanislav-podlesny/cpp-driver | be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2014-2015 DataStax
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 __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__
#define __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__
#include "cassandra.h"
#include "iterator.hpp"
#include "value.hpp"
#include "serialization.hpp"
namespace cass {
class CollectionIterator : public Iterator {
public:
CollectionIterator(const Value* collection)
: Iterator(CASS_ITERATOR_TYPE_COLLECTION)
, collection_(collection)
, position_(collection->buffer().data())
, index_(-1)
, count_(collection_->type() == CASS_VALUE_TYPE_MAP
? (2 * collection_->count())
: collection->count()) {}
virtual bool next();
const Value* value() {
assert(index_ >= 0 && index_ < count_);
return &value_;
}
private:
char* decode_value(char* position);
private:
const Value* collection_;
char* position_;
Value value_;
int32_t index_;
const int32_t count_;
};
} // namespace cass
#endif
| 25.542373 | 74 | 0.711347 | stanislav-podlesny |
7856065930e739509cee13ad26aea5f0acf43ca8 | 1,035 | cpp | C++ | jsUnits/jsEnergy.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsEnergy.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsEnergy.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 DNV AS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <jsUnits/jsEnergy.h>
#include <jsUnits/jsUnitClass.h>
#include <Units/Energy.h>
#include "jsMomentOfForce.h"
#include "jsRotationalStiffness.h"
using namespace DNVS::MoFa::Units;
Runtime::DynamicPhenomenon jsEnergy::GetPhenomenon()
{
return EnergyPhenomenon();
}
void jsEnergy::init(jsTypeLibrary& typeLibrary)
{
jsUnitClass<jsEnergy,Energy> cls(typeLibrary);
if(cls.reinit()) return;
cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsMomentOfForce>);
cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsRotationalStiffness>);
cls.ImplicitConstructorConversion([](const jsEnergy& val) {return MomentOfForce(val); });
cls.ImplicitConstructorConversion([](const jsEnergy& val) {return RotationalStiffness(val); });
}
| 34.5 | 126 | 0.770048 | dnv-opensource |
785914de32d34ecb74d516c667d9108859f24afa | 697 | cpp | C++ | Source/Runtime/Foundation/Filesystem/FileStream.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | Source/Runtime/Foundation/Filesystem/FileStream.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | Source/Runtime/Foundation/Filesystem/FileStream.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | // Copyright 2008-2014 Simon Ekström
#include "Common.h"
#include "FileStream.h"
namespace sb
{
FileStream::FileStream(const File& file) : _file(file)
{
Assert(_file.IsOpen());
}
FileStream::~FileStream()
{
_file.Close();
}
size_t FileStream::Read(void* dst, size_t size)
{
return _file.Read(dst, (uint32_t)size);
}
size_t FileStream::Write(const void* src, size_t size)
{
return _file.Write(src, (uint32_t)size);
}
int64_t FileStream::Seek(int64_t offset)
{
return _file.Seek(offset, File::SEEK_ORIGIN_BEGIN);
}
int64_t FileStream::Tell() const
{
return _file.Tell();
}
int64_t FileStream::Length() const
{
return _file.Length();
}
} // namespace sb
| 15.152174 | 55 | 0.681492 | simeks |
785d578f6507848e8cf41c80bbecf74b5faf81d2 | 7,764 | cpp | C++ | NtpRsk/NtpRsk.cpp | bochen8709/core | d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d | [
"MIT"
] | 1 | 2021-07-11T10:27:46.000Z | 2021-07-11T10:27:46.000Z | NtpRsk/NtpRsk.cpp | bochen8709/core | d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d | [
"MIT"
] | null | null | null | NtpRsk/NtpRsk.cpp | bochen8709/core | d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d | [
"MIT"
] | null | null | null | #include <openssl/bn.h>
#include "NtpRsk.h"
#include <openssl/rand.h>
#include <iostream>
/**
* A is signature, X is the signed message hash
* A^e = X
*
* e is the RSA exponent, typically 2^16 + 1
*
* The proof is d where 1 < d < e (typically 2^16)
*
* r is a random number, then:
*
* (A^d *r)^e = X^d * (r^e) mod n
* t T
*
*
* (A^d1 *r)^e = X^d1 * (r^e) mod n
* (A^d2 *r)^e = X^d2 * (r^e) mod n
* (A^d3 *r)^e = X^d3 * (r^e) mod n
* (A^d4 *r)^e = X^d4 * (r^e) mod n
* (A^d5 *r)^e = X^d5 * (r^e) mod n
*
* what is published is T = (r^e)
* t1 = (A^d1 *r)
* t2 = (A^d2 *r)
* t3 = (A^d3 *r)
* t4 = (A^d4 *r)
* t5 = (A^d5 *r)
*
*/
NtpRskSignatureVerificationObject* NtpRsk::signWithNtpRsk(NtpRskSignatureRequestObject *ntpRskSignatureRequestObject) {
NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject = new NtpRskSignatureVerificationObject();
const BIGNUM* n = ntpRskSignatureRequestObject->getN();
const BIGNUM* e = ntpRskSignatureRequestObject->getE();
BIGNUM* e2 = BN_new();
BIGNUM* sub = BN_new();
BIGNUM* add = BN_new();
BN_dec2bn(&add, "2");
BN_dec2bn(&sub, "4");
BN_sub(e2, e, sub);
BIGNUM* signature = ntpRskSignatureRequestObject->getSignature();
BIGNUM* nm = ntpRskSignatureRequestObject->getNm();
BN_CTX *ctx = BN_CTX_new();
BIGNUM* r = randomBignum(n);
BIGNUM* d = BN_new();
BN_mod(d, nm, e2, ctx);
BN_add(d, d, add);
BIGNUM* t1 = BN_new();
BIGNUM* T = BN_new();
BIGNUM* salt = BN_new();
std::cout << "d1 : " << BN_bn2dec(d) << std::endl;
std::cout << "e : " << BN_bn2dec(e) << std::endl;
std::cout << "n : " << BN_bn2dec(n) << std::endl;
// T = r^v
BN_mod_exp(T, r, e, n, ctx);
ntpRskSignatureVerificationObject->setT(T);
std::cout << "T : " << BN_bn2dec(T) << std::endl;
// t1 = (A^d *r)
BN_mod_exp(t1, signature, d, n, ctx);
BN_mod_mul(t1, t1, r, n, ctx);
ntpRskSignatureVerificationObject->setT1(t1);
// t2 = (A^d *r)
BIGNUM* t2 = BN_new();
BIGNUM* XT = BN_new();
BN_mod_exp(XT, t1, e, n, ctx);
BN_dec2bn(&salt, "1618446177786864861468428776289946168463");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t2, signature, d, n, ctx);
BN_mod_mul(t2, t2, r, n, ctx);
ntpRskSignatureVerificationObject->setT2(t2);
// t3 = (A^d *r)
BIGNUM* t3 = BN_new();
BN_mod_exp(XT, t2, e, n, ctx);
BN_dec2bn(&salt, "2468284666624768462658468131846646451821");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t3, signature, d, n, ctx);
BN_mod_mul(t3, t3, r, n, ctx);
ntpRskSignatureVerificationObject->setT3(t3);
// t4 = (A^d *r)
BIGNUM* t4 = BN_new();
BN_mod_exp(XT, t3, e, n, ctx);
BN_dec2bn(&salt, "386846284626847646244761844687764462164");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t4, signature, d, n, ctx);
BN_mod_mul(t4, t4, r, n, ctx);
ntpRskSignatureVerificationObject->setT4(t4);
// t5 = (A^d *r)
BIGNUM* t5 = BN_new();
BN_mod_exp(XT, t4, e, n, ctx);
BN_dec2bn(&salt, "456156843515512741515122247552415322464");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t5, signature, d, n, ctx);
BN_mod_mul(t5, t5, r, n, ctx);
ntpRskSignatureVerificationObject->setT5(t5);
ntpRskSignatureVerificationObject->setPaddedM(ntpRskSignatureRequestObject->getPaddedM());
ntpRskSignatureVerificationObject->setM(ntpRskSignatureRequestObject->getM());
ntpRskSignatureVerificationObject->setNm(ntpRskSignatureRequestObject->getNm());
ntpRskSignatureVerificationObject->setE(ntpRskSignatureRequestObject->getE());
ntpRskSignatureVerificationObject->setN(ntpRskSignatureRequestObject->getN());
ntpRskSignatureVerificationObject->setMdAlg(ntpRskSignatureRequestObject->getMdAlg());
ntpRskSignatureVerificationObject->setSignedPayload(ntpRskSignatureRequestObject->getSignedPayload());
return ntpRskSignatureVerificationObject;
}
bool NtpRsk::verifyNtpRsk(NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject) {
BIGNUM* T = ntpRskSignatureVerificationObject->getT();
BIGNUM* t1 = ntpRskSignatureVerificationObject->getT1();
BIGNUM* t2 = ntpRskSignatureVerificationObject->getT2();
BIGNUM* t3 = ntpRskSignatureVerificationObject->getT3();
BIGNUM* t4 = ntpRskSignatureVerificationObject->getT4();
BIGNUM* t5 = ntpRskSignatureVerificationObject->getT5();
const BIGNUM* e = ntpRskSignatureVerificationObject->getE();
BIGNUM* e2 = BN_new();
BIGNUM* sub = BN_new();
BIGNUM* add = BN_new();
BN_dec2bn(&add, "2");
BN_dec2bn(&sub, "4");
BN_sub(e2, e, sub);
const BIGNUM* n = ntpRskSignatureVerificationObject->getN();
BIGNUM* m = ntpRskSignatureVerificationObject->getPaddedM();
BIGNUM* nm = ntpRskSignatureVerificationObject->getNm();
BN_CTX *ctx = BN_CTX_new();
// verify t^v = X^d * T mod n
BIGNUM* XT = BN_new();
BIGNUM* salt = BN_new();
BIGNUM* d = BN_new();
BN_mod(d, nm, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t1, t1, e, n, ctx);
BN_mod_exp(XT, m, d, n, ctx);
BN_mod_mul(XT, XT, T, n, ctx);
if(BN_cmp(XT, t1) != 0) {
std::cout << "d1 : " << BN_bn2dec(d) << std::endl;
std::cout << "e1 : " << BN_bn2dec(e) << std::endl;
std::cout << "n1 : " << BN_bn2dec(n) << std::endl;
std::cout << "T1 : " << BN_bn2dec(T) << std::endl;
std::cout << "BN_cmp(XT, t1) failed" << std::endl;
std::cout << "XT " << BN_bn2dec(XT) << std::endl;
std::cout << "t1 " << BN_bn2dec(t1) << std::endl;
BN_CTX_free(ctx);
return false;
}
// verify t^v = X^d * T mod n
BN_dec2bn(&salt, "1618446177786864861468428776289946168463");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t2, t2, e, n, ctx);
BN_mod_exp(XT, m, d, n, ctx);
BN_mod_mul(XT, XT, T, n, ctx);
if(BN_cmp(XT, t2) != 0) {
std::cout << "BN_cmp(XT, t2) failed";
BN_CTX_free(ctx);
return false;
}
// verify t^v = X^d * T mod n
BN_dec2bn(&salt, "2468284666624768462658468131846646451821");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t3, t3, e, n, ctx);
BN_mod_exp(XT, m, d, n, ctx);
BN_mod_mul(XT, XT, T, n, ctx);
if(BN_cmp(XT, t3) != 0) {
std::cout << "BN_cmp(XT, t3) failed" << std::endl;
BN_CTX_free(ctx);
return false;
}
// verify t^v = X^d * T mod n
BN_dec2bn(&salt, "386846284626847646244761844687764462164");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t4, t4, e, n, ctx);
BN_mod_exp(XT, m, d, n, ctx);
BN_mod_mul(XT, XT, T, n, ctx);
if(BN_cmp(XT, t4) != 0) {
std::cout << "BN_cmp(XT, t4) failed" << std::endl;
BN_CTX_free(ctx);
return false;
}
// verify t^v = X^d * T mod n
BN_dec2bn(&salt, "456156843515512741515122247552415322464");
BN_add(XT, XT, salt);
BN_mod(d, XT, e2, ctx);
BN_add(d, d, add);
BN_mod_exp(t5, t5, e, n, ctx);
BN_mod_exp(XT, m, d, n, ctx);
BN_mod_mul(XT, XT, T, n, ctx);
if(BN_cmp(XT, t5) != 0) {
std::cout << "BN_cmp(XT, t5) failed" << std::endl;
BN_CTX_free(ctx);
return false;
}
BN_CTX_free(ctx);
return true;
}
BIGNUM* NtpRsk::randomBignum(const BIGNUM* maxSize) {
int byteLength = BN_num_bytes(maxSize);
unsigned char buf[byteLength];
RAND_bytes(buf, byteLength);
return BN_bin2bn(buf, byteLength, NULL);
}
| 30.932271 | 119 | 0.607805 | bochen8709 |
785e169d4eb1829aa7edce93cd7a20a7269ce9f2 | 6,418 | hpp | C++ | SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file CCGNSMeshReaderFVM.hpp
* \brief Header file for the class CCGNSMeshReaderFVM.
* The implementations are in the <i>CCGNSMeshReaderFVM.cpp</i> file.
* \author T. Economon
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifdef HAVE_CGNS
#include "cgnslib.h"
#endif
#include "CMeshReaderFVM.hpp"
/*!
* \class CCGNSMeshReaderFVM
* \brief Reads a CGNS zone into linear partitions for the finite volume solver (FVM).
* \author: T. Economon
*/
class CCGNSMeshReaderFVM: public CMeshReaderFVM {
private:
#ifdef HAVE_CGNS
int cgnsFileID; /*!< \brief CGNS file identifier. */
int cgnsBase; /*!< \brief CGNS database index. */
int cgnsZone; /*!< \brief CGNS zone index. */
int nZones; /*!< \brief Total number of zones in the CGNS file. */
int nSections; /*!< \brief Total number of sections in the CGNS file. */
vector<bool> isInterior; /*!< \brief Vector of booleans to store whether each section in the CGNS file is an interior or boundary section. */
vector<unsigned long> nElems; /*!< \brief Vector containing the local number of elements found within each CGNS section. */
vector<unsigned long> elemOffset; /*!< \brief Global ID offset for each interior section (i.e., the total number of global elements that came before it). */
vector<vector<cgsize_t> > connElems; /*!< \brief Vector containing the local element connectivity found within each CGNS section. First index is the section, second contains the connectivity in format [globalID VTK n1 n2 n3 n4 n5 n6 n7 n8] for each element. */
vector<vector<char> > sectionNames; /*!< \brief Vector for storing the names of each boundary section (marker). */
/*!
* \brief Open the CGNS file and checks for errors.
* \param[in] val_filename - string name of the CGNS file to be read.
*/
void OpenCGNSFile(string val_filename);
/*!
* \brief Reads all CGNS database metadata and checks for errors.
*/
void ReadCGNSDatabaseMetadata();
/*!
* \brief Reads all CGNS zone metadata and checks for errors.
*/
void ReadCGNSZoneMetadata();
/*!
* \brief Reads the grid points from a CGNS zone into linear partitions across all ranks.
*/
void ReadCGNSPointCoordinates();
/*!
* \brief Reads the metadata for each CGNS section in a zone and collect information, including the size and whether it is an interior or boundary section.
*/
void ReadCGNSSectionMetadata();
/*!
* \brief Reads the interior volume elements from one section of a CGNS zone into linear partitions across all ranks.
* \param[in] val_section - CGNS section index.
*/
void ReadCGNSVolumeSection(int val_section);
/*!
* \brief Reads the surface (boundary) elements from the CGNS zone. Only the master rank currently reads and stores the connectivity, which is linearly partitioned later.
* \param[in] val_section - CGNS section index.
*/
void ReadCGNSSurfaceSection(int val_section);
/*!
* \brief Reformats the CGNS volume connectivity from file into the standard base class data structures.
*/
void ReformatCGNSVolumeConnectivity();
/*!
* \brief Reformats the CGNS volume connectivity from file into the standard base class data structures.
*/
void ReformatCGNSSurfaceConnectivity();
/*!
* \brief Get the VTK type and string name for a CGNS element type.
* \param[in] val_elem_type - CGNS element type.
* \param[out] val_vtk_type - VTK type identifier index.
* \returns String containing the name of the element type.
*/
string GetCGNSElementType(ElementType_t val_elem_type,
int &val_vtk_type);
#endif
/*!
* \brief Routine to launch non-blocking sends and recvs amongst all processors.
* \param[in] bufSend - Buffer of data to be sent.
* \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage format.
* \param[in] sendReq - Array of MPI send requests.
* \param[in] bufRecv - Buffer of data to be received.
* \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative storage format.
* \param[in] sendReq - Array of MPI recv requests.
* \param[in] countPerElem - Pieces of data per element communicated.
*/
void InitiateCommsAll(void *bufSend,
const int *nElemSend,
SU2_MPI::Request *sendReq,
void *bufRecv,
const int *nElemRecv,
SU2_MPI::Request *recvReq,
unsigned short countPerElem,
unsigned short commType);
/*!
* \brief Routine to complete the set of non-blocking communications launched with InitiateComms() with MPI_Waitany().
* \param[in] nSends - Number of sends to be completed.
* \param[in] sendReq - Array of MPI send requests.
* \param[in] nRecvs - Number of receives to be completed.
* \param[in] sendReq - Array of MPI recv requests.
*/
void CompleteCommsAll(int nSends,
SU2_MPI::Request *sendReq,
int nRecvs,
SU2_MPI::Request *recvReq);
public:
/*!
* \brief Constructor of the CCGNSMeshReaderFVM class.
*/
CCGNSMeshReaderFVM(CConfig *val_config,
unsigned short val_iZone,
unsigned short val_nZone);
/*!
* \brief Destructor of the CCGNSMeshReaderFVM class.
*/
~CCGNSMeshReaderFVM(void);
};
| 38.89697 | 262 | 0.677158 | Agony5757 |
785f5be53030f26aed620cfbc7be6e04a6babcc4 | 1,442 | cc | C++ | ui/color/color_recipe.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/color/color_recipe.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/color/color_recipe.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/color/color_recipe.h"
#include <utility>
#include "base/logging.h"
#include "ui/color/color_mixer.h"
#include "ui/color/color_provider_utils.h"
namespace ui {
ColorRecipe::ColorRecipe() = default;
ColorRecipe::ColorRecipe(const ColorTransform& transform) {
*this += transform;
}
ColorRecipe::ColorRecipe(const ColorRecipe&) = default;
ColorRecipe& ColorRecipe::operator=(const ColorRecipe&) = default;
ColorRecipe::ColorRecipe(ColorRecipe&&) noexcept = default;
ColorRecipe& ColorRecipe::operator=(ColorRecipe&&) noexcept = default;
ColorRecipe::~ColorRecipe() = default;
ColorRecipe& ColorRecipe::operator+=(const ColorTransform& transform) {
transforms_.push_back(transform);
return *this;
}
SkColor ColorRecipe::GenerateResult(SkColor input,
const ColorMixer& mixer) const {
SkColor output_color = input;
for (const auto& transform : transforms_)
output_color = transform.Run(output_color, mixer);
DVLOG(2) << "ColorRecipe::GenerateResult: InputColor: " << SkColorName(input)
<< " Result: " << SkColorName(output_color);
return output_color;
}
ColorRecipe operator+(ColorRecipe recipe, const ColorTransform& transform) {
recipe += transform;
return recipe;
}
} // namespace ui | 28.27451 | 79 | 0.727462 | Ron423c |
7862bbdc33bd8140cebfb77e683542fee6a9221f | 2,009 | cpp | C++ | src/EchoMidiApp.cpp | Mystfit/ShowtimePlugin-Midi | d803a56305ce2460cb9b496fa696492d67aeab25 | [
"MIT"
] | null | null | null | src/EchoMidiApp.cpp | Mystfit/ShowtimePlugin-Midi | d803a56305ce2460cb9b496fa696492d67aeab25 | [
"MIT"
] | null | null | null | src/EchoMidiApp.cpp | Mystfit/ShowtimePlugin-Midi | d803a56305ce2460cb9b496fa696492d67aeab25 | [
"MIT"
] | null | null | null | #include <showtime/ShowtimeClient.h>
#include <showtime/ShowtimeServer.h>
#include <showtime/ZstLogging.h>
#include <signal.h>
using namespace showtime;
int s_interrupted = 0;
typedef void (*SignalHandlerPointer)(int);
void s_signal_handler(int signal_value) {
switch (signal_value) {
case SIGINT:
s_interrupted = 1;
case SIGTERM:
s_interrupted = 1;
case SIGABRT:
s_interrupted = 1;
case SIGSEGV:
s_interrupted = 1;
signal(signal_value, SIG_DFL);
raise(SIGABRT);
default:
break;
}
}
void s_catch_signals() {
#ifdef WIN32
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGSEGV, &s_signal_handler);
#else
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
sigaction(SIGSEGV, &action, NULL);
#endif
}
class EchoMidi {
public:
EchoMidi() {
m_server.init("EchoMidiServer");
m_client.init("EchoMidi", true);
m_client.auto_join_by_name("EchoMidiServer");
ZstURI midi_factory_path = m_client.get_root()->URI() + ZstURI("midi_ports");
auto midi_factory = dynamic_cast<ZstEntityFactory*>(m_client.find_entity(midi_factory_path));
if (midi_factory) {
ZstURIBundle bundle;
midi_factory->get_creatables(&bundle);
for (auto creatable : bundle) {
m_client.create_entity(creatable, (std::string(creatable.last().path()) + "_echo").c_str());
}
}
}
~EchoMidi() {
m_server.destroy();
m_client.destroy();
}
ShowtimeClient& get_client() {
return m_client;
}
ShowtimeServer& get_server() {
return m_server;
}
private:
ShowtimeClient m_client;
ShowtimeServer m_server;
};
int main(int argc, char** argv){
s_catch_signals();
EchoMidi echo;
Log::app(Log::Level::notification, "Listening for midi events...");
while (!s_interrupted)
echo.get_client().poll_once();
Log::app(Log::Level::notification, "Quitting");
echo.get_client().destroy();
echo.get_server().destroy();
return 0;
}
| 21.37234 | 96 | 0.722748 | Mystfit |
78644bcea21477a3d64a6355845324d2669e0442 | 11,011 | cpp | C++ | rmf_task/src/rmf_task/requests/Delivery.cpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/src/rmf_task/requests/Delivery.cpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/src/rmf_task/requests/Delivery.cpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <map>
#include <rmf_task/requests/Delivery.hpp>
namespace rmf_task {
namespace requests {
//==============================================================================
class Delivery::Model : public Task::Model
{
public:
std::optional<Estimate> estimate_finish(
const State& initial_state,
const Constraints& task_planning_constraints,
const TravelEstimator& travel_estimator) const final;
rmf_traffic::Duration invariant_duration() const final;
Model(
const rmf_traffic::Time earliest_start_time,
const Parameters& parameters,
std::size_t pickup_waypoint,
rmf_traffic::Duration pickup_wait,
std::size_t dropoff_waypoint,
rmf_traffic::Duration dropoff_wait);
private:
rmf_traffic::Time _earliest_start_time;
Parameters _parameters;
std::size_t _pickup_waypoint;
std::size_t _dropoff_waypoint;
rmf_traffic::Duration _invariant_duration;
double _invariant_battery_drain;
};
//==============================================================================
Delivery::Model::Model(
const rmf_traffic::Time earliest_start_time,
const Parameters& parameters,
std::size_t pickup_waypoint,
rmf_traffic::Duration pickup_wait,
std::size_t dropoff_waypoint,
rmf_traffic::Duration dropoff_wait)
: _earliest_start_time(earliest_start_time),
_parameters(parameters),
_pickup_waypoint(pickup_waypoint),
_dropoff_waypoint(dropoff_waypoint)
{
// Calculate duration of invariant component of task
_invariant_duration = pickup_wait + dropoff_wait;
_invariant_battery_drain =
_parameters.ambient_sink()->compute_change_in_charge(
rmf_traffic::time::to_seconds(pickup_wait + dropoff_wait));
if (_pickup_waypoint != _dropoff_waypoint)
{
rmf_traffic::agv::Planner::Start start{
_earliest_start_time,
_pickup_waypoint,
0.0};
rmf_traffic::agv::Planner::Goal goal{_dropoff_waypoint};
const auto result_to_dropoff = _parameters.planner()->plan(start, goal);
auto itinerary_start_time = _earliest_start_time;
for (const auto& itinerary : result_to_dropoff->get_itinerary())
{
const auto& trajectory = itinerary.trajectory();
const auto& finish_time = *trajectory.finish_time();
const auto itinerary_duration = finish_time - itinerary_start_time;
// Compute the invariant battery drain
const double dSOC_motion =
_parameters.motion_sink()->compute_change_in_charge(trajectory);
const double dSOC_device =
_parameters.ambient_sink()->compute_change_in_charge(
rmf_traffic::time::to_seconds(itinerary_duration));
_invariant_battery_drain += dSOC_motion + dSOC_device;
_invariant_duration += itinerary_duration;
itinerary_start_time = finish_time;
}
}
}
//==============================================================================
std::optional<rmf_task::Estimate> Delivery::Model::estimate_finish(
const State& initial_state,
const Constraints& task_planning_constraints,
const TravelEstimator& travel_estimator) const
{
rmf_traffic::agv::Plan::Start final_plan_start{
initial_state.time().value(),
_dropoff_waypoint,
initial_state.orientation().value()};
auto state = State().load_basic(
std::move(final_plan_start),
initial_state.dedicated_charging_waypoint().value(),
initial_state.battery_soc().value());
rmf_traffic::Duration variant_duration(0);
double battery_soc = initial_state.battery_soc().value();
const bool drain_battery = task_planning_constraints.drain_battery();
const auto& ambient_sink = *_parameters.ambient_sink();
const double battery_threshold = task_planning_constraints.threshold_soc();
// Factor in battery drain while moving to start waypoint of task
if (initial_state.waypoint() != _pickup_waypoint)
{
const auto travel = travel_estimator.estimate(
initial_state.extract_plan_start().value(),
_pickup_waypoint);
if (!travel)
return std::nullopt;
variant_duration = travel->duration();
if (drain_battery)
battery_soc = battery_soc - travel->change_in_charge();
if (battery_soc <= battery_threshold)
return std::nullopt;
}
const rmf_traffic::Time ideal_start = _earliest_start_time - variant_duration;
const rmf_traffic::Time wait_until =
initial_state.time().value() > ideal_start ?
initial_state.time().value() : ideal_start;
// Factor in battery drain while waiting to move to start waypoint. If a robot
// is initially at a charging waypoint, it is assumed to be continually charging
if (drain_battery && wait_until > initial_state.time().value() &&
initial_state.waypoint() != initial_state.dedicated_charging_waypoint())
{
const rmf_traffic::Duration wait_duration(
wait_until - initial_state.time().value());
const double dSOC_device = ambient_sink.compute_change_in_charge(
rmf_traffic::time::to_seconds(wait_duration));
battery_soc = battery_soc - dSOC_device;
if (battery_soc <= battery_threshold)
return std::nullopt;
}
// Factor in invariants
state.time(wait_until + variant_duration + _invariant_duration);
if (drain_battery)
{
// Calculate how much battery is drained while waiting for the pickup and
// waiting for the dropoff
battery_soc -= _invariant_battery_drain;
if (battery_soc <= battery_threshold)
return std::nullopt;
// Check if the robot has enough charge to head back to nearest charger
if (_dropoff_waypoint != state.dedicated_charging_waypoint().value())
{
const auto travel = travel_estimator.estimate(
state.extract_plan_start().value(),
state.dedicated_charging_waypoint().value());
if (!travel.has_value())
return std::nullopt;
if (battery_soc - travel->change_in_charge() <= battery_threshold)
return std::nullopt;
}
state.battery_soc(battery_soc);
}
return Estimate(state, wait_until);
}
//==============================================================================
rmf_traffic::Duration Delivery::Model::invariant_duration() const
{
return _invariant_duration;
}
//==============================================================================
class Delivery::Description::Implementation
{
public:
std::size_t pickup_waypoint;
rmf_traffic::Duration pickup_wait;
std::size_t dropoff_waypoint;
rmf_traffic::Duration dropoff_wait;
rmf_task::Payload payload;
std::string pickup_from_dispenser;
std::string dropoff_to_ingestor;
};
//==============================================================================
Task::ConstDescriptionPtr Delivery::Description::make(
std::size_t pickup_waypoint,
rmf_traffic::Duration pickup_wait,
std::size_t dropoff_waypoint,
rmf_traffic::Duration dropoff_wait,
Payload payload,
std::string pickup_from_dispenser,
std::string dropoff_to_ingestor)
{
std::shared_ptr<Description> delivery(new Description());
delivery->_pimpl = rmf_utils::make_impl<Implementation>(
Implementation{
pickup_waypoint,
pickup_wait,
dropoff_waypoint,
dropoff_wait,
std::move(payload),
std::move(pickup_from_dispenser),
std::move(dropoff_to_ingestor)
});
return delivery;
}
//==============================================================================
Delivery::Description::Description()
{
// Do nothing
}
//==============================================================================
Task::ConstModelPtr Delivery::Description::make_model(
rmf_traffic::Time earliest_start_time,
const Parameters& parameters) const
{
return std::make_shared<Delivery::Model>(
earliest_start_time,
parameters,
_pimpl->pickup_waypoint,
_pimpl->pickup_wait,
_pimpl->dropoff_waypoint,
_pimpl->dropoff_wait);
}
//==============================================================================
auto Delivery::Description::generate_info(
const State&,
const Parameters& parameters) const -> Info
{
const auto& graph = parameters.planner()->get_configuration().graph();
return Info{
"Delivery from " + standard_waypoint_name(graph, _pimpl->pickup_waypoint)
+ " to " + standard_waypoint_name(graph, _pimpl->dropoff_waypoint),
"" // TODO(MXG): Add details about the payload
};
}
//==============================================================================
std::size_t Delivery::Description::pickup_waypoint() const
{
return _pimpl->pickup_waypoint;
}
//==============================================================================
std::string Delivery::Description::pickup_from_dispenser() const
{
return _pimpl->pickup_from_dispenser;
}
//==============================================================================
std::string Delivery::Description::dropoff_to_ingestor() const
{
return _pimpl->dropoff_to_ingestor;
}
//==============================================================================
rmf_traffic::Duration Delivery::Description::pickup_wait() const
{
return _pimpl->pickup_wait;
}
//==============================================================================
rmf_traffic::Duration Delivery::Description::dropoff_wait() const
{
return _pimpl->dropoff_wait;
}
//==============================================================================
std::size_t Delivery::Description::dropoff_waypoint() const
{
return _pimpl->dropoff_waypoint;
}
//==============================================================================
const Payload& Delivery::Description::payload() const
{
return _pimpl->payload;
}
//==============================================================================
ConstRequestPtr Delivery::make(
std::size_t pickup_waypoint,
rmf_traffic::Duration pickup_wait,
std::size_t dropoff_waypoint,
rmf_traffic::Duration dropoff_wait,
Payload payload,
const std::string& id,
rmf_traffic::Time earliest_start_time,
ConstPriorityPtr priority,
bool automatic,
std::string pickup_from_dispenser,
std::string dropoff_to_ingestor)
{
const auto description = Description::make(
pickup_waypoint,
pickup_wait,
dropoff_waypoint,
dropoff_wait,
std::move(payload),
std::move(pickup_from_dispenser),
std::move(dropoff_to_ingestor));
return std::make_shared<Request>(
id, earliest_start_time, std::move(priority), description, automatic);
}
} // namespace requests
} // namespace rmf_task
| 31.550143 | 82 | 0.647625 | Rouein |
7864c13983b093bb4dfd300b70170b23e7c788f7 | 4,998 | cpp | C++ | AK/LexicalPath.cpp | phoffmeister/serenity | b7af536f9bc925bf29de9b2d032b9c95c9bb55bc | [
"BSD-2-Clause"
] | 6 | 2021-06-11T13:51:40.000Z | 2021-12-14T02:29:35.000Z | AK/LexicalPath.cpp | phoffmeister/serenity | b7af536f9bc925bf29de9b2d032b9c95c9bb55bc | [
"BSD-2-Clause"
] | 1 | 2021-11-19T19:20:49.000Z | 2021-11-19T19:20:49.000Z | AK/LexicalPath.cpp | phoffmeister/serenity | b7af536f9bc925bf29de9b2d032b9c95c9bb55bc | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, Max Wipfli <max.wipfli@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/LexicalPath.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
namespace AK {
char s_single_dot = '.';
LexicalPath::LexicalPath(String path)
: m_string(canonicalized_path(move(path)))
{
if (m_string.is_empty()) {
m_string = ".";
m_dirname = m_string;
m_basename = {};
m_title = {};
m_extension = {};
m_parts.clear();
return;
}
m_parts = m_string.split_view('/');
auto last_slash_index = m_string.view().find_last('/');
if (!last_slash_index.has_value()) {
// The path contains a single part and is not absolute. m_dirname = "."sv
m_dirname = { &s_single_dot, 1 };
} else if (*last_slash_index == 0) {
// The path contains a single part and is absolute. m_dirname = "/"sv
m_dirname = m_string.substring_view(0, 1);
} else {
m_dirname = m_string.substring_view(0, *last_slash_index);
}
if (m_string == "/")
m_basename = m_string;
else {
VERIFY(m_parts.size() > 0);
m_basename = m_parts.last();
}
auto last_dot_index = m_basename.find_last('.');
// NOTE: if the dot index is 0, this means we have ".foo", it's not an extension, as the title would then be "".
if (last_dot_index.has_value() && *last_dot_index != 0) {
m_title = m_basename.substring_view(0, *last_dot_index);
m_extension = m_basename.substring_view(*last_dot_index + 1);
} else {
m_title = m_basename;
m_extension = {};
}
}
Vector<String> LexicalPath::parts() const
{
Vector<String> vector;
vector.ensure_capacity(m_parts.size());
for (auto& part : m_parts)
vector.unchecked_append(part);
return vector;
}
bool LexicalPath::has_extension(StringView extension) const
{
return m_string.ends_with(extension, CaseSensitivity::CaseInsensitive);
}
String LexicalPath::canonicalized_path(String path)
{
if (path.is_null())
return {};
// NOTE: We never allow an empty m_string, if it's empty, we just set it to '.'.
if (path.is_empty())
return ".";
// NOTE: If there are no dots, no '//' and the path doesn't end with a slash, it is already canonical.
if (!path.contains("."sv) && !path.contains("//"sv) && !path.ends_with('/'))
return path;
auto is_absolute = path[0] == '/';
auto parts = path.split_view('/');
size_t approximate_canonical_length = 0;
Vector<String> canonical_parts;
for (auto& part : parts) {
if (part == ".")
continue;
if (part == "..") {
if (canonical_parts.is_empty()) {
if (is_absolute) {
// At the root, .. does nothing.
continue;
}
} else {
if (canonical_parts.last() != "..") {
// A .. and a previous non-.. part cancel each other.
canonical_parts.take_last();
continue;
}
}
}
approximate_canonical_length += part.length() + 1;
canonical_parts.append(part);
}
if (canonical_parts.is_empty() && !is_absolute)
canonical_parts.append(".");
StringBuilder builder(approximate_canonical_length);
if (is_absolute)
builder.append('/');
builder.join('/', canonical_parts);
return builder.to_string();
}
String LexicalPath::absolute_path(String dir_path, String target)
{
if (LexicalPath(target).is_absolute()) {
return LexicalPath::canonicalized_path(target);
}
return LexicalPath::canonicalized_path(join(dir_path, target).string());
}
String LexicalPath::relative_path(StringView a_path, StringView a_prefix)
{
if (!a_path.starts_with('/') || !a_prefix.starts_with('/')) {
// FIXME: This should probably VERIFY or return an Optional<String>.
return {};
}
if (a_path == a_prefix)
return ".";
// NOTE: Strip optional trailing slashes, except if the full path is only "/".
auto path = canonicalized_path(a_path);
auto prefix = canonicalized_path(a_prefix);
if (path == prefix)
return ".";
// NOTE: Handle this special case first.
if (prefix == "/"sv)
return path.substring_view(1);
// NOTE: This means the prefix is a direct child of the path.
if (path.starts_with(prefix) && path[prefix.length()] == '/') {
return path.substring_view(prefix.length() + 1);
}
// FIXME: It's still possible to generate a relative path in this case, it just needs some "..".
return path;
}
LexicalPath LexicalPath::append(StringView value) const
{
return LexicalPath::join(m_string, value);
}
LexicalPath LexicalPath::parent() const
{
return append("..");
}
}
| 28.890173 | 116 | 0.605242 | phoffmeister |
7867615a8dc6fde056fc32a23fcc05e5958e5643 | 1,555 | cpp | C++ | algorithm/algorithm/1/34/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | 1 | 2020-10-01T14:52:45.000Z | 2020-10-01T14:52:45.000Z | algorithm/algorithm/1/34/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | 3 | 2020-08-13T07:51:54.000Z | 2021-01-29T11:17:25.000Z | algorithm/algorithm/1/34/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left_index = -2;
int right_index = -2;
//寻找左右边界
left_index = get_left(nums, target);
right_index = get_right(nums, target);
// 情况一
if (left_index == -2 || right_index == -2) return {-1, -1};
// 情况三
if (right_index - left_index > 1) return {left_index + 1, right_index - 1};
// 情况二
return {-1, -1};
}
private:
int get_left(vector<int> nums, int target)
{
int m_num = nums.size();
int left = 0;
int right = m_num - 1;
int mid = 0;
int left_index = -2;
while(left <= right)
{
mid = left + ((right - left) / 2);
if(nums[mid] >= target)
{
right = mid - 1;
left_index = right;
}
else
{
left = mid + 1;
}
}
return left_index;
}
int get_right(vector<int> nums, int target)
{
int m_num = nums.size();
int left = 0;
int right = m_num - 1;
int mid = 0;
int right_index = -2;
while(left <= right)
{
mid = left + ((right - left) / 2);
if(nums[mid] > target)
{
right = mid - 1;
}
else
{
left = mid + 1;
right_index = left;
}
}
return right_index;
}
}; | 23.923077 | 83 | 0.416077 | 6923403 |
786c621a3913178ff704534f47c67e734488b933 | 2,324 | cpp | C++ | Test/ListenerTest/Test_listener.cpp | tzimer/private-transaction-families | f67a1fe9fdb8a4525736114dc2e464eb4b6d595e | [
"Apache-2.0"
] | null | null | null | Test/ListenerTest/Test_listener.cpp | tzimer/private-transaction-families | f67a1fe9fdb8a4525736114dc2e464eb4b6d595e | [
"Apache-2.0"
] | null | null | null | Test/ListenerTest/Test_listener.cpp | tzimer/private-transaction-families | f67a1fe9fdb8a4525736114dc2e464eb4b6d595e | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "data_map.h"
#include "rest_handler.h"
#include "Enclave_u.h"
#include "mock_sawtooth.h"
#include "config.h"
#include "txn_handler.h"
//declare the extern global
std::string config::g_key_path;
std::string config::g_rest_url;
std::string addr1, addr2, addr3;
namespace txn_handler
{
sawtooth::GlobalStateUPtr contextPtr;
}
using namespace listener;
void set_sawtooth_mock()
{
std::unique_ptr<SawtoothStateMock> mock_ctx_uptr(new SawtoothStateMock);
txn_handler::contextPtr = std::move(mock_ctx_uptr);
}
void SetUpListener()
{
set_sawtooth_mock();
std::array<uint8_t, ADDRESS_LENGTH / 2> addr_bytes = {};
std::iota(std::begin(addr_bytes), std::end(addr_bytes), 13);
addr1 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str();
std::iota(std::begin(addr_bytes), std::end(addr_bytes), 25);
addr2 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str();
std::iota(std::begin(addr_bytes), std::end(addr_bytes), 41);
addr3 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str();
}
TEST(Listener, tl_call_stl_write)
{
std::string str = "mock value in addr1";
ASSERT_EQ(tl_call_stl_write(addr1.c_str(), str.c_str(), str.size() + 1), 0);
}
TEST(Listener, tl_call_stl_read)
{
uint32_t id;
std::vector<char> value = {};
std::string res_str = "mock value in addr1";
int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0);
ASSERT_EQ(res_len, res_str.size() + 1);
value.reserve(res_len);
res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len);
ASSERT_EQ(res_len, res_str.size() + 1);
ASSERT_EQ(std::string(std::begin(value), std::begin(value) + res_len - 1), res_str.c_str());
// read again should return empty string
res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len);
ASSERT_EQ(res_len, 0);
}
TEST(Listener, tl_call_stl_delete)
{
ASSERT_EQ(tl_call_stl_delete(addr1.c_str(), 1), 0);
uint32_t id;
std::vector<char> value = {};
int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0);
ASSERT_EQ(res_len, 0);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
SetUpListener();
auto ret = RUN_ALL_TESTS();
deleteAllValues();
return ret;
}
| 29.794872 | 96 | 0.686317 | tzimer |
786c9acf12e9132b25b1f5767186dfd6a1a0e1b3 | 2,680 | cpp | C++ | mygraphicsscene.cpp | rbax/qtKabuChart | 0604b32389e897174da3bb342bdee21ead498c7c | [
"MIT"
] | 1 | 2021-02-16T10:49:00.000Z | 2021-02-16T10:49:00.000Z | mygraphicsscene.cpp | rbax/qtKabuChart | 0604b32389e897174da3bb342bdee21ead498c7c | [
"MIT"
] | null | null | null | mygraphicsscene.cpp | rbax/qtKabuChart | 0604b32389e897174da3bb342bdee21ead498c7c | [
"MIT"
] | null | null | null | /*********************************************************************
* Copyright (c) 2016 nari
* This source is released under the MIT license
* http://opensource.org/licenses/mit-license.php
*
* This source code is a modification of article website below.
* http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php
* Cppyright (c) Walletfox.com, 2014
* *******************************************************************/
#include "mygraphicsscene.h"
#include <QDebug>
/*
*refer to
* How to draw QGraphicsLineItem during run time with mouse coordinates
* http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php
*/
MyGraphicsScene::MyGraphicsScene(QObject* parent)
{
sceneMode = NoMode;
itemToDraw = 0;
}
void MyGraphicsScene::setLineColor(QString colorname){
lineColor = colorname;
}
void MyGraphicsScene::clearDraw(){
//lineを消せない
//itemToDraw->~QGraphicsLineItem();
if(freeLines.count() > 0){
for(int i = 0; i < freeLines.count() ; i++){
//freeLines.at(i)->setVisible(false);
QGraphicsLineItem *item = freeLines.at(i);
freeLines.removeAt(i); //これ必要
delete item;
//freeLines.at(i)->~QGraphicsLineItem();
}
}
}
void MyGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event){
if(sceneMode == DrawLine)
origPoint = event->scenePos();
QGraphicsScene::mousePressEvent(event);
}
void MyGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
if(sceneMode == DrawLine){
if(!itemToDraw && origPoint.x() > 0 && origPoint.y() > 0){
itemToDraw = new QGraphicsLineItem;
this->addItem(itemToDraw);
freeLines.append(itemToDraw);
QPen pen;
pen.setColor(lineColor);
pen.setWidth(3);
pen.setStyle(Qt::SolidLine);
itemToDraw->setPen(pen);
itemToDraw->setPos(origPoint);
}
if(origPoint.x() > 0 && origPoint.y() > 0){
itemToDraw->setLine(0,0,event->scenePos().x() - origPoint.x(),event->scenePos().y() - origPoint.y());
}
}
else
QGraphicsScene::mouseMoveEvent(event);
}
void MyGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
itemToDraw = 0;
sceneMode = NoMode;
QGraphicsScene::mouseReleaseEvent(event);
}
void MyGraphicsScene::setMode(Mode mode){
sceneMode = mode;
itemToDraw = 0;
}
void MyGraphicsScene::setModeDraw(){
sceneMode = DrawLine;
origPoint.setX(-1);
origPoint.setY(-1);
itemToDraw = 0;
}
| 29.130435 | 114 | 0.587687 | rbax |
786fcc1bb43f7f1a89aee484c9057dbaf2eb0488 | 8,152 | hxx | C++ | include/crab/streams.hxx | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | 3 | 2020-02-13T02:08:06.000Z | 2020-10-06T16:26:30.000Z | include/crab/streams.hxx | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | include/crab/streams.hxx | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.
#include <algorithm>
#include <cstring>
#include <iostream>
#include <limits>
#include <stdexcept>
#include "streams.hpp"
namespace crab {
CRAB_INLINE void IStream::read(uint8_t *val, size_t count) {
while (count != 0) {
size_t rc = read_some(val, count);
if (rc == 0)
throw std::runtime_error("crab::IStream reading from empty stream");
val += rc;
count -= rc;
}
}
CRAB_INLINE void OStream::write(const uint8_t *val, size_t count) {
while (count != 0) {
size_t wc = write_some(val, count);
if (wc == 0)
throw std::runtime_error("crab::OStream writing to full stream");
val += wc;
count -= wc;
}
}
CRAB_INLINE size_t Buffer::read_some(uint8_t *val, size_t count) {
size_t rc = std::min(count, read_count());
std::memcpy(val, read_ptr(), rc);
did_read(rc);
return rc;
}
CRAB_INLINE size_t Buffer::write_some(const uint8_t *val, size_t count) {
size_t rc = std::min(count, write_count());
std::memcpy(write_ptr(), val, rc);
did_write(rc);
return rc;
}
CRAB_INLINE size_t Buffer::read_from(IStream &in) {
size_t total_count = 0;
while (true) {
size_t wc = write_count();
if (wc == 0)
break;
size_t count = in.read_some(write_ptr(), wc);
did_write(count);
total_count += count;
if (count == 0)
break;
}
return total_count;
}
CRAB_INLINE size_t Buffer::write_to(OStream &out, size_t max_count) {
size_t total_count = 0;
while (true) {
size_t rc = std::min(read_count(), max_count);
if (rc == 0)
break;
size_t count = out.write_some(read_ptr(), rc);
did_read(count);
max_count -= count;
total_count += count;
if (count == 0)
break;
}
return total_count;
}
CRAB_INLINE bool Buffer::read_enough_data(IStream &in, size_t count) {
if (size() < count)
read_from(in);
return size() >= count;
}
CRAB_INLINE bool Buffer::peek(uint8_t *val, size_t count) const {
// Compiler thinks memcpy can affect "this", local vars greatly help
auto rc = read_count();
auto rc2 = read_count2();
if (rc + rc2 < count)
return false;
auto rp = read_ptr();
if (rc >= count) {
std::memcpy(val, rp, count);
return true;
}
std::memcpy(val, rp, rc);
std::memcpy(val + rc, read_ptr2(), count - rc);
return true;
}
/*
// Invariant - at least 1 chunk in rope container to avoid ifs
Rope::Rope(size_t chunk_size) : chunk_size(chunk_size) {
rope.emplace_back(chunk_size);
}
void Rope::clear() {
if (rope.size() >= 1) {
Buffer buf = std::move(rope.front());
rope.clear();
rope.push_back(std::move(buf));
} else {
rope.clear();
rope.emplace_back(chunk_size);
}
rope_size = 0;
}
void Rope::did_write(size_t count) {
rope_size += count;
rope.back().did_write(count);
if (rope.back().full())
rope.emplace_back(chunk_size);
}
void Rope::did_read(size_t count) {
invariant(count <= rope_size, "Rope underflow");
rope_size -= count;
rope.front().did_read(count);
if (rope.front().empty()) {
rope.pop_front();
if (rope.empty())
rope.emplace_back(chunk_size);
}
}
size_t Rope::read_from(IStream &in) {
size_t total_count = 0;
while (true) {
size_t wc = write_count();
if (wc == 0)
break;
size_t count = in.read_some(write_ptr(), wc);
did_write(count);
total_count += count;
if (count == 0)
break;
}
return total_count;
}
size_t Rope::write_to(OStream &out, size_t max_count) {
size_t total_count = 0;
while (true) {
size_t rc = std::min(read_count(), max_count);
if (rc == 0)
break;
size_t count = out.write_some(read_ptr(), rc);
did_read(count);
max_count -= count;
total_count += count;
if (count == 0)
break;
}
return total_count;
}*/
/*void Buffer::write(const uint8_t *val, size_t count) {
size_t rc = std::min(count, write_count());
std::memcpy(write_ptr(), val, rc);
did_write(rc);
val += rc;
count -= rc;
if (count == 0)
return;
rc = std::min(count, write_count());
std::memcpy(write_ptr(), val, rc);
did_write(rc);
val += rc;
count -= rc;
if (count == 0)
return;
throw std::runtime_error("Buffer overflow");
}
void Buffer::write(const char *val, size_t count) {
write(reinterpret_cast<const uint8_t *>(val), count);
}*/
CRAB_INLINE size_t IMemoryStream::read_some(uint8_t *val, size_t count) {
size_t rc = std::min(count, si);
std::memcpy(val, data, rc);
data += rc;
si -= rc;
return rc;
}
CRAB_INLINE size_t IMemoryStream::write_to(OStream &out, size_t max_count) {
size_t total_count = 0;
while (true) {
size_t rc = std::min(size(), max_count);
if (rc == 0)
break;
size_t count = out.write_some(data, rc);
data += count;
si -= rc;
max_count -= count;
total_count += count;
if (count == 0)
break;
}
return total_count;
}
CRAB_INLINE size_t OMemoryStream::write_some(const uint8_t *val, size_t count) {
size_t rc = std::min(count, si);
std::memcpy(data, val, rc);
data += rc;
si -= rc;
return rc;
}
CRAB_INLINE size_t IVectorStream::read_some(uint8_t *val, size_t count) {
size_t rc = std::min(count, rimpl->size() - read_pos);
std::memcpy(val, rimpl->data() + read_pos, rc);
read_pos += rc;
return rc;
}
CRAB_INLINE size_t IVectorStream::write_to(OStream &out, size_t max_count) {
size_t total_count = 0;
while (true) {
size_t rc = std::min(size(), max_count);
if (rc == 0)
break;
size_t count = out.write_some(rimpl->data() + read_pos, rc);
read_pos += count;
max_count -= count;
total_count += count;
if (count == 0)
break;
}
return total_count;
}
CRAB_INLINE size_t OVectorStream::write_some(const uint8_t *val, size_t count) {
wimpl->insert(wimpl->end(), val, val + count);
return count;
}
CRAB_INLINE size_t IStringStream::read_some(uint8_t *val, size_t count) {
size_t rc = std::min(count, rimpl->size() - read_pos);
std::memcpy(val, rimpl->data() + read_pos, rc);
read_pos += rc;
return rc;
}
CRAB_INLINE size_t IStringStream::write_to(OStream &out, size_t max_count) {
size_t total_count = 0;
while (true) {
size_t rc = std::min(size(), max_count);
if (rc == 0)
break;
size_t count = out.write_some(rimpl->data() + read_pos, rc);
read_pos += count;
max_count -= count;
total_count += count;
if (count == 0)
break;
}
return total_count;
}
CRAB_INLINE size_t OStringStream::write_some(const uint8_t *val, size_t count) {
wimpl->insert(wimpl->end(), val, val + count);
return count;
}
/*
// Some experimental code
// Inspirated by boost::streams
class IStreamBuffer {
static constexpr size_t SMALL_READ = 256;
static constexpr size_t BUFFER_SIZE = SMALL_READ * 4;
uint8_t buffer_storage[BUFFER_SIZE];
uint8_t *buffer = buffer_storage;
size_t buffer_size = 0;
IStreamRaw *raw_stream;
public:
void read(uint8_t *data, size_t size) {
if (size <= buffer_size) { // Often, also when zero size
std::memcpy(data, buffer, size);
buffer += size;
buffer_size -= size;
return;
}
// size > 0 here
std::memcpy(data, buffer, buffer_size);
buffer = buffer_storage;
buffer_size = 0;
size -= buffer_size;
data += buffer_size;
if (size < BUFFER_SIZE / 4) { // Often
buffer_size = raw_stream->read_some(buffer, BUFFER_SIZE);
if (buffer_size == 0)
throw std::runtime_error("IStreamRaw underflow");
std::memcpy(data, buffer, size);
buffer += size;
buffer_size -= size;
return;
}
// size > 0 here
while (true) {
size_t cou = raw_stream->read_some(data, size);
if (cou == 0)
throw std::runtime_error("IStreamRaw underflow");
size -= cou;
data += cou;
if (size == 0)
return;
}
};
};
*/
} // namespace crab
| 24.70303 | 80 | 0.616658 | hrissan |
7870d51f7968bced59fbe92f44aaadb74120d3b1 | 935 | hpp | C++ | entregas/01-cifrado/CifradoVigenere.hpp | gerardogtn/Calidad-y-Pruebas-de-Software | ed338b5627a343b7dee366aaa36cd735f74e53af | [
"MIT"
] | null | null | null | entregas/01-cifrado/CifradoVigenere.hpp | gerardogtn/Calidad-y-Pruebas-de-Software | ed338b5627a343b7dee366aaa36cd735f74e53af | [
"MIT"
] | null | null | null | entregas/01-cifrado/CifradoVigenere.hpp | gerardogtn/Calidad-y-Pruebas-de-Software | ed338b5627a343b7dee366aaa36cd735f74e53af | [
"MIT"
] | null | null | null | // Copyright 2017 Gerardo Teruel
#ifndef UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_
#define UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_
#include <string>
class CifradoVigenere : public Cifrado {
private:
const std::string key;
public:
explicit CifradoVigenere(const std::string key) : key(key) {}
virtual ~CifradoVigenere() {}
virtual std::string decipher(const std::string& cipher) {
std::string out = "";
int special = 0;
for (int i = 0; i < cipher.size(); i++) {
if (cipher[i] == '.' || cipher[i] == ' ') {
special++;
out.append(1, cipher[i]);
} else {
/** int to be able to hold negative numbers */
int c = cipher[i] - key[(i - special) % key.size()];
if (c < 0) {
out.append(1, 91 + c);
} else {
out.append(1, (c % 26) + 65);
}
}
}
return out;
}
};
#endif // UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_
| 23.375 | 63 | 0.581818 | gerardogtn |
787578fd45a6eb7cfbc8056ca441dcf39569aff1 | 348 | cpp | C++ | Olympiad Solutions/URI/2463.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Olympiad Solutions/URI/2463.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Olympiad Solutions/URI/2463.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/2463
#include <cstdio>
#include <algorithm>
using namespace std;
int main(){
int n, m1 = 0, m2 = 0,d;
scanf("%d",&n);
while(n--){
scanf("%d",&d);
m1 = max(0,m1+d);
m2 = max(m1,m2);
}
printf("%d\n",m2);
return 0;
}
| 20.470588 | 73 | 0.543103 | Ashwanigupta9125 |
787601bab6e036ffa10b8ead9aa11363a2b98cb0 | 5,170 | cpp | C++ | src/asm/Instruction.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | src/asm/Instruction.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | src/asm/Instruction.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | /*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include "Instruction.h"
#include "../Values.h"
#include "ALUInstruction.h"
#include "BranchInstruction.h"
#include "LoadInstruction.h"
#include "SemaphoreInstruction.h"
#include <cstdbool>
#include <memory>
using namespace vc4c;
using namespace vc4c::qpu_asm;
LCOV_EXCL_START
std::string Instruction::toASMString() const
{
if(auto op = as<ALUInstruction>())
return op->toASMString();
if(auto op = as<BranchInstruction>())
return op->toASMString();
if(auto op = as<LoadInstruction>())
return op->toASMString();
if(auto op = as<SemaphoreInstruction>())
return op->toASMString();
throw CompilationError(CompilationStep::CODE_GENERATION, "Invalid instruction type", std::to_string(value));
}
std::string Instruction::toHexString(bool withAssemblerCode) const
{
uint64_t binaryCode = toBinaryCode();
if(withAssemblerCode)
{
return qpu_asm::toHexString(binaryCode) + "//" + toASMString();
}
return qpu_asm::toHexString(binaryCode);
}
LCOV_EXCL_STOP
bool Instruction::isValidInstruction() const
{
return as<ALUInstruction>() || as<BranchInstruction>() || as<LoadInstruction>() || as<SemaphoreInstruction>();
}
Register Instruction::getAddOutput() const
{
Register reg{RegisterFile::PHYSICAL_ANY, getAddOut()};
if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4)
// cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such
return Register{RegisterFile::ACCUMULATOR, reg.num};
if(getWriteSwap() == WriteSwap::SWAP)
return Register{RegisterFile::PHYSICAL_B, reg.num};
return Register{RegisterFile::PHYSICAL_A, reg.num};
}
Register Instruction::getMulOutput() const
{
Register reg{RegisterFile::PHYSICAL_ANY, getMulOut()};
if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4)
// cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such
return Register{RegisterFile::ACCUMULATOR, reg.num};
if(getWriteSwap() == WriteSwap::DONT_SWAP)
return Register{RegisterFile::PHYSICAL_B, reg.num};
return Register{RegisterFile::PHYSICAL_A, reg.num};
}
LCOV_EXCL_START
std::string Instruction::toInputRegister(
const InputMultiplex mux, const Address regA, const Address regB, const bool hasImmediate)
{
if(mux == InputMultiplex::ACC0)
return "r0";
if(mux == InputMultiplex::ACC1)
return "r1";
if(mux == InputMultiplex::ACC2)
return "r2";
if(mux == InputMultiplex::ACC3)
return "r3";
if(mux == InputMultiplex::ACC4)
return "r4";
if(mux == InputMultiplex::ACC5)
return "r5";
// general register-file
if(mux == InputMultiplex::REGA)
{
const Register tmp{RegisterFile::PHYSICAL_A, regA};
return tmp.to_string(true, true);
}
else if(hasImmediate)
{
// is immediate value
return static_cast<SmallImmediate>(regB).to_string();
}
else
{
const Register tmp{RegisterFile::PHYSICAL_B, regB};
return tmp.to_string(true, true);
}
}
std::string Instruction::toOutputRegister(bool regFileA, const Address reg)
{
const Register tmp{regFileA ? RegisterFile::PHYSICAL_A : RegisterFile::PHYSICAL_B, reg};
return tmp.to_string(true, false);
}
std::string Instruction::toExtrasString(const Signaling sig, const ConditionCode cond, const SetFlag flags,
const Unpack unpack, const Pack pack, bool usesOutputA, bool usesInputAOrR4)
{
std::string result{};
if(sig != SIGNAL_NONE && sig != SIGNAL_ALU_IMMEDIATE)
result += std::string(".") + sig.to_string();
if(cond != COND_ALWAYS)
result += std::string(".") + cond.to_string();
if(flags == SetFlag::SET_FLAGS)
result += std::string(".") + toString(flags);
if(usesInputAOrR4 && unpack.hasEffect())
result += std::string(".") + unpack.to_string();
if(usesOutputA && pack.hasEffect())
result += std::string(".") + pack.to_string();
return result;
}
std::string qpu_asm::toHexString(const uint64_t code)
{
// lower half before upper half
char buffer[64];
snprintf(buffer, sizeof(buffer), "0x%08x, 0x%08x, ", static_cast<uint32_t>(code & 0xFFFFFFFFLL),
static_cast<uint32_t>((code & 0xFFFFFFFF00000000LL) >> 32));
return buffer;
}
std::string DecoratedInstruction::toASMString(bool addComments) const
{
auto tmp = instruction.toASMString();
return addComments ? addComment(std::move(tmp)) : tmp;
}
std::string DecoratedInstruction::toHexString(bool withAssemblerCode) const
{
auto tmp = instruction.toHexString(withAssemblerCode);
if(withAssemblerCode)
{
return addComment(std::move(tmp));
}
return tmp;
}
std::string DecoratedInstruction::addComment(std::string&& s) const
{
std::string r;
if(!comment.empty())
r = s.append(" // ").append(comment);
else
r = s;
if(!previousComment.empty())
r = "// " + previousComment + "\n" + r;
return r;
}
LCOV_EXCL_STOP
| 30.77381 | 114 | 0.67234 | rigred |
78796f3c89bf6e8a8d616f7be1ffc902210e22fe | 67,345 | cpp | C++ | test/word_break_34.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | null | null | null | test/word_break_34.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | 1 | 2021-03-05T12:56:59.000Z | 2021-03-05T13:11:53.000Z | test/word_break_34.cpp | eightysquirrels/text | d935545648777786dc196a75346cde8906da846a | [
"BSL-1.0"
] | 3 | 2019-10-30T18:38:15.000Z | 2021-03-05T12:10:13.000Z | // Warning! This file is autogenerated.
#include <boost/text/word_break.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(word, breaks_34)
{
// ÷ 0031 × 002E × 2060 × 0031 ÷ 0027 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3]
{
std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x27 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
}
// ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 0027 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x27 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 002E × 2060 × 0031 ÷ 002C ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3]
{
std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2c }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
}
// ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002C ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2c }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 002E × 2060 × 0031 ÷ 002E × 2060 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2e, 0x2060 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002E × 2060 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3]
{
std::array<uint32_t, 7> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2e, 0x2060 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7);
}
// ÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷
// ÷ [0.2] <CARRIAGE RETURN (CR)> (CR) × [3.0] <LINE FEED (LF)> (LF) ÷ [3.1] LATIN SMALL LETTER A (ALetter) ÷ [3.2] <LINE FEED (LF)> (LF) ÷ [3.1] COMBINING DIAERESIS (Extend_FE) ÷ [0.3]
{
std::array<uint32_t, 5> cps = {{ 0xd, 0xa, 0x61, 0xa, 0x308 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
}
// ÷ 0061 × 0308 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x61, 0x308 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 0020 × 200D ÷ 0646 ÷
// ÷ [0.2] SPACE (WSegSpace) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] ARABIC LETTER NOON (ALetter) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x20, 0x200d, 0x646 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0646 × 200D ÷ 0020 ÷
// ÷ [0.2] ARABIC LETTER NOON (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] SPACE (WSegSpace) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x646, 0x200d, 0x20 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0041 × 0041 × 0041 ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x41, 0x41, 0x41 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0041 × 003A × 0041 ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [6.0] COLON (MidLetter) × [7.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x41, 0x3a, 0x41 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0041 ÷ 003A ÷ 003A ÷ 0041 ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x41, 0x3a, 0x3a, 0x41 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 05D0 × 0027 ÷
// ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.1] APOSTROPHE (Single_Quote) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x5d0, 0x27 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 05D0 × 0022 × 05D0 ÷
// ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.2] QUOTATION MARK (Double_Quote) × [7.3] HEBREW LETTER ALEF (Hebrew_Letter) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x5d0, 0x22, 0x5d0 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0041 × 0030 × 0030 × 0041 ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [9.0] DIGIT ZERO (Numeric) × [8.0] DIGIT ZERO (Numeric) × [10.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x41, 0x30, 0x30, 0x41 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
}
// ÷ 0030 × 002C × 0030 ÷
// ÷ [0.2] DIGIT ZERO (Numeric) × [12.0] COMMA (MidNum) × [11.0] DIGIT ZERO (Numeric) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x30, 0x2c, 0x30 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0030 ÷ 002C ÷ 002C ÷ 0030 ÷
// ÷ [0.2] DIGIT ZERO (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [999.0] COMMA (MidNum) ÷ [999.0] DIGIT ZERO (Numeric) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x30, 0x2c, 0x2c, 0x30 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 3031 × 3031 ÷
// ÷ [0.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.0] VERTICAL KANA REPEAT MARK (Katakana) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x3031, 0x3031 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 0041 × 005F × 0030 × 005F × 3031 × 005F ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ZERO (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.1] LOW LINE (ExtendNumLet) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x41, 0x5f, 0x30, 0x5f, 0x3031, 0x5f }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
}
// ÷ 0041 × 005F × 005F × 0041 ÷
// ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x41, 0x5f, 0x5f, 0x41 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4);
}
// ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
// ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [15.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 5> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
}
// ÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x200d, 0x1f1e8, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0061 ÷ 1F1E6 × 200D × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x200d, 0x1f1e7, 0x1f1e8, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER D (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x1f1e9, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 1F476 × 1F3FF ÷ 1F476 ÷
// ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [999.0] BABY (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1f476, 0x1f3ff, 0x1f476 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 1F6D1 × 200D × 1F6D1 ÷
// ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1f6d1, 0x200d, 0x1f6d1 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0061 × 200D × 1F6D1 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x1f6d1 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 2701 × 200D × 2701 ÷
// ÷ [0.2] UPPER BLADE SCISSORS (Other) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x2701, 0x200d, 0x2701 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 0061 × 200D × 2701 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x2701 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷
// ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x1f476, 0x1f3ff, 0x308, 0x200d, 0x1f476, 0x1f3ff }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6);
}
// ÷ 1F6D1 × 1F3FF ÷
// ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f3ff }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 200D × 1F6D1 × 1F3FF ÷
// ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x200d, 0x1f6d1, 0x1f3ff }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
}
// ÷ 200D × 1F6D1 ÷
// ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 200D × 1F6D1 ÷
// ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2);
}
// ÷ 1F6D1 ÷ 1F6D1 ÷
// ÷ [0.2] OCTAGONAL SIGN (ExtPict) ÷ [999.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f6d1 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0061 × 0308 × 200D × 0308 × 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [5.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 5> cps = {{ 0x61, 0x308, 0x200d, 0x308, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5);
}
// ÷ 0061 ÷ 0020 × 0020 ÷ 0062 ÷
// ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] SPACE (WSegSpace) × [3.4] SPACE (WSegSpace) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x61, 0x20, 0x20, 0x62 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0031 ÷ 003A ÷ 003A ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 ÷ 003A ÷ 003A ÷ 0061 ÷
// ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x61 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0061 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x61 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0061 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x61 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 ÷ 003A ÷ 002E ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 × 005F × 0061 ÷ 003A ÷ 002E ÷ 0031 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x2e, 0x31 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
// ÷ 0031 ÷ 003A ÷ 002E ÷ 0061 ÷
// ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x61 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
}
// ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0061 ÷
// ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3]
{
std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x61 }};
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5);
EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6);
}
}
| 76.010158 | 292 | 0.594239 | eightysquirrels |
787d6eac8148288a839a06c366f15b75c55bee35 | 2,711 | cpp | C++ | Src/Server/OSSupport/IPLookup.cpp | lcmftianci/licodeanalysis | 62e2722eba1b75ef82f7c1328585873d08bb41cc | [
"Apache-2.0"
] | 2 | 2019-11-17T14:01:21.000Z | 2019-12-24T14:29:45.000Z | Src/Server/OSSupport/IPLookup.cpp | lcmftianci/licodeanalysis | 62e2722eba1b75ef82f7c1328585873d08bb41cc | [
"Apache-2.0"
] | null | null | null | Src/Server/OSSupport/IPLookup.cpp | lcmftianci/licodeanalysis | 62e2722eba1b75ef82f7c1328585873d08bb41cc | [
"Apache-2.0"
] | 3 | 2019-08-28T14:37:01.000Z | 2020-06-17T16:46:32.000Z |
// IPLookup.cpp
// Implements the cIPLookup class representing an IP-to-hostname lookup in progress.
#include "stdafx.h"
#include "IPLookup.h"
#include <event2/dns.h>
#include "NetworkSingleton.h"
#include <log4z.h>
using namespace zsummer::log4z;
////////////////////////////////////////////////////////////////////////////////
// cIPLookup:
cIPLookup::cIPLookup(cNetwork::cResolveNameCallbacksPtr a_Callbacks):
m_Callbacks(a_Callbacks)
{
ASSERT(a_Callbacks != nullptr);
}
bool cIPLookup::Lookup(const AString & a_IP)
{
// Parse the IP address string into a sockaddr structure:
m_IP = a_IP;
sockaddr_storage sa;
int salen = static_cast<int>(sizeof(sa));
memset(&sa, 0, sizeof(sa));
if (evutil_parse_sockaddr_port(a_IP.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen) != 0)
{
LOGD("Failed to parse IP address \"%s\"." << a_IP.c_str());
return false;
}
// Call the proper resolver based on the address family:
// Note that there's no need to store the evdns_request handle returned, LibEvent frees it on its own.
switch (sa.ss_family)
{
case AF_INET:
{
sockaddr_in * sa4 = reinterpret_cast<sockaddr_in *>(&sa);
evdns_base_resolve_reverse(cNetworkSingleton::Get().GetDNSBase(), &(sa4->sin_addr), 0, Callback, this);
break;
}
case AF_INET6:
{
sockaddr_in6 * sa6 = reinterpret_cast<sockaddr_in6 *>(&sa);
evdns_base_resolve_reverse_ipv6(cNetworkSingleton::Get().GetDNSBase(), &(sa6->sin6_addr), 0, Callback, this);
break;
}
default:
{
LOGWARNING("%s: Unknown address family: %d", __FUNCTION__, sa.ss_family);
ASSERT(!"Unknown address family");
return false;
}
} // switch (address family)
return true;
}
void cIPLookup::Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self)
{
// Get the Self class:
cIPLookup * Self = reinterpret_cast<cIPLookup *>(a_Self);
ASSERT(Self != nullptr);
// Call the proper callback based on the event received:
if ((a_Result != 0) || (a_Addresses == nullptr))
{
// An error has occurred, notify the error callback:
Self->m_Callbacks->OnError(a_Result, evutil_socket_error_to_string(a_Result));
}
else
{
// Call the success handler:
Self->m_Callbacks->OnNameResolved(*(reinterpret_cast<char **>(a_Addresses)), Self->m_IP);
Self->m_Callbacks->OnFinished();
}
cNetworkSingleton::Get().RemoveIPLookup(Self);
}
////////////////////////////////////////////////////////////////////////////////
// cNetwork API:
bool cNetwork::IPToHostName(
const AString & a_IP,
cNetwork::cResolveNameCallbacksPtr a_Callbacks
)
{
auto res = std::make_shared<cIPLookup>(a_Callbacks);
cNetworkSingleton::Get().AddIPLookup(res);
return res->Lookup(a_IP);
}
| 25.819048 | 112 | 0.669864 | lcmftianci |
787e7f8cd1c9c5266eef712814c2dcafd3c3c3af | 1,570 | cpp | C++ | src/io/spoiler_writer.cpp | Nanarki/randstalker | 003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5 | [
"MIT"
] | 10 | 2020-01-19T22:10:01.000Z | 2021-12-27T15:30:22.000Z | src/io/spoiler_writer.cpp | Nanarki/randstalker | 003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5 | [
"MIT"
] | 34 | 2020-01-19T14:31:02.000Z | 2022-03-31T22:02:47.000Z | src/io/spoiler_writer.cpp | Nanarki/randstalker | 003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5 | [
"MIT"
] | 6 | 2020-01-19T09:37:47.000Z | 2022-01-06T01:12:17.000Z | #include "io.hpp"
#include <landstalker_lib/tools/json.hpp>
#include <landstalker_lib/model/world_teleport_tree.hpp>
#include <landstalker_lib/model/entity_type.hpp>
#include "../logic_model/world_region.hpp"
#include "../logic_model/randomizer_world.hpp"
#include "../logic_model/hint_source.hpp"
#include "../randomizer_options.hpp"
Json SpoilerWriter::build_spoiler_json(const RandomizerWorld& world, const RandomizerOptions& options)
{
Json json;
// Export dark node
json["spawnLocation"] = world.spawn_location().id();
json["darkRegion"] = world.dark_region()->name();
// Export hints
for(HintSource* hint_source : world.used_hint_sources())
json["hints"][hint_source->description()] = hint_source->text();
if(options.shuffle_tibor_trees())
{
json["tiborTrees"] = Json::array();
for(auto& pair : world.teleport_tree_pairs())
json["tiborTrees"].emplace_back(pair.first->name() + " <--> " + pair.second->name());
}
// Export item sources
for(WorldRegion* region : world.regions())
{
for(WorldNode* node : region->nodes())
{
for(ItemSource* source : node->item_sources())
{
Item* item = world.item(source->item_id());
json["itemSources"][region->name()][source->name()] = item->name();
}
}
}
// Fahl enemies
json["fahlEnemies"] = Json::array();
for(EntityType* enemy : world.fahl_enemies())
json["fahlEnemies"].emplace_back(enemy->name());
return json;
}
| 30.784314 | 102 | 0.63121 | Nanarki |
787f2835bbc3f6b69581d16d01f1f5606afe8664 | 2,141 | hpp | C++ | src/Service.hpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | 2 | 2018-10-10T12:37:05.000Z | 2018-12-07T22:36:42.000Z | src/Service.hpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | src/Service.hpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "Task.hpp"
#include <map>
#include <vector>
#include <functional>
#ifndef SERVICE_HPP
#define SERVICE_HPP
#ifdef _DEBUG
// This macros works only with string literals, and cannot be used in headers files.
#define SERVICES_PRINTF(format, ...) Serial.printf_P(PSTR(format), ##__VA_ARGS__)
#define SERVICES_PRINT(text) SERVICES_PRINTF(text)
#define SERVICE_PRINTF(format, ...) Serial.printf_P(PSTR("[%s] " format), _ServiceName.c_str(), ##__VA_ARGS__)
#define SERVICE_PRINT(text) SERVICE_PRINTF(text)
#else
#define SERVICES_PRINT(text)
#define SERVICES_PRINTF(...)
#define SERVICE_PRINTF(...)
#define SERVICE_PRINT(text)
#endif
#define S(name, type) ((type*)Service::Get(name))
struct char_compare
{
bool operator () (const char *a, const char *b) const { return strcmp(a, b) < 0; }
};
enum UpdateType
{
UPDATE_SYNC,
UPDATE_ASYNC
};
enum UpdateRequest
{
NO_UPDATE,
DO_UPDATE,
ALWAYS_UPDATE
};
class Service
{
public:
typedef std::function<void(Service* svc)> EventCallback;
typedef std::map<const char*, Service*, char_compare> ServiceMap;
typedef std::map<const char*, std::vector<EventCallback>, char_compare> EventMap;
Service() {};
virtual void Init() = 0;
virtual void Update() = 0;
static Service* Get(const char* name);
static void BindEvent(const char* event, EventCallback callback);
static void InitAll();
static void SyncUpdate();
static void SuspendAsyncUpdates();
protected:
static void RegisterService(Service* service, const char* name, std::vector<const char*> events);
static void FireEvent(Service* service, const char* event);
void SetPeriodicUpdate(unsigned int period, UpdateType ut = UPDATE_ASYNC);
void EnablePeriodicUpdate();
void DisablePeriodicUpdate();
UpdateRequest _UpdateRequest;
String _ServiceName;
private:
Task _UpdateTask;
// List of service (name,instance) pairs.
static ServiceMap _Services;
// Map every event name (declared by services in register_service) with one or more callbacks.
static EventMap _Events;
};
#endif
| 24.609195 | 111 | 0.711817 | dancol90 |
787fb1bc3b0b162f0fe957aa87b1795024df620b | 3,555 | cc | C++ | third_party/blink/renderer/core/page/scrolling/text_fragment_selector.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | third_party/blink/renderer/core/page/scrolling/text_fragment_selector.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/core/page/scrolling/text_fragment_selector.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/page/scrolling/text_fragment_selector.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace {
// The prefix and suffix terms are specified to begin/end with a '-' character.
// These methods will find the prefix/suffix and return it without the '-', and
// remove the prefix/suffix from the |target_text| string. If not found, we
// return an empty string to indicate no prefix/suffix was specified or it
// was malformed and should be ignored.
String ExtractPrefix(String* target_text) {
size_t comma_pos = target_text->find(',');
size_t hyphen_pos = target_text->find('-');
if (hyphen_pos != kNotFound && hyphen_pos == comma_pos - 1) {
String prefix = target_text->Substring(0, hyphen_pos);
target_text->Remove(0, comma_pos + 1);
return prefix;
}
return "";
}
String ExtractSuffix(String* target_text) {
size_t last_comma_pos = target_text->ReverseFind(',');
size_t last_hyphen_pos = target_text->ReverseFind('-');
if (last_hyphen_pos != kNotFound && last_hyphen_pos == last_comma_pos + 1) {
String suffix = target_text->Substring(last_hyphen_pos + 1);
target_text->Truncate(last_comma_pos);
return suffix;
}
return "";
}
} // namespace
TextFragmentSelector TextFragmentSelector::Create(String target_text) {
SelectorType type;
String start;
String end;
String prefix = ExtractPrefix(&target_text);
String suffix = ExtractSuffix(&target_text);
size_t comma_pos = target_text.find(',');
// If there are more commas, this is an invalid text fragment selector.
size_t next_comma_pos = target_text.find(',', comma_pos + 1);
if (next_comma_pos != kNotFound)
return TextFragmentSelector(kInvalid);
if (comma_pos == kNotFound) {
type = kExact;
start = target_text;
end = "";
} else {
type = kRange;
start = target_text.Substring(0, comma_pos);
end = target_text.Substring(comma_pos + 1);
}
return TextFragmentSelector(
type, DecodeURLEscapeSequences(start, DecodeURLMode::kUTF8),
DecodeURLEscapeSequences(end, DecodeURLMode::kUTF8),
DecodeURLEscapeSequences(prefix, DecodeURLMode::kUTF8),
DecodeURLEscapeSequences(suffix, DecodeURLMode::kUTF8));
}
TextFragmentSelector::TextFragmentSelector(SelectorType type,
const String& start,
const String& end,
const String& prefix,
const String& suffix)
: type_(type), start_(start), end_(end), prefix_(prefix), suffix_(suffix) {}
TextFragmentSelector::TextFragmentSelector(SelectorType type) : type_(type) {}
String TextFragmentSelector::ToString() const {
StringBuilder selector;
if (!prefix_.IsEmpty()) {
selector.Append(EncodeWithURLEscapeSequences(prefix_));
selector.Append("-,");
}
if (!start_.IsEmpty()) {
selector.Append(EncodeWithURLEscapeSequences(start_));
}
if (!end_.IsEmpty()) {
selector.Append(",");
selector.Append(EncodeWithURLEscapeSequences(end_));
}
if (!suffix_.IsEmpty()) {
selector.Append(",-");
selector.Append(EncodeWithURLEscapeSequences(suffix_));
}
return selector.ToString();
}
} // namespace blink
| 32.318182 | 82 | 0.688045 | Ron423c |
788353cd8ee9e32879120d99dc27e3862029ff18 | 9,436 | cpp | C++ | compiler/luci/pass/src/QuantizePreCheckerPass.test.cpp | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | compiler/luci/pass/src/QuantizePreCheckerPass.test.cpp | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | compiler/luci/pass/src/QuantizePreCheckerPass.test.cpp | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2022 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "luci/Pass/QuantizePreCheckerPass.h"
#include <luci/IR/CircleNodes.h>
#include <gtest/gtest.h>
class SimpleConv2DGraph
{
public:
SimpleConv2DGraph(bool make_valid)
{
conv2d_node = g.nodes()->create<luci::CircleConv2D>();
input_1 = g.nodes()->create<luci::CircleInput>();
filter = g.nodes()->create<luci::CircleConst>();
conv2d_node->input(input_1);
conv2d_node->filter(filter);
if (make_valid)
{
bias = g.nodes()->create<luci::CircleConst>();
conv2d_node->bias(bias);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
conv2d_node->bias(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(conv2d_node);
}
public:
loco::Graph g;
private:
luci::CircleConv2D *conv2d_node = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *filter = nullptr;
luci::CircleConst *bias = nullptr;
luci::CircleOutput *output = nullptr;
};
class SimpleDepthConv2DGraph
{
public:
SimpleDepthConv2DGraph(bool make_valid)
{
depth_conv2d_node = g.nodes()->create<luci::CircleDepthwiseConv2D>();
input_1 = g.nodes()->create<luci::CircleInput>();
filter = g.nodes()->create<luci::CircleConst>();
depth_conv2d_node->input(input_1);
depth_conv2d_node->filter(filter);
if (make_valid)
{
bias = g.nodes()->create<luci::CircleConst>();
depth_conv2d_node->bias(bias);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
depth_conv2d_node->bias(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(depth_conv2d_node);
}
public:
loco::Graph g;
private:
luci::CircleDepthwiseConv2D *depth_conv2d_node = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *filter = nullptr;
luci::CircleConst *bias = nullptr;
luci::CircleOutput *output = nullptr;
};
class SimpleFCGraph
{
public:
SimpleFCGraph(bool make_valid)
{
fc_node = g.nodes()->create<luci::CircleFullyConnected>();
input_1 = g.nodes()->create<luci::CircleInput>();
weights = g.nodes()->create<luci::CircleConst>();
fc_node->input(input_1);
fc_node->weights(weights);
if (make_valid)
{
bias = g.nodes()->create<luci::CircleConst>();
fc_node->bias(bias);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
fc_node->bias(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(fc_node);
}
public:
loco::Graph g;
private:
luci::CircleFullyConnected *fc_node = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *weights = nullptr;
luci::CircleConst *bias = nullptr;
luci::CircleOutput *output = nullptr;
};
class SimpleInstanceNormGraph
{
public:
SimpleInstanceNormGraph(bool make_valid)
{
instance_norm_node = g.nodes()->create<luci::CircleInstanceNorm>();
input_1 = g.nodes()->create<luci::CircleInput>();
gamma = g.nodes()->create<luci::CircleConst>();
instance_norm_node->input(input_1);
instance_norm_node->gamma(gamma);
if (make_valid)
{
beta = g.nodes()->create<luci::CircleConst>();
instance_norm_node->beta(beta);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
instance_norm_node->beta(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(instance_norm_node);
}
public:
loco::Graph g;
private:
luci::CircleInstanceNorm *instance_norm_node = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *gamma = nullptr;
luci::CircleConst *beta = nullptr;
luci::CircleOutput *output = nullptr;
};
class SimpleTransposeConvGraph
{
public:
SimpleTransposeConvGraph(bool make_valid)
{
transpose_conv = g.nodes()->create<luci::CircleTransposeConv>();
input_1 = g.nodes()->create<luci::CircleInput>();
input_sizes = g.nodes()->create<luci::CircleConst>();
filter = g.nodes()->create<luci::CircleConst>();
transpose_conv->outBackprop(input_1);
transpose_conv->filter(filter);
transpose_conv->inputSizes(input_sizes);
if (make_valid)
{
bias = g.nodes()->create<luci::CircleConst>();
transpose_conv->bias(bias);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
transpose_conv->bias(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(transpose_conv);
}
public:
loco::Graph g;
private:
luci::CircleTransposeConv *transpose_conv = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *input_sizes = nullptr;
luci::CircleConst *filter = nullptr;
luci::CircleConst *bias = nullptr;
luci::CircleOutput *output = nullptr;
};
class SimplePReluGraph
{
public:
SimplePReluGraph(bool make_valid)
{
prelu = g.nodes()->create<luci::CirclePRelu>();
input_1 = g.nodes()->create<luci::CircleInput>();
prelu->input(input_1);
if (make_valid)
{
alpha = g.nodes()->create<luci::CircleConst>();
prelu->alpha(alpha);
}
else
{
input_2 = g.nodes()->create<luci::CircleInput>();
prelu->alpha(input_2);
}
output = g.nodes()->create<luci::CircleOutput>();
auto graph_output = g.outputs()->create();
output->index(graph_output->index());
output->from(prelu);
}
public:
loco::Graph g;
private:
luci::CirclePRelu *prelu = nullptr;
luci::CircleInput *input_1 = nullptr;
luci::CircleInput *input_2 = nullptr;
luci::CircleConst *alpha = nullptr;
luci::CircleOutput *output = nullptr;
};
TEST(QuantizePreCheckerPassTest, name)
{
luci::QuantizePreCheckerPass pass{};
auto const name = pass.name();
ASSERT_NE(nullptr, name);
}
// Test Conv2d
TEST(QuantizePreCheckerPassTest, conv2d)
{
SimpleConv2DGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, conv2d_NEG)
{
SimpleConv2DGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
// Test DepthwiseConv2d
TEST(QuantizePreCheckerPassTest, depthwise_conv2d)
{
SimpleDepthConv2DGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, depthwise_conv2d_NEG)
{
SimpleDepthConv2DGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
// Test FullyConnected
TEST(QuantizePreCheckerPassTest, fully_connected)
{
SimpleFCGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, fully_connected_NEG)
{
SimpleFCGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
// Test InstanceNorm
TEST(QuantizePreCheckerPassTest, instance_norm)
{
SimpleInstanceNormGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, instance_norm_NEG)
{
SimpleInstanceNormGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
// Test TransposeConv
TEST(QuantizePreCheckerPassTest, transpose_conv)
{
SimpleTransposeConvGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, transpose_conv_NEG)
{
SimpleTransposeConvGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
// Test PRelu
TEST(QuantizePreCheckerPassTest, prelu)
{
SimplePReluGraph valid_graph(true);
luci::QuantizePreCheckerPass checker{};
EXPECT_NO_THROW(checker.run(&valid_graph.g));
}
TEST(QuantizePreCheckerPassTest, prelu_NEG)
{
SimplePReluGraph invalid_graph(false);
luci::QuantizePreCheckerPass checker{};
EXPECT_ANY_THROW(checker.run(&invalid_graph.g));
}
| 23.472637 | 75 | 0.697541 | glistening |
78836e890c63a0acf24b58b9e5d9df42ee918320 | 4,000 | cpp | C++ | src/Stepper.cpp | zakimadaoui/TinyStepLib | 196e9277f470b57fe79d30b3f3a6f127eff77510 | [
"MIT"
] | 2 | 2021-01-04T20:42:23.000Z | 2021-01-27T14:15:42.000Z | src/Stepper.cpp | zakimadaoui/TinyStepLib | 196e9277f470b57fe79d30b3f3a6f127eff77510 | [
"MIT"
] | null | null | null | src/Stepper.cpp | zakimadaoui/TinyStepLib | 196e9277f470b57fe79d30b3f3a6f127eff77510 | [
"MIT"
] | null | null | null | #include "Stepper.h"
#include <Arduino.h>
uint16_t getPortAddress(char port){
switch (port)
{
case 'B':
return 0x05;
case 'C':
return 0x08;
default://'D'
return 0x0B;
}
}
uint16_t getDDrAddress(char port)
{
switch (port)
{
case 'B':
return 0x04;
case 'C':
return 0x07;
default: //'D'
return 0x0A;
}
}
Stepper::Stepper(char *step_port_pin, char *dir_port_pin, double stepper_angle, int micro_stepping)
{
// set both step and dir ports and pins
step_port_addr = getPortAddress(step_port_pin[0]);
step_pin = step_port_pin[1] - '0';
dir_port_addr = getPortAddress(dir_port_pin[0]);
dir_pin = dir_port_pin[1] - '0';
// set both step and dir as output
_SFR_IO8(getDDrAddress(step_port_pin[0])) |= (1 << step_pin);
_SFR_IO8(getDDrAddress(dir_port_pin[0])) |= (1 << dir_pin );
// init the direction
setDirection(0);
//calculate stepper resolution
this->angle_per_step = stepper_angle / micro_stepping;
// set default speed
setSpeedInDegrees(100);
}
void Stepper::setDirection(uint8_t dir)
{
dir = dir % 2; //correct the dir if not 1 or 0
this->dir = dir;
if (dir == 0) _SFR_IO8(dir_port_addr) &= ~(1 << dir_pin); //set the dir pin to 0
else _SFR_IO8(dir_port_addr) |= (1 << dir_pin); //set the dir pin to 1
}
uint8_t Stepper::getDirection() {return dir;}
void Stepper::pulseStepPin()
{
_SFR_IO8(step_port_addr) &= ~(1 << step_pin); //set pin to 0
//_delay_us(1); //delay for meeting condition
_SFR_IO8(step_port_addr) |= (1 << step_pin); //set pin to 1
}
void Stepper::makeAstep()
{
if (rotateMotor)
{
current_tick++;
if (current_tick == ticks_for_one_step) //this condition controlls the speed of the motor
{
current_tick = 0;
if (isInSpinMode) // keep spinning
pulseStepPin();
else if (current_step != target_steps) // target angle not reached yet
{
pulseStepPin();
current_step++;
}
else
{
stop(); //stop the motor
if (__onTagetReached != nullptr) __onTagetReached();// trigger callback,
}
}
}
}
//this takes only positive values
void Stepper::moveWithAngle(double angle){
//stop, cancel spin and reset current_steps
stop();
// calculate target steps
target_steps = abs(round(angle / angle_per_step));
//move towards target
rotateMotor = true;
}
void Stepper::moveWithSteps(uint32_t steps)
{
//stop, cancel spin and reset all states
stop();
// calculate target steps
target_steps = steps;
//move towards target
rotateMotor = true;
}
void Stepper::stop(){
rotateMotor = false;
isInSpinMode = false;
current_tick = 0;
current_step = 0;
target_steps = 0;
}
void Stepper::spin(){
isInSpinMode = true;
rotateMotor = true;
}
void Stepper::setSpeedInDegrees(uint16_t spd)
{
speed = abs(spd) / angle_per_step; //convert deg/sec to step/sec
if (speed >= MAX_SPEED) speed = MAX_SPEED;
ticks_for_one_step = round(MAX_SPEED / speed);
current_tick = 0; // reset tick
}
void Stepper::setSpeedInSteps(uint16_t spd)
{
speed = abs(spd);
if (speed >= MAX_SPEED) speed = MAX_SPEED;
ticks_for_one_step = round(MAX_SPEED / speed);
current_tick = 0; // reset tick
}
uint16_t Stepper::getSpeedInDegrees() { return (uint16_t)(speed * angle_per_step); }
uint16_t Stepper::getSpeedInSteps() { return (uint16_t)speed; }
void Stepper::setStepperIndex(uint8_t stepper_index){
this->stepper_index = stepper_index;
};
uint8_t Stepper::getStepperIndex(){
return stepper_index;
};
void Stepper::setOnTargetReachedCallback(void (*callback)(void)){
__onTagetReached = callback;
}
| 23.809524 | 99 | 0.6115 | zakimadaoui |
7885036a6de923a917c87290c429c078b761c428 | 5,675 | hpp | C++ | include/UnityEngine/UI/ToggleGroup_--c.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/UI/ToggleGroup_--c.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/UI/ToggleGroup_--c.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.UI.ToggleGroup
#include "UnityEngine/UI/ToggleGroup.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Predicate`1<T>
template<typename T>
class Predicate_1;
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Toggle
class Toggle;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::UI::ToggleGroup::$$c);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::ToggleGroup::$$c*, "UnityEngine.UI", "ToggleGroup/<>c");
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class ToggleGroup::$$c : public ::Il2CppObject {
public:
// Get static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9
static ::UnityEngine::UI::ToggleGroup::$$c* _get_$$9();
// Set static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9
static void _set_$$9(::UnityEngine::UI::ToggleGroup::$$c* value);
// Get static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0
static ::System::Predicate_1<::UnityEngine::UI::Toggle*>* _get_$$9__13_0();
// Set static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0
static void _set_$$9__13_0(::System::Predicate_1<::UnityEngine::UI::Toggle*>* value);
// Get static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0
static ::System::Func_2<::UnityEngine::UI::Toggle*, bool>* _get_$$9__14_0();
// Set static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0
static void _set_$$9__14_0(::System::Func_2<::UnityEngine::UI::Toggle*, bool>* value);
// static private System.Void .cctor()
// Offset: 0x1145354
static void _cctor();
// System.Boolean <AnyTogglesOn>b__13_0(UnityEngine.UI.Toggle x)
// Offset: 0x11453BC
bool $AnyTogglesOn$b__13_0(::UnityEngine::UI::Toggle* x);
// System.Boolean <ActiveToggles>b__14_0(UnityEngine.UI.Toggle x)
// Offset: 0x11453D4
bool $ActiveToggles$b__14_0(::UnityEngine::UI::Toggle* x);
// public System.Void .ctor()
// Offset: 0x11453B4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ToggleGroup::$$c* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::UI::ToggleGroup::$$c::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ToggleGroup::$$c*, creationType>()));
}
}; // UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::UI::ToggleGroup::$$c::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0
// Il2CppName: <AnyTogglesOn>b__13_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<AnyTogglesOn>b__13_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0
// Il2CppName: <ActiveToggles>b__14_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<ActiveToggles>b__14_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 53.037383 | 204 | 0.715771 | RedBrumbler |
7885bbd7dca3a8088cabc113fe6db4c1f1ad4870 | 33,720 | cpp | C++ | Wrappers/java/jni/org_openni_NativeMethods.cpp | BEIWG/OpenNI2 | 3d144e98884dd78703a3e145856dded166f87e60 | [
"Apache-2.0"
] | null | null | null | Wrappers/java/jni/org_openni_NativeMethods.cpp | BEIWG/OpenNI2 | 3d144e98884dd78703a3e145856dded166f87e60 | [
"Apache-2.0"
] | 2 | 2018-04-16T10:51:56.000Z | 2018-04-24T06:35:09.000Z | Wrappers/java/jni/org_openni_NativeMethods.cpp | BEIWG/OpenNI2 | 3d144e98884dd78703a3e145856dded166f87e60 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
#include <jni.h>
#include "OniProperties.h"
#include "OniEnums.h"
#include "OniCAPI.h"
#include "org_openni_NativeMethods.h"
#include <XnPlatform.h>
#ifdef ANDROID
#include <android/log.h>
#endif
#define DEBUG 1
#if DEBUG && defined(ANDROID)
#include <android/log.h>
# define LOGD(x...) __android_log_print(ANDROID_LOG_INFO,"OpenNIJNI",x)
# define LOGE(x...) __android_log_print(ANDROID_LOG_ERROR,"OpenNIJNI",x)
#else
# define LOGD(...)
# define LOGE(...)
#endif
using namespace openni;
JavaVM* g_pVM = NULL;
jclass g_videoStreamClass;
jclass g_openNIClass;
jclass g_deviceInfoClass;
class JNIEnvSupplier
{
public:
JNIEnvSupplier() : m_pEnv(NULL), m_bShouldDetach(FALSE)
{
if (JNI_EDETACHED == g_pVM->GetEnv((void**)&m_pEnv, JNI_VERSION_1_2))
{
g_pVM->AttachCurrentThread((void**)&m_pEnv, NULL);
m_bShouldDetach = TRUE;
}
}
~JNIEnvSupplier()
{
if (m_bShouldDetach)
{
g_pVM->DetachCurrentThread();
}
}
JNIEnv* GetEnv() { return m_pEnv; }
private:
JNIEnv* m_pEnv;
XnBool m_bShouldDetach;
};
void SetOutArgObjectValue(JNIEnv*env, jobject p, jobject value)
{
jclass cls = env->GetObjectClass(p);
jfieldID fieldID = env->GetFieldID(cls, "mValue", "Ljava/lang/Object;");
env->SetObjectField(p, fieldID, value);
}
void SetOutArgVideoModeValue(JNIEnv*env, jobject p, jobject value)
{
SetOutArgObjectValue(env, p, value);
}
void SetOutArgDoubleValue(JNIEnv*env, jobject p, double value)
{
jclass cls = env->FindClass("java/lang/Double");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(D)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgLongValue(JNIEnv*env, jobject p, XnUInt64 value)
{
jclass cls = env->FindClass("java/lang/Long");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(J)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgIntValue(JNIEnv*env, jobject p, int value)
{
jclass cls = env->FindClass("java/lang/Integer");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(I)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgShortValue(JNIEnv*env, jobject p, short value)
{
jclass cls = env->FindClass("java/lang/Short");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(S)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgByteValue(JNIEnv*env, jobject p, XnUInt8 value)
{
jclass cls = env->FindClass("java/lang/Byte");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(B)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgBoolValue(JNIEnv*env, jobject p, jboolean value)
{
jclass cls = env->FindClass("java/lang/Boolean");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(Z)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgFloatValue(JNIEnv*env, jobject p, jfloat value)
{
jclass cls = env->FindClass("java/lang/Float");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(F)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgStringValue(JNIEnv*env, jobject p, const XnChar* value)
{
SetOutArgObjectValue(env, p, env->NewStringUTF(value));
}
JNIEnv *g_env;
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameRelease
(JNIEnv *, jclass, jlong frame)
{
// oniFrameRelease((OniFrame*)frame);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameAddRef
(JNIEnv *, jclass, jlong frame)
{
//oniFrameAddRef((OniFrame*)frame);
}
static void ONI_CALLBACK_TYPE callback(OniStreamHandle streamHandle, void*)
{
JNIEnvSupplier suplier;
jmethodID methodID = suplier.GetEnv()->GetStaticMethodID(g_videoStreamClass, "onFrameReady", "(J)V");
jlong handle = (jlong)streamHandle;
suplier.GetEnv()->CallStaticVoidMethod(g_videoStreamClass, methodID, handle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceCreateStream
(JNIEnv *env, jclass, jlong device, jint sensorType, jobject videoStreamObj)
{
OniStreamHandle* streamHandle;
jint status = oniDeviceCreateStream((OniDeviceHandle)device, (OniSensorType)sensorType, (OniStreamHandle*)&streamHandle);
if (status == ONI_STATUS_OK)
{
jclass videoStreamCls = env->FindClass("org/openni/VideoStream");
jfieldID fieldID = env->GetFieldID(videoStreamCls, "mStreamHandle", "J");
env->SetLongField(videoStreamObj, fieldID, (jlong)streamHandle);
OniCallbackHandle handle = 0;
status = oniStreamRegisterNewFrameCallback((OniStreamHandle)streamHandle, callback, videoStreamCls, &handle);
fieldID = env->GetFieldID(videoStreamCls, "mCallbackHandle", "J");
env->SetLongField(videoStreamObj, fieldID, (jlong)handle);
}
return status;
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamDestroy
(JNIEnv *, jclass, jlong streamHandle, jlong callbackHandle)
{
oniStreamUnregisterNewFrameCallback((OniStreamHandle)streamHandle,(OniCallbackHandle)callbackHandle);
oniStreamDestroy((OniStreamHandle)streamHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamStart
(JNIEnv *, jclass, jlong streamHandle)
{
return oniStreamStart((OniStreamHandle)streamHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamStop
(JNIEnv *, jclass, jlong streamHandle)
{
oniStreamStop((OniStreamHandle)streamHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamReadFrame
(JNIEnv *env, jclass, jlong streamHandle, jobject outArgObj)
{
OniFrame* pOniFrame;
int status = oniStreamReadFrame((OniStreamHandle)streamHandle, &pOniFrame);
if (status == STATUS_OK)
{
jclass videoFrameRefCls = env->FindClass("org/openni/VideoFrameRef");
jmethodID videoFrameCtor = env->GetMethodID(videoFrameRefCls, "<init>", "(J)V");
jobject videoFrameRefObj = env->NewObject(videoFrameRefCls, videoFrameCtor, (jlong)pOniFrame);
jfieldID fieldID = env->GetFieldID(videoFrameRefCls, "mTimestamp", "J");
env->SetLongField(videoFrameRefObj,fieldID, (jlong)pOniFrame->timestamp);
fieldID = env->GetFieldID(videoFrameRefCls, "mIndex", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->frameIndex);
fieldID = env->GetFieldID(videoFrameRefCls, "mWidth", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->width);
fieldID = env->GetFieldID(videoFrameRefCls, "mHeight", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->height);
fieldID = env->GetFieldID(videoFrameRefCls, "mIsCropping", "Z");
env->SetBooleanField(videoFrameRefObj,fieldID, (pOniFrame->croppingEnabled == TRUE));
fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigX", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginX);
fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigY", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginY);
fieldID = env->GetFieldID(videoFrameRefCls, "mStride", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->stride);
jclass byteOrderCls = env->FindClass("java/nio/ByteOrder");
jfieldID littleEndianField = env->GetStaticFieldID(byteOrderCls, "LITTLE_ENDIAN", "Ljava/nio/ByteOrder;");
jobject littleEndian = env->GetStaticObjectField(byteOrderCls, littleEndianField);
jclass byteBufferCls = env->FindClass("java/nio/ByteBuffer");
jmethodID orderMethodId = env->GetMethodID(byteBufferCls, "order", "(Ljava/nio/ByteOrder;)Ljava/nio/ByteBuffer;");
jobject buffer = env->NewDirectByteBuffer(pOniFrame->data, pOniFrame->dataSize);
env->CallObjectMethod(buffer, orderMethodId, littleEndian);
fieldID = env->GetFieldID(videoFrameRefCls, "mData", "Ljava/nio/ByteBuffer;");
env->SetObjectField(videoFrameRefObj,fieldID, buffer);
jclass sensorTypeCls = env->FindClass("org/openni/SensorType");
jmethodID sensorFromNative = env->GetStaticMethodID(sensorTypeCls, "fromNative", "(I)Lorg/openni/SensorType;");
jobject sensorTypeObj = env->CallStaticObjectMethod(sensorTypeCls, sensorFromNative, pOniFrame->sensorType);
fieldID = env->GetFieldID(videoFrameRefCls, "mSensorType", "Lorg/openni/SensorType;");
env->SetObjectField(videoFrameRefObj,fieldID, sensorTypeObj);
jclass videoModeCls = env->FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, (jint)pOniFrame->videoMode.resolutionX,
(jint)pOniFrame->videoMode.resolutionY, (jint)pOniFrame->videoMode.fps, (jint)pOniFrame->videoMode.pixelFormat);
fieldID = env->GetFieldID(videoFrameRefCls, "mVideoMode", "Lorg/openni/VideoMode;");
env->SetObjectField(videoFrameRefObj,fieldID, videoModeObj);
SetOutArgObjectValue(env, outArgObj, videoFrameRefObj);
// release this frame. The java object is its owner now.
oniFrameRelease(pOniFrame);
}
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getCropping
(JNIEnv *env, jclass, jlong streamHandle, jobject origXOutArg, jobject origYOutArg, jobject widthOurArg, jobject heightOurArg)
{
OniCropping cropping;
int size = sizeof(cropping);
int status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, &size);
SetOutArgIntValue(env, origXOutArg, cropping.originX);
SetOutArgIntValue(env, origYOutArg, cropping.originY);
SetOutArgIntValue(env, widthOurArg, cropping.width);
SetOutArgIntValue(env, heightOurArg, cropping.height);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setCropping
(JNIEnv *, jclass, jlong streamHandle, jint originX, jint originY, jint width, jint height)
{
OniCropping cropping;
cropping.enabled = true;
cropping.originX = originX;
cropping.originY = originY;
cropping.width = width;
cropping.height = height;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isCroppingSupported
(JNIEnv *, jclass, jlong streamHandle)
{
return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING) == TRUE);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_resetCropping
(JNIEnv *, jclass, jlong streamHandle)
{
OniCropping cropping;
cropping.enabled = FALSE;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getVideoMode
(JNIEnv *env, jclass, jlong streamHandle, jobject videoModeArgOutObj)
{
jclass videoModeCls = env->FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
OniVideoMode videoMode;
int size = sizeof(OniVideoMode);
jint status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, &size);
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, videoMode.pixelFormat);
SetOutArgVideoModeValue(env, videoModeArgOutObj, videoModeObj);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setVideoMode
(JNIEnv *, jclass, jlong streamHandle, jint resX, jint resY, jint fps, jint pixelFormat)
{
OniVideoMode videoMode;
int size = sizeof(OniVideoMode);
videoMode.resolutionX = resX;
videoMode.resolutionY = resY;
videoMode.fps = fps;
videoMode.pixelFormat = (OniPixelFormat)pixelFormat;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, size);
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniStreamGetSensorInfo
(JNIEnv *env, jclass, jlong streamHandle)
{
jclass arrayListCls = (*env).FindClass("java/util/ArrayList");
jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V"));
jclass videoModeCls = (*env).FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
const OniSensorInfo* sensorInfo = oniStreamGetSensorInfo((OniStreamHandle)streamHandle);
int i = 0;
while (i < sensorInfo->numSupportedVideoModes)
{
OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i];
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat);
(*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj);
i++;
}
jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo");
jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj);
return obj;
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_hasSensor
(JNIEnv *, jclass, jlong deviceHandle, jint sensorType)
{
const OniSensorInfo* pInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType);
if (pInfo == NULL)
{
return false;
}
return true;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetIntProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
int value = 0;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgIntValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetBoolProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
OniBool value = false;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgBoolValue(env, argOutObj, value == TRUE);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetFloatProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
float value = 0;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgFloatValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JII
(JNIEnv *, jclass, jlong streamHandle, jint property, jint value)
{
int size = sizeof(value);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIZ
(JNIEnv *, jclass, jlong streamHandle, jint property, jboolean value)
{
OniBool val = value?TRUE:FALSE;
int size = sizeof(val);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &val, size);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIF
(JNIEnv *, jclass, jlong streamHandle, jint property, jfloat value)
{
int size = sizeof(value);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniStreamIsPropertySupported
(JNIEnv *, jclass, jlong streamHandle, jint property)
{
return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, property) == TRUE);
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetSensorInfo
(JNIEnv *env, jclass, jlong deviceHandle, jint sensorType)
{
jclass arrayListCls = (*env).FindClass("java/util/ArrayList");
jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V"));
jclass videoModeCls = (*env).FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
const OniSensorInfo* sensorInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType);
if (sensorInfo == NULL)
return NULL;
int i = 0;
while (i < sensorInfo->numSupportedVideoModes)
{
OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i];
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat);
(*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj);
i++;
}
jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo");
jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj);
return obj;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceEnableDepthColorSync
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceEnableDepthColorSync((OniDeviceHandle)deviceHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniDeviceDisableDepthColorSync
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceDisableDepthColorSync((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceGetDepthColorSyncEnabled
(JNIEnv *, jclass, jlong deviceHandle)
{
return (jboolean)oniDeviceGetDepthColorSyncEnabled((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_seek
(JNIEnv *, jclass, jlong deviceHandle, jlong streamHandle, jint frameIndex)
{
OniSeek seek;
seek.frameIndex = frameIndex;
seek.stream = (OniStreamHandle)streamHandle;
return oniDeviceInvoke((OniDeviceHandle)deviceHandle, DEVICE_COMMAND_SEEK, &seek, sizeof(seek));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isImageRegistrationModeSupported
(JNIEnv *, jclass, jlong deviceHandle, jint mode)
{
return (oniDeviceIsImageRegistrationModeSupported((OniDeviceHandle)deviceHandle, (OniImageRegistrationMode)mode) == TRUE);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getImageRegistrationMode
(JNIEnv *env, jclass, jlong deviceHandle, jobject argOutObj)
{
ImageRegistrationMode mode;
int size = sizeof(mode);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, &size);
SetOutArgIntValue(env, argOutObj, mode);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setImageRegistrationMode
(JNIEnv *, jclass, jlong deviceHandle, jint mode)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, sizeof(mode));
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetInfo
(JNIEnv *env, jclass, jlong deviceHandle)
{
OniDeviceInfo deviceInfo;
oniDeviceGetInfo((OniDeviceHandle)deviceHandle, &deviceInfo);
jobject nameObj = env->NewStringUTF(deviceInfo.name);
jobject uriObj = env->NewStringUTF(deviceInfo.uri);
jobject vendorObj = env->NewStringUTF(deviceInfo.vendor);
jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo");
return (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, deviceInfo.usbVendorId, deviceInfo.usbProductId);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderStart
(JNIEnv *, jclass, jlong recorderHandle)
{
return oniRecorderStart((OniRecorderHandle)recorderHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderDestroy
(JNIEnv *, jclass, jlong recorderHandle)
{
return oniRecorderDestroy((OniRecorderHandle*)&recorderHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniRecorderStop
(JNIEnv *, jclass, jlong recorderHandle)
{
oniRecorderStop((OniRecorderHandle)recorderHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderAttachStream
(JNIEnv *, jclass, jlong recorderHandle, jlong streamHadle, jboolean allowLossy)
{
return oniRecorderAttachStream((OniRecorderHandle)recorderHandle, (OniStreamHandle)streamHadle, allowLossy);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetIntProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
int value;
int size = sizeof(value);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgIntValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetBoolProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
OniBool value;
int size = sizeof(value);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgBoolValue(env, argOutObj, (value==TRUE)?JNI_TRUE:JNI_FALSE);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetFloatProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
float value;
int size = sizeof(float);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgFloatValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JII
(JNIEnv *, jclass, jlong deviceHandle, jint property, jint value)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIZ
(JNIEnv *, jclass, jlong deviceHandle, jint property, jboolean value)
{
OniBool oniValue = (value == JNI_TRUE)?TRUE:FALSE;
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &oniValue, sizeof(oniValue));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIF
(JNIEnv *, jclass, jlong deviceHandle, jint property, float value)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsPropertySupported
(JNIEnv *, jclass, jlong deviceHandle, jint property)
{
return (oniDeviceIsPropertySupported((OniDeviceHandle)deviceHandle, property) == TRUE);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsCommandSupported
(JNIEnv *, jclass, jlong deviceHandle, jint command)
{
return (oniDeviceIsCommandSupported((OniDeviceHandle)deviceHandle, command) == TRUE);
}
static void ONI_CALLBACK_TYPE deviceConnectedCallback(const OniDeviceInfo* pInfo, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceConnected", "(Lorg/openni/DeviceInfo;)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj);
}
static void ONI_CALLBACK_TYPE deviceDisconnectedCallback(const OniDeviceInfo* pInfo, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceDisconnected", "(Lorg/openni/DeviceInfo;)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj);
}
static void ONI_CALLBACK_TYPE deviceStateChangedCallback(const OniDeviceInfo* pInfo, OniDeviceState state, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceStateChanged", "(Lorg/openni/DeviceInfo;I)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj, state);
}
static OniCallbackHandle callbackHandle = 0;
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniInitialize
(JNIEnv *env, jclass)
{
int status = oniInitialize(ONI_API_VERSION);
if (status == ONI_STATUS_OK)
{
OniDeviceCallbacks callbacks;
callbacks.deviceConnected = deviceConnectedCallback;
callbacks.deviceDisconnected = deviceDisconnectedCallback;
callbacks.deviceStateChanged = deviceStateChangedCallback;
status = oniRegisterDeviceCallbacks(&callbacks, env, &callbackHandle);
}
return status;
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniShutdown
(JNIEnv *, jclass)
{
if (callbackHandle != 0)
oniUnregisterDeviceCallbacks(callbackHandle);
return oniShutdown();
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniGetVersion
(JNIEnv *env , jclass)
{
OniVersion version = oniGetVersion();
jclass versionCls = env->FindClass("org/openni/Version");
return (*env).NewObject(versionCls, (*env).GetMethodID(versionCls, "<init>", "(IIII)V"),
version.major, version.minor, version.maintenance, version.build);
}
JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetExtendedError
(JNIEnv *env , jclass)
{
return env->NewStringUTF(oniGetExtendedError());
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniGetDeviceList
(JNIEnv *env, jclass, jobject deviceListObj)
{
OniDeviceInfo* m_pDeviceInfos;
int m_deviceInfoCount;
jint status = oniGetDeviceList(&m_pDeviceInfos, &m_deviceInfoCount);
if (status == 0)
{
for (int i = 0; i < m_deviceInfoCount; i++)
{
jobject nameObj = env->NewStringUTF(m_pDeviceInfos[i].name);
jobject uriObj = env->NewStringUTF(m_pDeviceInfos[i].uri);
jobject vendorObj = env->NewStringUTF(m_pDeviceInfos[i].vendor);
jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo");
jobject deviceInfObj = (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, m_pDeviceInfos[i].usbVendorId, m_pDeviceInfos[i].usbProductId);
jclass vectorCls = (*env).FindClass("java/util/List");
jmethodID methodId = (*env).GetMethodID(vectorCls, "add", "(Ljava/lang/Object;)Z");
(*env).CallBooleanMethod(deviceListObj, methodId, deviceInfObj);
}
}
return status;
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniWaitForAnyStream
(JNIEnv *env, jclass, jlongArray streamsArray, jobject outArgObj, jint timeout)
{
jlong *streams = env->GetLongArrayElements(streamsArray, JNI_FALSE);
int size = env->GetArrayLength(streamsArray);
int id = 0;
int rc = oniWaitForAnyStream((OniStreamHandle*)streams, size, &id, timeout);
env->ReleaseLongArrayElements(streamsArray, streams, JNI_ABORT);
SetOutArgIntValue(env, outArgObj, id);
return rc == ONI_STATUS_OK;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterWorldToDepth
(JNIEnv *env, jclass, jlong streamHandle, jfloat worldX, jfloat worldY, jfloat worldZ, jobject depthXOutArg, jobject depthYOutArg, jobject depthZOutArg)
{
float x,y,z;
int status = oniCoordinateConverterWorldToDepth((OniStreamHandle)streamHandle, worldX, worldY, worldZ, &x, &y, &z);
SetOutArgFloatValue(env, depthXOutArg, x);
SetOutArgFloatValue(env, depthYOutArg, y);
SetOutArgFloatValue(env, depthZOutArg, z);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToWorld
(JNIEnv *env, jclass, jlong streamHandle, jfloat depthX, jfloat depthY, jfloat depthZ, jobject colorXOutArg, jobject colorYOutArg, jobject colorZOutArg)
{
float x,y,z;
int status = oniCoordinateConverterDepthToWorld((OniStreamHandle)streamHandle, depthX, depthY, depthZ, &x, &y, &z);
SetOutArgFloatValue(env, colorXOutArg, x);
SetOutArgFloatValue(env, colorYOutArg, y);
SetOutArgFloatValue(env, colorZOutArg, z);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToColor
(JNIEnv *env, jclass, jlong depthHandle, jlong colorHandle, jint depthX, jint depthY, jshort depthZ, jobject colorXOutArg, jobject colorYOutArg)
{
int x,y;
int status = oniCoordinateConverterDepthToColor((OniStreamHandle)depthHandle, (OniStreamHandle)colorHandle, depthX, depthY, depthZ, &x, &y);
SetOutArgIntValue(env, colorXOutArg, x);
SetOutArgIntValue(env, colorYOutArg, y);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCreateRecorder
(JNIEnv *env, jclass, jstring filename, jobject recorder)
{
OniRecorderHandle handle;
jclass recorderCls = env->FindClass("org/openni/Recorder");
const char * str = env->GetStringUTFChars(filename, JNI_FALSE);
int status = oniCreateRecorder(str, &handle);
jfieldID fieldID = env->GetFieldID(recorderCls, "mRecorderHandle", "J");
env->SetLongField(recorder, fieldID, (long)handle);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Ljava_lang_String_2Lorg_openni_Device_2
(JNIEnv *env, jclass, jstring uriStrObj, jobject device)
{
OniDeviceHandle handle;
const char * str = env->GetStringUTFChars(uriStrObj, JNI_FALSE);
int status = oniDeviceOpen(str, &handle);
jclass deviceCls = env->FindClass("org/openni/Device");
jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J");
env->SetLongField(device, fieldID, (long)handle);
return status;
}
static const char* ANY_DEVICE = NULL;
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Lorg_openni_Device_2
(JNIEnv *env, jclass, jobject device)
{
OniDeviceHandle handle;
int status = oniDeviceOpen(ANY_DEVICE, &handle);
jclass deviceCls = env->FindClass("org/openni/Device");
jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J");
env->SetLongField(device, fieldID, (long)handle);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceClose
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceClose((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogOutputFolder
(JNIEnv * env, jclass, jstring path)
{
const char * str = env->GetStringUTFChars(path, JNI_FALSE);
return oniSetLogOutputFolder(str);
}
JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetLogFileName
(JNIEnv *env, jclass)
{
XnChar fileName[XN_FILE_MAX_PATH];
oniGetLogFileName(fileName, sizeof(fileName));
return env->NewStringUTF(fileName);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogMinSeverity
(JNIEnv *, jclass, jint minSeverity)
{
return oniSetLogMinSeverity(minSeverity);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogConsoleOutput
(JNIEnv *, jclass, jboolean enabled)
{
return oniSetLogConsoleOutput(enabled);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogFileOutput
(JNIEnv *, jclass, jboolean enabled)
{
return oniSetLogFileOutput(enabled);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogAndroidOutput
(JNIEnv *, jclass, jboolean enabled)
{
(void)(enabled);
#ifdef ANDROID
return oniSetLogAndroidOutput(enabled);
#else
return ONI_STATUS_NOT_SUPPORTED;
#endif
}
| 40.095125 | 169 | 0.742408 | BEIWG |
78866ed8a7475c7e6aa2a6c8548b3fef33f6718e | 10,643 | cc | C++ | chrome/browser/ui/webui/favicon_source.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/favicon_source.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/favicon_source.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/favicon_source.h"
#include <cmath>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/favicon/favicon_utils.h"
#include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h"
#include "chrome/browser/history/top_sites_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "components/favicon/core/history_ui_favicon_request_handler.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "components/history/core/browser/top_sites.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/constants.h"
#include "extensions/common/manifest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/native_theme/native_theme.h"
#include "ui/resources/grit/ui_resources.h"
#include "url/gurl.h"
namespace {
// web_contents->GetLastCommittedURL in general will not necessarily yield the
// original URL that started the request, but we're only interested in verifying
// if it was issued by a history page, for whom this is the case. If it is not
// possible to obtain the URL, we return the empty GURL.
GURL GetUnsafeRequestOrigin(const content::WebContents::Getter& wc_getter) {
content::WebContents* web_contents = wc_getter.Run();
return web_contents ? web_contents->GetLastCommittedURL() : GURL();
}
bool ParseHistoryUiOrigin(const GURL& url,
favicon::HistoryUiFaviconRequestOrigin* origin) {
GURL history_url(chrome::kChromeUIHistoryURL);
if (url == history_url) {
*origin = favicon::HistoryUiFaviconRequestOrigin::kHistory;
return true;
}
if (url == history_url.Resolve(chrome::kChromeUIHistorySyncedTabs)) {
*origin = favicon::HistoryUiFaviconRequestOrigin::kHistorySyncedTabs;
return true;
}
return false;
}
} // namespace
FaviconSource::FaviconSource(Profile* profile,
chrome::FaviconUrlFormat url_format)
: profile_(profile->GetOriginalProfile()), url_format_(url_format) {}
FaviconSource::~FaviconSource() {
}
std::string FaviconSource::GetSource() {
switch (url_format_) {
case chrome::FaviconUrlFormat::kFaviconLegacy:
return chrome::kChromeUIFaviconHost;
case chrome::FaviconUrlFormat::kFavicon2:
return chrome::kChromeUIFavicon2Host;
}
NOTREACHED();
return "";
}
void FaviconSource::StartDataRequest(
const GURL& url,
const content::WebContents::Getter& wc_getter,
content::URLDataSource::GotDataCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string path = content::URLDataSource::URLToRequestPath(url);
favicon::FaviconService* favicon_service =
FaviconServiceFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS);
if (!favicon_service) {
SendDefaultResponse(std::move(callback));
return;
}
chrome::ParsedFaviconPath parsed;
bool success = chrome::ParseFaviconPath(path, url_format_, &parsed);
if (!success) {
SendDefaultResponse(std::move(callback));
return;
}
GURL page_url(parsed.page_url);
GURL icon_url(parsed.icon_url);
if (!page_url.is_valid() && !icon_url.is_valid()) {
SendDefaultResponse(std::move(callback));
return;
}
if (url_format_ == chrome::FaviconUrlFormat::kFaviconLegacy) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile_)
->enabled_extensions()
.GetExtensionOrAppByURL(GetUnsafeRequestOrigin(wc_getter));
if (extension) {
base::UmaHistogramEnumeration("Extensions.FaviconResourceRequested",
extension->GetType(),
extensions::Manifest::NUM_LOAD_TYPES);
}
}
int desired_size_in_pixel =
std::ceil(parsed.size_in_dip * parsed.device_scale_factor);
if (parsed.page_url.empty()) {
// Request by icon url.
// TODO(michaelbai): Change GetRawFavicon to support combination of
// IconType.
favicon_service->GetRawFavicon(
icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel,
base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
base::Unretained(this), std::move(callback), parsed),
&cancelable_task_tracker_);
} else {
// Intercept requests for prepopulated pages if TopSites exists.
scoped_refptr<history::TopSites> top_sites =
TopSitesFactory::GetForProfile(profile_);
if (top_sites) {
for (const auto& prepopulated_page : top_sites->GetPrepopulatedPages()) {
if (page_url == prepopulated_page.most_visited.url) {
ui::ScaleFactor resource_scale_factor =
ui::GetSupportedScaleFactor(parsed.device_scale_factor);
std::move(callback).Run(
ui::ResourceBundle::GetSharedInstance()
.LoadDataResourceBytesForScale(prepopulated_page.favicon_id,
resource_scale_factor));
return;
}
}
}
favicon::HistoryUiFaviconRequestOrigin parsed_history_ui_origin;
if (!parsed.allow_favicon_server_fallback ||
!ParseHistoryUiOrigin(GetUnsafeRequestOrigin(wc_getter),
&parsed_history_ui_origin)) {
// Request from local storage only.
// TODO(victorvianna): Expose fallback_to_host in FaviconRequestHandler
// API and move the explanatory comment for |fallback_to_host| here.
const bool fallback_to_host = true;
favicon_service->GetRawFaviconForPageURL(
page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel,
fallback_to_host,
base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
base::Unretained(this), std::move(callback), parsed),
&cancelable_task_tracker_);
return;
}
// Request from both local storage and favicon server using
// HistoryUiFaviconRequestHandler.
favicon::HistoryUiFaviconRequestHandler*
history_ui_favicon_request_handler =
HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext(
profile_);
if (!history_ui_favicon_request_handler) {
SendDefaultResponse(std::move(callback), parsed);
return;
}
history_ui_favicon_request_handler->GetRawFaviconForPageURL(
page_url, desired_size_in_pixel,
base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
weak_ptr_factory_.GetWeakPtr(), std::move(callback),
parsed),
parsed_history_ui_origin);
}
}
std::string FaviconSource::GetMimeType(const std::string&) {
// We need to explicitly return a mime type, otherwise if the user tries to
// drag the image they get no extension.
return "image/png";
}
bool FaviconSource::AllowCaching() {
return false;
}
bool FaviconSource::ShouldReplaceExistingSource() {
// Leave the existing DataSource in place, otherwise we'll drop any pending
// requests on the floor.
return false;
}
bool FaviconSource::ShouldServiceRequest(
const GURL& url,
content::BrowserContext* browser_context,
int render_process_id) {
if (url.SchemeIs(chrome::kChromeSearchScheme)) {
return InstantService::ShouldServiceRequest(url, browser_context,
render_process_id);
}
return URLDataSource::ShouldServiceRequest(url, browser_context,
render_process_id);
}
ui::NativeTheme* FaviconSource::GetNativeTheme() {
return ui::NativeTheme::GetInstanceForNativeUi();
}
void FaviconSource::OnFaviconDataAvailable(
content::URLDataSource::GotDataCallback callback,
const chrome::ParsedFaviconPath& parsed,
const favicon_base::FaviconRawBitmapResult& bitmap_result) {
if (bitmap_result.is_valid()) {
// Forward the data along to the networking system.
std::move(callback).Run(bitmap_result.bitmap_data.get());
} else {
SendDefaultResponse(std::move(callback), parsed);
}
}
void FaviconSource::SendDefaultResponse(
content::URLDataSource::GotDataCallback callback,
const chrome::ParsedFaviconPath& parsed) {
if (!parsed.show_fallback_monogram) {
SendDefaultResponse(std::move(callback), parsed.size_in_dip,
parsed.device_scale_factor);
return;
}
int icon_size = std::ceil(parsed.size_in_dip * parsed.device_scale_factor);
SkBitmap bitmap = favicon::GenerateMonogramFavicon(GURL(parsed.page_url),
icon_size, icon_size);
std::vector<unsigned char> bitmap_data;
bool result = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_data);
DCHECK(result);
std::move(callback).Run(base::RefCountedBytes::TakeVector(&bitmap_data));
}
void FaviconSource::SendDefaultResponse(
content::URLDataSource::GotDataCallback callback) {
SendDefaultResponse(std::move(callback), 16, 1.0f);
}
void FaviconSource::SendDefaultResponse(
content::URLDataSource::GotDataCallback callback,
int size_in_dip,
float scale_factor) {
const bool dark = GetNativeTheme()->ShouldUseDarkColors();
int resource_id;
switch (size_in_dip) {
case 64:
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK_64 : IDR_DEFAULT_FAVICON_64;
break;
case 32:
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK_32 : IDR_DEFAULT_FAVICON_32;
break;
default:
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK : IDR_DEFAULT_FAVICON;
break;
}
std::move(callback).Run(LoadIconBytes(scale_factor, resource_id));
}
base::RefCountedMemory* FaviconSource::LoadIconBytes(float scale_factor,
int resource_id) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
resource_id, ui::GetSupportedScaleFactor(scale_factor));
}
| 37.875445 | 80 | 0.705628 | mghgroup |
788827b84d5761fad86b03e6121a2df93ead4f74 | 1,557 | hh | C++ | src/event_manager.hh | nojhan/kakoune | c8156429c4685189e0a6b7bd0f273dc64432db2c | [
"Unlicense"
] | null | null | null | src/event_manager.hh | nojhan/kakoune | c8156429c4685189e0a6b7bd0f273dc64432db2c | [
"Unlicense"
] | null | null | null | src/event_manager.hh | nojhan/kakoune | c8156429c4685189e0a6b7bd0f273dc64432db2c | [
"Unlicense"
] | null | null | null | #ifndef event_manager_hh_INCLUDED
#define event_manager_hh_INCLUDED
#include "utils.hh"
#include <chrono>
#include <unordered_set>
namespace Kakoune
{
class FDWatcher
{
public:
using Callback = std::function<void (FDWatcher& watcher)>;
FDWatcher(int fd, Callback callback);
~FDWatcher();
int fd() const { return m_fd; }
void run() { m_callback(*this); }
private:
int m_fd;
Callback m_callback;
};
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
class Timer
{
public:
using Callback = std::function<void (Timer& timer)>;
Timer(TimePoint date, Callback callback);
~Timer();
TimePoint next_date() const { return m_date; }
void set_next_date(TimePoint date) { m_date = date; }
void run();
private:
TimePoint m_date;
Callback m_callback;
};
// The EventManager provides an interface to file descriptor
// based event handling.
//
// The program main loop should call handle_next_events()
// until it's time to quit.
class EventManager : public Singleton<EventManager>
{
public:
EventManager();
~EventManager();
void handle_next_events();
// force the watchers associated with fd to be executed
// on next handle_next_events call.
void force_signal(int fd);
private:
friend class FDWatcher;
friend class Timer;
std::unordered_set<FDWatcher*> m_fd_watchers;
std::unordered_set<Timer*> m_timers;
std::vector<int> m_forced_fd;
TimePoint m_last;
};
}
#endif // event_manager_hh_INCLUDED
| 20.220779 | 62 | 0.69043 | nojhan |
7889266f1d23a3fe1cdc18e00d83eeb3a99b25b0 | 1,321 | cpp | C++ | firmware/common/Motor/L298Motors.cpp | romainreignier/robot2017 | 8d36689573a35d3f58184fecc5c3b17d8718f71a | [
"Apache-2.0"
] | 1 | 2019-04-01T12:17:26.000Z | 2019-04-01T12:17:26.000Z | firmware/common/Motor/L298Motors.cpp | romainreignier/robot2017 | 8d36689573a35d3f58184fecc5c3b17d8718f71a | [
"Apache-2.0"
] | null | null | null | firmware/common/Motor/L298Motors.cpp | romainreignier/robot2017 | 8d36689573a35d3f58184fecc5c3b17d8718f71a | [
"Apache-2.0"
] | null | null | null | #include "L298Motors.h"
L298Motors::L298Motors(L298& _leftMotor, L298& _rightMotor)
: Motors{_leftMotor, _rightMotor}
{
}
void L298Motors::begin()
{
// Only implement the 2 motors using the same PWM driver (timer)
L298 &leftMotor = static_cast<L298&>(m_leftMotor);
L298 &rightMotor = static_cast<L298&>(m_rightMotor);
// Only use the left config for both motors
m_leftPwmConfig.frequency = m_leftMotor.m_timerFrequency;
m_leftPwmConfig.period = m_leftMotor.m_timerPeriod;
m_leftPwmConfig.callback = NULL; // no pwm callback
m_leftPwmConfig.channels[leftMotor.m_channelA].mode =
(leftMotor.m_isAComplementaryChannel
? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH
: PWM_OUTPUT_ACTIVE_HIGH);
m_leftPwmConfig.channels[leftMotor.m_channelB].mode =
(leftMotor.m_isBComplementaryChannel
? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH
: PWM_OUTPUT_ACTIVE_HIGH);
m_leftPwmConfig.channels[rightMotor.m_channelA].mode =
(rightMotor.m_isAComplementaryChannel
? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH
: PWM_OUTPUT_ACTIVE_HIGH);
m_leftPwmConfig.channels[rightMotor.m_channelB].mode =
(rightMotor.m_isBComplementaryChannel
? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH
: PWM_OUTPUT_ACTIVE_HIGH);
pwmStart(m_leftMotor.m_driver, &m_leftPwmConfig);
stop();
}
| 33.871795 | 66 | 0.766843 | romainreignier |
78895d9f05d60511d555be5cfd10e4501ee3d249 | 1,460 | cpp | C++ | src/logic/axi4/stream/reset_sequence.cpp | trosenkranz/logic | 8bcb5ecbc2df08f32215053b34ddb2bf220f41aa | [
"Apache-2.0"
] | 209 | 2017-11-22T14:52:15.000Z | 2022-03-23T21:44:58.000Z | src/logic/axi4/stream/reset_sequence.cpp | trosenkranz/logic | 8bcb5ecbc2df08f32215053b34ddb2bf220f41aa | [
"Apache-2.0"
] | 2 | 2018-02-26T09:02:15.000Z | 2020-01-14T10:19:59.000Z | src/logic/axi4/stream/reset_sequence.cpp | trosenkranz/logic | 8bcb5ecbc2df08f32215053b34ddb2bf220f41aa | [
"Apache-2.0"
] | 53 | 2018-01-24T07:11:26.000Z | 2022-03-02T02:14:30.000Z | /* Copyright 2018 Tymoteusz Blazejczyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "logic/axi4/stream/reset_sequence.hpp"
using logic::axi4::stream::reset_sequence;
reset_sequence::reset_sequence() :
reset_sequence{"reset_sequence"}
{ }
reset_sequence::reset_sequence(const std::string& name) :
uvm::uvm_sequence<reset_sequence_item>{name},
items{}
{ }
reset_sequence::~reset_sequence() = default;
void reset_sequence::pre_body() {
if (starting_phase != nullptr) {
starting_phase->raise_objection(this);
}
}
void reset_sequence::body() {
UVM_INFO(get_name(), "Starting reset sequence", uvm::UVM_FULL);
for (auto& item : items) {
start_item(&item);
finish_item(&item);
}
UVM_INFO(get_name(), "Finishing reset sequence", uvm::UVM_FULL);
}
void reset_sequence::post_body() {
if (starting_phase != nullptr) {
starting_phase->drop_objection(this);
}
}
| 27.54717 | 75 | 0.704795 | trosenkranz |
788cacd411264e16f9c014d4c2a25d7da96a29e3 | 1,399 | cpp | C++ | lib/inputdev/NintendoPowerA.cpp | henriquegemignani/boo | 403291c191452139ca292f1d6c6067b893b8d8b0 | [
"MIT"
] | 7 | 2016-04-16T04:37:59.000Z | 2022-02-01T12:39:04.000Z | lib/inputdev/NintendoPowerA.cpp | henriquegemignani/boo | 403291c191452139ca292f1d6c6067b893b8d8b0 | [
"MIT"
] | 8 | 2016-07-13T03:20:04.000Z | 2021-06-30T05:07:10.000Z | lib/inputdev/NintendoPowerA.cpp | henriquegemignani/boo | 403291c191452139ca292f1d6c6067b893b8d8b0 | [
"MIT"
] | 11 | 2016-04-16T04:40:46.000Z | 2022-02-06T04:23:17.000Z | #include "boo/inputdev/NintendoPowerA.hpp"
#include <array>
#include <cstring>
#include "boo/inputdev/DeviceSignature.hpp"
namespace boo {
NintendoPowerA::NintendoPowerA(DeviceToken* token)
: TDeviceBase<INintendoPowerACallback>(dev_typeid(NintendoPowerA), token) {}
NintendoPowerA::~NintendoPowerA() = default;
void NintendoPowerA::deviceDisconnected() {
std::lock_guard lk{m_callbackLock};
if (m_callback != nullptr) {
m_callback->controllerDisconnected();
}
}
void NintendoPowerA::initialCycle() {}
void NintendoPowerA::transferCycle() {
std::array<uint8_t, 8> payload;
const size_t recvSz = receiveUSBInterruptTransfer(payload.data(), payload.size());
if (recvSz != payload.size()) {
return;
}
NintendoPowerAState state;
std::memcpy(&state, payload.data(), sizeof(state));
std::lock_guard lk{m_callbackLock};
if (state != m_last && m_callback != nullptr) {
m_callback->controllerUpdate(state);
}
m_last = state;
}
void NintendoPowerA::finalCycle() {}
void NintendoPowerA::receivedHIDReport(const uint8_t* data, size_t length, HIDReportType tp, uint32_t message) {}
bool NintendoPowerAState::operator==(const NintendoPowerAState& other) const {
return std::memcmp(this, &other, sizeof(NintendoPowerAState)) == 0;
}
bool NintendoPowerAState::operator!=(const NintendoPowerAState& other) const { return !operator==(other); }
} // namespace boo
| 27.431373 | 113 | 0.739814 | henriquegemignani |
78926939b2197b4e9886bdd949e2f89077f2d58e | 3,023 | hpp | C++ | libs/mockturtle/io/write_dimacs.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 96 | 2019-12-11T10:18:10.000Z | 2022-03-27T20:16:33.000Z | libs/mockturtle/io/write_dimacs.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 43 | 2020-01-08T00:59:07.000Z | 2022-03-28T21:35:59.000Z | libs/mockturtle/io/write_dimacs.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 21 | 2019-12-15T01:40:48.000Z | 2021-12-31T05:27:34.000Z | /* mockturtle: C++ logic network library
* Copyright (C) 2018-2019 EPFL EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file write_dimacs.hpp
\brief Write networks CNF encoding to DIMACS format
\author Mathias Soeken
*/
#pragma once
#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <fmt/format.h>
#include "../traits.hpp"
#include "../algorithms/cnf.hpp"
namespace mockturtle {
/*! \brief Writes network into CNF DIMACS format
*
* It also adds unit clauses for the outputs. Therefore a satisfying solution
* is one that makes all outputs 1.
*
* \param ntk Logic network
* \param out Output stream
*/
template <class Ntk>
void write_dimacs(Ntk const& ntk, std::ostream& out = std::cout) {
std::stringstream clauses;
uint32_t num_clauses = 0u;
const auto lits =
generate_cnf(ntk, [&](std::vector<uint32_t> const& clause) {
for (auto lit : clause) {
const auto var = (lit / 2) + 1;
const auto pol = lit % 2;
clauses << fmt::format("{}{} ", pol ? "-" : "", var);
}
clauses << fmt::format("0\n");
++num_clauses;
});
for (auto lit : lits) {
const auto var = (lit / 2) + 1;
const auto pol = lit % 2;
clauses << fmt::format("{}{} 0\n", pol ? "-" : "", var);
++num_clauses;
}
out << fmt::format("p cnf {} {}\n{}", ntk.size(), num_clauses,
clauses.str());
}
/*! \brief Writes network into CNF DIMACS format
*
* It also adds unit clauses for the outputs. Therefore a satisfying solution
* is one that makes all outputs 1.
*
* \param ntk Logic network
* \param filename Filename
*/
template <class Ntk>
void write_dimacs(Ntk const& ntk, std::string const& filename) {
std::ofstream os(filename.c_str(), std::ofstream::out);
write_dimacs(ntk, os);
os.close();
}
} /* namespace mockturtle */
| 30.535354 | 78 | 0.656302 | wjyoumans |
78939ce1945f307b29f0c9dd3dbcc2e0c3649e78 | 1,347 | cpp | C++ | src/context.cpp | programmerjake/my-compiler | fa70f13e059b44674042cedf1bbf2d9b01132793 | [
"Zlib"
] | 7 | 2017-11-19T02:42:30.000Z | 2022-02-13T08:48:31.000Z | src/context.cpp | programmerjake/my-compiler | fa70f13e059b44674042cedf1bbf2d9b01132793 | [
"Zlib"
] | null | null | null | src/context.cpp | programmerjake/my-compiler | fa70f13e059b44674042cedf1bbf2d9b01132793 | [
"Zlib"
] | null | null | null | /* Copyright (c) 2015 Jacob R. Lifshay
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "context.h"
#include "types/type.h"
std::shared_ptr<TypeNode> CompilerContext::constructTypeNodeHelper(std::shared_ptr<TypeNode> retval)
{
std::size_t theHash = retval->getHash();
auto range = types.equal_range(theHash);
for(auto i = range.first; i != range.second; ++i)
{
if(*retval == *std::get<1>(*i))
return std::get<1>(*i);
}
types.emplace(theHash, retval);
return retval;
}
| 38.485714 | 100 | 0.710468 | programmerjake |
7895788e070824a3bf9fe1b3145af9859d2209a9 | 2,351 | hpp | C++ | include/cobalt/platform.hpp | mzhirnov/cool | 9c360ca8bfc127dffae6264675d9973fd2c6fd6d | [
"MIT"
] | 2 | 2020-03-23T19:12:14.000Z | 2020-08-03T13:29:38.000Z | include/cobalt/platform.hpp | mzhirnov/cool | 9c360ca8bfc127dffae6264675d9973fd2c6fd6d | [
"MIT"
] | null | null | null | include/cobalt/platform.hpp | mzhirnov/cool | 9c360ca8bfc127dffae6264675d9973fd2c6fd6d | [
"MIT"
] | null | null | null | #ifndef COBALT_PLATFORM_HPP_INCLUDED
#define COBALT_PLATFORM_HPP_INCLUDED
#pragma once
#include <boost/predef.h>
#define $on(...) __VA_ARGS__
#define $off(...)
////////////////////////////////////////////////////////////////////////////////
// Windows
#if BOOST_OS_WINDOWS
#include <winapifamily.h>
#define $windows $on
#if defined(WINAPI_FAMILY) && WINAPI_FAMILY == WINAPI_PARTITION_APP
#define $windows_app $on
#endif
#endif // BOOST_OS_WINDOWS
#ifdef $windows
#define $not_windows $off
#else
#define $windows $off
#define $not_windows $on
#endif // $windows
#ifdef $windows_app
#define $not_windows_app $off
#else
#define $windows_app $off
#define $not_windows_app $on
#endif // $windows_app
////////////////////////////////////////////////////////////////////////////////
// iOS
#if BOOST_OS_IOS
#include <TargetConditionals.h>
#define $ios $on
#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
#define $ios_simulator $on
#endif
#endif // BOOST_OS_IOS
#ifdef $ios
#define $not_ios $off
#else
#define $ios $off
#define $not_ios $on
#endif // $ios
#ifdef $ios_simulator
#define $not_ios_simulator $off
#else
#define $ios_simulator $off
#define $not_ios_simulator $on
#endif // $ios_simulator
////////////////////////////////////////////////////////////////////////////////
// macOS
#if BOOST_OS_MACOS
#define $macos $on
#endif // BOOST_OS_MACOS
#ifdef $macos
#define $not_macos $off
#else
#define $macos $off
#define $not_macos $on
#endif // $macos
////////////////////////////////////////////////////////////////////////////////
// Android
#if BOOST_OS_ANDROID
#define $android $on
#endif // BOOST_OS_ANDROID
#ifdef $android
#define $not_android $off
#else
#define $android $off
#define $not_android $on
#endif // $android
////////////////////////////////////////////////////////////////////////////////
// Linux
#if BOOST_OS_LINUX
#define $linux $on
#endif // BOOST_OS_LINUX
#ifdef $linux
#define $not_linux $off
#else
#define $linux $off
#define $not_linux $on
#endif // $linux
////////////////////////////////////////////////////////////////////////////////
// Desktop | Mobile
#if BOOST_OS_WINDOWS || BOOST_OS_MACOS || BOOST_OS_LINUX
#define $desktop $on
#endif //
#ifdef $desktop
#define $mobile $off
#else
#define $desktop $off
#define $mobile $on
#endif // $linux
#endif // COBALT_PLATFORM_HPP_INCLUDED
| 19.923729 | 80 | 0.586134 | mzhirnov |
78973096181449d12b341ef6923aba48905b0248 | 42,528 | cxx | C++ | Utilities/Cosmo/CosmoHaloFinderP.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | 2 | 2015-07-11T13:30:23.000Z | 2017-12-19T05:23:38.000Z | Utilities/Cosmo/CosmoHaloFinderP.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/Cosmo/CosmoHaloFinderP.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Copyright (c) 2007, Los Alamos National Security, LLC
All rights reserved.
Copyright 2007. Los Alamos National Security, LLC.
This software was produced under U.S. Government contract DE-AC52-06NA25396
for Los Alamos National Laboratory (LANL), which is operated by
Los Alamos National Security, LLC for the U.S. Department of Energy.
The U.S. Government has rights to use, reproduce, and distribute this software.
NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
If software is modified to produce derivative works, such modified software
should be clearly marked, so as not to confuse it with the version available
from LANL.
Additionally, redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Los Alamos National Security, LLC, Los Alamos National
Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <set>
#include <math.h>
#include "Partition.h"
#include "CosmoHaloFinderP.h"
using namespace std;
/////////////////////////////////////////////////////////////////////////
//
// Parallel manager for serial CosmoHaloFinder
// Particle data space is partitioned for the number of processors
// which currently is a factor of two but is easily extended. Particles
// are read in from files where each processor reads one file into a buffer,
// extracts the particles which really belong on the processor (ALIVE) and
// those in a buffer region around the edge (DEAD). The buffer is then
// passed round robin to every other processor so that all particles are
// examined by all processors. All dead particles are tagged with the
// neighbor zone (26 neighbors in 3D) so that later halos can be associated
// with zones.
//
// The serial halo finder is called on each processor and returns enough
// information so that it can be determined if a halo is completely ALIVE,
// completely DEAD, or mixed. A mixed halo that is shared between on two
// processors is kept by the processor that contains it in one of its
// high plane neighbors, and is given up if contained in a low plane neighbor.
//
// Mixed halos that cross more than two processors are bundled up and sent
// to the MASTER processor which decides the processor that should own it.
//
/////////////////////////////////////////////////////////////////////////
CosmoHaloFinderP::CosmoHaloFinderP() : haloData(NULL), haloList(NULL), haloStart(NULL), haloSize(NULL)
{
// Get the number of processors and rank of this processor
this->numProc = Partition::getNumProc();
this->myProc = Partition::getMyProc();
// Get the number of processors in each dimension
Partition::getDecompSize(this->layoutSize);
// Get my position within the Cartesian topology
Partition::getMyPosition(this->layoutPos);
// Get the neighbors of this processor
Partition::getNeighbors(this->neighbor);
// For each neighbor zone, how many dead particles does it contain to start
// and how many dead halos does it contain after the serial halo finder
// For analysis but not necessary to run the code
//
for (int n = 0; n < NUM_OF_NEIGHBORS; n++) {
this->deadParticle[n] = 0;
this->deadHalo[n] = 0;
}
}
CosmoHaloFinderP::~CosmoHaloFinderP()
{
for (unsigned int i = 0; i < this->myMixedHalos.size(); i++)
delete this->myMixedHalos[i];
if(this->haloList)
{
delete [] this->haloList;
}
if(this->haloStart)
{
delete [] this->haloStart;
}
if(this->haloSize)
{
delete [] this->haloSize;
}
if(this->haloData)
{
for (int dim = 0; dim < DIMENSION; dim++)
delete this->haloData[dim];
delete [] this->haloData;
}
}
/////////////////////////////////////////////////////////////////////////
//
// Set parameters for the serial halo finder
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::setParameters(
const string& outName,
POSVEL_T _rL,
POSVEL_T _deadSz,
long _np,
int _pmin,
POSVEL_T _bb)
{
// Particles for this processor output to file
ostringstream oname, hname;
if (this->numProc == 1) {
oname << outName;
hname << outName;
} else {
oname << outName << "." << myProc;
hname << outName << ".halo." << myProc;
}
this->outFile = oname.str();
this->outHaloFile = hname.str();
// Halo finder parameters
this->np = _np;
this->pmin = _pmin;
this->bb = _bb;
this->boxSize = _rL;
this->deadSize = _deadSz;
// First version of this code distributed the dead particles on a processor
// by taking the x,y,z position and adding or subtracting boxSize in all
// combinations. This revised x,y,z was then normalized and added to the
// haloData array which was passed to each serial halo finder.
// This did not get the same answer as the standalone serial version which
// read the x,y,z and normalized without adding or subtracting boxSize first.
// Then when comparing distance the normalized "np" was used for subtraction.
// By doing things in this order some particles were placed slightly off,
// which was enough for particles to be included in halos where they should
// not have been. In this first version, since I had placed particles by
// subtracting first, I made "periodic" false figuring all particles were
// placed where they should go.
//
// In the second version I normalize the dead particles, even from wraparound,
// using the actual x,y,z. So when looking at a processor the alive particles
// will appear all together and the wraparound will properly be on the other
// side of the box. Combined with doing this is setting "periodic" to true
// so that the serial halo finder works as it does in the standalone case
// and the normalization and subtraction from np happens in the same order.
//
// Third version went back to the first version because we need
// contiguous locations coming out of the halo finder for the center finder
this->haloFinder.np = _np;
this->haloFinder.pmin = _pmin;
this->haloFinder.bb = _bb;
this->haloFinder.rL = _rL;
this->haloFinder.periodic = false;
this->haloFinder.textmode = "ascii";
// Serial halo finder wants normalized locations on a grid superimposed
// on the physical rL grid. Grid size is np and number of particles in
// the problem is np^3
this->normalizeFactor = (POSVEL_T)((1.0 * _np) / _rL);
#ifndef USE_VTK_COSMO
if (this->myProc == MASTER) {
cout << endl << "------------------------------------" << endl;
cout << "np: " << this->np << endl;
cout << "bb: " << this->bb << endl;
cout << "pmin: " << this->pmin << endl << endl;
}
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// Set the particle vectors that have already been read and which
// contain only the alive particles for this processor
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::setParticles(
vector<POSVEL_T>* xLoc,
vector<POSVEL_T>* yLoc,
vector<POSVEL_T>* zLoc,
vector<POSVEL_T>* xVel,
vector<POSVEL_T>* yVel,
vector<POSVEL_T>* zVel,
vector<POTENTIAL_T>* potential,
vector<ID_T>* id,
vector<MASK_T>* maskData,
vector<STATUS_T>* state)
{
this->particleCount = (long)xLoc->size();
// Extract the contiguous data block from a vector pointer
this->xx = &(*xLoc)[0];
this->yy = &(*yLoc)[0];
this->zz = &(*zLoc)[0];
this->vx = &(*xVel)[0];
this->vy = &(*yVel)[0];
this->vz = &(*zVel)[0];
this->pot = &(*potential)[0];
this->tag = &(*id)[0];
this->mask = &(*maskData)[0];
this->status = &(*state)[0];
}
/////////////////////////////////////////////////////////////////////////
//
// Execute the serial halo finder on the particles for this processor
// Both ALIVE and DEAD particles we collected and normalized into
// haloData which is in the form that the serial halo finder wants
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::executeHaloFinder()
{
// Allocate data pointer which is sent to the serial halo finder
this->haloData = new POSVEL_T*[DIMENSION];
for (int dim = 0; dim < DIMENSION; dim++)
this->haloData[dim] = new POSVEL_T[this->particleCount];
// Fill it with normalized x,y,z of all particles on this processor
for (int p = 0; p < this->particleCount; p++) {
this->haloData[0][p] = this->xx[p] * this->normalizeFactor;
this->haloData[1][p] = this->yy[p] * this->normalizeFactor;
this->haloData[2][p] = this->zz[p] * this->normalizeFactor;
}
this->haloFinder.setParticleLocations(haloData);
this->haloFinder.setNumberOfParticles(this->particleCount);
this->haloFinder.setMyProc(this->myProc);
this->haloFinder.setOutFile(this->outFile);
#ifndef USE_VTK_COSMO
cout << "Rank " << setw(3) << this->myProc
<< " RUNNING SERIAL HALO FINDER on "
<< particleCount << " particles" << endl;
#endif
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
if (this->particleCount > 0)
this->haloFinder.Finding();
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// At this point each serial halo finder ran and
// the particles handed to it included alive and dead. Get back the
// halo tag array and figure out the indices of the particles in each halo
// and translate that into absolute particle tags and note alive or dead
//
// After the serial halo finder has run the halo tag is the INDEX of the
// lowest particle in the halo on this processor. It is not the absolute
// particle tag id over the entire problem.
//
// Serial partindex i = 0 haloTag = 0 haloSize = 1
// Serial partindex i = 1 haloTag = 1 haloSize = 1
// Serial partindex i = 2 haloTag = 2 haloSize = 1
// Serial partindex i = 3 haloTag = 3 haloSize = 1
// Serial partindex i = 4 haloTag = 4 haloSize = 2
// Serial partindex i = 5 haloTag = 5 haloSize = 1
// Serial partindex i = 6 haloTag = 6 haloSize = 1616
// Serial partindex i = 7 haloTag = 7 haloSize = 1
// Serial partindex i = 8 haloTag = 8 haloSize = 2
// Serial partindex i = 9 haloTag = 9 haloSize = 1738
// Serial partindex i = 10 haloTag = 10 haloSize = 4
// Serial partindex i = 11 haloTag = 11 haloSize = 1
// Serial partindex i = 12 haloTag = 12 haloSize = 78
// Serial partindex i = 13 haloTag = 12 haloSize = 0
// Serial partindex i = 14 haloTag = 12 haloSize = 0
// Serial partindex i = 15 haloTag = 12 haloSize = 0
// Serial partindex i = 16 haloTag = 16 haloSize = 2
// Serial partindex i = 17 haloTag = 17 haloSize = 1
// Serial partindex i = 18 haloTag = 6 haloSize = 0
// Serial partindex i = 19 haloTag = 6 haloSize = 0
// Serial partindex i = 20 haloTag = 6 haloSize = 0
// Serial partindex i = 21 haloTag = 6 haloSize = 0
//
// Halo of size 1616 has the low particle tag of 6 and other members are
// 18,19,20,21 indicated by a tag of 6 and haloSize of 0
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::collectHalos()
{
// Halo tag returned from the serial halo finder is actually the index
// of the particle on this processor. Must map to get to actual tag
// which is common information between all processors.
this->haloTag = haloFinder.getHaloTag();
// Record the halo size of each particle on this processor
this->haloSize = new int[this->particleCount];
this->haloAliveSize = new int[this->particleCount];
this->haloDeadSize = new int[this->particleCount];
// Create a list of particles in any halo by recording the index of the
// first particle and having that index give the index of the next particle
// Last particle index reports a -1
// List is built by iterating on the tags and storing in opposite order so
this->haloList = new int[this->particleCount];
this->haloStart = new int[this->particleCount];
for (int p = 0; p < this->particleCount; p++) {
this->haloList[p] = -1;
this->haloStart[p] = p;
this->haloSize[p] = 0;
this->haloAliveSize[p] = 0;
this->haloDeadSize[p] = 0;
}
// Build the chaining mesh of particles in all the halos and count particles
buildHaloStructure();
// Mixed halos are saved separately so that they can be merged
processMixedHalos();
delete [] this->haloAliveSize;
delete [] this->haloDeadSize;
}
/////////////////////////////////////////////////////////////////////////
//
// Examine every particle on this processor, both ALIVE and DEAD
// For that particle increment the count for the corresponding halo
// which is indicated by the lowest particle index in that halo
// Also build the haloList so that we can find all particles in any halo
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::buildHaloStructure()
{
// Build the chaining mesh so that all particles in a halo can be found
// This will include even small halos which will be excluded later
for (int p = 0; p < this->particleCount; p++) {
// Chain backwards the halo particles
// haloStart is the index of the last particle in a single halo in haloList
// The value found in haloList is the index of the next particle
if (this->haloTag[p] != p) {
this->haloList[p] = haloStart[this->haloTag[p]];
this->haloStart[this->haloTag[p]] = p;
}
// Count particles in the halos
if (this->status[p] == ALIVE)
this->haloAliveSize[this->haloTag[p]]++;
else
this->haloDeadSize[this->haloTag[p]]++;
this->haloSize[this->haloTag[p]]++;
}
// Iterate over particles and create a CosmoHalo for halos with size > pmin
// only for the mixed halos, not for those completely alive or dead
this->numberOfAliveHalos = 0;
this->numberOfDeadHalos = 0;
this->numberOfMixedHalos = 0;
// Only the first particle id for a halo records the size
// Succeeding particles which are members of a halo have a size of 0
// Record the start index of any legal halo which will allow the
// following of the chaining mesh to identify all particles in a halo
this->numberOfHaloParticles = 0;
for (ID_T p = 0; p < this->particleCount; p++) {
if (this->haloSize[p] >= this->pmin) {
if (this->haloAliveSize[p] > 0 && this->haloDeadSize[p] == 0) {
this->numberOfAliveHalos++;
this->numberOfHaloParticles += this->haloAliveSize[p];
// Save start of legal alive halo for halo properties
this->halos.push_back(this->haloStart[p]);
this->haloCount.push_back(this->haloAliveSize[p]);
}
else if (this->haloDeadSize[p] > 0 && this->haloAliveSize[p] == 0) {
this->numberOfDeadHalos++;
}
else {
this->numberOfMixedHalos++;
CosmoHalo* halo = new CosmoHalo(p,
this->haloAliveSize[p], this->haloDeadSize[p]);
this->myMixedHalos.push_back(halo);
}
}
}
#ifndef USE_VTK_COSMO
#ifdef DEBUG
cout << "Rank " << this->myProc
<< " #alive halos = " << this->numberOfAliveHalos
<< " #dead halos = " << this->numberOfDeadHalos
<< " #mixed halos = " << this->numberOfMixedHalos << endl;
#endif
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// Mixed halos (which cross several processors) have been collected
// By applying a high/low rule most mixed halos are assigned immediately
// to one processor or another. This requires extra processing so that
// it is known which neighbor processors share the halo.
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::processMixedHalos()
{
// Iterate over all particles and add tags to large mixed halos
for (ID_T p = 0; p < this->particleCount; p++) {
// All particles in the same halo have the same haloTag
if (this->haloSize[this->haloTag[p]] >= pmin &&
this->haloAliveSize[this->haloTag[p]] > 0 &&
this->haloDeadSize[this->haloTag[p]] > 0) {
// Check all each mixed halo to see which this particle belongs to
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
// If the tag of the particle matches the halo ID it belongs
if (this->haloTag[p] == this->myMixedHalos[h]->getHaloID()) {
// Add the index to that mixed halo. Also record which neighbor
// the dead particle is associated with for merging
this->myMixedHalos[h]->addParticle(
p, this->tag[p], this->status[p]);
// For debugging only
if (this->status[p] > 0)
this->deadHalo[this->status[p]]++;
// Do some bookkeeping for the final output
// This processor should output all ALIVE particles, unless they
// are in a mixed halo that ends up being INVALID
// This processor should output none of the DEAD particles,
// unless they are in a mixed halo that ends up being VALID
// So since this particle is in a mixed halo set it to MIXED
// which is going to be one less than ALIVE. Later when we
// determine we have a VALID mixed, we'll add one to the status
// for every particle turning all into ALIVE
// Now when we output we only do the ALIVE particles
this->status[p] = MIXED;
}
}
}
}
// Iterate over the mixed halos that were just created checking to see if
// the halo is on the "high" side of the 3D data space or not
// If it is on the high side and is shared with one other processor, keep it
// If it is on the low side and is shared with one other processor, delete it
// Any remaining halos are shared with more than two processors and must
// be merged by having the MASTER node decide
//
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
int lowCount = 0;
int highCount = 0;
set<int>* neighbors = this->myMixedHalos[h]->getNeighbors();
set<int>::iterator iter;
set<int> haloNeighbor;
for (iter = neighbors->begin(); iter != neighbors->end(); ++iter) {
if ((*iter) == X1 || (*iter) == Y1 || (*iter) == Z1 ||
(*iter) == X1_Y1 || (*iter) == Y1_Z1 || (*iter) == Z1_X1 ||
(*iter) == X1_Y1_Z1) {
highCount++;
} else {
lowCount++;
}
// Neighbor zones are on what actual processors
haloNeighbor.insert(this->neighbor[(*iter)]);
}
// Halo is kept by this processor and is marked as VALID
// May be in multiple neighbor zones, but all the same processor neighbor
if (highCount > 0 && lowCount == 0 && haloNeighbor.size() == 1) {
this->numberOfAliveHalos++;
this->numberOfMixedHalos--;
this->myMixedHalos[h]->setValid(VALID);
int id = this->myMixedHalos[h]->getHaloID();
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead before
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter2;
for (iter2 = particles->begin(); iter2 != particles->end(); ++iter2)
this->status[(*iter2)] = ALIVE;
}
// Halo will be kept by some other processor and is marked INVALID
// May be in multiple neighbor zones, but all the same processor neighbor
else if (highCount == 0 && lowCount > 0 && haloNeighbor.size() == 1) {
this->numberOfDeadHalos++;
this->numberOfMixedHalos--;
this->myMixedHalos[h]->setValid(INVALID);
}
// Remaining mixed halos must be examined by MASTER and stay UNMARKED
// Sort them on the tag field for easy comparison
else {
this->myMixedHalos[h]->setValid(UNMARKED);
this->myMixedHalos[h]->sortParticleTags();
}
}
// If only one processor is running there are no halos to merge
if (this->numProc == 1)
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++)
this->myMixedHalos[h]->setValid(INVALID);
}
/////////////////////////////////////////////////////////////////////////
//
// Using the MASTER node merge all mixed halos so that only one processor
// takes credit for them.
//
// Each processor containing mixed halos that are UNMARKED sends:
// Rank
// Number of mixed halos to merge
// for each halo
// id
// number of alive (for debugging)
// number of dead (for debugging)
// first MERGE_COUNT particle ids (for merging)
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::mergeHalos()
{
// What size integer buffer is needed to hold the largest halo data
int maxNumberOfMixed;
int numberOfMixed = (int)this->myMixedHalos.size();
#ifdef USE_SERIAL_COSMO
maxNumberOfMixed = numberOfMixed;
#else
MPI_Allreduce((void*) &numberOfMixed, (void*) &maxNumberOfMixed,
1, MPI_INT, MPI_MAX, Partition::getComm());
#endif
// If there are no halos to merge, return
if (maxNumberOfMixed == 0)
return;
// Everyone creates the buffer for maximum halos
// MASTER will receive into it, others will send from it
int haloBufSize = maxNumberOfMixed * MERGE_COUNT * 2;
ID_T* haloBuffer = new ID_T[haloBufSize];
// MASTER moves its own mixed halos to mixed halo vector (change index to tag)
// then gets messages from others and creates those mixed halos
collectMixedHalos(haloBuffer, haloBufSize);
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// MASTER has all data and runs algorithm to make decisions
assignMixedHalos();
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// MASTER sends merge results to all processors
sendMixedHaloResults(haloBuffer, haloBufSize);
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// Collect totals for result checking
int totalAliveHalos;
#ifdef USE_SERIAL_COSMO
totalAliveHalos = this->numberOfAliveHalos;
#else
MPI_Allreduce((void*) &this->numberOfAliveHalos, (void*) &totalAliveHalos,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
int totalAliveHaloParticles;
#ifdef USE_SERIAL_COSMO
totalAliveHaloParticles = this->numberOfHaloParticles;
#else
MPI_Allreduce((void*) &this->numberOfHaloParticles,
(void*) &totalAliveHaloParticles,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
#ifndef USE_VTK_COSMO
if (this->myProc == MASTER) {
cout << endl;
cout << "Total halos found: " << totalAliveHalos << endl;
cout << "Total halo particles: " << totalAliveHaloParticles << endl;
}
#endif
for (unsigned int i = 0; i < this->allMixedHalos.size(); i++)
delete this->allMixedHalos[i];
delete [] haloBuffer;
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER collects all mixed halos which are UNMARKED from all processors
// including its own mixed halos
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::collectMixedHalos
#ifdef USE_SERIAL_COSMO
(ID_T* , int )
#else
(ID_T* haloBuffer, int haloBufSize)
#endif
{
// How many processors have mixed halos
int haveMixedHalo = (this->numberOfMixedHalos > 0 ? 1 : 0);
int processorsWithMixedHalos;
#ifdef USE_SERIAL_COSMO
processorsWithMixedHalos = haveMixedHalo;
#else
MPI_Allreduce((void*) &haveMixedHalo, (void*) &processorsWithMixedHalos,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
// MASTER moves its own mixed halos to mixed halo vector (change index to tag)
// then gets messages from others and creates those mixed halos
#ifndef USE_SERIAL_COSMO
if (this->myProc == MASTER) {
#endif
// If MASTER has any mixed halos add them to the mixed halo vector
if (this->numberOfMixedHalos > 0) {
processorsWithMixedHalos--;
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getValid() == UNMARKED) {
CosmoHalo* halo = new CosmoHalo(
this->myMixedHalos[h]->getHaloID(),
this->myMixedHalos[h]->getAliveCount(),
this->myMixedHalos[h]->getDeadCount());
halo->setRankID(this->myProc);
this->allMixedHalos.push_back(halo);
// Translate index of particle to tag of particle
vector<ID_T>* tags = this->myMixedHalos[h]->getTags();
for (int i = 0; i < MERGE_COUNT; i++)
halo->addParticle((*tags)[i]);
}
}
}
#ifndef USE_SERIAL_COSMO
// Wait on messages from other processors and process
int notReceived = processorsWithMixedHalos;
MPI_Status mpistatus;
while (notReceived > 0) {
// Get message containing mixed halo information
#ifdef ID_64
MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MPI_ANY_SOURCE,
0, Partition::getComm(), &mpistatus);
#else
MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MPI_ANY_SOURCE,
0, Partition::getComm(), &mpistatus);
#endif
// Gather halo information from the message
int index = 0;
int rank = haloBuffer[index++];
int numMixed = haloBuffer[index++];
for (int m = 0; m < numMixed; m++) {
ID_T id = haloBuffer[index++];
int aliveCount = haloBuffer[index++];
int deadCount = haloBuffer[index++];
// Create the CosmoHalo to hold the data and add to vector
CosmoHalo* halo = new CosmoHalo(id, aliveCount, deadCount);
halo->setRankID(rank);
this->allMixedHalos.push_back(halo);
for (int t = 0; t < MERGE_COUNT; t++)
halo->addParticle(haloBuffer[index++]);
}
notReceived--;
}
#ifndef USE_VTK_COSMO
cout << "Number of halos to merge: " << this->allMixedHalos.size() << endl;
#endif
}
// Other processors bundle up mixed and send to MASTER
else {
int index = 0;
if (this->numberOfMixedHalos > 0) {
haloBuffer[index++] = this->myProc;
haloBuffer[index++] = this->numberOfMixedHalos;
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getValid() == UNMARKED) {
haloBuffer[index++] = this->myMixedHalos[h]->getHaloID();
haloBuffer[index++] = this->myMixedHalos[h]->getAliveCount();
haloBuffer[index++] = this->myMixedHalos[h]->getDeadCount();
vector<ID_T>* tags = this->myMixedHalos[h]->getTags();
for (int i = 0; i < MERGE_COUNT; i++) {
haloBuffer[index++] = (*tags)[i];
}
}
}
MPI_Request request;
#ifdef ID_64
MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, MASTER,
0, Partition::getComm(), &request);
#else
MPI_Isend(haloBuffer, haloBufSize, MPI_INT, MASTER,
0, Partition::getComm(), &request);
#endif
}
}
#endif // USE_SERIAL_COSMO
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER has collected all the mixed halos and decides which processors
// will get which by matching them up
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::assignMixedHalos()
{
// MASTER has all data and runs algorithm to make decisions
if (this->myProc == MASTER) {
#ifndef USE_VTK_COSMO
#ifdef DEBUG
for (int m = 0; m < this->allMixedHalos.size(); m++) {
vector<ID_T>* tags = this->allMixedHalos[m]->getTags();
cout << "Mixed Halo " << m << ": "
<< " rank=" << this->allMixedHalos[m]->getRankID()
<< " index=" << this->allMixedHalos[m]->getHaloID()
<< " tag=" << (*tags)[0]
<< " alive=" << this->allMixedHalos[m]->getAliveCount()
<< " dead=" << this->allMixedHalos[m]->getDeadCount() << endl;
}
#endif
#endif
// Iterate over mixed halo vector and match and mark
// Remember that I can have 3 or 4 that match
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
// If this halo has not already been paired with another
if (this->allMixedHalos[m]->getPartners()->empty() == true) {
// Current mixed halo has the most alive particles so far
int numberAlive = this->allMixedHalos[m]->getAliveCount();
int haloWithLeastAlive = m;
// Iterate on the rest of the mixed halos
unsigned int n = m + 1;
while (n < this->allMixedHalos.size()) {
// Compare to see if there are a number of tags in common
int match = compareHalos(this->allMixedHalos[m],
this->allMixedHalos[n]);
// Keep track of the mixed halo with the most alive particles
if (match > 0) {
if (numberAlive > this->allMixedHalos[n]->getAliveCount()) {
numberAlive = this->allMixedHalos[n]->getAliveCount();
haloWithLeastAlive = n;
}
this->allMixedHalos[m]->addPartner(n);
this->allMixedHalos[n]->addPartner(m);
this->allMixedHalos[m]->setValid(INVALID);
this->allMixedHalos[n]->setValid(INVALID);
}
n++;
}
// Mixed halo with the least alive particles gets it as VALID
this->allMixedHalos[haloWithLeastAlive]->setValid(VALID);
}
}
#ifndef USE_VTK_COSMO
#ifdef DEBUG
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
cout << "Mixed Halo " << m;
if (this->allMixedHalos[m]->getValid() == VALID)
cout << " is VALID on "
<< " Rank " << this->allMixedHalos[m]->getRankID();
cout << " partners with ";
set<int>::iterator iter;
set<int>* partner = this->allMixedHalos[m]->getPartners();
for (iter = partner->begin(); iter != partner->end(); ++iter)
cout << (*iter) << " ";
cout << endl;
}
#endif
#endif
}
}
/////////////////////////////////////////////////////////////////////////
//
// Compare the tags of two halos to see if they are somewhat the same
// This needs to be made better
//
/////////////////////////////////////////////////////////////////////////
int CosmoHaloFinderP::compareHalos(CosmoHalo* halo1, CosmoHalo* halo2)
{
vector<ID_T>* member1 = halo1->getTags();
vector<ID_T>* member2 = halo2->getTags();
int numFound = 0;
for (unsigned int i = 0; i < member1->size(); i++) {
bool done = false;
unsigned int j = 0;
while (!done &&
(*member1)[i] >= (*member2)[j] &&
j < member2->size()) {
if ((*member1)[i] == (*member2)[j]) {
done = true;
numFound++;
}
j++;
}
}
if (numFound == 0)
return numFound;
else
return numFound;
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER sends the result of the merge back to the processors which
// label their previously UNMARKED mixed halos as VALID or INVALID
// VALID halos have all their particles made ALIVE for output
// INVALID halos have all their particles made DEAD because other
// processors will report them
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::sendMixedHaloResults
#ifdef USE_SERIAL_COSMO
(ID_T* haloBuffer, int)
#else
(ID_T* haloBuffer, int haloBufSize)
#endif
{
#ifndef USE_SERIAL_COSMO
// MASTER sends merge results to all processors
if (this->myProc == MASTER) {
#endif
// Share the information
// Send to each processor the rank, id, and valid status
// Use the same haloBuffer
int index = 0;
haloBuffer[index++] = (ID_T)this->allMixedHalos.size();
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
haloBuffer[index++] = this->allMixedHalos[m]->getRankID();
haloBuffer[index++] = this->allMixedHalos[m]->getHaloID();
haloBuffer[index++] = this->allMixedHalos[m]->getValid();
}
#ifndef USE_SERIAL_COSMO
MPI_Request request;
for (int proc = 1; proc < this->numProc; proc++) {
#ifdef ID_64
MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, proc,
0, Partition::getComm(), &request);
#else
MPI_Isend(haloBuffer, haloBufSize, MPI_INT, proc,
0, Partition::getComm(), &request);
#endif
}
#endif
// MASTER must claim the mixed halos assigned to him
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
if (this->allMixedHalos[m]->getRankID() == MASTER &&
this->allMixedHalos[m]->getValid() == VALID) {
// Locate the mixed halo in question
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
int id = this->myMixedHalos[h]->getHaloID();
if (id == this->allMixedHalos[m]->getHaloID()) {
this->myMixedHalos[h]->setValid(VALID);
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
this->numberOfAliveHalos++;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter;
for (iter = particles->begin(); iter != particles->end(); ++iter)
this->status[(*iter)] = ALIVE;
}
}
}
}
#ifndef USE_SERIAL_COSMO
}
// Other processors wait for result and adjust their halo vector
else {
MPI_Status mpistatus;
#ifdef ID_64
MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MASTER,
0, Partition::getComm(), &mpistatus);
#else
MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MASTER,
0, Partition::getComm(), &mpistatus);
#endif
// Unpack information to see which of mixed halos are still valid
int index = 0;
int numMixed = haloBuffer[index++];
for (int m = 0; m < numMixed; m++) {
int rank = haloBuffer[index++];
int id = haloBuffer[index++];
int valid = haloBuffer[index++];
// If this mixed halo is on my processor
if (rank == this->myProc && valid == VALID) {
// Locate the mixed halo in question
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getHaloID() == id) {
this->myMixedHalos[h]->setValid(VALID);
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
this->numberOfAliveHalos++;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter;
for (iter = particles->begin(); iter != particles->end(); ++iter)
this->status[(*iter)] = ALIVE;
}
}
}
}
}
#endif // USE_SERIAL_COSMO
}
#ifndef USE_VTK_COSMO
/////////////////////////////////////////////////////////////////////////
//
// Write the output of the halo finder in the form of the input .cosmo file
//
// Encoded mixed halo VALID or INVALID into the status array such that
// ALIVE particles that are part of an INVALID mixed array will not write
// but DEAD particles that are part of a VALID mixed array will be written
//
// In order to make the output consistent with the serial output where the
// lowest tagged particle in a halo owns the halo, work must be done to
// identify the lowest tag. This is because as particles are read onto
// this processor using the round robin read of every particle, those
// particles are no longer in tag order. When the serial halo finder is
// called it has to use the index of the particle on this processor which
// is no longer the tag.
//
// p haloTag tag haloSize
// 0 0 523 3
// 1 0 522 0
// 2 0 266 0
//
// In the above example the halo will be credited to 523 instead of 266
// because the index of 523 is 0 and the index of 266 is 2. So we must
// make a pass to map the indexes.
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::writeTaggedParticles()
{
// Map the index of the particle on this process to the index of the
// particle with the lowest tag value so that the written output refers
// to the lowest tag as being the owner of the halo
int* mapIndex = new int[this->particleCount];
for (int p = 0; p < this->particleCount; p++)
mapIndex[p] = p;
// If the tag for the first particle of this halo is bigger than the tag
// for this particle, change the map to identify this particle as the lowest
for (int p = 0; p < this->particleCount; p++) {
if (this->tag[mapIndex[this->haloTag[p]]] > this->tag[p])
mapIndex[this->haloTag[p]] = p;
}
// Write the tagged particle file
ofstream* outStream = new ofstream(this->outFile.c_str(), ios::out);
string textMode = "ascii";
char str[1024];
string ascii = "ascii";
if (textMode == "ascii") {
// Output all ALIVE particles that were not part of a mixed halo
// unless that halo is VALID. Output only the DEAD particles that are
// part of a VALID halo. This was encoded when mixed halos were found
// so any ALIVE particle is VALID
for (int p = 0; p < this->particleCount; p++) {
if (this->status[p] == ALIVE) {
// Every alive particle appears in the particle output
sprintf(str, "%12.4E %12.4E ", this->xx[p], this->vx[p]);
*outStream << str;
sprintf(str, "%12.4E %12.4E ", this->yy[p], this->vy[p]);
*outStream << str;
sprintf(str, "%12.4E %12.4E ", this->zz[p], this->vz[p]);
*outStream << str;
int result = (this->haloSize[this->haloTag[p]] < this->pmin)
? -1: this->tag[mapIndex[this->haloTag[p]]];
sprintf(str, "%12d %12d\n", result, this->tag[p]);
*outStream << str;
}
}
}
else {
// output in COSMO form
for (int p = 0; p < this->particleCount; p++) {
float fBlock[COSMO_FLOAT];
fBlock[0] = this->xx[p];
fBlock[1] = this->vx[p];
fBlock[2] = this->yy[p];
fBlock[3] = this->vy[p];
fBlock[4] = this->zz[p];
fBlock[5] = this->vz[p];
fBlock[6] = (this->haloSize[this->haloTag[p]] < this->pmin)
? -1.0: 1.0 * this->tag[this->haloTag[p]];
outStream->write((char *)fBlock, COSMO_FLOAT * sizeof(float));
int iBlock[COSMO_INT];
iBlock[0] = this->tag[p];
outStream->write((char *)iBlock, COSMO_INT * sizeof(int));
}
}
outStream->close();
delete outStream;
delete [] mapIndex;
}
#endif // USE_VTK_COSMO
| 37.602122 | 102 | 0.608752 | SCS-B3C |
7898e349b2fa142d82fb16ea237b63fba1765daf | 653 | cpp | C++ | src/gen/detail/ExecHandler.cpp | bgn9000/rapidcheck | 593ada72f6938221973bf30bf7a7f7e6a24160de | [
"BSD-2-Clause"
] | null | null | null | src/gen/detail/ExecHandler.cpp | bgn9000/rapidcheck | 593ada72f6938221973bf30bf7a7f7e6a24160de | [
"BSD-2-Clause"
] | null | null | null | src/gen/detail/ExecHandler.cpp | bgn9000/rapidcheck | 593ada72f6938221973bf30bf7a7f7e6a24160de | [
"BSD-2-Clause"
] | 1 | 2019-03-05T13:52:28.000Z | 2019-03-05T13:52:28.000Z | #include "rapidcheck/gen/detail/ExecHandler.h"
#include "rapidcheck/Gen.h"
namespace rc {
namespace gen {
namespace detail {
ExecHandler::ExecHandler(Recipe &recipe)
: m_recipe(recipe)
, m_random(m_recipe.random)
, m_it(begin(m_recipe.ingredients)) {}
rc::detail::Any ExecHandler::onGenerate(const Gen<rc::detail::Any> &gen) {
rc::detail::ImplicitScope newScope;
Random random = m_random.split();
if (m_it == end(m_recipe.ingredients)) {
m_it = m_recipe.ingredients.insert(m_it, gen(random, m_recipe.size));
}
auto current = m_it++;
return current->value();
}
} // namespace detail
} // namespace gen
} // namespace rc
| 23.321429 | 74 | 0.698315 | bgn9000 |
789ae1fadb38be5a53cf6de771eef086900f3266 | 774 | cpp | C++ | 2018/day13/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | 3 | 2021-07-01T14:31:06.000Z | 2022-03-29T20:41:21.000Z | 2018/day13/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | 2018/day13/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | #include "TestClass.h"
#include "../test.h"
namespace aoc2018_day13 {
TEST_F(Tests2018Day13, part_1_test) {
auto sol = part_1("../2018/day13/input_test.in");
ASSERT_EQ(sol.first, 7);
ASSERT_EQ(sol.second, 3);
}
TEST_F(Tests2018Day13, part_1_real_test) {
auto sol = part_1("../2018/day13/input.in");
ASSERT_EQ(sol.first, 103);
ASSERT_EQ(sol.second, 85);
}
TEST_F(Tests2018Day13, part_2_test) {
auto sol = part_2("../2018/day13/input_test2.in");
ASSERT_EQ(sol.first, 6);
ASSERT_EQ(sol.second, 4);
}
TEST_F(Tests2018Day13, part_2_real_test) {
auto sol = part_2("../2018/day13/input.in");
ASSERT_EQ(sol.first, 88);
ASSERT_EQ(sol.second, 64);
}
}
| 26.689655 | 58 | 0.600775 | alexandru-andronache |
789aea9b69e07b0615e0f2e4af79b9122a55cf63 | 1,796 | cc | C++ | chrome/browser/feature_engagement/new_tab/new_tab_tracker.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/feature_engagement/new_tab/new_tab_tracker.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/feature_engagement/new_tab/new_tab_tracker.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // 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 "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h"
#include "base/time/time.h"
#include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h"
#include "chrome/browser/ui/views/tabs/new_tab_button.h"
#include "components/feature_engagement/public/event_constants.h"
#include "components/feature_engagement/public/feature_constants.h"
#include "components/feature_engagement/public/tracker.h"
namespace {
const int kDefaultNewTabPromoShowTimeInHours = 2;
constexpr char kNewTabObservedSessionTimeKey[] =
"new_tab_in_product_help_observed_session_time_key";
} // namespace
namespace feature_engagement {
NewTabTracker::NewTabTracker(Profile* profile)
: FeatureTracker(
profile,
&kIPHNewTabFeature,
kNewTabObservedSessionTimeKey,
base::TimeDelta::FromHours(kDefaultNewTabPromoShowTimeInHours)) {}
NewTabTracker::~NewTabTracker() = default;
void NewTabTracker::OnNewTabOpened() {
GetTracker()->NotifyEvent(events::kNewTabOpened);
}
void NewTabTracker::OnOmniboxNavigation() {
GetTracker()->NotifyEvent(events::kOmniboxInteraction);
}
void NewTabTracker::OnOmniboxFocused() {
if (ShouldShowPromo())
ShowPromo();
}
void NewTabTracker::OnPromoClosed() {
GetTracker()->Dismissed(kIPHNewTabFeature);
}
void NewTabTracker::OnSessionTimeMet() {
GetTracker()->NotifyEvent(events::kNewTabSessionTimeMet);
}
void NewTabTracker::ShowPromo() {
NewTabButton::ShowPromoForLastActiveBrowser();
}
void NewTabTracker::CloseBubble() {
NewTabButton::CloseBubbleForLastActiveBrowser();
}
} // namespace feature_engagement
| 28.967742 | 93 | 0.77951 | zipated |
789b5cceacf0f4601a7c391bc7590c069b3cce16 | 4,287 | cc | C++ | ThirdParty/webrtc/src/webrtc/video/video_loopback.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 8 | 2018-12-27T14:57:13.000Z | 2021-04-07T07:03:15.000Z | ThirdParty/webrtc/src/webrtc/video/video_loopback.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 1 | 2019-03-13T01:35:03.000Z | 2020-10-08T04:13:04.000Z | ThirdParty/webrtc/src/webrtc/video/video_loopback.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 9 | 2018-12-28T11:45:12.000Z | 2021-05-11T02:15:31.000Z | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <map>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
namespace webrtc {
namespace flags {
DEFINE_int32(width, 640, "Video width.");
size_t Width() {
return static_cast<size_t>(FLAGS_width);
}
DEFINE_int32(height, 480, "Video height.");
size_t Height() {
return static_cast<size_t>(FLAGS_height);
}
DEFINE_int32(fps, 30, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
return static_cast<size_t>(FLAGS_min_bitrate);
}
DEFINE_int32(start_bitrate, 300, "Video starting bitrate.");
size_t StartBitrate() {
return static_cast<size_t>(FLAGS_start_bitrate);
}
DEFINE_int32(max_bitrate, 800, "Maximum video bitrate.");
size_t MaxBitrate() {
return static_cast<size_t>(FLAGS_max_bitrate);
}
int MinTransmitBitrate() {
return 0;
} // No min padding for regular video.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
DEFINE_int32(num_temporal_layers,
0,
"Number of temporal layers. Set to 1-4 to override.");
size_t NumTemporalLayers() {
return static_cast<size_t>(FLAGS_num_temporal_layers);
}
} // namespace flags
void Loopback() {
test::Loopback::Config config{flags::Width(),
flags::Height(),
flags::Fps(),
flags::MinBitrate(),
flags::StartBitrate(),
flags::MaxBitrate(),
0, // No min transmit bitrate.
flags::Codec(),
flags::NumTemporalLayers(),
flags::LossPercent(),
flags::LinkCapacity(),
flags::QueueSize(),
flags::AvgPropagationDelayMs(),
flags::StdPropagationDelayMs(),
flags::FLAGS_logs};
test::Loopback loopback(config);
loopback.Run();
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
| 29.363014 | 79 | 0.643107 | JokeJoe8806 |
789df601a83c28a5e244af60d16398e0e0033551 | 1,302 | cpp | C++ | src/kernel/liveupdate.cpp | jaeh/IncludeOS | 1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02 | [
"Apache-2.0"
] | 3,673 | 2015-12-01T22:14:02.000Z | 2019-03-22T03:07:20.000Z | src/kernel/liveupdate.cpp | jaeh/IncludeOS | 1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02 | [
"Apache-2.0"
] | 960 | 2015-12-01T20:40:36.000Z | 2019-03-22T13:21:21.000Z | src/kernel/liveupdate.cpp | jaeh/IncludeOS | 1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02 | [
"Apache-2.0"
] | 357 | 2015-12-02T09:32:50.000Z | 2019-03-22T09:32:34.000Z | #include <kernel.hpp>
#include <os.hpp>
#include <kernel/memory.hpp>
#define HIGHMEM_LOCATION (1ull << 45)
//#define LIU_DEBUG 1
#ifdef LIU_DEBUG
#define PRATTLE(fmt, ...) kprintf(fmt, ##__VA_ARGS__)
#else
#define PRATTLE(fmt, ...) /* fmt */
#endif
void kernel::setup_liveupdate()
{
#if defined(ARCH_x86_64)
// highmem location
kernel::state().liveupdate_loc = HIGHMEM_LOCATION;
#else
// other platforms, without paging
kernel::state().liveupdate_loc = kernel::state().liveupdate_phys;
#endif
const size_t size = kernel::state().liveupdate_size;
if (size == 0) return;
PRATTLE("Setting up LiveUpdate from %p to %p, %zx\n",
(void*) kernel::state().liveupdate_phys,
(void*) kernel::state().liveupdate_loc, size);
#if defined(ARCH_x86_64)
os::mem::vmmap().assign_range({
kernel::state().liveupdate_phys,
kernel::state().liveupdate_phys + kernel::state().liveupdate_size-1,
"LiveUpdate physical"
});
// move location to high memory
PRATTLE("virtual_move %p to %p (%zu bytes)\n",
(void*) kernel::state().liveupdate_phys,
(void*) kernel::state().liveupdate_loc, size);
os::mem::virtual_move(kernel::state().liveupdate_phys, size,
kernel::state().liveupdate_loc, "LiveUpdate");
#endif
}
| 29.590909 | 76 | 0.660522 | jaeh |
789e40a496280fa94f47a1bc308617b30efd0608 | 3,507 | cpp | C++ | libs/interprocess/example/doc_managed_aligned_allocation.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/interprocess/example/doc_managed_aligned_allocation.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/interprocess/example/doc_managed_aligned_allocation.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_managed_aligned_allocation
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cassert>
//<-
#include "../test/get_process_id_name.hpp"
//->
int main()
{
using namespace boost::interprocess;
//Remove shared memory on construction and destruction
struct shm_remove
{
//<-
#if 1
shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
#else
//->
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
//<-
#endif
//->
} remover;
//Managed memory segment that allocates portions of a shared memory
//segment with the default management algorithm
//<-
#if 1
managed_shared_memory managed_shm(create_only, test::get_process_id_name(), 65536);
#else
//->
managed_shared_memory managed_shm(create_only, "MySharedMemory", 65536);
//<-
#endif
//->
const std::size_t Alignment = 128;
//Allocate 100 bytes aligned to Alignment from segment, throwing version
void *ptr = managed_shm.allocate_aligned(100, Alignment);
//Check alignment
assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
//Deallocate it
managed_shm.deallocate(ptr);
//Non throwing version
ptr = managed_shm.allocate_aligned(100, Alignment, std::nothrow);
//Check alignment
assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
//Deallocate it
managed_shm.deallocate(ptr);
//If we want to efficiently allocate aligned blocks of memory
//use managed_shared_memory::PayloadPerAllocation value
assert(Alignment > managed_shared_memory::PayloadPerAllocation);
//This allocation will maximize the size of the aligned memory
//and will increase the possibility of finding more aligned memory
ptr = managed_shm.allocate_aligned
(3*Alignment - managed_shared_memory::PayloadPerAllocation, Alignment);
//Check alignment
assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
//Deallocate it
managed_shm.deallocate(ptr);
return 0;
}
//]
/*
#include <vector>
#include <boost/interprocess/managed_windows_shared_memory.hpp>
int main()
{
using namespace boost::interprocess;
typedef boost::interprocess::
managed_windows_shared_memory shared_segment;
std::vector<void *> ptrs;
shared_segment m_segment(create_only, "shmem", 4096*16);
try{
while(1){
//Now I have several allocate_aligned operations:
ptrs.push_back(m_segment.allocate_aligned(128, 128));
}
}
catch(...){
m_segment.deallocate(ptrs.back());
ptrs.pop_back();
ptrs.push_back(m_segment.allocate_aligned(128, 128));
}
return 0;
}
*/
#include <boost/interprocess/detail/config_end.hpp>
| 30.232759 | 87 | 0.648417 | Ron2014 |
a192aad2c3bbb4071b8e8490ed2c5a78fda1df77 | 8,941 | cpp | C++ | opt/nomad/src/Algos/MeshBase.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 31 | 2019-02-05T16:39:18.000Z | 2022-03-11T23:14:11.000Z | opt/nomad/src/Algos/MeshBase.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 20 | 2020-04-13T09:22:53.000Z | 2021-08-16T16:14:13.000Z | opt/nomad/src/Algos/MeshBase.cpp | scikit-quant/scikit-quant | 397ab0b6287f3815e9bcadbfadbe200edbee5a23 | [
"BSD-3-Clause-LBNL"
] | 6 | 2020-04-21T17:43:47.000Z | 2021-03-10T04:12:34.000Z | /*---------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */
/* */
/* NOMAD - Version 4 has been created by */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* The copyright of NOMAD - version 4 is owned by */
/* Charles Audet - Polytechnique Montreal */
/* Sebastien Le Digabel - Polytechnique Montreal */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */
/* NSERC (Natural Sciences and Engineering Research Council of Canada), */
/* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */
/* for Data Valorization) */
/* */
/* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */
/* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */
/* and Exxon Mobil. */
/* */
/* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */
/* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */
/* Exxon Mobil. */
/* */
/* Contact information: */
/* Polytechnique Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* */
/* This program 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. */
/* */
/* 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 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/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*---------------------------------------------------------------------------------*/
#include "../Algos/MeshBase.hpp"
NOMAD::MeshBase::MeshBase(const std::shared_ptr<NOMAD::PbParameters> pbParams)
: _n(pbParams->getAttributeValue<size_t>("DIMENSION")),
_pbParams(pbParams),
_initialMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_MESH_SIZE")),
_minMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_MESH_SIZE")),
_initialFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_FRAME_SIZE")),
_minFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_FRAME_SIZE")),
_lowerBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("LOWER_BOUND")),
_upperBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("UPPER_BOUND"))
{
init();
}
void NOMAD::MeshBase::init()
{
if ( _pbParams->toBeChecked() )
{
throw NOMAD::Exception(__FILE__, __LINE__, "Parameters::checkAndComply() needs to be called before constructing a mesh.");
}
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getRho(void) const
{
NOMAD::ArrayOfDouble rho(_n);
for (size_t i = 0; i < _n; i++)
{
rho[i] = getRho(i);
}
return rho;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getdeltaMeshSize(void) const
{
NOMAD::ArrayOfDouble delta(_n);
for (size_t i = 0; i < _n; i++)
{
delta[i] = getdeltaMeshSize(i);
}
return delta;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSize() const
{
NOMAD::ArrayOfDouble Delta(_n);
for (size_t i = 0; i < _n; i++)
{
Delta[i] = getDeltaFrameSize(i);
}
return Delta;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSizeCoarser() const
{
NOMAD::ArrayOfDouble Delta(_n);
for (size_t i = 0; i < _n; i++)
{
Delta[i] = getDeltaFrameSizeCoarser(i);
}
return Delta;
}
void NOMAD::MeshBase::setDeltas(const NOMAD::ArrayOfDouble &deltaMeshSize,
const NOMAD::ArrayOfDouble &deltaFrameSize)
{
for (size_t i = 0; i < _n; i++)
{
setDeltas(i, deltaMeshSize[i], deltaFrameSize[i]);
}
}
/*-----------------------------------------------------------*/
/* scale and project on the mesh */
/*-----------------------------------------------------------*/
NOMAD::Double NOMAD::MeshBase::scaleAndProjectOnMesh(size_t i, const NOMAD::Double &l) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase.");
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::scaleAndProjectOnMesh(
const NOMAD::Direction &dir) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase.");
}
NOMAD::Point NOMAD::MeshBase::projectOnMesh(const NOMAD::Point& point,
const NOMAD::Point& frameCenter) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "projectOnMesh() not defined for MeshBase.");
}
bool NOMAD::MeshBase::verifyPointIsOnMesh(const NOMAD::Point& point, const NOMAD::Point& center) const
{
bool isOnMesh = true;
for (size_t i = 0; i < point.size(); i++)
{
NOMAD::Double pointRebaseI = point[i];
NOMAD::Double centerI = center[i];
NOMAD::Double deltaI = getdeltaMeshSize(i);
if ( (_lowerBound[i].isDefined() && _lowerBound[i] == pointRebaseI)
|| (_upperBound[i].isDefined() && _upperBound[i] == pointRebaseI))
{
isOnMesh = true;
}
else
{
if (!centerI.isMultipleOf(deltaI))
{
// Rebase point on the mesh centered on center Point
pointRebaseI -= centerI;
}
if (!pointRebaseI.isMultipleOf(deltaI))
{
isOnMesh = false;
break;
}
}
}
return isOnMesh;
}
std::ostream& NOMAD::operator<<(std::ostream& os, const NOMAD::MeshBase& mesh)
{
os << "DELTA_MESH_SIZE " << mesh.getdeltaMeshSize() << std::endl;
os << "DELTA_FRAME_SIZE " << mesh.getDeltaFrameSize() << std::endl;
return os;
}
std::istream& NOMAD::operator>>(std::istream& is, NOMAD::MeshBase& mesh)
{
size_t n = mesh.getSize();
// Read line by line
std::string name;
NOMAD::ArrayOfDouble deltaMeshSize(n), deltaFrameSize(n);
while (is >> name && is.good() && !is.eof())
{
if ("DELTA_MESH_SIZE" == name)
{
is >> deltaMeshSize;
}
else if ("DELTA_FRAME_SIZE" == name)
{
is >> deltaFrameSize;
}
else
{
// Put back name to istream. Maybe there is a simpler way.
for (unsigned i = 0; i < name.size(); i++)
{
is.unget();
}
break;
}
}
mesh.setDeltas(deltaMeshSize, deltaFrameSize);
return is;
}
| 39.043668 | 130 | 0.489766 | scikit-quant |
a193a90473aed44aade937251dfbd67d33fb5d3b | 1,820 | cpp | C++ | ZROI/20zr提高组十连测附加赛4/B/B.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | ZROI/20zr提高组十连测附加赛4/B/B.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | ZROI/20zr提高组十连测附加赛4/B/B.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=100005;
int n;
vector<int> v[N];
ll up[N],down[N],deg[N],ans=0;
void dfs1(int u,int f){
up[u]=deg[u];
for(auto &to : v[u]){
if(to==f) continue;
dfs1(to,u); up[u]+=up[to];
}
down[u]=2*n-2-up[u];
}
ll mx1[N],mx2[N];
ll dp[N],dp2[N],sum[N],sz[N];
void dfs2(int u,int f){
dp[u]=down[u]; ll mx=0;
sum[u]=down[u]; sz[u]=1;
for(auto &to : v[u]){
if(to==f) continue;
dfs2(to,u);
if(mx1[u]<dp[to]) mx2[u]=mx1[u],mx1[u]=dp[to];
else if(mx2[u]<dp[to]) mx2[u]=dp[to];
sz[u]+=sz[to];
}
dp[u]+=mx1[u];
}
void dfs3(int u,int f,ll S){
if(f!=-1){
dp2[u]=dp2[f]+(2*n-2-(up[f]-up[u])-S);
if(dp[u]==mx1[f]) checkmax(dp2[u],mx2[f]+(2*n-2-(up[f]-up[u])-S));
else checkmax(dp2[u],mx1[f]+(2*n-2-(up[f]-up[u])-S));
}
checkmax(ans,dp2[u]);
for(auto &to : v[u]){
if(to==f) continue;
dfs3(to,u,u==1 ? 0 : S+up[f]-up[u]);
}
}
int main()
{
n=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
v[x].push_back(y); v[y].push_back(x);
deg[x]++; deg[y]++;
}
dfs1(1,-1);
dfs2(1,-1);
ans=dp[1];
dfs3(1,-1,0);
printf("%.5lf\n",(double)ans);
return 0;
} | 24.266667 | 74 | 0.48956 | jinzhengyu1212 |
a1946188d3263494de2715006ad285a3ae003587 | 855 | cpp | C++ | Algorithms/Minimum Cost to Connect Sticks/solution.cpp | MishaVernik/LeetCode | 5f4823706f472b59fbc0c936524477dc039a46ee | [
"MIT"
] | null | null | null | Algorithms/Minimum Cost to Connect Sticks/solution.cpp | MishaVernik/LeetCode | 5f4823706f472b59fbc0c936524477dc039a46ee | [
"MIT"
] | null | null | null | Algorithms/Minimum Cost to Connect Sticks/solution.cpp | MishaVernik/LeetCode | 5f4823706f472b59fbc0c936524477dc039a46ee | [
"MIT"
] | null | null | null | /*
You have some sticks with positive integer lengths.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
Example 1:
Input: sticks = [2,4,3]
Output: 14
Example 2:
Input: sticks = [1,8,3,5]
Output: 30
Constraints:
1 <= sticks.length <= 10^4
1 <= sticks[i] <= 10^4
*/
class Solution {
public:
int connectSticks(vector<int>& sticks) {
int ans = 0;
priority_queue<int, vector<int> ,greater<int>> pq(sticks.begin(), sticks.end());
while (pq.size() != 1){
int s1 = pq.top();pq.pop();
int s2 = pq.top();pq.pop();
pq.push(s1+s2);
ans += s1 + s2;
}
return ans;
}
}; | 21.923077 | 152 | 0.59883 | MishaVernik |
a194e0d2bd4ac009e3e06485ecf0b217ffede005 | 5,987 | cpp | C++ | rndlevelsource/Polygon.cpp | Telefragged/rndlevelsource | 17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1 | [
"MIT"
] | null | null | null | rndlevelsource/Polygon.cpp | Telefragged/rndlevelsource | 17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1 | [
"MIT"
] | null | null | null | rndlevelsource/Polygon.cpp | Telefragged/rndlevelsource | 17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1 | [
"MIT"
] | null | null | null | #include "Polygon.h"
#include <algorithm>
#include <numeric>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include "Vector.h"
#include "Vertex.h"
Polygon::classification Polygon::classify(const Plane& plane) const
{
size_t count = points.size();
size_t front = 0, back = 0, onplane = 0;
for (const auto& p : points)
{
auto test = plane.evaluate(p);
if (test <= 0) back++;
if (test >= 0) front++;
if (test == 0) onplane++;
}
if (onplane == count) return Polygon::classification::onPlane;
if (front == count) return Polygon::classification::front;
if (back == count) return Polygon::classification::back;
return Polygon::classification::spanning;
}
Vertex Polygon::origin() const
{
return std::accumulate(points.cbegin(), points.cend(), Vertex{ 0, 0, 0 }) / double(points.size());
}
Plane Polygon::plane() const
{
if(points.size() < 3)
return Plane();
return { points[0], points[1], points[2] };
}
void Polygon::rotate(const Vertex & point, const Matrix3d & rotmat)
{
for (auto &p : points)
p = p.rotate(point, rotmat);
}
void Polygon::move(const Vertex & v)
{
for (auto &p : points)
p += v;
}
void Polygon::moveTo(const Vertex & p)
{
Vertex dist = p - origin();
for (auto &p : points)
p += dist;
}
void Polygon::scale(const Vertex &scale)
{
this->scale(origin(), scale);
}
void Polygon::scale(const Vertex& origin, const Vertex& scale)
{
for (auto &point : points)
{
Vertex vec = Vector::diff(origin, point).vec();
vec.x(vec.x() * scale.x());
vec.y(vec.y() * scale.y());
vec.z(vec.z() * scale.z());
point = origin + vec;
}
}
void Polygon::sliceThis(const Plane &plane)
{
auto[back, front] = slice(plane);
if (!back.points.empty() && !front.points.empty())
points = back.points;
}
std::pair<Polygon, Polygon> Polygon::slice(const Plane& plane) const
{
auto classification = classify(plane);
std::pair<Polygon, Polygon> ret;
if (classification != classification::spanning)
{
if (classification == classification::back) ret.first = *this;
else if (classification == classification::front) ret.second = *this;
return ret;
}
size_t prev = 0;
for (size_t i = 0; i <= points.size(); i++)
{
size_t index = i % points.size();
Vertex end = points[index];
auto c = plane.evaluate(end);
if (i > 0 && c != 0 && prev != 0 && c != prev)
{
Vertex start = points[i - 1];
Vector line = Vector::diff(start, end);
Vertex intersect = Plane::intersectPoint(plane, line);
if (!Vertex::isVertex(intersect))
throw new std::exception("Expected intersection");
ret.first.points.push_back(intersect);
ret.second.points.push_back(intersect);
}
if (i < points.size())
{
if (c <= 0) ret.first.points.push_back(end);
if (c >= 0) ret.second.points.push_back(end);
}
prev = c;
}
return ret;
}
void Polygon::flip()
{
std::reverse(points.begin(), points.end());
}
void Polygon::roundPoints(size_t precision)
{
double exp = std::pow(10, precision);
std::transform(points.begin(), points.end(), points.begin(), [exp](Vertex v) {
v.x(std::round(v.x() * exp) / exp);
v.y(std::round(v.y() * exp) / exp);
v.z(std::round(v.z() * exp) / exp);
return v;
});
}
Vertex Polygon::intersectPoint(const Vector& line, int flags) const
{
Plane plane = this->plane();
auto point = Plane::intersectPoint(plane, line);
Vertex defaultRet = (flags & lineBoundsFlag::RETURN_END_ON_FAIL) > 0 ? line.end() : Vertex();
flags = flags & lineBoundsFlag::ALLOW_BOTH;
if (!Vertex::isVertex(point))
return defaultRet;
bool test = testCollision(point);
if (!test)
return defaultRet;
if (flags != lineBoundsFlag::ALLOW_BOTH)
{
double position = line.calculatePosition(point);
if ((lineBoundsFlag::ALLOW_BACK & flags) == 0 && (position < 0 || doubleeq(position, 0)))
return defaultRet;
if ((lineBoundsFlag::ALLOW_FRONT & flags) == 0 && (position > 1 || doubleeq(position, 1)))
return defaultRet;
}
return point;
}
bool Polygon::testCollision(const Vertex& point) const
{
double sum = 0;
for (size_t n = 0; n < points.size(); n++)
{
Vertex p1 = points[n] - point;
Vertex p2 = points[(n + 1) % points.size()] - point;
double nom = p1.length() * p2.length();
if (doubleeq(nom, 0))
return false;
sum += acos(p1.dotProduct(p2) / nom);
}
return doubleeq(sum, M_PI * 2);
}
bool Polygon::testCollision(const Vector& line, int flags) const
{
// Ensure method returns NaN vector if it fails so we can test it.
Vertex intersect = intersectPoint(line, flags);
if (!Vertex::isVertex(intersect))
return false;
return true;
}
bool Polygon::testCollision(const Polygon& polygon) const
{
if (&polygon == this)
return true;
if (points.size() < 3 || polygon.points.size() < 3)
return false;
Vertex thisNorm = this->plane().normal();
Vertex polyNorm = polygon.plane().normal();
if (thisNorm == polyNorm || thisNorm == -polyNorm)
return false;
for (size_t n = 0; n < points.size(); n++)
{
Vector line = Vector::diff(points[n], points[(n + 1) % points.size()]);
if (polygon.testCollision(line, ALLOW_NONE))
return true;
}
for (size_t n = 0; n < polygon.points.size(); n++)
{
Vector line = Vector::diff(polygon.points[n], polygon.points[(n + 1) % polygon.points.size()]);
if (this->testCollision(line, ALLOW_NONE))
return true;
}
return false;
}
Polygon::Polygon(const Plane & p)
{
auto dir = p.closestAxisToNormal();
auto tempV = dir == Vertex::unitZ ? -Vertex::unitY : -Vertex::unitZ;
auto normal = p.normal();
auto up = tempV.crossProduct(normal).normalize();
auto right = normal.crossProduct(up).normalize();
points = {
p.p1() + right + up,
p.p1() - right + up,
p.p1() - right - up,
p.p1() + right + up
};
auto orig = origin();
std::transform(points.begin(), points.end(), points.begin(), [&orig](Vertex v) {
return (v - orig).normalize() * 10'000'000.0 + orig;
});
}
Polygon::Polygon(const std::initializer_list<Vertex>& points)
: points(points)
{
}
| 21.692029 | 99 | 0.645899 | Telefragged |
a19673293f85493ba96b642f196b5550331fbfa9 | 6,426 | cpp | C++ | llvm-gcc-4.2-2.9/gcc/config/alpha/llvm-alpha.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/gcc/config/alpha/llvm-alpha.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/gcc/config/alpha/llvm-alpha.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /* LLVM LOCAL begin (ENTIRE FILE!) */
/* High-level LLVM backend interface
Copyright (C) 2005 Free Software Foundation, Inc.
Contributed by Evan Cheng (evan.cheng@apple.com)
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
//===----------------------------------------------------------------------===//
// This is a C++ source file that implements specific llvm alpha ABI.
//===----------------------------------------------------------------------===//
#include "llvm-abi.h"
#include "llvm-internal.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
extern "C" {
#include "toplev.h"
}
static LLVMContext &Context = getGlobalContext();
enum alpha_builtin
{
ALPHA_BUILTIN_CMPBGE,
ALPHA_BUILTIN_EXTBL,
ALPHA_BUILTIN_EXTWL,
ALPHA_BUILTIN_EXTLL,
ALPHA_BUILTIN_EXTQL,
ALPHA_BUILTIN_EXTWH,
ALPHA_BUILTIN_EXTLH,
ALPHA_BUILTIN_EXTQH,
ALPHA_BUILTIN_INSBL,
ALPHA_BUILTIN_INSWL,
ALPHA_BUILTIN_INSLL,
ALPHA_BUILTIN_INSQL,
ALPHA_BUILTIN_INSWH,
ALPHA_BUILTIN_INSLH,
ALPHA_BUILTIN_INSQH,
ALPHA_BUILTIN_MSKBL,
ALPHA_BUILTIN_MSKWL,
ALPHA_BUILTIN_MSKLL,
ALPHA_BUILTIN_MSKQL,
ALPHA_BUILTIN_MSKWH,
ALPHA_BUILTIN_MSKLH,
ALPHA_BUILTIN_MSKQH,
ALPHA_BUILTIN_UMULH,
ALPHA_BUILTIN_ZAP,
ALPHA_BUILTIN_ZAPNOT,
ALPHA_BUILTIN_AMASK,
ALPHA_BUILTIN_IMPLVER,
ALPHA_BUILTIN_RPCC,
ALPHA_BUILTIN_THREAD_POINTER,
ALPHA_BUILTIN_SET_THREAD_POINTER,
/* TARGET_MAX */
ALPHA_BUILTIN_MINUB8,
ALPHA_BUILTIN_MINSB8,
ALPHA_BUILTIN_MINUW4,
ALPHA_BUILTIN_MINSW4,
ALPHA_BUILTIN_MAXUB8,
ALPHA_BUILTIN_MAXSB8,
ALPHA_BUILTIN_MAXUW4,
ALPHA_BUILTIN_MAXSW4,
ALPHA_BUILTIN_PERR,
ALPHA_BUILTIN_PKLB,
ALPHA_BUILTIN_PKWB,
ALPHA_BUILTIN_UNPKBL,
ALPHA_BUILTIN_UNPKBW,
/* TARGET_CIX */
ALPHA_BUILTIN_CTTZ,
ALPHA_BUILTIN_CTLZ,
ALPHA_BUILTIN_CTPOP,
ALPHA_BUILTIN_max
};
/* TargetIntrinsicLower - For builtins that we want to expand to normal LLVM
* code, emit the code now. If we can handle the code, this macro should emit
* the code, return true.
*/
bool TreeToLLVM::TargetIntrinsicLower(tree exp,
unsigned FnCode,
const MemRef *DestLoc,
Value *&Result,
const Type *ResultType,
std::vector<Value*> &Ops) {
switch (FnCode) {
case ALPHA_BUILTIN_UMULH: {
Value *Arg0 = Ops[0];
Value *Arg1 = Ops[1];
Arg0 = Builder.CreateZExt(Arg0, IntegerType::get(Context, 128));
Arg1 = Builder.CreateZExt(Arg1, IntegerType::get(Context, 128));
Result = Builder.CreateMul(Arg0, Arg1);
Result = Builder.CreateLShr(Result, ConstantInt::get(
Type::getInt64Ty(Context), 64));
Result = Builder.CreateTrunc(Result, Type::getInt64Ty(Context));
return true;
}
case ALPHA_BUILTIN_CMPBGE: {
Value *Arg0 = Ops[0];
Value *Arg1 = Ops[1];
Value* cmps[8];
for (unsigned x = 0; x < 8; ++x) {
Value* LHS = Builder.CreateLShr(Arg0, ConstantInt::get(
Type::getInt64Ty(Context), x*8));
LHS = Builder.CreateTrunc(LHS, Type::getInt8Ty(Context));
Value* RHS = Builder.CreateLShr(Arg1, ConstantInt::get(
Type::getInt64Ty(Context), x*8));
RHS = Builder.CreateTrunc(RHS, Type::getInt8Ty(Context));
Value* cmps = Builder.CreateICmpUGE(LHS, RHS);
cmps = Builder.CreateIsNotNull(cmps);
cmps = Builder.CreateZExt(cmps, Type::getInt64Ty(Context));
cmps = Builder.CreateShl(cmps, ConstantInt::get(
Type::getInt64Ty(Context), x));
if (x == 0)
Result = cmps;
else
Result = Builder.CreateOr(Result,cmps);
}
return true;
}
case ALPHA_BUILTIN_EXTBL:
case ALPHA_BUILTIN_EXTWL:
case ALPHA_BUILTIN_EXTLL:
case ALPHA_BUILTIN_EXTQL: {
unsigned long long mask = 0;
switch (FnCode) {
case ALPHA_BUILTIN_EXTBL: mask = 0x00000000000000FFULL; break;
case ALPHA_BUILTIN_EXTWL: mask = 0x000000000000FFFFULL; break;
case ALPHA_BUILTIN_EXTLL: mask = 0x00000000FFFFFFFFULL; break;
case ALPHA_BUILTIN_EXTQL: mask = 0xFFFFFFFFFFFFFFFFULL; break;
};
Value *Arg0 = Ops[0];
Value *Arg1 = Builder.CreateAnd(Ops[1], ConstantInt::get(
Type::getInt64Ty(Context), 7));
Arg0 = Builder.CreateLShr(Arg0, Arg1);
Result = Builder.CreateAnd(Arg0, ConstantInt::get(
Type::getInt64Ty(Context), mask));
return true;
}
case ALPHA_BUILTIN_EXTWH:
case ALPHA_BUILTIN_EXTLH:
case ALPHA_BUILTIN_EXTQH: {
unsigned long long mask = 0;
switch (FnCode) {
case ALPHA_BUILTIN_EXTWH: mask = 0x000000000000FFFFULL; break;
case ALPHA_BUILTIN_EXTLH: mask = 0x00000000FFFFFFFFULL; break;
case ALPHA_BUILTIN_EXTQH: mask = 0xFFFFFFFFFFFFFFFFULL; break;
};
Value *Arg0 = Ops[0];
Value *Arg1 = Builder.CreateAnd(Ops[1], ConstantInt::get(
Type::getInt64Ty(Context), 7));
Arg1 = Builder.CreateSub(ConstantInt::get(
Type::getInt64Ty(Context), 64), Arg1);
Arg0 = Builder.CreateShl(Arg0, Arg1);
Result = Builder.CreateAnd(Arg0, ConstantInt::get(
Type::getInt64Ty(Context), mask));
return true;
}
default: break;
}
return false;
}
bool llvm_alpha_should_return_scalar_as_shadow(const Type* Ty) {
if (Ty && Ty->isIntegerTy(128))
return true;
return false;
}
/* LLVM LOCAL end (ENTIRE FILE!) */
| 33.123711 | 80 | 0.644569 | vidkidz |
a196bb870df02b117de37985f649874b412388f8 | 822 | cpp | C++ | algorithms/fillingJars.cpp | kosmaz/HackerRank | 1107804c8213d169070a5529de26b97eb190e06c | [
"MIT"
] | 1 | 2015-03-21T20:08:28.000Z | 2015-03-21T20:08:28.000Z | algorithms/fillingJars.cpp | kosmaz/HackerRank | 1107804c8213d169070a5529de26b97eb190e06c | [
"MIT"
] | null | null | null | algorithms/fillingJars.cpp | kosmaz/HackerRank | 1107804c8213d169070a5529de26b97eb190e06c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct three{unsigned long a,b,k;};
unsigned long long averageOperations(vector<three> data,
unsigned long long N,
unsigned long long M)
{
long double average=0;
for(unsigned long long i=0; i<M; ++i)
{
unsigned long diff=data[i].b-data[i].a;
++diff;
average+=(long double)(data[i].k*diff);
}
return ((unsigned long long)(average/=N));
}
void Run()
{
//enter values of N && M
unsigned long long N,M;
cin>>N>>M;
//enter value of a,b && k for M operations
vector<three> data;
for(unsigned long long i=0; i<M; ++i)
{
three temp;
cin>>temp.a>>temp.b>>temp.k;
data.push_back(temp);
}
cout<<averageOperations(data,N,M)<<endl;
}
int main()
{
Run();
return 0;
} | 20.04878 | 57 | 0.594891 | kosmaz |
a196d3603872516ec0b2ffd4037c74db31831a36 | 12,394 | cc | C++ | applications/query/cencalvmisosurface.cc | baagaard-usgs/cencalvm | c6cca356c722f150178416e5f98a1506dd733db6 | [
"CC0-1.0"
] | null | null | null | applications/query/cencalvmisosurface.cc | baagaard-usgs/cencalvm | c6cca356c722f150178416e5f98a1506dd733db6 | [
"CC0-1.0"
] | null | null | null | applications/query/cencalvmisosurface.cc | baagaard-usgs/cencalvm | c6cca356c722f150178416e5f98a1506dd733db6 | [
"CC0-1.0"
] | null | null | null | // ======================================================================
//
// Brad T. Aagaard
// U.S. Geological Survey
//
// ======================================================================
//
// C++ application to extract depth (in meters) of specified Vs (m/s)
// in the San Francisco Bay Area seismic velocity model at a list of
// points.
#include "cencalvm/query/VMQuery.h" // USES VMQuery
#include "cencalvm/storage/ErrorHandler.h" // USES ErrorHandler
#include <stdlib.h> // USES exit()
#include <stdio.h> // USES EOF
#include <unistd.h> // USES getopt()
#include <fstream> // USES std::ifstream, std::ofstream
#include <iomanip> // USES setw(), setiosflags(), resetiosflags()
#include <iostream> // USES std::cerr
#include <sstream> // USES std::ostringstream
#include <cassert> // USES assert()
#include <stdexcept> // USES std::runtime_error()
#include <string> // USES std::string
#include <cmath> // USES log(), ceil()
// ----------------------------------------------------------------------
// Dump usage to stderr.
void
usage(void)
{ // usage
std::cerr
<< "usage: cencalvmisosurface [-h] -v vs -i fileIn -o fileOut -d dbfile\n"
<< " [-e dbextfile] [-c cacheSize] [-s squashLimit] [-z elevMin]\n"
<< "\n"
<< " -v vs Value of shear wave speed for isosurface\n"
<< " -s squashLim Turn on squashing of topography and set limit\n"
<< " -i fileIn File containing list of locations: 'lon lat'.\n"
<< " -o fileOut Output file with locations and elev of isosurface.\n"
<< " -d dbfile Etree database file to query.\n"
<< " -e dbextfile Etree extended database file to query.\n"
<< " -c cacheSize Size of cache in MB to use in query\n"
<< " -s squashLim Turn on squashing of topography and set limit\n"
<< " -z elevMin Minimum elevation to consider for isosurface\n"
<< " -h Display usage and exit.\n";
} // usage
// ----------------------------------------------------------------------
// Parse command line arguments.
void
parseArgs(double* vs,
std::string* filenameIn,
std::string* filenameOut,
std::string* filenameDB,
std::string* filenameDBExt,
int* cacheSize,
double* squashLimit,
double* elevMin,
int argc,
char** argv)
{ // parseArgs
assert(0 != vs);
assert(0 != filenameIn);
assert(0 != filenameOut);
assert(0 != filenameDB);
assert(0 != filenameDBExt);
assert(0 != cacheSize);
assert(0 != squashLimit);
assert(0 != elevMin);
extern char* optarg;
int nparsed = 1;
*vs = 0.0;
*filenameIn = "";
*filenameOut = "";
*filenameDB = "";
*filenameDBExt = "";
int c = EOF;
while ( (c = getopt(argc, argv, "c:d:e:hi:o:s:v:z:") ) != EOF) {
switch (c)
{ // switch
case 'c' : // process -c option
*cacheSize = atoi(optarg);
nparsed += 2;
break;
case 'd' : // process -d option
*filenameDB = optarg;
nparsed += 2;
break;
case 'e' : // process -e option
*filenameDBExt = optarg;
nparsed += 2;
break;
case 'h' : // process -h option
nparsed += 1;
usage();
exit(0);
break;
case 'i' : // process -i option
*filenameIn = optarg;
nparsed += 2;
break;
case 'o' : // process -o option
*filenameOut = optarg;
nparsed += 2;
break;
case 's': // process -s option
*squashLimit = atof(optarg);
nparsed += 2;
break;
case 'v': // process -v option
*vs = atof(optarg);
nparsed += 2;
break;
case 'z': // process -z option
*elevMin = atof(optarg);
nparsed += 2;
break;
default :
usage();
exit(1);
} // switch
} // while
if (nparsed != argc ||
0 == *vs ||
0 == filenameIn->length() ||
0 == filenameOut->length() ||
0 == filenameDB->length()) {
usage();
exit(1);
} // if
} // parseArgs
// ----------------------------------------------------------------------
int
initialize(cencalvm::query::VMQuery* query,
const char* filenameDB,
const char* filenameDBExt,
const int cacheSize,
const double squashLimit,
const bool squashOn)
{ // initialize
assert(0 != query);
// Get handle to error handler
cencalvm::storage::ErrorHandler* errHandler = query->errorHandler();
if (0 == errHandler) {
std::cerr << "Could not get handle to error handler.\n";
return 1;
} // if
// Set database filename
query->filename(filenameDB);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
// Set cache size
query->cacheSize(cacheSize);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
// Set extended database filename if given
if ("" != filenameDBExt) {
query->filenameExt(filenameDBExt);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
// Set cache size
query->cacheSizeExt(cacheSize);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
} // if
// Turn on squashing if requested
if (squashOn) {
query->squash(true, squashLimit);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
} // if
// Open database for querying
query->open();
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
// Set query type to maximum resolution
query->queryType(cencalvm::query::VMQuery::MAXRES);
return 0;
} // initialize
// ----------------------------------------------------------------------
double
queryElev(cencalvm::query::VMQuery* query,
const double lon,
const double lat)
{ // queryElev
assert(0 != query);
// Get handle to error handler
cencalvm::storage::ErrorHandler* errHandler = query->errorHandler();
if (0 == errHandler) {
std::cerr << "Could not get handle to error handler.\n";
return 1;
} // if
const int numVals = 1;
const char* elevName[] = { "Elevation" };
query->queryVals(elevName, numVals);
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
throw std::runtime_error("Could not get elevation.");
} // if
double* vals = (numVals > 0) ? new double[numVals] : 0;
assert(0 != vals);
// Query for elevation at location
query->query(&vals, numVals, lon, lat, -5.0e+3);
double elev = vals[0];
// Correct elevation for stair-stepping grid
const char* valNames[] = { "Vs" };
query->queryVals(valNames, numVals);
const int niters = 10;
const double dx = -12.5;
for (int iter=0; iter < niters; ++iter) {
const double elevQ = elev + iter*dx;
query->query(&vals, numVals, lon, lat, elevQ);
const double vs = vals[0];
if (vs > 0.0) {
elev = elevQ;
break;
} // if
} // for
delete[] vals; vals = 0;
return elev;
} // queryElev
// ----------------------------------------------------------------------
double
searchVs(cencalvm::query::VMQuery* query,
const double vsTarget,
const double lon,
const double lat,
const double elevLimitUpper,
const double elevLimitLower)
{ // searchVs
assert(0 != query);
const int niters =
int(1 + ceil(log( (elevLimitUpper - elevLimitLower) / 25.0) / log(2.0)));
const int numVals = 1;
double* vals = (numVals > 0) ? new double[numVals] : 0;
assert(0 != vals);
double elevUpper = elevLimitUpper;
double elevLower = elevLimitLower;
double elevVs = elevLower;
// Set values to be returned in queries
const char* valNames[] = { "Vs" };
query->queryVals(valNames, numVals);
for (int iter=0; iter < niters; ++iter) {
query->query(&vals, numVals, lon, lat, elevUpper);
const double vsU = vals[0];
query->query(&vals, numVals, lon, lat, elevLower);
const double vsL = vals[0];
const double elevMiddle = 0.5 * (elevUpper + elevLower);
query->query(&vals, numVals, lon, lat, elevMiddle);
const double vsM = vals[0];
if (vsTarget > vsU && vsTarget <= vsM) {
elevLower = elevMiddle;
elevVs = elevLower;
} else if (vsTarget > vsM && vsTarget <= vsL) {
elevUpper = elevMiddle;
elevVs = elevLower;
} else if (vsTarget <= vsU) {
elevVs = elevUpper;
break;
} else if (vsL < 0.0) {
elevVs = 1.0e+6;
break;
} else {
std::cerr
<< "Invalid search range!\n"
<< "Target vs: " << vsTarget << "\n"
<< "Location: (" << lon << ", " << lat << ")\n"
<< "Upper Vs(z=" << elevUpper << "): " << vsU << "\n"
<< "Lower Vs(z=" << elevLower << "): " << vsL << "\n"
<< "Middle Vs(z=" << elevMiddle << "): " << vsM
<< std::endl;
exit(1);
} // else
} // for
return elevVs;
} // searchVs
// ----------------------------------------------------------------------
// main
int
main(int argc,
char* argv[])
{ // main
double vsTarget = 0.0;
std::string filenameIn = "";
std::string filenameOut = "";
std::string filenameDB = "";
std::string filenameDBExt = "";
double queryRes = 0.0;
int cacheSize = 128;
const double squashDefault = 1.0e+06;
double squashLimit = squashDefault;
double elevMin = -45.0e+03;
// Parse command line arguments
parseArgs(&vsTarget, &filenameIn, &filenameOut, &filenameDB, &filenameDBExt,
&cacheSize, &squashLimit, &elevMin,
argc, argv);
// Create query
cencalvm::query::VMQuery query;
const bool squashOn = squashLimit != squashDefault;
initialize(&query, filenameDB.c_str(), filenameDBExt.c_str(),
cacheSize, squashLimit, squashOn);
// Open input file to read locations
std::ifstream fileIn(filenameIn.c_str());
if (!fileIn.is_open()) {
std::cerr << "Could not open file '" << filenameIn
<< "' to read query locations.\n";
return 1;
} // if
// Open output file to accept data
std::ofstream fileOut(filenameOut.c_str());
if (!fileOut.is_open()) {
std::cerr << "Could not open file '" << filenameOut
<< "' to receive query data.\n";
return 1;
} // if
const int numVals = 1; // Vs
// Create array to hold values returned in queries
double* vals = (numVals > 0) ? new double[numVals] : 0;
// Read location from input file
double lon = 0.0;
double lat = 0.0;
fileIn >> lon >> lat;
// Get handle to error handler
cencalvm::storage::ErrorHandler* errHandler = query.errorHandler();
if (0 == errHandler) {
std::cerr << "Could not get handle to error handler.\n";
return 1;
} // if
// Continue operating on locations until end of file, reading fails,
// or writing fails
while (!fileIn.eof() && fileIn.good() && fileOut.good()) {
const double elevTopo = queryElev(&query, lon, lat);
double elevUpper = (squashOn) ? 0.0 : elevTopo;
double elevLower = (squashOn) ? -elevTopo+elevMin : elevMin;
const double elevVs = searchVs(&query, vsTarget, lon, lat, elevUpper, elevLower);
// If query generated a warning or error, dump message to std::cerr
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
// If query generated an error, then bail out, otherwise reset status
if (cencalvm::storage::ErrorHandler::ERROR == errHandler->status())
return 1;
errHandler->resetStatus();
} // if
const double distIsosurf = (elevVs != 1.0e+6) ? elevTopo - elevVs : -999.0;
// Write values returned by query to output file
fileOut
<< std::resetiosflags(std::ios::scientific)
<< std::setiosflags(std::ios::fixed)
<< std::setprecision(5)
<< std::setw(10) << lon
<< std::setw(9) << lat
<< std::setprecision(1) << std::setw(9) << distIsosurf
<< "\n";
// Read in next location from input file
fileIn >> lon >> lat;
} // while
// Close database
query.close();
// Close input and output files
fileIn.close();
fileOut.close();
// If an error was generated, write error message and bail out
if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) {
std::cerr << errHandler->message();
return 1;
} // if
return 0;
} // main
// End of file
| 28.296804 | 85 | 0.579555 | baagaard-usgs |
a199cf405dac1df8ee49d0b116a55105db367ed5 | 8,393 | hpp | C++ | include/UnityEngine/Internal_DrawTextureArguments.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/Internal_DrawTextureArguments.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/Internal_DrawTextureArguments.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: UnityEngine.Rect
#include "UnityEngine/Rect.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
// Including type: UnityEngine.Vector4
#include "UnityEngine/Vector4.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Texture
class Texture;
// Forward declaring type: Material
class Material;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0xB8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.Internal_DrawTextureArguments
// [TokenAttribute] Offset: FFFFFFFF
// [VisibleToOtherModulesAttribute] Offset: FFFFFFFF
struct Internal_DrawTextureArguments/*, public System::ValueType*/ {
public:
// public UnityEngine.Rect screenRect
// Size: 0x10
// Offset: 0x0
UnityEngine::Rect screenRect;
// Field size check
static_assert(sizeof(UnityEngine::Rect) == 0x10);
// public UnityEngine.Rect sourceRect
// Size: 0x10
// Offset: 0x10
UnityEngine::Rect sourceRect;
// Field size check
static_assert(sizeof(UnityEngine::Rect) == 0x10);
// public System.Int32 leftBorder
// Size: 0x4
// Offset: 0x20
int leftBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 rightBorder
// Size: 0x4
// Offset: 0x24
int rightBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 topBorder
// Size: 0x4
// Offset: 0x28
int topBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 bottomBorder
// Size: 0x4
// Offset: 0x2C
int bottomBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public UnityEngine.Color leftBorderColor
// Size: 0x10
// Offset: 0x30
UnityEngine::Color leftBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color rightBorderColor
// Size: 0x10
// Offset: 0x40
UnityEngine::Color rightBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color topBorderColor
// Size: 0x10
// Offset: 0x50
UnityEngine::Color topBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color bottomBorderColor
// Size: 0x10
// Offset: 0x60
UnityEngine::Color bottomBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color color
// Size: 0x10
// Offset: 0x70
UnityEngine::Color color;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Vector4 borderWidths
// Size: 0x10
// Offset: 0x80
UnityEngine::Vector4 borderWidths;
// Field size check
static_assert(sizeof(UnityEngine::Vector4) == 0x10);
// public UnityEngine.Vector4 cornerRadiuses
// Size: 0x10
// Offset: 0x90
UnityEngine::Vector4 cornerRadiuses;
// Field size check
static_assert(sizeof(UnityEngine::Vector4) == 0x10);
// public System.Boolean smoothCorners
// Size: 0x1
// Offset: 0xA0
bool smoothCorners;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: smoothCorners and: pass
char __padding13[0x3] = {};
// public System.Int32 pass
// Size: 0x4
// Offset: 0xA4
int pass;
// Field size check
static_assert(sizeof(int) == 0x4);
// public UnityEngine.Texture texture
// Size: 0x8
// Offset: 0xA8
UnityEngine::Texture* texture;
// Field size check
static_assert(sizeof(UnityEngine::Texture*) == 0x8);
// public UnityEngine.Material mat
// Size: 0x8
// Offset: 0xB0
UnityEngine::Material* mat;
// Field size check
static_assert(sizeof(UnityEngine::Material*) == 0x8);
// Creating value type constructor for type: Internal_DrawTextureArguments
constexpr Internal_DrawTextureArguments(UnityEngine::Rect screenRect_ = {}, UnityEngine::Rect sourceRect_ = {}, int leftBorder_ = {}, int rightBorder_ = {}, int topBorder_ = {}, int bottomBorder_ = {}, UnityEngine::Color leftBorderColor_ = {}, UnityEngine::Color rightBorderColor_ = {}, UnityEngine::Color topBorderColor_ = {}, UnityEngine::Color bottomBorderColor_ = {}, UnityEngine::Color color_ = {}, UnityEngine::Vector4 borderWidths_ = {}, UnityEngine::Vector4 cornerRadiuses_ = {}, bool smoothCorners_ = {}, int pass_ = {}, UnityEngine::Texture* texture_ = {}, UnityEngine::Material* mat_ = {}) noexcept : screenRect{screenRect_}, sourceRect{sourceRect_}, leftBorder{leftBorder_}, rightBorder{rightBorder_}, topBorder{topBorder_}, bottomBorder{bottomBorder_}, leftBorderColor{leftBorderColor_}, rightBorderColor{rightBorderColor_}, topBorderColor{topBorderColor_}, bottomBorderColor{bottomBorderColor_}, color{color_}, borderWidths{borderWidths_}, cornerRadiuses{cornerRadiuses_}, smoothCorners{smoothCorners_}, pass{pass_}, texture{texture_}, mat{mat_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get instance field reference: public UnityEngine.Rect screenRect
UnityEngine::Rect& dyn_screenRect();
// Get instance field reference: public UnityEngine.Rect sourceRect
UnityEngine::Rect& dyn_sourceRect();
// Get instance field reference: public System.Int32 leftBorder
int& dyn_leftBorder();
// Get instance field reference: public System.Int32 rightBorder
int& dyn_rightBorder();
// Get instance field reference: public System.Int32 topBorder
int& dyn_topBorder();
// Get instance field reference: public System.Int32 bottomBorder
int& dyn_bottomBorder();
// Get instance field reference: public UnityEngine.Color leftBorderColor
UnityEngine::Color& dyn_leftBorderColor();
// Get instance field reference: public UnityEngine.Color rightBorderColor
UnityEngine::Color& dyn_rightBorderColor();
// Get instance field reference: public UnityEngine.Color topBorderColor
UnityEngine::Color& dyn_topBorderColor();
// Get instance field reference: public UnityEngine.Color bottomBorderColor
UnityEngine::Color& dyn_bottomBorderColor();
// Get instance field reference: public UnityEngine.Color color
UnityEngine::Color& dyn_color();
// Get instance field reference: public UnityEngine.Vector4 borderWidths
UnityEngine::Vector4& dyn_borderWidths();
// Get instance field reference: public UnityEngine.Vector4 cornerRadiuses
UnityEngine::Vector4& dyn_cornerRadiuses();
// Get instance field reference: public System.Boolean smoothCorners
bool& dyn_smoothCorners();
// Get instance field reference: public System.Int32 pass
int& dyn_pass();
// Get instance field reference: public UnityEngine.Texture texture
UnityEngine::Texture*& dyn_texture();
// Get instance field reference: public UnityEngine.Material mat
UnityEngine::Material*& dyn_mat();
}; // UnityEngine.Internal_DrawTextureArguments
#pragma pack(pop)
static check_size<sizeof(Internal_DrawTextureArguments), 176 + sizeof(UnityEngine::Material*)> __UnityEngine_Internal_DrawTextureArgumentsSizeCheck;
static_assert(sizeof(Internal_DrawTextureArguments) == 0xB8);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Internal_DrawTextureArguments, "UnityEngine", "Internal_DrawTextureArguments");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 44.643617 | 1,067 | 0.699869 | Fernthedev |
a19a54247e6952d9e54875804e9a3bf0b9012eeb | 472 | cpp | C++ | llvm-project/clang/test/CodeGen/aix-init-priority-attribute.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 305 | 2019-09-14T17:16:05.000Z | 2022-03-31T15:05:20.000Z | llvm-project/clang/test/CodeGen/aix-init-priority-attribute.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 410 | 2019-06-06T20:52:32.000Z | 2022-01-18T14:21:48.000Z | llvm-project/clang/test/CodeGen/aix-init-priority-attribute.cpp | AgesX/llvm | 841024dce9c0263f302491b5c27fa0df6ef222df | [
"MIT"
] | 50 | 2019-05-10T21:12:24.000Z | 2022-01-21T06:39:47.000Z | // RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -x c++ -emit-llvm < %s \
// RUN: 2>&1 | \
// RUN: FileCheck %s
// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -x c++ -emit-llvm < %s \
// RUN: 2>&1 | \
// RUN: FileCheck %s
class test {
int a;
public:
test(int c) { a = c; }
~test() { a = 0; }
};
__attribute__((init_priority(2000)))
test t(1);
// CHECK: fatal error: error in backend: 'init_priority' attribute is not yet supported on AIX
| 23.6 | 94 | 0.597458 | AgesX |
a19ab8c171610582786195a3635f1f91abab6bbd | 646 | hpp | C++ | common/SoapyIfAddrs.hpp | kerel-fs/SoapyRemote | 29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f | [
"BSL-1.0"
] | 89 | 2015-09-13T14:48:08.000Z | 2022-03-26T17:32:18.000Z | common/SoapyIfAddrs.hpp | kerel-fs/SoapyRemote | 29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f | [
"BSL-1.0"
] | 77 | 2015-09-17T05:50:45.000Z | 2022-03-09T14:53:58.000Z | common/SoapyIfAddrs.hpp | kerel-fs/SoapyRemote | 29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f | [
"BSL-1.0"
] | 24 | 2015-09-26T04:54:36.000Z | 2022-02-05T15:10:08.000Z | // Copyright (c) 2018-2018 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "SoapyRemoteConfig.hpp"
#include <string>
#include <vector>
struct SoapyIfAddr
{
SoapyIfAddr(void);
int ethno; //! The ethernet index
int ipVer; //! The ip protocol: 4 or 6
bool isUp; //! Is this link active?
bool isLoopback; //! Is this a loopback interface?
bool isMulticast; //! Does this interface support multicast?
std::string name; //! The interface name: ex eth0
std::string addr; //! The ip address as a string
};
//! Get a list of IF addrs
SOAPY_REMOTE_API std::vector<SoapyIfAddr> listSoapyIfAddrs(void);
| 28.086957 | 65 | 0.693498 | kerel-fs |
a19ccb7eb6ad863b1002be875fb337a6d398ffdd | 587 | cpp | C++ | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 192 | 2016-03-23T04:33:24.000Z | 2022-03-28T14:41:06.000Z | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 9 | 2017-03-08T14:45:16.000Z | 2021-09-06T09:28:47.000Z | Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp | Vinay1705/cs2cpp | d07d3206fb57edb959df8536562909a4d516e359 | [
"MIT"
] | 56 | 2016-03-22T20:37:08.000Z | 2022-03-28T12:20:47.000Z | #include "System.Private.CoreLib.h"
namespace CoreLib { namespace System { namespace Diagnostics {
namespace _ = ::CoreLib::System::Diagnostics;
// Method : System.Diagnostics.StackTrace.GetStackFramesInternal(System.Diagnostics.StackFrameHelper, int, bool, System.Exception)
void StackTrace::GetStackFramesInternal(_::StackFrameHelper* sfh, int32_t iSkip, bool fNeedFileInfo, ::CoreLib::System::Exception* e)
{
throw 3221274624U;
}
}}}
namespace CoreLib { namespace System { namespace Diagnostics {
namespace _ = ::CoreLib::System::Diagnostics;
}}}
| 36.6875 | 137 | 0.735945 | Vinay1705 |
a19fec56457ddb7d51ea5e3314f73962b0615502 | 423 | cpp | C++ | UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | 298 | 2019-05-09T20:54:35.000Z | 2022-03-31T20:10:51.000Z | UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | 14 | 2019-07-07T15:25:15.000Z | 2022-02-05T02:44:29.000Z | UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | 137 | 2019-05-07T20:58:34.000Z | 2022-03-30T08:01:34.000Z | //--------------------------------------------------------------------------------------
// pch.cpp
//
// Include the standard header and generate the precompiled header.
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#pragma warning(disable : 4996)
#include "pch.h"
| 32.538462 | 90 | 0.399527 | ComputeWorks |
a1a1e3d9cb16da0a66c586b22636a9fea28c5acf | 841 | cc | C++ | src/quipper/quipper_lib_test.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | null | null | null | src/quipper/quipper_lib_test.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | 1 | 2019-10-18T07:50:07.000Z | 2019-10-19T02:14:40.000Z | src/quipper/quipper_lib_test.cc | cervantesyu/perf_data_converter | 5fe21942c1db6625963e657f458fea5c30af40e2 | [
"BSD-3-Clause"
] | null | null | null | #include "quipper_lib.h"
#include "compat/test.h"
namespace {
TEST(QuipperLibTest, ValidOldPerfCommandLine) {
int argc = 6;
const char* argv[] = {"quipper", "10", "perf", "record", "-e", "cycles"};
std::vector<string> perf_args;
int perf_duration = 0;
EXPECT_TRUE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args));
EXPECT_EQ(10, perf_duration);
for (int i = 0; i < perf_args.size(); ++i) {
EXPECT_EQ(argv[i + 2], perf_args[i]);
}
}
TEST(QuipperLibTest, InValidOldPerfCommandLine) {
int argc = 6;
const char* argv[] = {
"quipper", "--duration", "10", "--perf_path",
"perf", "--output_file", "file", "-- record -e cycles"};
std::vector<string> perf_args;
int perf_duration = 0;
EXPECT_FALSE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args));
}
} // namespace
| 26.28125 | 78 | 0.646849 | cervantesyu |
a1a35480c731e0dd92a085dc8856a876f3c0f7f9 | 5,295 | cc | C++ | tensorflow/compiler/tf2xla/kernels/const_op.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/tf2xla/kernels/const_op.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/tf2xla/kernels/const_op.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.pb.h"
namespace tensorflow {
namespace {
class ConstOp : public XlaOpKernel {
public:
explicit ConstOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
const TensorProto* proto = nullptr;
OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
proto_ = *proto;
OP_REQUIRES(
ctx, ctx->output_type(0) == proto_.dtype(),
errors::InvalidArgument("Type mismatch between value (",
DataTypeString(proto_.dtype()), ") and dtype (",
DataTypeString(ctx->output_type(0)), ")"));
OP_REQUIRES_OK(ctx, TensorShape::IsValidShape(proto_.tensor_shape()));
}
void Compile(XlaOpKernelContext* ctx) override {
TensorShape shape(proto_.tensor_shape());
xla::XlaBuilder* b = ctx->builder();
// To avoid blowups for large constants filled with the same value,
// recognize that case and emit a scalar broadcast instead.
if (shape.num_elements() > 1) {
switch (proto_.dtype()) {
case DT_BOOL:
if (proto_.bool_val_size() == 1) {
ctx->SetOutput(
0, xla::Broadcast(xla::ConstantR0<bool>(b, proto_.bool_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_FLOAT:
if (proto_.float_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<float>(
b, proto_.float_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_DOUBLE:
if (proto_.double_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<double>(
b, proto_.double_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_COMPLEX64:
if (proto_.scomplex_val_size() == 2) {
ctx->SetOutput(
0,
xla::Broadcast(xla::ConstantR0<xla::complex64>(
b, xla::complex64(proto_.scomplex_val(0),
proto_.scomplex_val(1))),
shape.dim_sizes()));
return;
}
break;
case DT_COMPLEX128:
if (proto_.scomplex_val_size() == 2) {
ctx->SetOutput(
0,
xla::Broadcast(xla::ConstantR0<xla::complex128>(
b, xla::complex128(proto_.dcomplex_val(0),
proto_.dcomplex_val(1))),
shape.dim_sizes()));
return;
}
break;
case DT_INT32:
if (proto_.int_val_size() == 1) {
ctx->SetOutput(
0, xla::Broadcast(xla::ConstantR0<int32>(b, proto_.int_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_INT64:
if (proto_.int64_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<int64>(
b, proto_.int64_val(0)),
shape.dim_sizes()));
return;
}
break;
default:
break;
}
}
// General case
Tensor tensor(proto_.dtype());
OP_REQUIRES(ctx, tensor.FromProto(cpu_allocator(), proto_),
errors::InvalidArgument("Cannot parse tensor from proto: ",
proto_.DebugString()));
ctx->SetConstantOutput(0, tensor);
}
private:
TensorProto proto_;
TF_DISALLOW_COPY_AND_ASSIGN(ConstOp);
};
// XLA_* devices also register a "real" Const operator so we suppress the
// dummy operator using CompilationOnly().
REGISTER_XLA_OP(Name("Const").CompilationOnly(), ConstOp);
} // namespace
} // namespace tensorflow
| 38.649635 | 81 | 0.526346 | uve |
a1a6c6f24b6a5c64c43f463d70b3c15476546b26 | 8,561 | cpp | C++ | src/CryptoNoteCore/Transactions/TransactionUtils.cpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/CryptoNoteCore/Transactions/TransactionUtils.cpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/CryptoNoteCore/Transactions/TransactionUtils.cpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin 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.
//
// Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "CryptoNoteCore/Transactions/TransactionUtils.h"
#include <unordered_set>
#include <numeric>
#include <iterator>
#include <exception>
#include <algorithm>
#include <Xi/Exceptions.hpp>
#include <crypto/crypto.h>
#include "CryptoNoteCore/Account.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#include "CryptoNoteCore/Transactions/TransactionExtra.h"
using namespace Crypto;
namespace CryptoNote {
bool checkInputsKeyimagesDiff(const CryptoNote::TransactionPrefix& tx) {
std::unordered_set<Crypto::KeyImage> ki;
for (const auto& in : tx.inputs) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
if (!ki.insert(keyInput->keyImage).second)
return false;
}
}
return true;
}
// TransactionInput helper functions
size_t getRequiredSignaturesCount(const TransactionInput& in) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
return keyInput->outputIndices.size();
}
return 0;
}
uint64_t getTransactionInputAmount(const TransactionInput& in) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
return keyInput->amount;
} else {
return 0;
}
}
uint64_t getTransactionInputAmount(const Transaction& transaction) {
return std::accumulate(transaction.inputs.begin(), transaction.inputs.end(), 0ULL,
[](uint64_t acc, const auto& input) { return acc + getTransactionInputAmount(input); });
}
uint64_t getTransactionOutputAmount(const TransactionOutput& out) {
if (const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(out))) {
return amountOutput->amount;
} else {
return 0ULL;
}
}
uint64_t getTransactionOutputAmount(const Transaction& transaction) {
return std::accumulate(transaction.outputs.begin(), transaction.outputs.end(), 0ULL,
[](uint64_t acc, const auto& out) { return acc + getTransactionOutputAmount(out); });
}
boost::optional<KeyImage> getTransactionInputKeyImage(const TransactionInput& input) {
if (auto keyInput = std::get_if<KeyInput>(&input)) {
return boost::optional<KeyImage>{keyInput->keyImage};
} else {
return boost::optional<KeyImage>{};
}
}
std::vector<KeyImage> getTransactionKeyImages(const Transaction& transaction) {
std::vector<KeyImage> reval{};
reval.reserve(transaction.inputs.size());
for (const auto& input : transaction.inputs) {
auto keyImage = getTransactionInputKeyImage(input);
if (keyImage) {
reval.push_back(*keyImage);
}
}
return reval;
}
std::vector<PublicKey> getTransactionOutputKeys(const Transaction& transaction) {
std::vector<PublicKey> keys;
keys.reserve(transaction.outputs.size());
for (const auto& output : transaction.outputs) {
const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(output));
if (amountOutput == nullptr) {
continue;
}
const auto keyTarget = std::get_if<KeyOutput>(std::addressof(amountOutput->target));
if (keyTarget == nullptr) {
continue;
}
keys.emplace_back(keyTarget->key);
}
return keys;
}
TransactionTypes::InputType getTransactionInputType(const TransactionInput& in) {
if (std::holds_alternative<KeyInput>(in)) {
return TransactionTypes::InputType::Key;
}
if (std::holds_alternative<BaseInput>(in)) {
return TransactionTypes::InputType::Generating;
}
return TransactionTypes::InputType::Invalid;
}
const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) {
if (transaction.inputs.size() <= index) {
throw std::runtime_error("Transaction input index out of range");
}
return transaction.inputs[index];
}
const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index,
TransactionTypes::InputType type) {
const auto& input = getInputChecked(transaction, index);
if (getTransactionInputType(input) != type) {
throw std::runtime_error("Unexpected transaction input type");
}
return input;
}
// TransactionOutput helper functions
TransactionTypes::OutputType getTransactionOutputType(const TransactionOutput& out) {
if (std::holds_alternative<TransactionAmountOutput>(out)) {
return TransactionTypes::OutputType::Amount;
}
return TransactionTypes::OutputType::Invalid;
}
TransactionTypes::OutputTargetType getTransactionOutputTargetType(const TransactionOutputTarget& out) {
if (std::holds_alternative<KeyOutput>(out)) {
return TransactionTypes::OutputTargetType::Key;
}
return TransactionTypes::OutputTargetType::Invalid;
}
const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) {
if (transaction.outputs.size() <= index) {
throw std::runtime_error("Transaction output index out of range");
}
return transaction.outputs[index];
}
const TransactionOutputTarget& getOutputTargetChecked(const TransactionOutput& out) {
if (!std::holds_alternative<TransactionAmountOutput>(out)) {
throw std::runtime_error{"Unexpected transaction output type"};
}
return std::get<TransactionAmountOutput>(out).target;
}
const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index,
TransactionTypes::OutputType outType,
TransactionTypes::OutputTargetType type) {
const auto& output = getOutputChecked(transaction, index);
const auto outputType = getTransactionOutputType(output);
if (outputType != outType) {
throw std::runtime_error{"Unexpected transaction output type"};
}
const auto& target = getOutputTargetChecked(output);
if (getTransactionOutputTargetType(target) != type) {
throw std::runtime_error("Unexpected transaction output target type");
}
return output;
}
bool isOutToKey(const Crypto::PublicKey& spendPublicKey, const Crypto::PublicKey& outKey,
const Crypto::KeyDerivation& derivation, size_t keyIndex) {
Crypto::PublicKey pk;
derive_public_key(derivation, keyIndex, spendPublicKey, pk);
return pk == outKey;
}
bool findOutputsToAccount(const CryptoNote::TransactionPrefix& transaction, const AccountPublicAddress& addr,
const SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount) {
using namespace Xi;
AccountKeys keys;
keys.address = addr;
// only view secret key is used, spend key is not needed
keys.viewSecretKey = viewSecretKey;
::Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(transaction.extra);
amount = 0;
size_t keyIndex = 0;
uint32_t outputIndex = 0;
::Crypto::KeyDerivation derivation;
generate_key_derivation(txPubKey, keys.viewSecretKey, derivation);
for (const TransactionOutput& o : transaction.outputs) {
exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<TransactionAmountOutput>(o));
const auto& amountOutput = std::get<TransactionAmountOutput>(o);
exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<KeyOutput>(amountOutput.target));
const auto& keyOutput = std::get<KeyOutput>(amountOutput.target);
if (is_out_to_acc(keys, keyOutput, derivation, keyIndex)) {
out.push_back(outputIndex);
amount += amountOutput.amount;
}
++keyIndex;
++outputIndex;
}
return true;
}
std::vector<uint32_t> getTransactionInputIndices(const KeyInput& input) {
std::vector<uint32_t> indices{};
if (input.outputIndices.empty())
return indices;
indices.resize(input.outputIndices.size());
indices[0] = input.outputIndices[0];
for (size_t i = 1; i < input.outputIndices.size(); ++i) {
indices[i] = indices[i - 1] + input.outputIndices[i];
}
return indices;
}
} // namespace CryptoNote
| 33.311284 | 113 | 0.726667 | ElSamaritan |
a1a7059f2e89693609ee893afda08fc805e57bc9 | 337 | cpp | C++ | C++ Classes/Operator Overloading (+).cpp | Aditya9056/cpp-mastering-concepts | b8bd0df0adb960fa6fc57fff5648d34e720bdc11 | [
"MIT"
] | 1 | 2021-05-16T10:41:07.000Z | 2021-05-16T10:41:07.000Z | C++ Classes/Operator Overloading (+).cpp | Aditya9056/cpp-mastering-concepts | b8bd0df0adb960fa6fc57fff5648d34e720bdc11 | [
"MIT"
] | null | null | null | C++ Classes/Operator Overloading (+).cpp | Aditya9056/cpp-mastering-concepts | b8bd0df0adb960fa6fc57fff5648d34e720bdc11 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class hello
{
public:
int var;
hello()
{
}
hello(int a) : var(a)
{
}
hello operator+(hello &obj)
{
hello res;
res.var = this->var+obj.var;
return res;
}
};
main()
{
hello obj1(12), obj2(55);
hello res = obj1+obj2;
cout<<res.var<<endl;
}
| 8.868421 | 30 | 0.534125 | Aditya9056 |
a1abc5986ded3b0ed1f8bd49e395d4e1b3ab9968 | 1,258 | cpp | C++ | aws-cpp-sdk-medialive/source/model/ListOfferingsResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-medialive/source/model/ListOfferingsResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-medialive/source/model/ListOfferingsResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/medialive/model/ListOfferingsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::MediaLive::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListOfferingsResult::ListOfferingsResult()
{
}
ListOfferingsResult::ListOfferingsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListOfferingsResult& ListOfferingsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
if(jsonValue.ValueExists("offerings"))
{
Array<JsonView> offeringsJsonList = jsonValue.GetArray("offerings");
for(unsigned offeringsIndex = 0; offeringsIndex < offeringsJsonList.GetLength(); ++offeringsIndex)
{
m_offerings.push_back(offeringsJsonList[offeringsIndex].AsObject());
}
}
return *this;
}
| 25.16 | 106 | 0.749603 | Neusoft-Technology-Solutions |
a1acc106d6ff085e86454b5a88158df1999a5e60 | 4,135 | cpp | C++ | benchmarks/rf_feats_kernel_comp.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | benchmarks/rf_feats_kernel_comp.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | benchmarks/rf_feats_kernel_comp.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | #include <shogun/base/init.h>
#include <shogun/features/RandomFourierDotFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/kernel/normalizer/SqrtDiagKernelNormalizer.h>
#include <shogun/classifier/svm/LibLinear.h>
#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/classifier/svm/LibSVM.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/evaluation/PRCEvaluation.h>
#include <shogun/lib/Time.h>
#include <stdio.h>
#include <ctime>
using namespace shogun;
/** Code that compares the times needed to train
* a linear svm using the RandomFourierDotFeatures class
* vs a non-linear svm using the Gaussian Kernel.
*/
int main(int argv, char** argc)
{
init_shogun_with_defaults();
int32_t dims[] = {10, 100, 1000};
int32_t vecs[] = {10000, 100000, 1000000};
CTime* timer = new CTime(false);
float64_t epsilon = 0.001;
float64_t lin_C = 0.1;
float64_t non_lin_C = 0.1;
CPRCEvaluation* evaluator = new CPRCEvaluation();
CSqrtDiagKernelNormalizer* normalizer = new CSqrtDiagKernelNormalizer(true);
SG_REF(normalizer);
for (index_t d=0; d<4; d++)
{
int32_t num_dim = dims[d];
SG_SPRINT("Starting experiment for number of dimensions = %d\n", num_dim);
for (index_t v=0; v<3; v++)
{
int32_t num_vecs = vecs[v];
SG_SPRINT(" Using %d examples\n", num_vecs);
SGMatrix<float64_t> mat(num_dim, num_vecs);
SGVector<float64_t> labs(num_vecs);
for (index_t i=0; i<num_vecs; i++)
{
for (index_t j=0; j<num_dim; j++)
{
if ((i+j)%2==0)
{
labs[i] = -1;
mat(j,i) = CMath::random(0,1) + 0.5;
}
else
{
labs[i] = 1;
mat(j,i) = CMath::random(0,1) - 0.5;
}
}
}
SGVector<float64_t> params(1);
params[0] = 8;
SG_SPRINT(" Using kernel_width = %f\n", params[0]);
CDenseFeatures<float64_t>* dense_feats = new CDenseFeatures<float64_t>(mat);
SG_REF(dense_feats);
CBinaryLabels* labels = new CBinaryLabels(labs);
SG_REF(labels);
/** LibLinear SVM using RandomFourierDotFeatures */
int32_t D[] = {50, 100, 300, 1000};
for (index_t d=0; d<4; d++)
{
CRandomFourierDotFeatures* r_feats = new CRandomFourierDotFeatures(
dense_feats, D[d], KernelName::GAUSSIAN, params);
//CLibLinear* lin_svm = new CLibLinear(C, r_feats, labels);
CSVMOcas* lin_svm = new CSVMOcas(lin_C, r_feats, labels);
lin_svm->set_epsilon(epsilon);
clock_t t = clock();
timer->start();
lin_svm->train();
t = clock() - t;
timer->stop();
SG_SPRINT("\tSVMOcas using RFDotFeatures(D=%d) finished training. Took %fs (or %fs), ",
D[d], timer->time_diff_sec(), (float64_t) t /CLOCKS_PER_SEC);
t = clock();
timer->start();
CBinaryLabels* predicted = CLabelsFactory::to_binary(lin_svm->apply());
timer->stop();
t = clock() - t;
float64_t auPRC = evaluator->evaluate(predicted, labels);
SG_SPRINT("SVMOcas auPRC=%f (Applying took %fs (%fs)\n", auPRC,
timer->time_diff_sec(), (float64_t) t / CLOCKS_PER_SEC);
SG_UNREF(lin_svm);
SG_UNREF(predicted);
}
/** End of LibLinear code */
/** LibSVM using Gaussian Kernel */
CGaussianKernel* kernel = new CGaussianKernel(dense_feats, dense_feats, params[0]);
//kernel->set_normalizer(normalizer);
CLibSVM* svm = new CLibSVM(non_lin_C, kernel, labels);
svm->set_epsilon(epsilon);
clock_t t = clock();
timer->start();
svm->train();
t = clock() - t;
timer->stop();
SG_SPRINT("\tLibSVM using GaussianKernel finished training. Took %fs (or %fs), ",
timer->time_diff_sec(), (float64_t) t /CLOCKS_PER_SEC);
t = clock();
timer->start();
CBinaryLabels* predicted = CLabelsFactory::to_binary(svm->apply());
timer->stop();
t = clock() - t;
float64_t auPRC = evaluator->evaluate(predicted, labels);
SG_SPRINT("LibSVM auPRC=%f (Applying took %fs (%fs)\n", auPRC,
timer->time_diff_sec(), (float64_t) t / CLOCKS_PER_SEC);
SG_UNREF(svm);
SG_UNREF(predicted);
/** End of LibSVM code */
SG_UNREF(labels);
SG_UNREF(dense_feats);
}
}
SG_UNREF(timer);
SG_UNREF(evaluator);
SG_UNREF(normalizer);
exit_shogun();
}
| 30.182482 | 91 | 0.662394 | srgnuclear |
a1adbc63c0c8c3af12f36f286e651b630b745e9b | 26,287 | cpp | C++ | unit-tests/co/test-tpdo-sdo.cpp | DroidDrive/lely-core | 2ec4560f513264a53d2afaedecdae4a49a39023c | [
"Apache-2.0"
] | 1 | 2021-10-02T21:08:05.000Z | 2021-10-02T21:08:05.000Z | unit-tests/co/test-tpdo-sdo.cpp | DroidDrive/lely-core | 2ec4560f513264a53d2afaedecdae4a49a39023c | [
"Apache-2.0"
] | null | null | null | unit-tests/co/test-tpdo-sdo.cpp | DroidDrive/lely-core | 2ec4560f513264a53d2afaedecdae4a49a39023c | [
"Apache-2.0"
] | null | null | null | /**@file
* This file is part of the CANopen Library Unit Test Suite.
*
* @copyright 2020 N7 Space Sp. z o.o.
*
* Unit Test Suite was developed under a programme of,
* and funded by, the European Space Agency.
*
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <memory>
#include <CppUTest/TestHarness.h>
#include <lely/co/csdo.h>
#include <lely/co/tpdo.h>
#include <lely/co/sdo.h>
#include <libtest/allocators/default.hpp>
#include <libtest/tools/lely-cpputest-ext.hpp>
#include <libtest/tools/lely-unit-test.hpp>
#include "holder/dev.hpp"
#include "holder/obj.hpp"
TEST_BASE(CO_SdoTpdoBase) {
TEST_BASE_SUPER(CO_SdoTpdoBase);
Allocators::Default allocator;
const co_unsigned8_t DEV_ID = 0x01u;
const co_unsigned16_t TPDO_NUM = 0x0001u;
co_dev_t* dev = nullptr;
can_net_t* net = nullptr;
co_tpdo_t* tpdo = nullptr;
std::unique_ptr<CoDevTHolder> dev_holder;
std::unique_ptr<CoObjTHolder> obj1800;
std::unique_ptr<CoObjTHolder> obj1a00;
void CreateObjInDev(std::unique_ptr<CoObjTHolder> & obj_holder,
co_unsigned16_t idx) {
obj_holder.reset(new CoObjTHolder(idx));
CHECK(obj_holder->Get() != nullptr);
CHECK_EQUAL(0, co_dev_insert_obj(dev, obj_holder->Take()));
}
void SetPdoCommCobid(const co_unsigned32_t cobid) {
co_sub_t* const sub_comm_cobid = co_dev_find_sub(dev, 0x1800u, 0x01u);
CHECK(sub_comm_cobid != nullptr);
co_sub_set_val_u32(sub_comm_cobid, cobid);
}
void RestartTPDO() {
co_tpdo_stop(tpdo);
co_tpdo_start(tpdo);
}
TEST_SETUP() {
LelyUnitTest::DisableDiagnosticMessages();
net = can_net_create(allocator.ToAllocT());
CHECK(net != nullptr);
dev_holder.reset(new CoDevTHolder(DEV_ID));
dev = dev_holder->Get();
CHECK(dev != nullptr);
CreateObjInDev(obj1800, 0x1800u);
CreateObjInDev(obj1a00, 0x1a00u);
// 0x00 - highest sub-index supported
obj1800->InsertAndSetSub(0x00u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x02u));
// 0x01 - COB-ID used by TPDO
obj1800->InsertAndSetSub(0x01u, CO_DEFTYPE_UNSIGNED32,
co_unsigned32_t(DEV_ID));
// 0x02 - transmission type
obj1800->InsertAndSetSub(0x02u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0xfeu)); // event-driven
tpdo = co_tpdo_create(net, dev, TPDO_NUM);
CHECK(tpdo != nullptr);
CoCsdoDnCon::Clear();
}
TEST_TEARDOWN() {
co_tpdo_destroy(tpdo);
dev_holder.reset();
can_net_destroy(net);
}
};
TEST_GROUP_BASE(CO_SdoTpdo1800, CO_SdoTpdoBase) {
int clang_format_fix = 0; // unused
void Insert1800Values() {
// adjust highest subindex supported
co_sub_t* const sub = co_dev_find_sub(dev, 0x1800u, 0x00u);
CHECK(sub != nullptr);
co_sub_set_val_u8(sub, 0x06u);
// 0x03 - inhibit time
obj1800->InsertAndSetSub(0x03u, CO_DEFTYPE_UNSIGNED16,
co_unsigned16_t(0x0000u)); // n*100 us
// 0x04 - reserved (compatibility entry)
obj1800->InsertAndSetSub(0x04u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x00u));
// 0x05 - event-timer
obj1800->InsertAndSetSub(0x05u, CO_DEFTYPE_UNSIGNED16,
co_unsigned16_t(0x0000u)); // ms
// 0x06 - sync value
obj1800->InsertAndSetSub(0x06u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x00u));
}
TEST_SETUP() {
TEST_BASE_SETUP();
Insert1800Values();
co_tpdo_start(tpdo);
}
TEST_TEARDOWN() {
co_tpdo_stop(tpdo);
TEST_BASE_TEARDOWN();
}
};
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_TYPE_LEN_HI abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TooLongData) {
const co_unsigned16_t data = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x00u, CO_DEFTYPE_UNSIGNED16, &data,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_TYPE_LEN_HI, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_NO_WRITE abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_HighestSubIdxSupported) {
const co_unsigned8_t num_of_elems = 0x7fu;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_elems, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_WRITE, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidSameAsPrevious) {
const co_unsigned32_t cobid = DEV_ID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToValid_NewCanId) {
SetPdoCommCobid(DEV_ID);
RestartTPDO();
const co_unsigned32_t cobid = DEV_ID + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidInvalidToValid_NewCanId) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned32_t cobid = DEV_ID + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToValid_FrameBit) {
const co_unsigned32_t cobid = DEV_ID | CO_PDO_COBID_FRAME;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: COB-ID with frame bit and CO_PDO_COBID_VALID set is downloaded
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToInvalid_ExtendedId_NoFrameBit) {
co_unsigned32_t cobid = DEV_ID | (1u << 28u) | CO_PDO_COBID_VALID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: COB-ID with CO_PDO_COBID_VALID set is downloaded
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToInvalid) {
const co_unsigned32_t cobid = DEV_ID | CO_PDO_COBID_VALID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeSameAsPrevious) {
const co_unsigned8_t transmission_type = 0xfeu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeReserved) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xf1u;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_SynchronousRTR_RTRBitSet) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xfcu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_EventDrivenRTR_RTRBitSet) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xfdu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_RTROnly_RTRBitNotSet) {
const co_unsigned8_t transmission_type = 0xfdu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeMax) {
const co_unsigned8_t transmission_type = 0xffu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType) {
const co_unsigned8_t transmission_type = 0x35u;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTimeSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned16_t inhibit_time = 0x0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTimeValidTPDO) {
const co_unsigned16_t inhibit_time = 0x0001u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTime) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned16_t inhibit_time = 0x0003u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_NO_SUB abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CompatibilityEntry) {
const co_unsigned8_t compat = 0x44u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x04u, CO_DEFTYPE_UNSIGNED8, &compat,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_SUB, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_EventTimerSameAsPrevious) {
const co_unsigned16_t event_timer = 0x0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x05u, CO_DEFTYPE_UNSIGNED16,
&event_timer, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_EventTimer) {
const co_unsigned16_t event_timer = 0x3456u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x05u, CO_DEFTYPE_UNSIGNED16,
&event_timer, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncSameAsPrevious) {
const co_unsigned8_t sync = 0x00u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncNewValue_TPDOValid) {
const co_unsigned8_t sync = 0x01u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncNewValue_TPDOInvalid) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t sync = 0x01u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
TEST_GROUP_BASE(CO_SdoTpdo1a00, CO_SdoTpdoBase) {
std::unique_ptr<CoObjTHolder> obj2021;
void Insert1a00Values() {
// 0x00 - number of mapped application objects in PDO
obj1a00->InsertAndSetSub(0x00, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(CO_PDO_NUM_MAPS));
// 0x01-0x40 - application objects
for (co_unsigned8_t i = 0x01u; i <= CO_PDO_NUM_MAPS; ++i) {
obj1a00->InsertAndSetSub(i, CO_DEFTYPE_UNSIGNED32, co_unsigned32_t(0));
}
}
void Set1a00Sub1Mapping(co_unsigned32_t mapping) {
co_sub_t* const sub = co_dev_find_sub(dev, 0x1a00u, 0x01u);
co_sub_set_val_u32(sub, mapping);
}
void Insert2021Values() {
assert(obj2021->Get());
obj2021->InsertAndSetSub(0x00u, CO_DEFTYPE_UNSIGNED32,
co_unsigned32_t(0xdeadbeefu));
co_sub_t* sub2021 = obj2021->GetLastSub();
co_sub_set_access(sub2021, CO_ACCESS_RW);
co_sub_set_pdo_mapping(sub2021, 1);
}
void SetNumOfMappings(co_unsigned8_t mappings_num) {
co_sub_t* const sub_map_n = co_dev_find_sub(dev, 0x1a00u, 0x00u);
co_sub_set_val_u8(sub_map_n, mappings_num);
}
TEST_SETUP() {
TEST_BASE_SETUP();
Insert1a00Values();
co_tpdo_start(tpdo);
CoCsdoDnCon::Clear();
}
TEST_TEARDOWN() {
co_tpdo_stop(tpdo);
TEST_BASE_TEARDOWN();
}
};
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PDO_LEN abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsLenGreaterThanMax) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x202100ffu);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PDO_LEN, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_EmptyMapping) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x00000000u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: too long value is downloaded
// then: CO_SDO_AC_TYPE_LEN_HI abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsRequestFailed) {
const co_unsigned32_t data = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED32, &data,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_TYPE_LEN_HI, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_NO_OBJ abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsNonExistingObjMapping) {
Set1a00Sub1Mapping(0xffff0000u);
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_OBJ, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = CO_PDO_NUM_MAPS;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsValidTPDO) {
const co_unsigned8_t num_of_mappings = 2u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsTooManyObjsToMap) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = CO_PDO_NUM_MAPS + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsNoMappings) {
const co_unsigned8_t num_of_mappings = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappings) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_NO_OBJ abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingNonexisting) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
RestartTPDO();
const co_unsigned32_t mapping = 0xffff0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_OBJ, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingNumOfMappingsNonzero) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x01u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingValidTPDO) {
SetPdoCommCobid(DEV_ID);
SetNumOfMappings(0x01u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_Mapping) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingZeros) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x00000000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
| 31.44378 | 79 | 0.703199 | DroidDrive |
a1af3a43f51140f778db2b8b0fa4df33354010ec | 49,825 | cc | C++ | src/storage/blobfs/blob.cc | Prajwal-Koirala/fuchsia | ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795 | [
"BSD-2-Clause"
] | 2 | 2021-12-29T10:11:08.000Z | 2022-01-04T15:37:09.000Z | src/storage/blobfs/blob.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-09-19T21:55:09.000Z | 2021-12-19T03:34:53.000Z | src/storage/blobfs/blob.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/storage/blobfs/blob.h"
#include <assert.h>
#include <ctype.h>
#include <fidl/fuchsia.io/cpp/wire.h>
#include <fuchsia/device/c/fidl.h>
#include <lib/fit/defer.h>
#include <lib/sync/completion.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/zx/status.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <zircon/assert.h>
#include <zircon/device/vfs.h>
#include <zircon/errors.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <algorithm>
#include <iterator>
#include <memory>
#include <string_view>
#include <utility>
#include <vector>
#include <fbl/algorithm.h>
#include <fbl/ref_ptr.h>
#include <fbl/string_buffer.h>
#include <safemath/checked_math.h>
#include "src/lib/digest/digest.h"
#include "src/lib/digest/merkle-tree.h"
#include "src/lib/digest/node-digest.h"
#include "src/lib/storage/vfs/cpp/journal/data_streamer.h"
#include "src/lib/storage/vfs/cpp/metrics/events.h"
#include "src/storage/blobfs/blob_data_producer.h"
#include "src/storage/blobfs/blob_layout.h"
#include "src/storage/blobfs/blob_verifier.h"
#include "src/storage/blobfs/blobfs.h"
#include "src/storage/blobfs/common.h"
#include "src/storage/blobfs/compression/chunked.h"
#include "src/storage/blobfs/compression_settings.h"
#include "src/storage/blobfs/format.h"
#include "src/storage/blobfs/iterator/allocated_extent_iterator.h"
#include "src/storage/blobfs/iterator/block_iterator.h"
#include "src/storage/blobfs/iterator/extent_iterator.h"
#include "src/storage/blobfs/iterator/node_populator.h"
#include "src/storage/blobfs/iterator/vector_extent_iterator.h"
#include "src/storage/blobfs/metrics.h"
namespace blobfs {
// Data used exclusively during writeback.
struct Blob::WriteInfo {
// See comment for merkle_tree() below.
static constexpr size_t kPreMerkleTreePadding = kBlobfsBlockSize;
WriteInfo() = default;
// Not copyable or movable because merkle_tree_creator has a pointer to digest.
WriteInfo(const WriteInfo&) = delete;
WriteInfo& operator=(const WriteInfo&) = delete;
// We leave room in the merkle tree buffer to add padding before the merkle tree which might be
// required with the compact blob layout.
uint8_t* merkle_tree() const {
ZX_ASSERT_MSG(merkle_tree_buffer, "Merkle tree buffer should not be nullptr");
return merkle_tree_buffer.get() + kPreMerkleTreePadding;
}
uint64_t bytes_written = 0;
std::vector<ReservedExtent> extents;
std::vector<ReservedNode> node_indices;
std::optional<BlobCompressor> compressor;
// Target compressed size for this blob indicates the possible on-disk compressed size in bytes.
std::optional<uint64_t> target_compression_size_;
// The fused write error. Once writing has failed, we return the same error on subsequent
// writes in case a higher layer dropped the error and returned a short write instead.
zx_status_t write_error = ZX_OK;
// As data is written, we build the merkle tree using this.
digest::MerkleTreeCreator merkle_tree_creator;
// The merkle tree creator stores the root digest here.
uint8_t digest[digest::kSha256Length];
// The merkle tree creator stores the rest of the tree here. The buffer includes space for
// padding. See the comment for merkle_tree() above.
std::unique_ptr<uint8_t[]> merkle_tree_buffer;
// The old blob that this write is replacing.
fbl::RefPtr<Blob> old_blob;
// Sets the target_compression_size_ field.
void SetTargetCompressionSize(uint64_t size) {
target_compression_size_ = std::make_optional(size);
}
};
zx_status_t Blob::VerifyNullBlob() const {
ZX_ASSERT_MSG(blob_size_ == 0, "Inode blob size is not zero :%lu", blob_size_);
auto verifier_or = BlobVerifier::CreateWithoutTree(digest(), blobfs_->GetMetrics(), 0,
&blobfs_->blob_corruption_notifier());
if (verifier_or.is_error())
return verifier_or.error_value();
return verifier_or->Verify(nullptr, 0, 0);
}
uint64_t Blob::SizeData() const {
std::lock_guard lock(mutex_);
if (state() == BlobState::kReadable)
return blob_size_;
return 0;
}
Blob::Blob(Blobfs* bs, const digest::Digest& digest) : CacheNode(bs->vfs(), digest), blobfs_(bs) {
write_info_ = std::make_unique<WriteInfo>();
}
Blob::Blob(Blobfs* bs, uint32_t node_index, const Inode& inode)
: CacheNode(bs->vfs(), digest::Digest(inode.merkle_root_hash)),
blobfs_(bs),
state_(BlobState::kReadable),
syncing_state_(SyncingState::kDone),
map_index_(node_index),
blob_size_(inode.blob_size),
block_count_(inode.block_count) {
write_info_ = std::make_unique<WriteInfo>();
}
zx_status_t Blob::WriteNullBlob() {
ZX_DEBUG_ASSERT(blob_size_ == 0);
ZX_DEBUG_ASSERT(block_count_ == 0);
if (zx_status_t status = VerifyNullBlob(); status != ZX_OK) {
return status;
}
BlobTransaction transaction;
if (zx_status_t status = WriteMetadata(transaction, CompressionAlgorithm::kUncompressed);
status != ZX_OK) {
return status;
}
transaction.Commit(*blobfs_->GetJournal(), {},
[blob = fbl::RefPtr(this)]() { blob->CompleteSync(); });
return MarkReadable(CompressionAlgorithm::kUncompressed);
}
zx_status_t Blob::PrepareWrite(uint64_t size_data, bool compress) {
if (size_data > 0 && fbl::round_up(size_data, kBlobfsBlockSize) == 0) {
// Fail early if |size_data| would overflow when rounded up to block size.
return ZX_ERR_OUT_OF_RANGE;
}
std::lock_guard lock(mutex_);
if (state() != BlobState::kEmpty) {
return ZX_ERR_BAD_STATE;
}
// Fail early if target_compression_size is set is not sane.
if (write_info_->target_compression_size_.has_value() &&
(write_info_->target_compression_size_.value() == 0 ||
(write_info_->target_compression_size_.value()) == std::numeric_limits<uint64_t>::max())) {
FX_LOGS(ERROR) << "Target compressed size is invalid: "
<< write_info_->target_compression_size_.value();
return ZX_ERR_INVALID_ARGS;
}
blob_size_ = size_data;
// Reserve a node for blob's inode. We might need more nodes for extents later.
zx_status_t status = blobfs_->GetAllocator()->ReserveNodes(1, &write_info_->node_indices);
if (status != ZX_OK) {
return status;
}
map_index_ = write_info_->node_indices[0].index();
// For compressed blobs, we only write into the compression buffer. For uncompressed blobs we
// write into the data vmo.
if (compress) {
write_info_->compressor =
BlobCompressor::Create(blobfs_->write_compression_settings(), blob_size_);
if (!write_info_->compressor) {
// TODO(fxbug.dev/70356)Make BlobCompressor::Create return the actual error instead.
// Replace ZX_ERR_INTERNAL with the correct error once fxbug.dev/70356 is fixed.
FX_LOGS(ERROR) << "Failed to initialize compressor: " << ZX_ERR_INTERNAL;
return ZX_ERR_INTERNAL;
}
} else if (blob_size_ != 0) {
if ((status = PrepareDataVmoForWriting()) != ZX_OK) {
return status;
}
}
write_info_->merkle_tree_creator.SetUseCompactFormat(
ShouldUseCompactMerkleTreeFormat(GetBlobLayoutFormat(blobfs_->Info())));
if ((status = write_info_->merkle_tree_creator.SetDataLength(blob_size_)) != ZX_OK) {
return status;
}
const size_t tree_len = write_info_->merkle_tree_creator.GetTreeLength();
// Allow for zero padding before and after.
write_info_->merkle_tree_buffer =
std::make_unique<uint8_t[]>(tree_len + WriteInfo::kPreMerkleTreePadding);
if ((status = write_info_->merkle_tree_creator.SetTree(write_info_->merkle_tree(), tree_len,
&write_info_->digest,
sizeof(write_info_->digest))) != ZX_OK) {
return status;
}
set_state(BlobState::kDataWrite);
// Special case for the null blob: We skip the write phase.
return blob_size_ == 0 ? WriteNullBlob() : ZX_OK;
}
void Blob::SetOldBlob(Blob& blob) {
std::lock_guard lock(mutex_);
write_info_->old_blob = fbl::RefPtr(&blob);
}
zx_status_t Blob::SpaceAllocate(uint32_t block_count) {
TRACE_DURATION("blobfs", "Blobfs::SpaceAllocate", "block_count", block_count);
ZX_ASSERT_MSG(block_count != 0, "Block count should not be zero.");
fs::Ticker ticker(blobfs_->GetMetrics()->Collecting());
std::vector<ReservedExtent> extents;
std::vector<ReservedNode> nodes;
// Reserve space for the blob.
const uint64_t reserved_blocks = blobfs_->GetAllocator()->ReservedBlockCount();
zx_status_t status = blobfs_->GetAllocator()->ReserveBlocks(block_count, &extents);
if (status == ZX_ERR_NO_SPACE && reserved_blocks > 0) {
// It's possible that a blob has just been unlinked but has yet to be flushed through the
// journal, and the blocks are still reserved, so if that looks likely, force a flush and then
// try again. This might need to be revisited if/when blobfs becomes multi-threaded.
sync_completion_t sync;
blobfs_->Sync([&](zx_status_t) { sync_completion_signal(&sync); });
sync_completion_wait(&sync, ZX_TIME_INFINITE);
status = blobfs_->GetAllocator()->ReserveBlocks(block_count, &extents);
}
if (status != ZX_OK) {
return status;
}
if (extents.size() > kMaxBlobExtents) {
FX_LOGS(ERROR) << "Error: Block reservation requires too many extents (" << extents.size()
<< " vs " << kMaxBlobExtents << " max)";
return ZX_ERR_BAD_STATE;
}
const ExtentCountType extent_count = safemath::checked_cast<ExtentCountType>(extents.size());
// Reserve space for all additional nodes necessary to contain this blob. The inode has already
// been reserved in Blob::PrepareWrite. Hence, we need to reserve one less node here.
size_t node_count = NodePopulator::NodeCountForExtents(extent_count) - 1;
status = blobfs_->GetAllocator()->ReserveNodes(node_count, &nodes);
if (status != ZX_OK) {
return status;
}
write_info_->extents = std::move(extents);
write_info_->node_indices.insert(write_info_->node_indices.end(),
std::make_move_iterator(nodes.begin()),
std::make_move_iterator(nodes.end()));
block_count_ = block_count;
blobfs_->GetMetrics()->UpdateAllocation(blob_size_, ticker.End());
return ZX_OK;
}
bool Blob::IsDataLoaded() const {
// Data is served out of the paged_vmo() when paged and the unpaged_backing_data_ when not, so
// either indicates validity.
return paged_vmo().is_valid() || unpaged_backing_data_.is_valid();
}
zx_status_t Blob::WriteMetadata(BlobTransaction& transaction,
CompressionAlgorithm compression_algorithm) {
TRACE_DURATION("blobfs", "Blobfs::WriteMetadata");
assert(state() == BlobState::kDataWrite);
if (block_count_) {
// We utilize the NodePopulator class to take our reserved blocks and nodes and fill the
// persistent map with an allocated inode / container.
// If |on_node| is invoked on a node, it means that node was necessary to represent this
// blob. Persist the node back to durable storage.
auto on_node = [this, &transaction](uint32_t node_index) {
blobfs_->PersistNode(node_index, transaction);
};
// If |on_extent| is invoked on an extent, it was necessary to represent this blob. Persist
// the allocation of these blocks back to durable storage.
auto on_extent = [this, &transaction](ReservedExtent& extent) {
blobfs_->PersistBlocks(extent, transaction);
return NodePopulator::IterationCommand::Continue;
};
auto mapped_inode_or_error = blobfs_->GetNode(map_index_);
if (mapped_inode_or_error.is_error()) {
return mapped_inode_or_error.status_value();
}
InodePtr mapped_inode = std::move(mapped_inode_or_error).value();
*mapped_inode = Inode{
.blob_size = blob_size_,
.block_count = block_count_,
};
digest().CopyTo(mapped_inode->merkle_root_hash);
NodePopulator populator(blobfs_->GetAllocator(), std::move(write_info_->extents),
std::move(write_info_->node_indices));
zx_status_t status = populator.Walk(on_node, on_extent);
ZX_ASSERT_MSG(status == ZX_OK, "populator.Walk failed with error: %s",
zx_status_get_string(status));
SetCompressionAlgorithm(&*mapped_inode, compression_algorithm);
} else {
// Special case: Empty node.
ZX_DEBUG_ASSERT(write_info_->node_indices.size() == 1);
auto mapped_inode_or_error = blobfs_->GetNode(map_index_);
if (mapped_inode_or_error.is_error()) {
return mapped_inode_or_error.status_value();
}
InodePtr mapped_inode = std::move(mapped_inode_or_error).value();
*mapped_inode = Inode{};
digest().CopyTo(mapped_inode->merkle_root_hash);
blobfs_->GetAllocator()->MarkInodeAllocated(std::move(write_info_->node_indices[0]));
blobfs_->PersistNode(map_index_, transaction);
}
return ZX_OK;
}
zx_status_t Blob::WriteInternal(const void* data, size_t len,
std::optional<size_t> requested_offset, size_t* actual) {
TRACE_DURATION("blobfs", "Blobfs::WriteInternal", "data", data, "len", len);
*actual = 0;
if (len == 0) {
return ZX_OK;
}
if (state() != BlobState::kDataWrite) {
if (state() == BlobState::kError && write_info_ && write_info_->write_error != ZX_OK) {
return write_info_->write_error;
}
return ZX_ERR_BAD_STATE;
}
const size_t to_write = std::min(len, blob_size_ - write_info_->bytes_written);
const size_t offset = write_info_->bytes_written;
if (requested_offset && *requested_offset != offset) {
FX_LOGS(ERROR) << "only append is currently supported (requested_offset: " << *requested_offset
<< ", expected: " << offset << ")";
return ZX_ERR_NOT_SUPPORTED;
}
*actual = to_write;
write_info_->bytes_written += to_write;
if (write_info_->compressor) {
if (zx_status_t status = write_info_->compressor->Update(data, to_write); status != ZX_OK) {
return status;
}
} else {
// In the uncompressed case, the backing vmo should have been set up to write into already.
ZX_ASSERT(unpaged_backing_data_.is_valid());
if (zx_status_t status = unpaged_backing_data_.write(data, offset, to_write); status != ZX_OK) {
FX_LOGS(ERROR) << "VMO write failed: " << zx_status_get_string(status);
return status;
}
}
if (zx_status_t status = write_info_->merkle_tree_creator.Append(data, to_write);
status != ZX_OK) {
FX_LOGS(ERROR) << "MerkleTreeCreator::Append failed: " << zx_status_get_string(status);
return status;
}
// More data to write.
if (write_info_->bytes_written < blob_size_) {
return ZX_OK;
}
if (zx_status_t status = Commit(); status != ZX_OK) {
// Record the status so that if called again, we return the same status again. This is done
// because it's possible that the end-user managed to partially write some data to this blob in
// which case the error could be dropped (by zxio or some other layer) and a short write
// returned instead. If this happens, the end-user will retry at which point it's helpful if we
// return the same error rather than ZX_ERR_BAD_STATE (see above).
write_info_->write_error = status;
MarkError();
return status;
}
return ZX_OK;
}
zx_status_t Blob::Commit() {
if (digest() != write_info_->digest) {
// Downloaded blob did not match provided digest.
FX_LOGS(ERROR) << "downloaded blob did not match provided digest " << digest();
return ZX_ERR_IO_DATA_INTEGRITY;
}
const size_t merkle_size = write_info_->merkle_tree_creator.GetTreeLength();
bool compress = write_info_->compressor.has_value();
if (compress) {
if (zx_status_t status = write_info_->compressor->End(); status != ZX_OK) {
return status;
}
// If we're using the chunked compressor, abort compression if we're not going to get any
// savings. We can't easily do it for the other compression formats without changing the
// decompression API to support streaming.
if (write_info_->compressor->algorithm() == CompressionAlgorithm::kChunked &&
fbl::round_up(write_info_->compressor->Size() + merkle_size, kBlobfsBlockSize) >=
fbl::round_up(blob_size_ + merkle_size, kBlobfsBlockSize)) {
compress = false;
}
}
fs::Duration generation_time;
const uint64_t data_size = compress ? write_info_->compressor->Size() : blob_size_;
auto blob_layout = BlobLayout::CreateFromSizes(GetBlobLayoutFormat(blobfs_->Info()), blob_size_,
data_size, GetBlockSize());
if (blob_layout.is_error()) {
FX_LOGS(ERROR) << "Failed to create blob layout: " << blob_layout.status_string();
return blob_layout.status_value();
}
const uint32_t total_block_count = blob_layout->TotalBlockCount();
if (zx_status_t status = SpaceAllocate(total_block_count); status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to allocate " << total_block_count
<< " blocks for the blob: " << zx_status_get_string(status);
return status;
}
std::variant<std::monostate, DecompressBlobDataProducer, SimpleBlobDataProducer> data;
BlobDataProducer* data_ptr = nullptr;
fzl::VmoMapper data_mapping;
CompressionAlgorithm compression_algorithm = CompressionAlgorithm::kUncompressed;
if (compress) {
// The data comes from the compression buffer.
data_ptr = &data.emplace<SimpleBlobDataProducer>(
cpp20::span(static_cast<const uint8_t*>(write_info_->compressor->Data()),
write_info_->compressor->Size()));
compression_algorithm = write_info_->compressor->algorithm();
} else if (write_info_->compressor) {
// In this case, we've decided against compressing because there are no savings, so we have to
// decompress.
if (auto producer_or = DecompressBlobDataProducer::Create(*write_info_->compressor, blob_size_);
producer_or.is_error()) {
return producer_or.error_value();
} else {
data_ptr = &data.emplace<DecompressBlobDataProducer>(std::move(producer_or).value());
}
} else {
// The data comes from the data buffer.
ZX_ASSERT(unpaged_backing_data_.is_valid());
uint64_t block_aligned_size = fbl::round_up(blob_size_, kBlobfsBlockSize);
if (zx_status_t status = data_mapping.Map(unpaged_backing_data_, 0, block_aligned_size);
status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to map blob VMO: " << zx_status_get_string(status);
return status;
}
data_ptr = &data.emplace<SimpleBlobDataProducer>(
cpp20::span(static_cast<const uint8_t*>(data_mapping.start()), blob_size_));
}
SimpleBlobDataProducer merkle(cpp20::span(write_info_->merkle_tree(), merkle_size));
MergeBlobDataProducer producer = [&]() {
switch (blob_layout->Format()) {
case BlobLayoutFormat::kDeprecatedPaddedMerkleTreeAtStart:
// Write the merkle data first followed by the data. The merkle data should be a multiple
// of the block size so we don't need any padding.
ZX_ASSERT_MSG(merkle.GetRemainingBytes() % kBlobfsBlockSize == 0,
"Merkle data size :%lu not a multiple of blobfs block size %lu",
merkle.GetRemainingBytes(), kBlobfsBlockSize);
return MergeBlobDataProducer(merkle, *data_ptr, /*padding=*/0);
case BlobLayoutFormat::kCompactMerkleTreeAtEnd:
// Write the data followed by the merkle tree. There might be some padding between the
// data and the merkle tree.
return MergeBlobDataProducer(
*data_ptr, merkle, blob_layout->MerkleTreeOffset() - data_ptr->GetRemainingBytes());
}
}();
fs::DataStreamer streamer(blobfs_->GetJournal(), blobfs_->WriteBufferBlockCount());
if (zx_status_t status = WriteData(total_block_count, producer, streamer); status != ZX_OK) {
return status;
}
// No more data to write. Flush to disk.
fs::Ticker ticker(blobfs_->GetMetrics()->Collecting()); // Tracking enqueue time.
// Enqueue the blob's final data work. Metadata must be enqueued separately.
zx_status_t data_status = ZX_ERR_IO;
sync_completion_t data_written;
// Issue the signal when the callback is destroyed rather than in the callback because the
// callback won't get called in some error paths.
auto data_written_finished = fit::defer([&] { sync_completion_signal(&data_written); });
auto write_all_data = streamer.Flush().then(
[&data_status, data_written_finished = std::move(data_written_finished)](
const fpromise::result<void, zx_status_t>& result) {
data_status = result.is_ok() ? ZX_OK : result.error();
return result;
});
// Discard things we don't need any more. This has to be after the Flush call above to ensure
// all data has been copied from these buffers.
data_mapping.Unmap();
unpaged_backing_data_.reset();
// FreePagedVmo() will return the reference that keeps this object alive on behalf of the paging
// system so we can free it outside the lock. However, when a Blob is being written it can't be
// mapped so we know there should be no pager reference. Otherwise, calling FreePagedVmo() will
// make future uses of the mapped data go invalid.
//
// If in the future we need to support memory mapping a paged VMO (like we allow mapping and using
// the portions of a blob that are already known), then this code will have to be changed to not
// free the VMO here (which will in turn require other changes).
fbl::RefPtr<fs::Vnode> pager_reference = FreePagedVmo();
ZX_DEBUG_ASSERT(!pager_reference);
write_info_->compressor.reset();
// Wrap all pending writes with a strong reference to this Blob, so that it stays
// alive while there are writes in progress acting on it.
BlobTransaction transaction;
if (zx_status_t status = WriteMetadata(transaction, compression_algorithm); status != ZX_OK) {
return status;
}
if (write_info_->old_blob) {
zx_status_t status = blobfs_->FreeInode(write_info_->old_blob->Ino(), transaction);
ZX_ASSERT_MSG(status == ZX_OK, "FreeInode failed with error: %s", zx_status_get_string(status));
auto& cache = GetCache();
status = cache.Evict(write_info_->old_blob);
ZX_ASSERT_MSG(status == ZX_OK, "Failed to evict old blob with error: %s",
zx_status_get_string(status));
status = cache.Add(fbl::RefPtr(this));
ZX_ASSERT_MSG(status == ZX_OK, "Failed to add blob to cache with error: %s",
zx_status_get_string(status));
}
transaction.Commit(*blobfs_->GetJournal(), std::move(write_all_data),
[self = fbl::RefPtr(this)]() {});
// It's not safe to continue until all data has been written because we might need to reload it
// (e.g. if the blob is immediately read after writing), and the journal caches data in ring
// buffers, so wait until that has happened. We don't need to wait for the metadata because we
// cache that.
sync_completion_wait(&data_written, ZX_TIME_INFINITE);
if (data_status != ZX_OK) {
return data_status;
}
blobfs_->GetMetrics()->UpdateClientWrite(block_count_ * kBlobfsBlockSize, merkle_size,
ticker.End(), generation_time);
return MarkReadable(compression_algorithm);
}
zx_status_t Blob::WriteData(uint32_t block_count, BlobDataProducer& producer,
fs::DataStreamer& streamer) {
BlockIterator block_iter(std::make_unique<VectorExtentIterator>(write_info_->extents));
const uint64_t data_start = DataStartBlock(blobfs_->Info());
return StreamBlocks(
&block_iter, block_count,
[&](uint64_t vmo_offset, uint64_t dev_offset, uint32_t block_count) {
while (block_count) {
if (producer.NeedsFlush()) {
// Queued operations might point at buffers that are about to be invalidated, so we have
// to force those operations to be issued which will cause them to be copied.
streamer.IssueOperations();
}
auto data = producer.Consume(block_count * kBlobfsBlockSize);
if (data.is_error())
return data.error_value();
ZX_ASSERT_MSG(!data->empty(), "Data span for writing should not be empty.");
storage::UnbufferedOperation op = {.data = data->data(),
.op = {
.type = storage::OperationType::kWrite,
.dev_offset = dev_offset + data_start,
.length = data->size() / kBlobfsBlockSize,
}};
// Pad if necessary.
const size_t alignment = data->size() % kBlobfsBlockSize;
if (alignment > 0) {
memset(const_cast<uint8_t*>(data->end()), 0, kBlobfsBlockSize - alignment);
++op.op.length;
}
block_count -= op.op.length;
dev_offset += op.op.length;
streamer.StreamData(std::move(op));
} // while (block_count)
return ZX_OK;
});
}
zx_status_t Blob::MarkReadable(CompressionAlgorithm compression_algorithm) {
if (readable_event_.is_valid()) {
zx_status_t status = readable_event_.signal(0u, ZX_USER_SIGNAL_0);
if (status != ZX_OK) {
MarkError();
return status;
}
}
set_state(BlobState::kReadable);
syncing_state_ = SyncingState::kSyncing;
write_info_.reset();
return ZX_OK;
}
void Blob::MarkError() {
if (state_ != BlobState::kError) {
if (zx_status_t status = GetCache().Evict(fbl::RefPtr(this)); status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to evict blob from cache";
}
set_state(BlobState::kError);
}
}
zx_status_t Blob::GetReadableEvent(zx::event* out) {
TRACE_DURATION("blobfs", "Blobfs::GetReadableEvent");
zx_status_t status;
// This is the first 'wait until read event' request received.
if (!readable_event_.is_valid()) {
status = zx::event::create(0, &readable_event_);
if (status != ZX_OK) {
return status;
} else if (state() == BlobState::kReadable) {
readable_event_.signal(0u, ZX_USER_SIGNAL_0);
}
}
zx::event out_event;
status = readable_event_.duplicate(ZX_RIGHTS_BASIC, &out_event);
if (status != ZX_OK) {
return status;
}
*out = std::move(out_event);
return ZX_OK;
}
zx_status_t Blob::CloneDataVmo(zx_rights_t rights, zx::vmo* out_vmo, size_t* out_size) {
TRACE_DURATION("blobfs", "Blobfs::CloneVmo", "rights", rights);
if (state_ != BlobState::kReadable) {
return ZX_ERR_BAD_STATE;
}
if (blob_size_ == 0) {
return ZX_ERR_BAD_STATE;
}
auto status = LoadVmosFromDisk();
if (status != ZX_OK) {
return status;
}
zx::vmo clone;
status = paged_vmo().create_child(ZX_VMO_CHILD_SNAPSHOT_AT_LEAST_ON_WRITE, 0, blob_size_, &clone);
if (status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to create child VMO: " << zx_status_get_string(status);
return status;
}
DidClonePagedVmo();
// Only add exec right to VMO if explictly requested. (Saves a syscall if we're just going to
// drop the right back again in replace() call below.)
if (rights & ZX_RIGHT_EXECUTE) {
// Check if the VMEX resource held by Blobfs is valid and fail if it isn't. We do this to make
// sure that we aren't implicitly relying on the ZX_POL_AMBIENT_MARK_VMO_EXEC job policy.
const zx::resource& vmex = blobfs_->vmex_resource();
if (!vmex.is_valid()) {
FX_LOGS(ERROR) << "No VMEX resource available, executable blobs unsupported";
return ZX_ERR_NOT_SUPPORTED;
}
if ((status = clone.replace_as_executable(vmex, &clone)) != ZX_OK) {
return status;
}
}
// Narrow rights to those requested.
if ((status = clone.replace(rights, &clone)) != ZX_OK) {
return status;
}
*out_vmo = std::move(clone);
*out_size = blob_size_;
return ZX_OK;
}
zx_status_t Blob::ReadInternal(void* data, size_t len, size_t off, size_t* actual) {
TRACE_DURATION("blobfs", "Blobfs::ReadInternal", "len", len, "off", off);
// The common case is that the blob is already loaded. To allow multiple readers, it's important
// to avoid taking an exclusive lock unless necessary.
fs::SharedLock lock(mutex_);
// Only expect this to be called when the blob is open. The fidl API guarantees this but tests
// can easily forget to open the blob before trying to read.
ZX_DEBUG_ASSERT(open_count() > 0);
if (state_ != BlobState::kReadable)
return ZX_ERR_BAD_STATE;
if (!IsDataLoaded()) {
// Release the shared lock and load the data from within an exclusive lock. LoadVmosFromDisk()
// can be called multiple times so the race condition caused by this unlocking will be benign.
lock.unlock();
{
// Load the VMO data from within the lock.
std::lock_guard exclusive_lock(mutex_);
if (zx_status_t status = LoadVmosFromDisk(); status != ZX_OK)
return status;
}
lock.lock();
// The readable state should never change (from the value we checked at the top of this
// function) by attempting to load from disk, that only happens when we try to write.
ZX_DEBUG_ASSERT(state_ == BlobState::kReadable);
}
if (blob_size_ == 0) {
*actual = 0;
return ZX_OK;
}
if (off >= blob_size_) {
*actual = 0;
return ZX_OK;
}
if (len > (blob_size_ - off)) {
len = blob_size_ - off;
}
ZX_DEBUG_ASSERT(IsDataLoaded());
// Send reads through the pager. This will potentially page-in the data by reentering us from the
// kernel on the pager thread.
ZX_DEBUG_ASSERT(paged_vmo().is_valid());
if (zx_status_t status = paged_vmo().read(data, off, len); status != ZX_OK)
return status;
*actual = len;
return ZX_OK;
}
zx_status_t Blob::LoadPagedVmosFromDisk() {
ZX_ASSERT_MSG(!IsDataLoaded(), "Data VMO is not loaded.");
// If there is an overridden cache policy for pager-backed blobs, apply it now. Otherwise the
// system-wide default will be used.
std::optional<CachePolicy> cache_policy = blobfs_->pager_backed_cache_policy();
if (cache_policy) {
set_overridden_cache_policy(*cache_policy);
}
zx::status<LoaderInfo> load_info_or =
blobfs_->loader().LoadBlob(map_index_, &blobfs_->blob_corruption_notifier());
if (load_info_or.is_error())
return load_info_or.error_value();
// Make the vmo.
if (auto status = EnsureCreatePagedVmo(load_info_or->layout->FileBlockAlignedSize());
status.is_error())
return status.error_value();
// Commit the other load information.
loader_info_ = std::move(*load_info_or);
return ZX_OK;
}
zx_status_t Blob::LoadVmosFromDisk() {
// We expect the file to be open in FIDL for this to be called. Whether the paged vmo is
// registered with the pager is dependent on the HasReferences() flag so this should not get
// out-of-sync.
ZX_DEBUG_ASSERT(HasReferences());
if (IsDataLoaded())
return ZX_OK;
if (blob_size_ == 0) {
// Null blobs don't need any loading, just verification that they're correct.
return VerifyNullBlob();
}
zx_status_t status = LoadPagedVmosFromDisk();
if (status == ZX_OK)
SetPagedVmoName(true);
syncing_state_ = SyncingState::kDone;
return status;
}
zx_status_t Blob::PrepareDataVmoForWriting() {
if (IsDataLoaded())
return ZX_OK;
uint64_t block_aligned_size = fbl::round_up(blob_size_, kBlobfsBlockSize);
if (zx_status_t status = zx::vmo::create(block_aligned_size, 0, &unpaged_backing_data_);
status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to create data vmo: " << zx_status_get_string(status);
return status;
}
return ZX_OK;
}
zx_status_t Blob::QueueUnlink() {
std::lock_guard lock(mutex_);
deletable_ = true;
// Attempt to purge in case the blob has been unlinked with no open fds
return TryPurge();
}
zx_status_t Blob::Verify() {
{
std::lock_guard lock(mutex_);
if (auto status = LoadVmosFromDisk(); status != ZX_OK)
return status;
}
// For non-pager-backed blobs, commit the entire blob in memory. This will cause all of the pages
// to be verified as they are read in (or for the null bob we just verify immediately). If the
// commit operation fails due to a verification failure, we do propagate the error back via the
// return status.
//
// This is a read-only operation on the blob so can be done with the shared lock. Since it will
// reenter the Blob object on the pager thread to satisfy this request, it actually MUST be done
// with only the shared lock or the reentrance on the pager thread will deadlock us.
{
fs::SharedLock lock(mutex_);
// There is a race condition if somehow this blob was unloaded in between the above exclusive
// lock and the shared lock in this block. Currently this is not possible because there is only
// one thread processing fidl messages and paging events on the pager threads can't unload the
// blob.
//
// But in the future certain changes might make this theoretically possible (though very
// difficult to imagine in practice). If this were to happen, we would prefer to err on the side
// of reporting a blob valid rather than mistakenly reporting errors that might cause a valid
// blob to be deleted.
if (state_ != BlobState::kReadable)
return ZX_OK;
if (blob_size_ == 0) {
// It's the null blob, so just verify.
return VerifyNullBlob();
}
return paged_vmo().op_range(ZX_VMO_OP_COMMIT, 0, blob_size_, nullptr, 0);
}
}
void Blob::OnNoPagedVmoClones() {
// Override the default behavior of PagedVnode to avoid clearing the paged_vmo. We keep this
// alive for caching purposes as long as this object is alive, and this object's lifetime is
// managed by the BlobCache.
if (!HasReferences()) {
// Mark the name to help identify the VMO is unused.
SetPagedVmoName(false);
// Hint that the VMO's pages are no longer needed, and can be evicted under memory pressure. If
// a page is accessed again, it will lose the hint.
zx_status_t status = paged_vmo().op_range(ZX_VMO_OP_DONT_NEED, 0, blob_size_, nullptr, 0);
if (status != ZX_OK) {
FX_LOGS(WARNING) << "Hinting DONT_NEED on blob " << digest()
<< " failed: " << zx_status_get_string(status);
}
// This might have been the last reference to a deleted blob, so try purging it.
if (zx_status_t status = TryPurge(); status != ZX_OK) {
FX_LOGS(WARNING) << "Purging blob " << digest()
<< " failed: " << zx_status_get_string(status);
}
}
}
BlobCache& Blob::GetCache() { return blobfs_->GetCache(); }
bool Blob::ShouldCache() const {
std::lock_guard lock(mutex_);
return state() == BlobState::kReadable;
}
void Blob::ActivateLowMemory() {
// The reference returned by FreePagedVmo() needs to be released outside of the lock since it
// could be keeping this class in scope.
fbl::RefPtr<fs::Vnode> pager_reference;
{
std::lock_guard lock(mutex_);
// We shouldn't be putting the blob into a low-memory state while it is still mapped.
//
// It is common for tests to trigger this assert during Blobfs tear-down. This will happen when
// the "no clones" message was not delivered before destruction. This can happen if the test
// code kept a vmo reference, but can also happen when there are no clones because the delivery
// of this message depends on running the message loop which is easy to skip in a test.
//
// Often, the solution is to call RunUntilIdle() on the loop after the test code has cleaned up
// its mappings but before deleting Blobfs. This will allow the pending notifications to be
// delivered.
ZX_ASSERT_MSG(!has_clones(), "Cannot put blob in low memory state as its mapped via clones.");
pager_reference = FreePagedVmo();
unpaged_backing_data_.reset();
loader_info_ = LoaderInfo(); // Release the verifiers and associated Merkle data.
}
// When the pager_reference goes out of scope here, it could delete |this|.
}
Blob::~Blob() { ActivateLowMemory(); }
fs::VnodeProtocolSet Blob::GetProtocols() const { return fs::VnodeProtocol::kFile; }
bool Blob::ValidateRights(fs::Rights rights) const {
// To acquire write access to a blob, it must be empty.
//
// TODO(fxbug.dev/67659) If we run FIDL on multiple threads (we currently don't) there is a race
// condition here where another thread could start writing at the same time. Decide whether we
// support FIDL from multiple threads and if so, whether this condition is important.
std::lock_guard lock(mutex_);
return !rights.write || state() == BlobState::kEmpty;
}
zx_status_t Blob::GetNodeInfoForProtocol([[maybe_unused]] fs::VnodeProtocol protocol,
[[maybe_unused]] fs::Rights rights,
fs::VnodeRepresentation* info) {
std::lock_guard lock(mutex_);
zx::event observer;
if (zx_status_t status = GetReadableEvent(&observer); status != ZX_OK) {
return status;
}
*info = fs::VnodeRepresentation::File{.observer = std::move(observer)};
return ZX_OK;
}
zx_status_t Blob::Read(void* data, size_t len, size_t off, size_t* out_actual) {
TRACE_DURATION("blobfs", "Blob::Read", "len", len, "off", off);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kRead);
zx_status_t status = ReadInternal(data, len, off, out_actual);
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
return status;
}
zx_status_t Blob::Write(const void* data, size_t len, size_t offset, size_t* out_actual) {
TRACE_DURATION("blobfs", "Blob::Write", "len", len, "off", offset);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kWrite);
std::lock_guard lock(mutex_);
zx_status_t status = WriteInternal(data, len, {offset}, out_actual);
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
return status;
}
zx_status_t Blob::Append(const void* data, size_t len, size_t* out_end, size_t* out_actual) {
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kAppend);
std::lock_guard lock(mutex_);
zx_status_t status = WriteInternal(data, len, std::nullopt, out_actual);
if (state() == BlobState::kDataWrite) {
ZX_DEBUG_ASSERT(write_info_ != nullptr);
*out_end = write_info_->bytes_written;
} else {
*out_end = blob_size_;
}
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
return status;
}
zx_status_t Blob::GetAttributes(fs::VnodeAttributes* a) {
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kGetAttr);
// SizeData() expects to be called outside the lock.
auto content_size = SizeData();
std::lock_guard lock(mutex_);
*a = fs::VnodeAttributes();
a->mode = V_TYPE_FILE | V_IRUSR | V_IXUSR;
a->inode = map_index_;
a->content_size = content_size;
a->storage_size = block_count_ * kBlobfsBlockSize;
a->link_count = 1;
a->creation_time = 0;
a->modification_time = 0;
event.mutable_latency_event()->mutable_options()->success = true;
return ZX_OK;
}
zx_status_t Blob::Truncate(size_t len) {
TRACE_DURATION("blobfs", "Blob::Truncate", "len", len);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kTruncate);
zx_status_t status =
PrepareWrite(len, blobfs_->ShouldCompress() && len > kCompressionSizeThresholdBytes);
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
return status;
}
void Blob::SetTargetCompressionSize(uint64_t size) {
std::lock_guard lock(mutex_);
write_info_.get()->SetTargetCompressionSize(size);
}
#ifdef __Fuchsia__
zx::status<std::string> Blob::GetDevicePath() const { return blobfs_->Device()->GetDevicePath(); }
zx_status_t Blob::GetVmo(fuchsia_io::wire::VmoFlags flags, zx::vmo* out_vmo, size_t* out_size) {
TRACE_DURATION("blobfs", "Blob::GetVmo", "flags", static_cast<uint64_t>(flags));
std::lock_guard lock(mutex_);
// Only expect this to be called when the blob is open. The fidl API guarantees this but tests
// can easily forget to open the blob before getting the VMO.
ZX_DEBUG_ASSERT(open_count() > 0);
if (flags & fuchsia_io::wire::VmoFlags::kWrite) {
return ZX_ERR_NOT_SUPPORTED;
} else if (flags & fuchsia_io::wire::VmoFlags::kSharedBuffer) {
return ZX_ERR_NOT_SUPPORTED;
}
// Let clients map and set the names of their VMOs.
zx_rights_t rights = ZX_RIGHTS_BASIC | ZX_RIGHT_MAP | ZX_RIGHTS_PROPERTY;
// We can ignore fuchsia_io_VMO_FLAG_PRIVATE, since private / shared access to the underlying VMO
// can both be satisfied with a clone due to the immutability of blobfs blobs.
rights |= (flags & fuchsia_io::wire::VmoFlags::kRead) ? ZX_RIGHT_READ : 0;
rights |= (flags & fuchsia_io::wire::VmoFlags::kExecute) ? ZX_RIGHT_EXECUTE : 0;
return CloneDataVmo(rights, out_vmo, out_size);
}
#endif // defined(__Fuchsia__)
void Blob::Sync(SyncCallback on_complete) {
// This function will issue its callbacks on either the current thread or the journal thread. The
// vnode interface says this is OK.
TRACE_DURATION("blobfs", "Blob::Sync");
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kSync);
SyncingState state;
{
std::scoped_lock guard(mutex_);
state = syncing_state_;
}
switch (state) {
case SyncingState::kDataIncomplete: {
// It doesn't make sense to sync a partial blob since it can't have its proper
// content-addressed name without all the data.
on_complete(ZX_ERR_BAD_STATE);
break;
}
case SyncingState::kSyncing: {
// The blob data is complete. When this happens the Blob object will automatically write its
// metadata, but it may not get flushed for some time. This call both encourages the sync to
// happen "soon" and provides a way to get notified when it does.
auto trace_id = TRACE_NONCE();
TRACE_FLOW_BEGIN("blobfs", "Blob.sync", trace_id);
blobfs_->Sync([event = std::move(event),
on_complete = std::move(on_complete)](zx_status_t status) mutable {
// Note: this may be executed on an arbitrary thread.
on_complete(status);
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
});
break;
}
case SyncingState::kDone: {
// All metadata has already been synced. Calling Sync() is a no-op.
on_complete(ZX_OK);
event.mutable_latency_event()->mutable_options()->success = true;
break;
}
}
}
// This function will get called on an arbitrary pager worker thread.
void Blob::VmoRead(uint64_t offset, uint64_t length) {
TRACE_DURATION("blobfs", "Blob::VmoRead", "offset", offset, "length", length);
// It's important that this function use only a shared read lock. This is for performance (to
// allow multiple page requests to be run in parallel) and to prevent deadlock with the non-paged
// Read() path. The non-paged path is implemented by reading from the vmo which will recursively
// call into this code and taking an exclusive lock would deadlock.
fs::SharedLock lock(mutex_);
if (!paged_vmo()) {
// Races with calling FreePagedVmo() on another thread can result in stale read requests. Ignore
// them if the VMO is gone.
return;
}
ZX_DEBUG_ASSERT(IsDataLoaded());
if (is_corrupt_) {
FX_LOGS(ERROR) << "Blobfs failing page request because blob was previously found corrupt.";
if (auto error_result =
paged_vfs()->ReportPagerError(paged_vmo(), offset, length, ZX_ERR_BAD_STATE);
error_result.is_error()) {
FX_LOGS(ERROR) << "Failed to report pager error to kernel: " << error_result.status_string();
}
return;
}
auto page_supplier = PageLoader::PageSupplier(
[paged_vfs = paged_vfs(), dest_vmo = &paged_vmo()](
uint64_t offset, uint64_t length, const zx::vmo& aux_vmo, uint64_t aux_offset) {
return paged_vfs->SupplyPages(*dest_vmo, offset, length, aux_vmo, aux_offset);
});
PagerErrorStatus pager_error_status =
blobfs_->page_loader().TransferPages(std::move(page_supplier), offset, length, loader_info_);
if (pager_error_status != PagerErrorStatus::kOK) {
FX_LOGS(ERROR) << "Pager failed to transfer pages to the blob, error: "
<< zx_status_get_string(static_cast<zx_status_t>(pager_error_status));
if (auto error_result = paged_vfs()->ReportPagerError(
paged_vmo(), offset, length, static_cast<zx_status_t>(pager_error_status));
error_result.is_error()) {
FX_LOGS(ERROR) << "Failed to report pager error to kernel: " << error_result.status_string();
}
// We've signaled a failure and unblocked outstanding page requests for this range. If the pager
// error was a verification error, fail future requests as well - we should not service further
// page requests on a corrupt blob.
//
// Note that we cannot simply detach the VMO from the pager here. There might be outstanding
// page requests which have been queued but are yet to be serviced. These need to be handled
// correctly - if the VMO is detached, there will be no way for us to communicate failure to
// the kernel, since zx_pager_op_range() requires a valid pager VMO handle. Without being able
// to make a call to zx_pager_op_range() to indicate a failed page request, the faulting thread
// would hang indefinitely.
if (pager_error_status == PagerErrorStatus::kErrDataIntegrity)
is_corrupt_ = true;
}
}
bool Blob::HasReferences() const { return open_count() > 0 || has_clones(); }
void Blob::CompleteSync() {
// Called on the journal thread when the syncing is complete.
{
std::scoped_lock guard(mutex_);
syncing_state_ = SyncingState::kDone;
}
}
void Blob::WillTeardownFilesystem() {
// Be careful to release the pager reference outside the lock.
fbl::RefPtr<fs::Vnode> pager_reference;
{
std::lock_guard lock(mutex_);
pager_reference = FreePagedVmo();
}
// When pager_reference goes out of scope here, it could cause |this| to be deleted.
}
zx_status_t Blob::OpenNode([[maybe_unused]] ValidatedOptions options,
fbl::RefPtr<Vnode>* out_redirect) {
std::lock_guard lock(mutex_);
if (IsDataLoaded() && open_count() == 1) {
// Just went from an unopened node that already had data to an opened node (the open_count()
// reflects the new state).
//
// This normally means that the node was closed but cached, and we're not re-opening it. This
// means we have to mark things as being open and register for the corresponding notifications.
//
// It's also possible to get in this state if there was a memory mapping for a file that
// was otherwise closed. In that case we don't need to do anything but the operations here
// can be performed multiple times with no bad effects. Avoiding these calls in the "mapped but
// opened" state would mean checking for no mappings which bundles this code more tightly to
// the HasReferences() implementation that is better avoided.
SetPagedVmoName(true);
}
return ZX_OK;
}
zx_status_t Blob::CloseNode() {
std::lock_guard lock(mutex_);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kClose);
if (paged_vmo() && !HasReferences()) {
// Mark the name to help identify the VMO is unused.
SetPagedVmoName(false);
// Hint that the VMO's pages are no longer needed, and can be evicted under memory pressure. If
// a page is accessed again, it will lose the hint.
zx_status_t status = paged_vmo().op_range(ZX_VMO_OP_DONT_NEED, 0, blob_size_, nullptr, 0);
if (status != ZX_OK) {
FX_LOGS(WARNING) << "Hinting DONT_NEED on blob " << digest()
<< " failed: " << zx_status_get_string(status);
}
}
// Attempt purge in case blob was unlinked prior to close.
zx_status_t status = TryPurge();
event.mutable_latency_event()->mutable_options()->success = (status == ZX_OK);
return status;
}
zx_status_t Blob::TryPurge() {
if (Purgeable()) {
return Purge();
}
return ZX_OK;
}
zx_status_t Blob::Purge() {
ZX_DEBUG_ASSERT(Purgeable());
if (state_ == BlobState::kReadable) {
// A readable blob should only be purged if it has been unlinked.
ZX_ASSERT_MSG(deletable_, "Should not purge blob which is not unlinked.");
BlobTransaction transaction;
if (zx_status_t status = blobfs_->FreeInode(map_index_, transaction); status != ZX_OK)
return status;
transaction.Commit(*blobfs_->GetJournal());
}
// If the blob is in the error state, it should have already been evicted from
// the cache (see MarkError).
if (state_ != BlobState::kError) {
if (zx_status_t status = GetCache().Evict(fbl::RefPtr(this)); status != ZX_OK)
return status;
}
set_state(BlobState::kPurged);
return ZX_OK;
}
uint32_t Blob::GetBlockSize() const { return blobfs_->Info().block_size; }
void Blob::SetPagedVmoName(bool active) {
fbl::StringBuffer<ZX_MAX_NAME_LEN> name;
if (active) {
FormatBlobDataVmoName(digest(), &name);
} else {
FormatInactiveBlobDataVmoName(digest(), &name);
}
// Ignore failures, the name is for informational purposes only.
paged_vmo().set_property(ZX_PROP_NAME, name.data(), name.size());
}
} // namespace blobfs
| 39.796326 | 100 | 0.692745 | Prajwal-Koirala |
a1b06e552b4ea9847d43278528cd5350a862aef3 | 3,654 | hpp | C++ | phonelibs/acado/include/acado/objective/mayer_term.hpp | Neptos/openpilot | 01914a1a91ade18bd7aead99e7d1bf38cd22ad89 | [
"MIT"
] | 116 | 2018-03-07T09:00:10.000Z | 2020-04-06T18:37:45.000Z | phonelibs/acado/include/acado/objective/mayer_term.hpp | Neptos/openpilot | 01914a1a91ade18bd7aead99e7d1bf38cd22ad89 | [
"MIT"
] | 66 | 2020-04-09T20:27:57.000Z | 2022-01-27T14:39:24.000Z | phonelibs/acado/include/acado/objective/mayer_term.hpp | Neptos/openpilot | 01914a1a91ade18bd7aead99e7d1bf38cd22ad89 | [
"MIT"
] | 154 | 2020-04-08T21:41:22.000Z | 2022-03-17T21:05:33.000Z | /*
* This file is part of ACADO Toolkit.
*
* ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization.
* Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau,
* Milan Vukov, Rien Quirynen, KU Leuven.
* Developed within the Optimization in Engineering Center (OPTEC)
* under supervision of Moritz Diehl. All rights reserved.
*
* ACADO Toolkit 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.
*
* ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/acado/objective/mayer_term.hpp
* \author Boris Houska, Hans Joachim Ferreau
*
*/
#ifndef ACADO_TOOLKIT_MAYER_TERM_HPP
#define ACADO_TOOLKIT_MAYER_TERM_HPP
#include <acado/objective/objective_element.hpp>
BEGIN_NAMESPACE_ACADO
/**
* \brief Stores and evaluates Mayer terms within optimal control problems.
*
* \ingroup BasicDataStructures
*
* The class MayerTerm allows to manage and evaluate Mayer terms
* within optimal control problems.
*
* \author Boris Houska, Hans Joachim Ferreau
*/
class MayerTerm : public ObjectiveElement{
//
// PUBLIC MEMBER FUNCTIONS:
//
public:
/** Default constructor. */
MayerTerm( );
/** Default constructor. */
MayerTerm( const Grid &grid_,
const Expression& arg );
/** Default constructor. */
MayerTerm( const Grid &grid_,
const Function& arg );
/** Copy constructor (deep copy). */
MayerTerm( const MayerTerm& rhs );
/** Destructor. */
virtual ~MayerTerm( );
/** Assignment operator (deep copy). */
MayerTerm& operator=( const MayerTerm& rhs );
// =======================================================================================
//
// INITIALIZATION ROUTINES
//
// =======================================================================================
inline returnValue init( const Grid &grid_, const Expression& arg );
// =======================================================================================
//
// EVALUATION ROUTINES
//
// =======================================================================================
returnValue evaluate( const OCPiterate &x );
/** Evaluates the objective gradient contribution from this term \n
* and computes the corresponding exact hessian if hessian != 0 \n
* \n
* \return SUCCESSFUL_RETURN \n
*/
returnValue evaluateSensitivities( BlockMatrix *hessian );
// =======================================================================================
//
// DATA MEMBERS:
//
protected:
};
CLOSE_NAMESPACE_ACADO
#include <acado/objective/mayer_term.ipp>
#endif // ACADO_TOOLKIT_MAYER_TERM_HPP
/*
* end of file
*/
| 26.478261 | 90 | 0.547893 | Neptos |
a1b074a4b4d6289dc156df5667c0b8ba6ea47693 | 312 | cpp | C++ | answers/leetcode/Power of Two/Power of Two.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | 3 | 2015-09-04T21:32:31.000Z | 2020-12-06T00:37:32.000Z | answers/leetcode/Power of Two/Power of Two.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | answers/leetcode/Power of Two/Power of Two.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | //@time complexity O(1)
//@space complexity O(1)
//@result 1108 / 1108 test cases passed. Status: Accepted Runtime: 8 ms Submitted: 0 minutes ago You are here! Your runtime beats 7.51% of cpp submissions.
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && ! (n & (n - 1));
}
};
| 28.363636 | 155 | 0.644231 | FeiZhan |
a1b0bfd6ad5f873e3ffaabb08221019091a3efe2 | 14,460 | hpp | C++ | include/System/Net/Http/Headers/AuthenticationHeaderValue.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/System/Net/Http/Headers/AuthenticationHeaderValue.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/System/Net/Http/Headers/AuthenticationHeaderValue.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ICloneable
#include "System/ICloneable.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: System::Net::Http::Headers
namespace System::Net::Http::Headers {
// Forward declaring type: Lexer
class Lexer;
// Forward declaring type: Token
struct Token;
}
// Completed forward declares
// Type namespace: System.Net.Http.Headers
namespace System::Net::Http::Headers {
// Forward declaring type: AuthenticationHeaderValue
class AuthenticationHeaderValue;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(System::Net::Http::Headers::AuthenticationHeaderValue);
DEFINE_IL2CPP_ARG_TYPE(System::Net::Http::Headers::AuthenticationHeaderValue*, "System.Net.Http.Headers", "AuthenticationHeaderValue");
// Type namespace: System.Net.Http.Headers
namespace System::Net::Http::Headers {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: System.Net.Http.Headers.AuthenticationHeaderValue
// [TokenAttribute] Offset: FFFFFFFF
class AuthenticationHeaderValue : public ::Il2CppObject/*, public System::ICloneable*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.String <Parameter>k__BackingField
// Size: 0x8
// Offset: 0x10
::Il2CppString* Parameter;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String <Scheme>k__BackingField
// Size: 0x8
// Offset: 0x18
::Il2CppString* Scheme;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
public:
// Creating interface conversion operator: operator System::ICloneable
operator System::ICloneable() noexcept {
return *reinterpret_cast<System::ICloneable*>(this);
}
// Get instance field reference: private System.String <Parameter>k__BackingField
::Il2CppString*& dyn_$Parameter$k__BackingField();
// Get instance field reference: private System.String <Scheme>k__BackingField
::Il2CppString*& dyn_$Scheme$k__BackingField();
// public System.String get_Parameter()
// Offset: 0x172E3C4
::Il2CppString* get_Parameter();
// private System.Void set_Parameter(System.String value)
// Offset: 0x172E3CC
void set_Parameter(::Il2CppString* value);
// public System.String get_Scheme()
// Offset: 0x172E3D4
::Il2CppString* get_Scheme();
// private System.Void set_Scheme(System.String value)
// Offset: 0x172E3DC
void set_Scheme(::Il2CppString* value);
// private System.Object System.ICloneable.Clone()
// Offset: 0x172E3E4
::Il2CppObject* System_ICloneable_Clone();
// static public System.Boolean TryParse(System.String input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue)
// Offset: 0x172E534
static bool TryParse(::Il2CppString* input, ByRef<System::Net::Http::Headers::AuthenticationHeaderValue*> parsedValue);
// static System.Boolean TryParse(System.String input, System.Int32 minimalCount, out System.Collections.Generic.List`1<System.Net.Http.Headers.AuthenticationHeaderValue> result)
// Offset: 0x172E774
static bool TryParse(::Il2CppString* input, int minimalCount, ByRef<System::Collections::Generic::List_1<System::Net::Http::Headers::AuthenticationHeaderValue*>*> result);
// static private System.Boolean TryParseElement(System.Net.Http.Headers.Lexer lexer, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue, out System.Net.Http.Headers.Token t)
// Offset: 0x172E62C
static bool TryParseElement(System::Net::Http::Headers::Lexer* lexer, ByRef<System::Net::Http::Headers::AuthenticationHeaderValue*> parsedValue, ByRef<System::Net::Http::Headers::Token> t);
// private System.Void .ctor()
// Offset: 0x172E3BC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AuthenticationHeaderValue* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::AuthenticationHeaderValue::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AuthenticationHeaderValue*, creationType>()));
}
// public override System.Boolean Equals(System.Object obj)
// Offset: 0x172E3EC
// Implemented from: System.Object
// Base method: System.Boolean Object::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0x172E4B4
// Implemented from: System.Object
// Base method: System.Int32 Object::GetHashCode()
int GetHashCode();
// public override System.String ToString()
// Offset: 0x172EB90
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::Il2CppString* ToString();
}; // System.Net.Http.Headers.AuthenticationHeaderValue
#pragma pack(pop)
static check_size<sizeof(AuthenticationHeaderValue), 24 + sizeof(::Il2CppString*)> __System_Net_Http_Headers_AuthenticationHeaderValueSizeCheck;
static_assert(sizeof(AuthenticationHeaderValue) == 0x20);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::get_Parameter
// Il2CppName: get_Parameter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::Net::Http::Headers::AuthenticationHeaderValue::*)()>(&System::Net::Http::Headers::AuthenticationHeaderValue::get_Parameter)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "get_Parameter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::set_Parameter
// Il2CppName: set_Parameter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::Http::Headers::AuthenticationHeaderValue::*)(::Il2CppString*)>(&System::Net::Http::Headers::AuthenticationHeaderValue::set_Parameter)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "set_Parameter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::get_Scheme
// Il2CppName: get_Scheme
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::Net::Http::Headers::AuthenticationHeaderValue::*)()>(&System::Net::Http::Headers::AuthenticationHeaderValue::get_Scheme)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "get_Scheme", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::set_Scheme
// Il2CppName: set_Scheme
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::Http::Headers::AuthenticationHeaderValue::*)(::Il2CppString*)>(&System::Net::Http::Headers::AuthenticationHeaderValue::set_Scheme)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "set_Scheme", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::System_ICloneable_Clone
// Il2CppName: System.ICloneable.Clone
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Net::Http::Headers::AuthenticationHeaderValue::*)()>(&System::Net::Http::Headers::AuthenticationHeaderValue::System_ICloneable_Clone)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "System.ICloneable.Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::TryParse
// Il2CppName: TryParse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, ByRef<System::Net::Http::Headers::AuthenticationHeaderValue*>)>(&System::Net::Http::Headers::AuthenticationHeaderValue::TryParse)> {
static const MethodInfo* get() {
static auto* input = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* parsedValue = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "AuthenticationHeaderValue")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "TryParse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, parsedValue});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::TryParse
// Il2CppName: TryParse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, int, ByRef<System::Collections::Generic::List_1<System::Net::Http::Headers::AuthenticationHeaderValue*>*>)>(&System::Net::Http::Headers::AuthenticationHeaderValue::TryParse)> {
static const MethodInfo* get() {
static auto* input = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* minimalCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* result = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "AuthenticationHeaderValue")})->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "TryParse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, minimalCount, result});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::TryParseElement
// Il2CppName: TryParseElement
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(System::Net::Http::Headers::Lexer*, ByRef<System::Net::Http::Headers::AuthenticationHeaderValue*>, ByRef<System::Net::Http::Headers::Token>)>(&System::Net::Http::Headers::AuthenticationHeaderValue::TryParseElement)> {
static const MethodInfo* get() {
static auto* lexer = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "Lexer")->byval_arg;
static auto* parsedValue = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "AuthenticationHeaderValue")->this_arg;
static auto* t = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "Token")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "TryParseElement", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lexer, parsedValue, t});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::Equals
// Il2CppName: Equals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::Http::Headers::AuthenticationHeaderValue::*)(::Il2CppObject*)>(&System::Net::Http::Headers::AuthenticationHeaderValue::Equals)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::GetHashCode
// Il2CppName: GetHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Net::Http::Headers::AuthenticationHeaderValue::*)()>(&System::Net::Http::Headers::AuthenticationHeaderValue::GetHashCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Net::Http::Headers::AuthenticationHeaderValue::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (System::Net::Http::Headers::AuthenticationHeaderValue::*)()>(&System::Net::Http::Headers::AuthenticationHeaderValue::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::AuthenticationHeaderValue*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 63.144105 | 296 | 0.734993 | sc2ad |
a1b16e81141b90aae983455f91c51150b957988b | 290 | cpp | C++ | cppsrc/main.cpp | ferserc1/node-api-test | 43a732b4d0539af812d8a8b86de756cbe915b1ab | [
"MIT"
] | null | null | null | cppsrc/main.cpp | ferserc1/node-api-test | 43a732b4d0539af812d8a8b86de756cbe915b1ab | [
"MIT"
] | null | null | null | cppsrc/main.cpp | ferserc1/node-api-test | 43a732b4d0539af812d8a8b86de756cbe915b1ab | [
"MIT"
] | null | null | null | #include <napi.h>
#include "Samples/functionalexample.h"
#include "Samples/classexample.h"
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
functionalexample::Init(env, exports);
return ClassExample::Init(env, exports);
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitAll)
| 26.363636 | 59 | 0.758621 | ferserc1 |
a1b3d03313775732713a2392675ae0ee6497415f | 455 | cpp | C++ | 200111Zad06/zad6.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | 200111Zad06/zad6.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | 200111Zad06/zad6.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | /*
*
* zad6.cpp
*
* Created on: Jan 15, 2020
* Author: eli
*/
#include <iostream>
using namespace std;
int main() {
int posl = 1;
int maxPosl = 1;
int digitOld;
int digitNew;
cin >> digitNew;
digitOld = -1;
while (digitNew != 0) {
if (digitOld == digitNew) {
posl++;
if (maxPosl < posl) {
maxPosl = posl;
}
} else {
posl = 1;
}
digitOld = digitNew;
cin >> digitNew;
}
cout << maxPosl << endl;
return 0;
}
| 13.382353 | 29 | 0.553846 | elenazaharieva |
a1b5d43994e173fad63c344fa45c8e49b3b8a20f | 101 | cpp | C++ | Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 110 | 2018-10-20T21:47:54.000Z | 2022-03-14T03:47:58.000Z | Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 68 | 2018-12-19T09:08:56.000Z | 2022-03-09T06:43:38.000Z | Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 45 | 2018-12-03T14:35:47.000Z | 2022-03-05T01:35:24.000Z | // Copyright 2015-2020 Piperift. All Rights Reserved.
#include "Multithreading/ScopedTaskManager.h"
| 25.25 | 53 | 0.80198 | foobit |