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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b810ec3f5ca1cb0bd9cfd2c2903caaed49c0e7e | 6,133 | hxx | C++ | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// AdvApp2Var_ApproxF2var.hxx
/*---------------------------------------------------------------
| description de la macro et du prototype des routines
| de l'approximation a deux variables
| a utiliser dans AdvApp2Var
|--------------------------------------------------------------*/
#ifndef AdvApp2Var_ApproxF2var_HeaderFile
#define AdvApp2Var_ApproxF2var_HeaderFile
#include <Standard_Macro.hxx>
#include <AdvApp2Var_Data_f2c.hxx>
#include <AdvApp2Var_EvaluatorFunc2Var.hxx>
//
class AdvApp2Var_ApproxF2var {
public:
Standard_EXPORT static int mma2fnc_(integer *ndimen,
integer *nbsesp,
integer *ndimse,
doublereal *uvfonc,
const AdvApp2Var_EvaluatorFunc2Var& foncnp,
doublereal *tconst,
integer *isofav,
integer *nbroot,
doublereal *rootlg,
integer *iordre,
integer *ideriv,
integer *ndgjac,
integer *nbcrmx,
integer *ncflim,
doublereal *epsapr,
integer *ncoeff,
doublereal *courbe,
integer *nbcrbe,
doublereal *somtab,
doublereal *diftab,
doublereal *contr1,
doublereal *contr2,
doublereal *tabdec,
doublereal *errmax,
doublereal *errmoy,
integer *iercod);
Standard_EXPORT static int mma2roo_(integer *nbpntu,
integer *nbpntv,
doublereal *urootl,
doublereal *vrootl);
Standard_EXPORT static int mma2jmx_(integer *ndgjac,
integer *iordre,
doublereal *xjacmx);
Standard_EXPORT static int mmapptt_(const integer * ,
const integer * ,
const integer * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma2cdi_(integer *ndimen,
integer *nbpntu,
doublereal *urootl,
integer *nbpntv,
doublereal *vrootl,
integer *iordru,
integer *iordrv,
doublereal *contr1,
doublereal *contr2,
doublereal *contr3,
doublereal *contr4,
doublereal *sotbu1,
doublereal *sotbu2,
doublereal *ditbu1,
doublereal *ditbu2,
doublereal *sotbv1,
doublereal *sotbv2,
doublereal *ditbv1,
doublereal *ditbv2,
doublereal *sosotb,
doublereal *soditb,
doublereal *disotb,
doublereal *diditb,
integer *iercod);
Standard_EXPORT static int mma2ds1_(integer *ndimen,
doublereal *uintfn,
doublereal *vintfn,
const AdvApp2Var_EvaluatorFunc2Var& foncnp,
integer *nbpntu,
integer *nbpntv,
doublereal *urootb,
doublereal *vrootb,
integer *isofav,
doublereal *sosotb,
doublereal *disotb,
doublereal *soditb,
doublereal *diditb,
doublereal *fpntab,
doublereal *ttable,
integer *iercod);
Standard_EXPORT static int mma2ce1_(integer *numdec,
integer *ndimen,
integer *nbsesp,
integer *ndimse,
integer *ndminu,
integer *ndminv,
integer *ndguli,
integer *ndgvli,
integer *ndjacu,
integer *ndjacv,
integer *iordru,
integer *iordrv,
integer *nbpntu,
integer *nbpntv,
doublereal *epsapr,
doublereal *sosotb,
doublereal *disotb,
doublereal *soditb,
doublereal *diditb,
doublereal *patjac,
doublereal *errmax,
doublereal *errmoy,
integer *ndegpu,
integer *ndegpv,
integer *itydec,
integer *iercod);
Standard_EXPORT static int mma2can_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal *,
doublereal * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma1her_(const integer * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma2ac2_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const integer * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2ac3_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const integer * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2ac1_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2fx6_(integer *ncfmxu,
integer *ncfmxv,
integer *ndimen,
integer *nbsesp,
integer *ndimse,
integer *nbupat,
integer *nbvpat,
integer *iordru,
integer *iordrv,
doublereal *epsapr,
doublereal *epsfro,
doublereal *patcan,
doublereal *errmax,
integer *ncoefu,
integer *ncoefv);
};
#endif
| 27.751131 | 81 | 0.585358 | mgreminger |
1b823b8aafefca059bd3731c308007b7c4e82603 | 31,992 | cc | C++ | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 316 | 2018-04-19T14:44:25.000Z | 2022-03-28T23:58:05.000Z | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 81 | 2018-04-21T11:04:46.000Z | 2022-02-22T19:51:08.000Z | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 23 | 2018-09-01T18:04:33.000Z | 2021-11-18T11:36:35.000Z | /*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.1
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "ui/components/wave_label.h"
#include "ui/components/info_display.h"
#include "adl/instrument.h"
#include "parameter_block.h"
#include <cmath>
//[/Headers]
#include "operator_editor.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
Operator_Editor::Operator_Editor (unsigned op_id, Parameter_Block &pb)
{
//[Constructor_pre] You can add your own custom stuff here..
operator_id_ = op_id;
parameter_block_ = &pb;
//[/Constructor_pre]
kn_attack.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_attack.get());
kn_attack->setName ("new component");
kn_attack->setBounds (24, 3, 48, 48);
kn_decay.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_decay.get());
kn_decay->setName ("new component");
kn_decay->setBounds (96, 3, 48, 48);
kn_sustain.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_sustain.get());
kn_sustain->setName ("new component");
kn_sustain->setBounds (24, 48, 48, 48);
kn_release.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_release.get());
kn_release->setName ("new component");
kn_release->setBounds (96, 48, 48, 48);
btn_prev_wave.reset (new TextButton ("new button"));
addAndMakeVisible (btn_prev_wave.get());
btn_prev_wave->setButtonText (TRANS("<"));
btn_prev_wave->setConnectedEdges (Button::ConnectedOnRight);
btn_prev_wave->addListener (this);
btn_prev_wave->setBounds (3, 96, 23, 24);
btn_next_wave.reset (new TextButton ("new button"));
addAndMakeVisible (btn_next_wave.get());
btn_next_wave->setButtonText (TRANS(">"));
btn_next_wave->setConnectedEdges (Button::ConnectedOnLeft);
btn_next_wave->addListener (this);
btn_next_wave->setBounds (132, 96, 23, 24);
btn_trem.reset (new TextButton ("new button"));
addAndMakeVisible (btn_trem.get());
btn_trem->setButtonText (String());
btn_trem->addListener (this);
btn_trem->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_trem->setBounds (168, 3, 15, 15);
btn_vib.reset (new TextButton ("new button"));
addAndMakeVisible (btn_vib.get());
btn_vib->setButtonText (String());
btn_vib->addListener (this);
btn_vib->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_vib->setBounds (168, 20, 15, 15);
btn_sus.reset (new TextButton ("new button"));
addAndMakeVisible (btn_sus.get());
btn_sus->setButtonText (String());
btn_sus->addListener (this);
btn_sus->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_sus->setBounds (168, 37, 15, 15);
btn_env.reset (new TextButton ("new button"));
addAndMakeVisible (btn_env.get());
btn_env->setButtonText (String());
btn_env->addListener (this);
btn_env->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_env->setBounds (168, 54, 15, 15);
lbl_level.reset (new Label ("new label",
TRANS("Lv")));
addAndMakeVisible (lbl_level.get());
lbl_level->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_level->setJustificationType (Justification::centredLeft);
lbl_level->setEditable (false, false, false);
lbl_level->setColour (Label::textColourId, Colours::aliceblue);
lbl_level->setColour (TextEditor::textColourId, Colours::black);
lbl_level->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_level->setBounds (163, 72, 28, 16);
lbl_wave.reset (new Wave_Label (chip_waves_));
addAndMakeVisible (lbl_wave.get());
lbl_wave->setName ("new component");
lbl_wave->setBounds (26, 96, 106, 24);
label.reset (new Label ("new label",
TRANS("A")));
addAndMakeVisible (label.get());
label->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label->setJustificationType (Justification::centredTop);
label->setEditable (false, false, false);
label->setColour (Label::textColourId, Colours::aliceblue);
label->setColour (TextEditor::textColourId, Colours::black);
label->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label->setBounds (4, 0, 20, 16);
label2.reset (new Label ("new label",
TRANS("D")));
addAndMakeVisible (label2.get());
label2->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label2->setJustificationType (Justification::centredTop);
label2->setEditable (false, false, false);
label2->setColour (Label::textColourId, Colours::aliceblue);
label2->setColour (TextEditor::textColourId, Colours::black);
label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label2->setBounds (76, 0, 20, 16);
label3.reset (new Label ("new label",
TRANS("S")));
addAndMakeVisible (label3.get());
label3->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label3->setJustificationType (Justification::centredTop);
label3->setEditable (false, false, false);
label3->setColour (Label::textColourId, Colours::aliceblue);
label3->setColour (TextEditor::textColourId, Colours::black);
label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label3->setBounds (4, 48, 20, 16);
label4.reset (new Label ("new label",
TRANS("R")));
addAndMakeVisible (label4.get());
label4->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label4->setJustificationType (Justification::centredTop);
label4->setEditable (false, false, false);
label4->setColour (Label::textColourId, Colours::aliceblue);
label4->setColour (TextEditor::textColourId, Colours::black);
label4->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label4->setBounds (76, 48, 20, 16);
label5.reset (new Label ("new label",
TRANS("Tremolo")));
addAndMakeVisible (label5.get());
label5->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label5->setJustificationType (Justification::centredLeft);
label5->setEditable (false, false, false);
label5->setColour (Label::textColourId, Colours::aliceblue);
label5->setColour (TextEditor::textColourId, Colours::black);
label5->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label5->setBounds (184, 3, 80, 15);
label6.reset (new Label ("new label",
TRANS("Vibrato")));
addAndMakeVisible (label6.get());
label6->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label6->setJustificationType (Justification::centredLeft);
label6->setEditable (false, false, false);
label6->setColour (Label::textColourId, Colours::aliceblue);
label6->setColour (TextEditor::textColourId, Colours::black);
label6->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label6->setBounds (184, 20, 80, 15);
label7.reset (new Label ("new label",
TRANS("Sustain")));
addAndMakeVisible (label7.get());
label7->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label7->setJustificationType (Justification::centredLeft);
label7->setEditable (false, false, false);
label7->setColour (Label::textColourId, Colours::aliceblue);
label7->setColour (TextEditor::textColourId, Colours::black);
label7->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label7->setBounds (184, 37, 80, 15);
label8.reset (new Label ("new label",
TRANS("Key scaling")));
addAndMakeVisible (label8.get());
label8->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label8->setJustificationType (Justification::centredLeft);
label8->setEditable (false, false, false);
label8->setColour (Label::textColourId, Colours::aliceblue);
label8->setColour (TextEditor::textColourId, Colours::black);
label8->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label8->setBounds (184, 54, 80, 15);
lbl_fmul.reset (new Label ("new label",
TRANS("F*")));
addAndMakeVisible (lbl_fmul.get());
lbl_fmul->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_fmul->setJustificationType (Justification::centredLeft);
lbl_fmul->setEditable (false, false, false);
lbl_fmul->setColour (Label::textColourId, Colours::aliceblue);
lbl_fmul->setColour (TextEditor::textColourId, Colours::black);
lbl_fmul->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_fmul->setBounds (163, 88, 28, 16);
lbl_ksl.reset (new Label ("new label",
TRANS("Ksl")));
addAndMakeVisible (lbl_ksl.get());
lbl_ksl->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_ksl->setJustificationType (Justification::centredLeft);
lbl_ksl->setEditable (false, false, false);
lbl_ksl->setColour (Label::textColourId, Colours::aliceblue);
lbl_ksl->setColour (TextEditor::textColourId, Colours::black);
lbl_ksl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_ksl->setBounds (163, 104, 28, 16);
sl_level.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_level.get());
sl_level->setName ("new component");
sl_level->setBounds (195, 70, 64, 20);
sl_fmul.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_fmul.get());
sl_fmul->setName ("new component");
sl_fmul->setBounds (195, 86, 64, 20);
sl_ksl.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_ksl.get());
sl_ksl->setName ("new component");
sl_ksl->setBounds (195, 102, 64, 20);
//[UserPreSize]
sl_level->add_listener(this);
sl_level->set_range(0, 63);
sl_level->set_max_increment(1);
sl_fmul->add_listener(this);
sl_fmul->set_range(0, 15);
sl_fmul->set_max_increment(1);
sl_ksl->add_listener(this);
sl_ksl->set_range(0, 3);
sl_ksl->set_max_increment(1);
kn_attack->add_listener(this);
kn_attack->set_max_increment(1);
kn_decay->add_listener(this);
kn_decay->set_max_increment(1);
kn_sustain->add_listener(this);
kn_sustain->set_max_increment(1);
kn_release->add_listener(this);
kn_release->set_max_increment(1);
btn_trem->setClickingTogglesState(true);
btn_vib->setClickingTogglesState(true);
btn_sus->setClickingTogglesState(true);
btn_env->setClickingTogglesState(true);
//[/UserPreSize]
setSize (264, 128);
//[Constructor] You can add your own custom stuff here..
kn_attack->set_range(0, 15);
kn_decay->set_range(0, 15);
kn_sustain->set_range(0, 15);
kn_release->set_range(0, 15);
//[/Constructor]
}
Operator_Editor::~Operator_Editor()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
kn_attack = nullptr;
kn_decay = nullptr;
kn_sustain = nullptr;
kn_release = nullptr;
btn_prev_wave = nullptr;
btn_next_wave = nullptr;
btn_trem = nullptr;
btn_vib = nullptr;
btn_sus = nullptr;
btn_env = nullptr;
lbl_level = nullptr;
lbl_wave = nullptr;
label = nullptr;
label2 = nullptr;
label3 = nullptr;
label4 = nullptr;
label5 = nullptr;
label6 = nullptr;
label7 = nullptr;
label8 = nullptr;
lbl_fmul = nullptr;
lbl_ksl = nullptr;
sl_level = nullptr;
sl_fmul = nullptr;
sl_ksl = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void Operator_Editor::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
{
int x = 25, y = 96, width = 108, height = 24;
Colour strokeColour = Colour (0xff8e989b);
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (strokeColour);
g.drawRect (x, y, width, height, 1);
}
{
float x = 0.0f, y = 0.0f, width = 264.0f, height = 128.0f;
Colour fillColour = Colour (0x662e4c4d);
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (fillColour);
g.fillRoundedRectangle (x, y, width, height, 7.0f);
}
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void Operator_Editor::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void Operator_Editor::buttonClicked (Button* buttonThatWasClicked)
{
//[UserbuttonClicked_Pre]
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
Button *btn = buttonThatWasClicked;
//[/UserbuttonClicked_Pre]
if (buttonThatWasClicked == btn_prev_wave.get())
{
//[UserButtonCode_btn_prev_wave] -- add your button handler code here..
AudioParameterChoice &p = *op.p_wave;
p.beginChangeGesture();
int wave = std::max(p.getIndex() - 1, 0);
p = wave;
p.endChangeGesture();
lbl_wave->set_wave(wave, dontSendNotification);
//[/UserButtonCode_btn_prev_wave]
}
else if (buttonThatWasClicked == btn_next_wave.get())
{
//[UserButtonCode_btn_next_wave] -- add your button handler code here..
AudioParameterChoice &p = *op.p_wave;
p.beginChangeGesture();
int wave = std::min(p.getIndex() + 1, p.choices.size() - 1);
p = wave;
p.endChangeGesture();
lbl_wave->set_wave(wave, dontSendNotification);
//[/UserButtonCode_btn_next_wave]
}
else if (buttonThatWasClicked == btn_trem.get())
{
//[UserButtonCode_btn_trem] -- add your button handler code here..
AudioParameterBool &p = *op.p_trem;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_trem]
}
else if (buttonThatWasClicked == btn_vib.get())
{
//[UserButtonCode_btn_vib] -- add your button handler code here..
AudioParameterBool &p = *op.p_vib;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_vib]
}
else if (buttonThatWasClicked == btn_sus.get())
{
//[UserButtonCode_btn_sus] -- add your button handler code here..
AudioParameterBool &p = *op.p_sus;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_sus]
}
else if (buttonThatWasClicked == btn_env.get())
{
//[UserButtonCode_btn_env] -- add your button handler code here..
AudioParameterBool &p = *op.p_env;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_env]
}
//[UserbuttonClicked_Post]
if (display_info_for_component(btn))
info_->expire_info_in();
//[/UserbuttonClicked_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
static unsigned swap_ksl(unsigned ksl)
{
// OPL mapping for KSL (dB/oct): 0=>0, 1=>3, 2=>1.5, 3=>6
// for user-friendly ordering, the UI control will swap 1 and 2
switch (ksl) {
case 1: return 2;
case 2: return 1;
default: return ksl;
}
}
void Operator_Editor::set_operator_parameters(const Instrument &ins, unsigned op, NotificationType ntf)
{
kn_attack->set_value(ins.attack(op), ntf);
kn_decay->set_value(ins.decay(op), ntf);
kn_sustain->set_value(ins.sustain(op), ntf);
kn_release->set_value(ins.release(op), ntf);
sl_level->set_value(ins.level(op), ntf);
sl_fmul->set_value(ins.fmul(op), ntf);
sl_ksl->set_value(swap_ksl(ins.ksl(op)), ntf);
btn_trem->setToggleState(ins.trem(op), ntf);
btn_vib->setToggleState(ins.vib(op), ntf);
btn_sus->setToggleState(ins.sus(op), ntf);
btn_env->setToggleState(ins.env(op), ntf);
lbl_wave->set_wave(ins.wave(op), ntf);
}
void Operator_Editor::set_operator_enabled(bool b)
{
if (b == operator_enabled_)
return;
operator_enabled_ = b;
repaint();
}
void Operator_Editor::knob_value_changed(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p = (int)std::lround(k->value());
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p = (int)std::lround(k->value());
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p = swap_ksl((int)std::lround(k->value()));
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p = (int)std::lround(k->value());
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p = (int)std::lround(k->value());
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p = (int)std::lround(k->value());
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p = (int)std::lround(k->value());
}
display_info_for_component(k);
}
void Operator_Editor::knob_drag_started(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p.beginChangeGesture();
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p.beginChangeGesture();
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p.beginChangeGesture();
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p.beginChangeGesture();
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p.beginChangeGesture();
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p.beginChangeGesture();
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p.beginChangeGesture();
}
display_info_for_component(k);
}
void Operator_Editor::knob_drag_ended(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p.endChangeGesture();
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p.endChangeGesture();
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p.endChangeGesture();
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p.endChangeGesture();
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p.endChangeGesture();
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p.endChangeGesture();
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p.endChangeGesture();
}
info_->expire_info_in();
}
void Operator_Editor::paintOverChildren(Graphics &g)
{
if (!operator_enabled_) {
Rectangle<int> bounds = getLocalBounds();
g.setColour(Colour(0x66777777));
g.fillRoundedRectangle(bounds.toFloat(), 7.0f);
}
}
bool Operator_Editor::display_info_for_component(Component *c)
{
String param;
int val = 0;
const char *prefixes[4] = {"Op2 ", "Op1 ", "Op4 ", "Op3 "};
String prefix = prefixes[operator_id_];
Knob *kn = static_cast<Knob *>(c);
if (c == sl_level.get()) {
param = prefix + "Level";
val = (int)std::lround(kn->value());
}
else if (c == sl_fmul.get()) {
param = prefix + "Frequency multiplier";
val = (int)std::lround(kn->value());
}
else if (c == sl_ksl.get()) {
param = prefix + "Key scale level";
val = swap_ksl((int)std::lround(kn->value()));
}
else if (c == kn_attack.get()) {
param = prefix + "Attack";
val = (int)std::lround(kn->value());
}
else if (c == kn_decay.get()) {
param = prefix + "Decay";
val = (int)std::lround(kn->value());
}
else if (c == kn_sustain.get()) {
param = prefix + "Sustain";
val = (int)std::lround(kn->value());
}
else if (c == kn_release.get()) {
param = prefix + "Release";
val = (int)std::lround(kn->value());
}
else if (c == btn_next_wave.get() || c == btn_prev_wave.get()) {
param = prefix + "Wave";
val = lbl_wave->wave();
}
if (param.isEmpty())
return false;
info_->display_info(param + " = " + String(val));
return true;
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Projucer information section --
This is where the Projucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="Operator_Editor" componentName=""
parentClasses="public Component, public Knob::Listener" constructorParams="unsigned op_id, Parameter_Block &pb"
variableInitialisers="" snapPixels="8" snapActive="1" snapShown="1"
overlayOpacity="0.33" fixedSize="0" initialWidth="264" initialHeight="128">
<BACKGROUND backgroundColour="323e44">
<RECT pos="25 96 108 24" fill="solid: 0" hasStroke="1" stroke="1, mitered, butt"
strokeColour="solid: ff8e989b"/>
<ROUNDRECT pos="0 0 264 128" cornerSize="7.0" fill="solid: 662e4c4d" hasStroke="0"/>
</BACKGROUND>
<GENERICCOMPONENT name="new component" id="7c54ff103d9f5d" memberName="kn_attack"
virtualName="" explicitFocusOrder="0" pos="24 3 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="be39ad00dcf6efe1" memberName="kn_decay"
virtualName="" explicitFocusOrder="0" pos="96 3 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="8d88729c124c7b16" memberName="kn_sustain"
virtualName="" explicitFocusOrder="0" pos="24 48 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="7d576b68e9b588f" memberName="kn_release"
virtualName="" explicitFocusOrder="0" pos="96 48 48 48" class="Styled_Knob_Default"
params=""/>
<TEXTBUTTON name="new button" id="cbf65c7349d1d293" memberName="btn_prev_wave"
virtualName="" explicitFocusOrder="0" pos="3 96 23 24" buttonText="<"
connectedEdges="2" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="6fc5dc04c6c5d6b9" memberName="btn_next_wave"
virtualName="" explicitFocusOrder="0" pos="132 96 23 24" buttonText=">"
connectedEdges="1" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="f60e70ed4f10ef32" memberName="btn_trem"
virtualName="" explicitFocusOrder="0" pos="168 3 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="501ccf7ad0bc53a7" memberName="btn_vib"
virtualName="" explicitFocusOrder="0" pos="168 20 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="3e46dd6b966c40b2" memberName="btn_sus"
virtualName="" explicitFocusOrder="0" pos="168 37 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="eb8e9dfd42dd8f57" memberName="btn_env"
virtualName="" explicitFocusOrder="0" pos="168 54 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<LABEL name="new label" id="ce54b68fc1a1f1e1" memberName="lbl_level"
virtualName="" explicitFocusOrder="0" pos="163 72 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Lv" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<GENERICCOMPONENT name="new component" id="dd16fb8d4c488877" memberName="lbl_wave"
virtualName="" explicitFocusOrder="0" pos="26 96 106 24" class="Wave_Label"
params="chip_waves_"/>
<LABEL name="new label" id="664ae98bd7a6b3a5" memberName="label" virtualName=""
explicitFocusOrder="0" pos="4 0 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="A" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="360efe252ecea296" memberName="label2" virtualName=""
explicitFocusOrder="0" pos="76 0 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="D" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="d276bb335fab1f40" memberName="label3" virtualName=""
explicitFocusOrder="0" pos="4 48 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="S" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="2ad02ec8c7135a27" memberName="label4" virtualName=""
explicitFocusOrder="0" pos="76 48 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="R" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="ffcd49be138de78b" memberName="label5" virtualName=""
explicitFocusOrder="0" pos="184 3 80 15" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="Tremolo" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="14.0"
kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="37e7947c4443e047" memberName="label6" virtualName=""
explicitFocusOrder="0" pos="184 20 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Vibrato" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="f04d949c957007e" memberName="label7" virtualName=""
explicitFocusOrder="0" pos="184 37 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Sustain" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="e8cd7412f499955d" memberName="label8" virtualName=""
explicitFocusOrder="0" pos="184 54 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Key scaling" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="e77fa8c6c00316b7" memberName="lbl_fmul"
virtualName="" explicitFocusOrder="0" pos="163 88 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="F*" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="dbcb4d45f32ea3e9" memberName="lbl_ksl" virtualName=""
explicitFocusOrder="0" pos="163 104 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Ksl" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<GENERICCOMPONENT name="new component" id="d7383c8ec7f64dfc" memberName="sl_level"
virtualName="" explicitFocusOrder="0" pos="195 70 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
<GENERICCOMPONENT name="new component" id="37e9a27164f2dd8e" memberName="sl_fmul"
virtualName="" explicitFocusOrder="0" pos="195 86 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
<GENERICCOMPONENT name="new component" id="1836679269ce1d4f" memberName="sl_ksl"
virtualName="" explicitFocusOrder="0" pos="195 102 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| 40.190955 | 133 | 0.624594 | jfrey-xx |
1b82c04d6fa6d0e0e0c770de4422db1b18a26c69 | 2,386 | inl | C++ | WebAssembly/fpzip/src/pcencoder.inl | jvo203/FITSWEBQLSE | 3b2b3c74d623c3510cfa81a4e30ac5bd0af48cb0 | [
"MIT"
] | 60 | 2020-01-03T20:12:39.000Z | 2022-03-14T19:46:22.000Z | src/pcencoder.inl | aras-p/fpzip | 79aa1b1bd5a0b9497b8ad4352d8561ab17113cdf | [
"BSD-3-Clause"
] | 4 | 2020-06-05T16:59:29.000Z | 2021-06-16T09:06:02.000Z | src/pcencoder.inl | aras-p/fpzip | 79aa1b1bd5a0b9497b8ad4352d8561ab17113cdf | [
"BSD-3-Clause"
] | 5 | 2020-03-13T10:18:17.000Z | 2021-08-28T18:04:41.000Z | // specialization for small alphabets -----------------------------------------
template <typename T, class M>
class PCencoder<T, M, false> {
public:
PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {}
T encode(T real, T pred, uint context = 0);
static const uint symbols = 2 * (1 << M::bits) - 1;
private:
static const uint bias = (1 << M::bits) - 1; // perfect prediction symbol
M map; // maps T to integer type
RCencoder*const re; // entropy encoder
RCmodel*const* rm; // probability modeler(s)
};
// encode narrow range type
template <typename T, class M>
T PCencoder<T, M, false>::encode(T real, T pred, uint context)
{
// map type T to unsigned integer type
typedef typename M::Range U;
U r = map.forward(real);
U p = map.forward(pred);
// entropy encode d = r - p
re->encode(static_cast<uint>(bias + r - p), rm[context]);
// return decoded value
return map.inverse(r);
}
// specialization for large alphabets -----------------------------------------
template <typename T, class M>
class PCencoder<T, M, true> {
public:
PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {}
T encode(T real, T pred, uint context = 0);
static const uint symbols = 2 * M::bits + 1;
private:
static const uint bias = M::bits; // perfect prediction symbol
M map; // maps T to integer type
RCencoder*const re; // entropy encoder
RCmodel*const* rm; // probability modeler(s)
};
// encode wide range type
template <typename T, class M>
T PCencoder<T, M, true>::encode(T real, T pred, uint context)
{
// map type T to unsigned integer type
typedef typename M::Range U;
U r = map.forward(real);
U p = map.forward(pred);
// compute (-1)^s (2^k + m) = r - p, entropy code (s, k),
// and encode the k-bit number m verbatim
if (p < r) { // underprediction
U d = r - p;
uint k = PC::bsr(d);
re->encode(bias + 1 + k, rm[context]);
re->encode(d - (U(1) << k), k);
}
else if (p > r) { // overprediction
U d = p - r;
uint k = PC::bsr(d);
re->encode(bias - 1 - k, rm[context]);
re->encode(d - (U(1) << k), k);
}
else // perfect prediction
re->encode(bias, rm[context]);
// return decoded value
return map.inverse(r);
}
| 33.138889 | 79 | 0.564962 | jvo203 |
1b82c19dfb057df6ede2b70d4cc2fce9324d6558 | 38 | hh | C++ | RAVL2/MSVC/include/Ravl/DP/Pipes.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/DP/Pipes.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/DP/Pipes.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null |
#include "../.././Core/IO/Pipes.hh"
| 9.5 | 35 | 0.526316 | isuhao |
1b875b3349081687e6b9c5fe6094e309e2713ab7 | 31,250 | cc | C++ | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016-2018 Doug Moen
// Licensed under the Apache License, version 2.0
// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <string>
#include <boost/math/constants/constants.hpp>
#include <boost/filesystem.hpp>
#include <curv/arg.h>
#include <curv/builtin.h>
#include <curv/program.h>
#include <curv/exception.h>
#include <curv/file.h>
#include <curv/function.h>
#include <curv/shape.h>
#include <curv/system.h>
#include <curv/gl_context.h>
#include <curv/array_op.h>
#include <curv/analyser.h>
#include <curv/math.h>
using namespace std;
using namespace boost::math::double_constants;
namespace curv {
Shared<Meaning>
Builtin_Value::to_meaning(const Identifier& id) const
{
return make<Constant>(share(id), value_);
}
struct Is_Null_Function : public Polyadic_Function
{
Is_Null_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_null()};
}
};
struct Is_Bool_Function : public Polyadic_Function
{
Is_Bool_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_bool()};
}
};
struct Is_Num_Function : public Polyadic_Function
{
Is_Num_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_num()};
}
};
struct Is_String_Function : public Polyadic_Function
{
Is_String_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<String>() != nullptr};
}
};
struct Is_List_Function : public Polyadic_Function
{
Is_List_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<List>() != nullptr};
}
};
struct Is_Record_Function : public Polyadic_Function
{
Is_Record_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<Structure>() != nullptr};
}
};
struct Is_Fun_Function : public Polyadic_Function
{
Is_Fun_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<Function>() != nullptr};
}
};
struct Bit_Function : public Polyadic_Function
{
Bit_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {double(args[0].to_bool(At_Arg(args)))};
}
GL_Value gl_call(GL_Frame& f) const override
{
auto arg = f[0];
if (arg.type != GL_Type::Bool)
throw Exception(At_GL_Arg(0, f),
"bit: argument is not a bool");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = float("<<arg<<");\n";
return result;
}
};
struct Sqrt_Function : public Polyadic_Function
{
Sqrt_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return sqrt(x); }
static Shared<const String> callstr(Value x) {
return stringify("sqrt(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "sqrt");
}
};
// log(x) is the natural logarithm of x
struct Log_Function : public Polyadic_Function
{
Log_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return log(x); }
static Shared<const String> callstr(Value x) {
return stringify("log(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "log");
}
};
struct Abs_Function : public Polyadic_Function
{
Abs_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return abs(x); }
static Shared<const String> callstr(Value x) {
return stringify("abs(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "abs");
}
};
struct Floor_Function : public Polyadic_Function
{
Floor_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return floor(x); }
static Shared<const String> callstr(Value x) {
return stringify("floor(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "floor");
}
};
// round(x) -- round x to nearest integer.
// CPU: in case of tie, round to even.
// GPU: in case of tie, it's GPU/driver dependent.
struct Round_Function : public Polyadic_Function
{
Round_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return rint(x); }
static Shared<const String> callstr(Value x) {
return stringify("round(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "round");
}
};
struct Sin_Function : public Polyadic_Function
{
Sin_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return sin(x); }
static Shared<const String> callstr(Value x) {
return stringify("sin(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "sin");
}
};
struct Asin_Function : public Polyadic_Function
{
Asin_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return asin(x); }
static Shared<const String> callstr(Value x) {
return stringify("asin(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "asin");
}
};
struct Cos_Function : public Polyadic_Function
{
Cos_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return cos(x); }
static Shared<const String> callstr(Value x) {
return stringify("cos(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "cos");
}
};
struct Acos_Function : public Polyadic_Function
{
Acos_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return acos(x); }
static Shared<const String> callstr(Value x) {
return stringify("acos(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "acos");
}
};
struct Atan2_Function : public Polyadic_Function
{
Atan2_Function() : Polyadic_Function(2) {}
struct Scalar_Op {
static double f(double x, double y) { return atan2(x, y); }
static const char* name() { return "atan2"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("atan2(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], args[1], At_Arg(args));
}
GL_Value gl_call(GL_Frame& f) const override
{
auto x = f[0];
auto y = f[1];
GL_Type rtype = GL_Type::Bool;
if (x.type == y.type)
rtype = x.type;
else if (x.type == GL_Type::Num)
rtype = y.type;
else if (y.type == GL_Type::Num)
rtype = x.type;
if (rtype == GL_Type::Bool)
throw Exception(At_GL_Phrase(f.call_phrase_, &f),
"GL domain error");
GL_Value result = f.gl.newvalue(rtype);
f.gl.out <<" "<<rtype<<" "<<result<<" = atan(";
gl_put_as(f, x, At_GL_Arg(0, f), rtype);
f.gl.out << ",";
gl_put_as(f, y, At_GL_Arg(1, f), rtype);
f.gl.out << ");\n";
return result;
}
};
GL_Value gl_minmax(const char* name, Operation& argx, GL_Frame& f)
{
auto list = dynamic_cast<List_Expr*>(&argx);
if (list) {
std::list<GL_Value> args;
GL_Type type = GL_Type::Num;
for (auto op : *list) {
auto val = op->gl_eval(f);
args.push_back(val);
if (val.type == GL_Type::Num)
;
else if (gl_type_count(val.type) >= 2) {
if (type == GL_Type::Num)
type = val.type;
else if (type != val.type)
throw Exception(At_GL_Phrase(op->source_, &f), stringify(
"GL: ",name,
": vector arguments of different lengths"));
} else {
throw Exception(At_GL_Phrase(op->source_, &f), stringify(
"GL: ",name,": argument has bad type"));
}
}
auto result = f.gl.newvalue(type);
if (args.size() == 0)
f.gl.out << " " << type << " " << result << " = -0.0/0.0;\n";
else if (args.size() == 1)
return args.front();
else {
f.gl.out << " " << type << " " << result << " = ";
int rparens = 0;
while (args.size() > 2) {
f.gl.out << name << "(" << args.front() << ",";
args.pop_front();
++rparens;
}
f.gl.out << name << "(" << args.front() << "," << args.back() << ")";
while (rparens > 0) {
f.gl.out << ")";
--rparens;
}
f.gl.out << ";\n";
}
return result;
} else {
auto arg = argx.gl_eval(f);
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = ";
if (arg.type == GL_Type::Vec2)
f.gl.out << name <<"("<<arg<<".x,"<<arg<<".y);\n";
else if (arg.type == GL_Type::Vec3)
f.gl.out << name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y),"
<<arg<<".z);\n";
else if (arg.type == GL_Type::Vec4)
f.gl.out << name<<"("<<name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y),"
<<arg<<".z),"<<arg<<".w);\n";
else
throw Exception(At_GL_Phrase(argx.source_, &f), stringify(
name,": argument is not a vector"));
return result;
}
}
struct Max_Function : public Polyadic_Function
{
Max_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x, double y) {
// return NaN if either argument is NaN.
if (x >= y) return x;
if (x < y) return y;
return 0.0/0.0;
}
static const char* name() { return "max"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("max(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.reduce(-INFINITY, args[0], At_Arg(args));
}
GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f)
const override
{
return gl_minmax("max",argx,f);
}
};
struct Min_Function : public Polyadic_Function
{
Min_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x, double y) {
// return NaN if either argument is NaN
if (x <= y) return x;
if (x > y) return y;
return 0.0/0.0;
}
static const char* name() { return "min"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("min(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.reduce(INFINITY, args[0], At_Arg(args));
}
GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f)
const override
{
return gl_minmax("min",argx,f);
}
};
// Generalized dot product that includes vector dot product and matrix product.
// Same as Mathematica Dot[A,B]. Like APL A+.×B, Python numpy.dot(A,B)
struct Dot_Function : public Polyadic_Function
{
Dot_Function() : Polyadic_Function(2) {}
Value call(Frame& args) override
{
return dot(args[0], args[1], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
auto a = f[0];
auto b = f[1];
if (gl_type_count(a.type) < 2)
throw Exception(At_GL_Arg(0, f), "dot: argument is not a vector");
if (a.type != b.type)
throw Exception(At_GL_Arg(1, f), "dot: arguments have different types");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = dot("<<a<<","<<b<<");\n";
return result;
}
};
struct Mag_Function : public Polyadic_Function
{
Mag_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
// TODO: use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm?
// Avoids overflow/underflow due to squaring of large/small values.
// Slower. https://forum.kde.org/viewtopic.php?f=74&t=62402
auto& list = arg_to_list(args[0], At_Arg(args));
double sum = 0.0;
for (auto val : list) {
double x = val.get_num_or_nan();
sum += x * x;
}
if (sum == sum)
return {sqrt(sum)};
throw Exception(At_Arg(args), "mag: domain error");
}
GL_Value gl_call(GL_Frame& f) const override
{
auto arg = f[0];
if (gl_type_count(arg.type) < 2)
throw Exception(At_GL_Arg(0, f), "mag: argument is not a vector");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = length("<<arg<<");\n";
return result;
}
};
struct Count_Function : public Polyadic_Function
{
Count_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto list = args[0].dycast<const List>())
return {double(list->size())};
if (auto string = args[0].dycast<const String>())
return {double(string->size())};
throw Exception(At_Arg(args), "not a list or string");
}
};
struct Fields_Function : public Polyadic_Function
{
Fields_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto structure = args[0].dycast<const Structure>())
return {structure->fields()};
throw Exception(At_Arg(args), "not a record");
}
};
struct Strcat_Function : public Polyadic_Function
{
Strcat_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto list = args[0].dycast<const List>()) {
String_Builder sb;
for (auto val : *list) {
if (auto str = val.dycast<const String>())
sb << str;
else
sb << val;
}
return {sb.get_string()};
}
throw Exception(At_Arg(args), "not a list");
}
};
struct Repr_Function : public Polyadic_Function
{
Repr_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
String_Builder sb;
sb << args[0];
return {sb.get_string()};
}
};
struct Decode_Function : public Polyadic_Function
{
Decode_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
String_Builder sb;
At_Arg cx(f);
auto list = f[0].to<List>(cx);
for (size_t i = 0; i < list->size(); ++i)
sb << (char)arg_to_int((*list)[i], 1, 127, At_Index(i,cx));
return {sb.get_string()};
}
};
struct Encode_Function : public Polyadic_Function
{
Encode_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
List_Builder lb;
At_Arg cx(f);
auto str = f[0].to<String>(cx);
for (size_t i = 0; i < str->size(); ++i)
lb.push_back({(double)(int)str->at(i)});
return {lb.get_list()};
}
};
struct Match_Function : public Polyadic_Function
{
Match_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
At_Arg ctx0(f);
auto list = f[0].to<List>(ctx0);
std::vector<Shared<Function>> cases;
for (size_t i = 0; i < list->size(); ++i)
cases.push_back(list->at(i).to<Function>(At_Index(i,ctx0)));
return {make<Piecewise_Function>(cases)};
}
};
// The filename argument to "file", if it is a relative filename,
// is interpreted relative to the parent directory of the script file from
// which "file" is called.
//
// Because "file" has this hidden parameter (the name of the script file from
// which it is called), it is not a pure function. For this reason, it isn't
// a function value at all, it's a metafunction.
struct File_Expr : public Just_Expression
{
Shared<Operation> arg_;
File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg)
:
Just_Expression(std::move(src)),
arg_(std::move(arg))
{}
virtual Value eval(Frame& f) const override
{
auto& callphrase = dynamic_cast<const Call_Phrase&>(*source_);
At_Phrase cx(*callphrase.arg_, &f);
Value arg = arg_->eval(f);
auto argstr = arg.to<String>(cx);
namespace fs = boost::filesystem;
fs::path filepath;
auto caller_script_name = source_->location().script().name_;
if (caller_script_name->empty()) {
filepath = fs::path(argstr->c_str());
} else {
filepath = fs::path(caller_script_name->c_str()).parent_path()
/ fs::path(argstr->c_str());
}
auto file = make<File_Script>(make_string(filepath.c_str()), cx);
Program prog{*file, f.system_};
std::unique_ptr<Frame> f2 =
Frame::make(0, f.system_, &f, &callphrase, nullptr);
prog.compile(nullptr, &*f2);
return prog.eval();
}
};
struct File_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env));
}
};
/// The meaning of a call to `print`, such as `print "foo"`.
struct Print_Action : public Just_Action
{
Shared<Operation> arg_;
Print_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value arg = arg_->eval(f);
if (auto str = arg.dycast<String>())
f.system_.console() << *str;
else
f.system_.console() << arg;
f.system_.console() << std::endl;
}
};
/// The meaning of the phrase `print` in isolation.
struct Print_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
struct Warning_Action : public Just_Action
{
Shared<Operation> arg_;
Warning_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value arg = arg_->eval(f);
Shared<String> msg;
if (auto str = arg.dycast<String>())
msg = str;
else
msg = stringify(arg);
Exception exc{At_Phrase(*source_, &f), msg};
f.system_.console() << "WARNING: " << exc << std::endl;
}
};
/// The meaning of the phrase `warning` in isolation.
struct Warning_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
/// The meaning of a call to `error`, such as `error("foo")`.
struct Error_Operation : public Operation
{
Shared<Operation> arg_;
Error_Operation(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Operation(std::move(source)),
arg_(std::move(arg))
{}
[[noreturn]] void run(Frame& f) const
{
Value val = arg_->eval(f);
Shared<const String> msg;
if (auto s = val.dycast<String>())
msg = s;
else
msg = stringify(val);
throw Exception(At_Frame(&f), msg);
}
virtual void exec(Frame& f) const override
{
run(f);
}
virtual Value eval(Frame& f) const override
{
run(f);
}
virtual void generate(Frame& f, List_Builder&) const override
{
run(f);
}
virtual void bind(Frame& f, Record&) const override
{
run(f);
}
};
/// The meaning of the phrase `error` in isolation.
struct Error_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env));
}
};
// exec(expr) -- a debug action that evaluates expr, then discards the result.
// It is used to call functions or scripts for their side effects.
struct Exec_Action : public Just_Action
{
Shared<Operation> arg_;
Exec_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
arg_->eval(f);
}
};
struct Exec_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
struct Assert_Action : public Just_Action
{
Shared<Operation> arg_;
Assert_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value a = arg_->eval(f);
if (!a.is_bool())
throw Exception(At_Phrase(*source_, &f), "domain error");
bool b = a.get_bool_unsafe();
if (!b)
throw Exception(At_Phrase(*source_, &f), "assertion failed");
}
};
struct Assert_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto args = ph.analyse_args(env);
if (args.size() != 1)
throw Exception(At_Phrase(ph, env), "assert: expecting 1 argument");
return make<Assert_Action>(share(ph), args.front());
}
};
struct Assert_Error_Action : public Just_Action
{
Shared<Operation> expected_message_;
Shared<const String> actual_message_;
Shared<Operation> expr_;
Assert_Error_Action(
Shared<const Phrase> source,
Shared<Operation> expected_message,
Shared<const String> actual_message,
Shared<Operation> expr)
:
Just_Action(std::move(source)),
expected_message_(std::move(expected_message)),
actual_message_(std::move(actual_message)),
expr_(std::move(expr))
{}
virtual void exec(Frame& f) const override
{
Value expected_msg_val = expected_message_->eval(f);
auto expected_msg_str = expected_msg_val.to<const String>(
At_Phrase(*expected_message_->source_, &f));
if (actual_message_ != nullptr) {
if (*actual_message_ != *expected_msg_str)
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", actual error \"",
actual_message_,
"\""));
return;
}
Value result;
try {
result = expr_->eval(f);
} catch (Exception& e) {
if (*e.shared_what() != *expected_msg_str) {
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", actual error \"",
e.shared_what(),
"\""));
}
return;
}
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", got value ", result));
}
};
struct Assert_Error_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto parens = cast<Paren_Phrase>(ph.arg_);
Shared<Comma_Phrase> commas = nullptr;
if (parens) commas = cast<Comma_Phrase>(parens->body_);
if (parens && commas && commas->args_.size() == 2) {
auto msg = analyse_op(*commas->args_[0].expr_, env);
Shared<Operation> expr = nullptr;
Shared<const String> actual_msg = nullptr;
try {
expr = analyse_op(*commas->args_[1].expr_, env);
} catch (Exception& e) {
actual_msg = e.shared_what();
}
return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr);
} else {
throw Exception(At_Phrase(ph, env),
"assert_error: expecting 2 arguments");
}
}
};
struct Defined_Expression : public Just_Expression
{
Shared<const Operation> expr_;
Atom_Expr selector_;
Defined_Expression(
Shared<const Phrase> source,
Shared<const Operation> expr,
Atom_Expr selector)
:
Just_Expression(std::move(source)),
expr_(std::move(expr)),
selector_(std::move(selector))
{
}
virtual Value eval(Frame& f) const override
{
auto val = expr_->eval(f);
auto s = val.dycast<Structure>();
if (s) {
auto id = selector_.eval(f);
return {s->hasfield(id)};
} else {
return {false};
}
}
};
struct Defined_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto arg = analyse_op(*ph.arg_, env);
auto dot = cast<Dot_Expr>(arg);
if (dot != nullptr)
return make<Defined_Expression>(
share(ph), dot->base_, dot->selector_);
throw Exception(At_Phrase(*ph.arg_, env),
"defined: argument must be `expression.identifier`");
}
};
const Namespace&
builtin_namespace()
{
static const Namespace names = {
{"pi", make<Builtin_Value>(pi)},
{"tau", make<Builtin_Value>(two_pi)},
{"inf", make<Builtin_Value>(INFINITY)},
{"null", make<Builtin_Value>(Value())},
{"false", make<Builtin_Value>(Value(false))},
{"true", make<Builtin_Value>(Value(true))},
{"is_null", make<Builtin_Value>(Value{make<Is_Null_Function>()})},
{"is_bool", make<Builtin_Value>(Value{make<Is_Bool_Function>()})},
{"is_num", make<Builtin_Value>(Value{make<Is_Num_Function>()})},
{"is_string", make<Builtin_Value>(Value{make<Is_String_Function>()})},
{"is_list", make<Builtin_Value>(Value{make<Is_List_Function>()})},
{"is_record", make<Builtin_Value>(Value{make<Is_Record_Function>()})},
{"is_fun", make<Builtin_Value>(Value{make<Is_Fun_Function>()})},
{"bit", make<Builtin_Value>(Value{make<Bit_Function>()})},
{"sqrt", make<Builtin_Value>(Value{make<Sqrt_Function>()})},
{"log", make<Builtin_Value>(Value{make<Log_Function>()})},
{"abs", make<Builtin_Value>(Value{make<Abs_Function>()})},
{"floor", make<Builtin_Value>(Value{make<Floor_Function>()})},
{"round", make<Builtin_Value>(Value{make<Round_Function>()})},
{"sin", make<Builtin_Value>(Value{make<Sin_Function>()})},
{"asin", make<Builtin_Value>(Value{make<Asin_Function>()})},
{"cos", make<Builtin_Value>(Value{make<Cos_Function>()})},
{"acos", make<Builtin_Value>(Value{make<Acos_Function>()})},
{"atan2", make<Builtin_Value>(Value{make<Atan2_Function>()})},
{"max", make<Builtin_Value>(Value{make<Max_Function>()})},
{"min", make<Builtin_Value>(Value{make<Min_Function>()})},
{"dot", make<Builtin_Value>(Value{make<Dot_Function>()})},
{"mag", make<Builtin_Value>(Value{make<Mag_Function>()})},
{"count", make<Builtin_Value>(Value{make<Count_Function>()})},
{"fields", make<Builtin_Value>(Value{make<Fields_Function>()})},
{"strcat", make<Builtin_Value>(Value{make<Strcat_Function>()})},
{"repr", make<Builtin_Value>(Value{make<Repr_Function>()})},
{"decode", make<Builtin_Value>(Value{make<Decode_Function>()})},
{"encode", make<Builtin_Value>(Value{make<Encode_Function>()})},
{"match", make<Builtin_Value>(Value{make<Match_Function>()})},
{"file", make<Builtin_Meaning<File_Metafunction>>()},
{"print", make<Builtin_Meaning<Print_Metafunction>>()},
{"warning", make<Builtin_Meaning<Warning_Metafunction>>()},
{"error", make<Builtin_Meaning<Error_Metafunction>>()},
{"assert", make<Builtin_Meaning<Assert_Metafunction>>()},
{"assert_error", make<Builtin_Meaning<Assert_Error_Metafunction>>()},
{"exec", make<Builtin_Meaning<Exec_Metafunction>>()},
{"defined", make<Builtin_Meaning<Defined_Metafunction>>()},
};
return names;
}
} // namespace curv
| 31.75813 | 84 | 0.588096 | iplayfast |
1b88e855a8002879c5a18bafa21bc646d65cfc8e | 13,643 | cpp | C++ | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2017, ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PCCCommon.h"
#include "PCCKdTree.h"
#include "tbb/tbb.h"
#include "PCCNormalsGenerator.h"
using namespace pcc;
void PCCNormalsGenerator3::init( const size_t pointCount, const PCCNormalsGenerator3Parameters& params ) {
normals_.resize( pointCount );
if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) {
numberOfNearestNeighborsInNormalEstimation_.resize( pointCount );
} else {
numberOfNearestNeighborsInNormalEstimation_.resize( 0 );
}
if ( params.storeEigenvalues_ ) {
eigenvalues_.resize( pointCount );
} else {
eigenvalues_.resize( 0 );
}
if ( params.storeCentroids_ ) {
barycenters_.resize( pointCount );
} else {
barycenters_.resize( 0 );
}
}
void PCCNormalsGenerator3::compute( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params,
const size_t nbThread ) {
nbThread_ = nbThread;
init( pointCloud.getPointCount(), params );
computeNormals( pointCloud, kdtree, params );
if ( params.numberOfIterationsInNormalSmoothing_ != 0u ) { smoothNormals( pointCloud, kdtree, params ); }
orientNormals( pointCloud, kdtree, params );
}
void PCCNormalsGenerator3::computeNormal( const size_t index,
const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params,
PCCNNResult& nNResult ) {
PCCVector3D bary( pointCloud[index][0], pointCloud[index][1], pointCloud[index][2] );
PCCVector3D normal( 0.0 );
PCCVector3D eigenval( 0.0 );
PCCMatrix3D covMat;
PCCMatrix3D Q;
PCCMatrix3D D;
kdtree.search( pointCloud[index], params.numberOfNearestNeighborsInNormalEstimation_, nNResult );
if ( nNResult.count() > 1 ) {
bary = 0.0;
for ( size_t i = 0; i < nNResult.count(); ++i ) { bary += pointCloud[nNResult.indices( i )]; }
bary /= double( nNResult.count() );
covMat = 0.0;
PCCVector3D pt;
for ( size_t i = 0; i < nNResult.count(); ++i ) {
pt = pointCloud[nNResult.indices( i )] - bary;
covMat[0][0] += pt[0] * pt[0];
covMat[1][1] += pt[1] * pt[1];
covMat[2][2] += pt[2] * pt[2];
covMat[0][1] += pt[0] * pt[1];
covMat[0][2] += pt[0] * pt[2];
covMat[1][2] += pt[1] * pt[2];
}
covMat[1][0] = covMat[0][1];
covMat[2][0] = covMat[0][2];
covMat[2][1] = covMat[1][2];
covMat /= ( nNResult.count() - 1.0 );
PCCDiagonalize( covMat, Q, D );
D[0][0] = fabs( D[0][0] );
D[1][1] = fabs( D[1][1] );
D[2][2] = fabs( D[2][2] );
if ( D[0][0] < D[1][1] && D[0][0] < D[2][2] ) {
normal[0] = Q[0][0];
normal[1] = Q[1][0];
normal[2] = Q[2][0];
eigenval[0] = D[0][0];
if ( D[1][1] < D[2][2] ) {
eigenval[1] = D[1][1];
eigenval[2] = D[2][2];
} else {
eigenval[2] = D[1][1];
eigenval[1] = D[2][2];
}
} else if ( D[1][1] < D[2][2] ) {
normal[0] = Q[0][1];
normal[1] = Q[1][1];
normal[2] = Q[2][1];
eigenval[0] = D[1][1];
if ( D[0][0] < D[2][2] ) {
eigenval[1] = D[0][0];
eigenval[2] = D[2][2];
} else {
eigenval[2] = D[0][0];
eigenval[1] = D[2][2];
}
} else {
normal[0] = Q[0][2];
normal[1] = Q[1][2];
normal[2] = Q[2][2];
eigenval[0] = D[2][2];
if ( D[0][0] < D[1][1] ) {
eigenval[1] = D[0][0];
eigenval[2] = D[1][1];
} else {
eigenval[2] = D[0][0];
eigenval[1] = D[1][1];
}
}
}
if ( normal * ( params.viewPoint_ - pointCloud[index] ) < 0.0 ) {
normals_[index] = -normal;
} else {
normals_[index] = normal;
}
if ( params.storeEigenvalues_ ) { eigenvalues_[index] = eigenval; }
if ( params.storeCentroids_ ) { barycenters_[index] = bary; }
if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) {
numberOfNearestNeighborsInNormalEstimation_[index] = uint32_t( nNResult.count() );
}
}
void PCCNormalsGenerator3::computeNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
const size_t pointCount = pointCloud.getPointCount();
normals_.resize( pointCount );
std::vector<size_t> subRanges;
const size_t chunckCount = 64;
PCCDivideRange( 0, pointCount, chunckCount, subRanges );
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) {
const size_t start = subRanges[i];
const size_t end = subRanges[i + 1];
PCCNNResult nNResult;
for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) {
computeNormal( ptIndex, pointCloud, kdtree, params, nNResult );
}
} );
} );
}
void PCCNormalsGenerator3::orientNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_SPANNING_TREE ) {
const size_t pointCount = pointCloud.getPointCount();
PCCNNResult nNResult;
visited_.resize( pointCount );
std::fill( visited_.begin(), visited_.end(), 0 );
PCCNNQuery3 nNQuery = {PCCPoint3D( 0.0 ),
static_cast<float>( params.radiusNormalOrientation_ ) * params.radiusNormalOrientation_,
params.numberOfNearestNeighborsInNormalOrientation_};
PCCNNQuery3 nNQuery2 = {PCCPoint3D( 0.0 ), ( std::numeric_limits<float>::max )(),
params.numberOfNearestNeighborsInNormalOrientation_};
size_t processedPointCount = 0;
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) {
if ( visited_[ptIndex] == 0u ) {
visited_[ptIndex] = 1;
++processedPointCount;
size_t numberOfNormals;
PCCVector3D accumulatedNormals;
addNeighbors( uint32_t( ptIndex ), pointCloud, kdtree, nNQuery2, nNResult, accumulatedNormals,
numberOfNormals );
if ( numberOfNormals == 0u ) {
if ( ptIndex != 0u ) {
accumulatedNormals = normals_[ptIndex - 1];
} else {
accumulatedNormals = ( params.viewPoint_ - pointCloud[ptIndex] );
}
}
if ( normals_[ptIndex] * accumulatedNormals < 0.0 ) { normals_[ptIndex] = -normals_[ptIndex]; }
while ( !edges_.empty() ) {
PCCWeightedEdge edge = edges_.top();
edges_.pop();
uint32_t current = edge.end_;
if ( visited_[current] == 0u ) {
visited_[current] = 1;
++processedPointCount;
if ( normals_[edge.start_] * normals_[current] < 0.0 ) { normals_[current] = -normals_[current]; }
addNeighbors( current, pointCloud, kdtree, nNQuery, nNResult, accumulatedNormals, numberOfNormals );
}
}
}
}
size_t negNormalCount = 0;
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) {
negNormalCount +=
static_cast<unsigned long long>( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 );
}
if ( negNormalCount > ( pointCount + 1 ) / 2 ) {
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) { normals_[ptIndex] = -normals_[ptIndex]; }
}
} else if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_VIEW_POINT ) {
const size_t pointCount = pointCloud.getPointCount();
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), pointCount, [&]( const size_t ptIndex ) {
if ( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 ) {
normals_[ptIndex] = -normals_[ptIndex];
}
} );
} );
}
}
void PCCNormalsGenerator3::addNeighbors( const uint32_t current,
const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
PCCNNQuery3& nNQuery,
PCCNNResult& nNResult,
PCCVector3D& accumulatedNormals,
size_t& numberOfNormals ) {
accumulatedNormals = 0.0;
numberOfNormals = 0;
if ( nNQuery.radius > 32768.0 ) {
kdtree.search( pointCloud[current], nNQuery.nearestNeighborCount, nNResult );
} else {
kdtree.searchRadius( pointCloud[current], nNQuery.nearestNeighborCount, nNQuery.radius, nNResult );
}
PCCWeightedEdge newEdge;
uint32_t index;
for ( size_t i = 0; i < nNResult.count(); ++i ) {
index = static_cast<uint32_t>( nNResult.indices( i ) );
if ( visited_[index] == 0u ) {
newEdge.weight_ = fabs( normals_[current] * normals_[index] );
newEdge.end_ = index;
newEdge.start_ = current;
edges_.push( newEdge );
} else if ( index != current ) {
accumulatedNormals += normals_[index];
++numberOfNormals;
}
}
}
void PCCNormalsGenerator3::smoothNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
const double w2 = params.weightNormalSmoothing_;
const double w0 = ( 1 - w2 );
const size_t pointCount = pointCloud.getPointCount();
PCCVector3D n0;
PCCVector3D n1;
PCCVector3D n2;
std::vector<size_t> subRanges;
const size_t chunckCount = 64;
PCCDivideRange( 0, pointCount, chunckCount, subRanges );
const double radius = params.radiusNormalSmoothing_ * params.radiusNormalSmoothing_;
for ( size_t it = 0; it < params.numberOfIterationsInNormalSmoothing_; ++it ) {
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) {
const size_t start = subRanges[i];
const size_t end = subRanges[i + 1];
PCCNNResult result;
for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) {
kdtree.searchRadius( pointCloud[ptIndex], params.numberOfNearestNeighborsInNormalSmoothing_, radius, result );
n0 = normals_[ptIndex];
n1 = 0.0;
for ( size_t i = 1; i < result.count(); ++i ) {
n2 = normals_[result.indices( i )];
if ( n0 * n2 < 0.0 ) {
n1 -= n2;
} else {
n1 += n2;
}
}
n1.normalize();
n1 = w0 * n0 + w2 * n1;
n1.normalize();
normals_[ptIndex] = n1;
}
} );
} );
}
}
| 44.152104 | 121 | 0.564978 | Dinghow |
1b8a52d6a1f2b485a9f6a9701005c7f41033b698 | 4,737 | cpp | C++ | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | /* ========================================
* UltrasonX - UltrasonX.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __UltrasonX_H
#include "UltrasonX.h"
#endif
AudioEffect* createEffectInstance(audioMasterCallback audioMaster) {return new UltrasonX(audioMaster);}
UltrasonX::UltrasonX(audioMasterCallback audioMaster) :
AudioEffectX(audioMaster, kNumPrograms, kNumParameters)
{
A = 0.5;
for (int x = 0; x < fix_total; x++) {fixA[x] = 0.0;}
fixA[fix_reso] = 0.7071; //butterworth Q
fpdL = 1.0; while (fpdL < 16386) fpdL = rand()*UINT32_MAX;
fpdR = 1.0; while (fpdR < 16386) fpdR = rand()*UINT32_MAX;
//this is reset: values being initialized only once. Startup values, whatever they are.
_canDo.insert("plugAsChannelInsert"); // plug-in can be used as a channel insert effect.
_canDo.insert("plugAsSend"); // plug-in can be used as a send effect.
_canDo.insert("x2in2out");
setNumInputs(kNumInputs);
setNumOutputs(kNumOutputs);
setUniqueID(kUniqueId);
canProcessReplacing(); // supports output replacing
canDoubleReplacing(); // supports double precision processing
programsAreChunks(true);
vst_strncpy (_programName, "Default", kVstMaxProgNameLen); // default program name
}
UltrasonX::~UltrasonX() {}
VstInt32 UltrasonX::getVendorVersion () {return 1000;}
void UltrasonX::setProgramName(char *name) {vst_strncpy (_programName, name, kVstMaxProgNameLen);}
void UltrasonX::getProgramName(char *name) {vst_strncpy (name, _programName, kVstMaxProgNameLen);}
//airwindows likes to ignore this stuff. Make your own programs, and make a different plugin rather than
//trying to do versioning and preventing people from using older versions. Maybe they like the old one!
static float pinParameter(float data)
{
if (data < 0.0f) return 0.0f;
if (data > 1.0f) return 1.0f;
return data;
}
VstInt32 UltrasonX::getChunk (void** data, bool isPreset)
{
float *chunkData = (float *)calloc(kNumParameters, sizeof(float));
chunkData[0] = A;
*data = chunkData;
return kNumParameters * sizeof(float);
}
VstInt32 UltrasonX::setChunk (void* data, VstInt32 byteSize, bool isPreset)
{
float *chunkData = (float *)data;
A = pinParameter(chunkData[0]);
/* We're ignoring byteSize as we found it to be a filthy liar */
/* calculate any other fields you need here - you could copy in
code from setParameter() here. */
return 0;
}
void UltrasonX::setParameter(VstInt32 index, float value) {
switch (index) {
case kParamA: A = value; break;
default: throw; // unknown parameter, shouldn't happen!
}
}
float UltrasonX::getParameter(VstInt32 index) {
switch (index) {
case kParamA: return A; break;
default: break; // unknown parameter, shouldn't happen!
} return 0.0; //we only need to update the relevant name, this is simple to manage
}
void UltrasonX::getParameterName(VstInt32 index, char *text) {
switch (index) {
case kParamA: vst_strncpy (text, "Q", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
} //this is our labels for displaying in the VST host
}
void UltrasonX::getParameterDisplay(VstInt32 index, char *text) {
switch (index) {
case kParamA: switch((VstInt32)( A * 4.999 )) //0 to almost edge of # of params
{ case kA: vst_strncpy (text, "Reso A", kVstMaxParamStrLen); break;
case kB: vst_strncpy (text, "Reso B", kVstMaxParamStrLen); break;
case kC: vst_strncpy (text, "Reso C", kVstMaxParamStrLen); break;
case kD: vst_strncpy (text, "Reso D", kVstMaxParamStrLen); break;
case kE: vst_strncpy (text, "Reso E", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
} break;
default: break; // unknown parameter, shouldn't happen!
} //this displays the values and handles 'popups' where it's discrete choices
}
void UltrasonX::getParameterLabel(VstInt32 index, char *text) {
switch (index) {
case kParamA: vst_strncpy (text, "", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
}
}
VstInt32 UltrasonX::canDo(char *text)
{ return (_canDo.find(text) == _canDo.end()) ? -1: 1; } // 1 = yes, -1 = no, 0 = don't know
bool UltrasonX::getEffectName(char* name) {
vst_strncpy(name, "UltrasonX", kVstMaxProductStrLen); return true;
}
VstPlugCategory UltrasonX::getPlugCategory() {return kPlugCategEffect;}
bool UltrasonX::getProductString(char* text) {
vst_strncpy (text, "airwindows UltrasonX", kVstMaxProductStrLen); return true;
}
bool UltrasonX::getVendorString(char* text) {
vst_strncpy (text, "airwindows", kVstMaxVendorStrLen); return true;
}
| 37.007813 | 104 | 0.695799 | themucha |
b8440821b6c2207c4e18a7d8705d5c5f3141435e | 9,091 | cpp | C++ | src/select/select_impl.cpp | b1nhm1nh/zsummerX | 0825d2a3b7476df614411c65a59f94df4fb927f6 | [
"MIT"
] | 343 | 2015-01-23T09:48:53.000Z | 2022-03-17T04:42:22.000Z | src/select/select_impl.cpp | zhuguang/zsummerX | 8e2e355aaa2f64d37348633ea5c2f1ec44a54152 | [
"MIT"
] | 22 | 2015-05-06T13:47:17.000Z | 2021-04-11T11:39:51.000Z | src/select/select_impl.cpp | zhuguang/zsummerX | 8e2e355aaa2f64d37348633ea5c2f1ec44a54152 | [
"MIT"
] | 178 | 2015-02-13T03:30:10.000Z | 2022-03-17T04:42:13.000Z | /*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2017 YaweiZhang <yawei.zhang@foxmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include <zsummerX/select/select_impl.h>
#include <zsummerX/select/tcpsocket_impl.h>
#include <zsummerX/select/tcpaccept_impl.h>
#include <zsummerX/select/udpsocket_impl.h>
using namespace zsummer::network;
bool EventLoop::initialize()
{
//////////////////////////////////////////////////////////////////////////
//create socket pair
sockaddr_in pairAddr;
memset(&pairAddr, 0, sizeof(pairAddr));
pairAddr.sin_family = AF_INET;
pairAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int acpt = socket(AF_INET, SOCK_STREAM, 0);
_sockpair[0] = socket(AF_INET, SOCK_STREAM, 0);
_sockpair[1] = socket(AF_INET, SOCK_STREAM, 0);
if (_sockpair[0] == -1 || _sockpair[1] == -1 || acpt == -1)
{
LCF("ZSummerImpl::initialize[this0x" << this << "] bind sockpair socket error. " );
return false;
}
if (::bind(acpt, (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] bind sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
if (listen(acpt, 1) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] listen sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
socklen_t len = sizeof(pairAddr);
if (getsockname(acpt, (sockaddr*)&pairAddr, &len) != 0)
{
LCF("EventLoop::initialize[this0x" << this << "] getsockname sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
if (::connect(_sockpair[0], (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] connect sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
_sockpair[1] = accept(acpt, (sockaddr*)&pairAddr, &len);
if (_sockpair[1] == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] accept sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
::close(acpt);
setNonBlock(_sockpair[0]);
setNonBlock(_sockpair[1]);
setNoDelay(_sockpair[0]);
setNoDelay(_sockpair[1]);
FD_ZERO(&_fdreads);
FD_ZERO(&_fdwrites);
FD_ZERO(&_fderrors);
setEvent(_sockpair[1], 0);
_arrayTcpAccept.resize(MAX_NUMBER_FD);
_arrayTcpSocket.resize(MAX_NUMBER_FD);
_arrayUdpSocket.resize(MAX_NUMBER_FD);
return true;
}
void EventLoop::setEvent(int fd, int op /*0 read, 1 write, 2 error*/)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
if (fd > _maxfd)
_maxfd = fd;
if (op == 0)
FD_SET(fd, &_fdreads);
else if(op == 1)
FD_SET(fd, &_fdwrites);
else if(op == 2)
FD_SET(fd, &_fderrors);
}
void EventLoop::unsetEvent(int fd, int op /*0 read, 1 write, 2 error*/)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
if (op == 0)
FD_CLR(fd, &_fdreads);
else if(op == 1)
FD_CLR(fd, &_fdwrites);
else if(op == 2)
FD_CLR(fd, &_fderrors);
}
void EventLoop::addTcpAccept(int fd, TcpAcceptPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayTcpAccept[fd] = s;
}
void EventLoop::addTcpSocket(int fd, TcpSocketPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayTcpSocket[fd] = s;
}
void EventLoop::addUdpSocket(int fd, UdpSocketPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayUdpSocket[fd] = s;
}
void EventLoop::clearSocket(int fd)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
unsetEvent(fd, 0);
unsetEvent(fd, 1);
unsetEvent(fd, 2);
_arrayTcpAccept[fd].reset();
_arrayTcpSocket[fd].reset();
_arrayUdpSocket[fd].reset();
}
void EventLoop::PostMessage(_OnPostHandler &&handle)
{
_OnPostHandler * pHandler = new _OnPostHandler(std::move(handle));
bool needNotice = false;
_postQueueLock.lock();
if (_postQueue.empty()){ needNotice = true;}
_postQueue.push_back(pHandler);
_postQueueLock.unlock();
if (needNotice)
{
char c = '0';
send(_sockpair[0], &c, 1, 0);
}
}
std::string EventLoop::logSection()
{
std::stringstream os;
_postQueueLock.lock();
MessageStack::size_type msgSize = _postQueue.size();
_postQueueLock.unlock();
os << " logSection: _sockpair[2]={" << _sockpair[0] << "," << _sockpair[1] << "}"
<< " _postQueue.size()=" << msgSize << ", current total timer=" << _timer.getTimersCount()
<< " _maxfd=" << _maxfd;
return os.str();
}
void EventLoop::runOnce(bool isImmediately)
{
fd_set fdr;
fd_set fdw;
fd_set fde;
memcpy(&fdr, &_fdreads, sizeof(_fdreads));
memcpy(&fdw, &_fdwrites, sizeof(_fdwrites));
memcpy(&fde, &_fderrors, sizeof(_fderrors));
timeval tv;
if (isImmediately)
{
tv.tv_sec = 0;
tv.tv_usec = 0;
}
else
{
unsigned int ms = _timer.getNextExpireTime();
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000) * 1000;
}
int retCount = ::select(_maxfd+1, &fdr, &fdw, &fde, &tv);
if (retCount == -1)
{
return;
}
//check timer
{
_timer.checkTimer();
if (retCount == 0) return;//timeout
}
if (FD_ISSET(_sockpair[1], &fdr))
{
char buf[1000];
while (recv(_sockpair[1], buf, 1000, 0) > 0);
MessageStack msgs;
_postQueueLock.lock();
msgs.swap(_postQueue);
_postQueueLock.unlock();
for (auto pfunc : msgs)
{
_OnPostHandler * p = (_OnPostHandler*)pfunc;
try
{
(*p)();
}
catch (const std::exception & e)
{
LCW("OnPostHandler have runtime_error exception. err=" << e.what());
}
catch (...)
{
LCW("OnPostHandler have unknown exception.");
}
delete p;
}
}
for (int i = 0; i <= _maxfd ; ++i)
{
//tagHandle type
if (FD_ISSET(i, &fdr) || FD_ISSET(i, &fdw) || FD_ISSET(i, &fde))
{
if (_arrayTcpAccept[i])
_arrayTcpAccept[i]->onSelectMessage();
if (_arrayTcpSocket[i])
{
_arrayTcpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde));
}
if (_arrayUdpSocket[i])
{
_arrayUdpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde));
}
}
}
}
| 29.420712 | 109 | 0.571554 | b1nhm1nh |
b84602d59cb7ef68d70b89dd04d7c07da56ae332 | 625 | ipp | C++ | libs/config/test/boost_no_std_typeinfo.ipp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 11 | 2015-07-12T13:04:52.000Z | 2021-05-30T23:23:46.000Z | libs/config/test/boost_no_std_typeinfo.ipp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | null | null | null | libs/config/test/boost_no_std_typeinfo.ipp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 3 | 2015-12-23T01:51:57.000Z | 2019-08-25T04:58:32.000Z | // (C) Copyright Peter Dimov 2007.
// Use, modification and distribution are subject to 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/config for most recent version.
// MACRO: BOOST_NO_STD_TYPEINFO
// TITLE: type_info not in namespace std
// DESCRIPTION: The <typeinfo> header declares type_info in the global namespace instead of std
#include <typeinfo>
namespace boost_no_std_typeinfo
{
int test()
{
std::type_info * p = 0;
return 0;
}
}
| 25 | 99 | 0.6768 | zyiacas |
b846d36adac564c33820141a84eebee099380df9 | 2,739 | cxx | C++ | sw/3rd_party/VTK-7.1.0/Examples/ParallelProcessing/Generic/Cxx/TaskParallelismWithPorts.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | 4 | 2019-05-30T01:52:12.000Z | 2021-09-29T21:12:13.000Z | sw/3rd_party/VTK-7.1.0/Examples/ParallelProcessing/Generic/Cxx/TaskParallelismWithPorts.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | null | null | null | sw/3rd_party/VTK-7.1.0/Examples/ParallelProcessing/Generic/Cxx/TaskParallelismWithPorts.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | 2 | 2019-08-30T23:36:13.000Z | 2019-11-08T16:52:01.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: TaskParallelismWithPorts.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example demonstrates how to write a task parallel application
// with VTK. It creates two different pipelines and assigns each to
// one processor. These pipelines are:
// 1. rtSource -> contour -> probe .-> append
// \ / port
// -> gradient magnitude /
// 2. rtSource -> gradient -> shrink -> glyph3D -> port
// See task3.cxx and task4.cxx for the pipelines.
#include "TaskParallelismWithPorts.h"
// This function sets up properties common to both processes
// and executes the task corresponding to the current process
void process(vtkMultiProcessController* controller, void* vtkNotUsed(arg))
{
taskFunction task;
int myId = controller->GetLocalProcessId();
// Chose the appropriate task (see task3.cxx and task4.cxx)
if ( myId == 0 )
{
task = task3;
}
else
{
task = task4;
}
// Run the tasks (see task3.cxx and task4.cxx)
(*task)(EXTENT);
}
int main( int argc, char* argv[] )
{
// Note that this will create a vtkMPIController if MPI
// is configured, vtkThreadedController otherwise.
vtkMultiProcessController* controller = vtkMultiProcessController::New();
controller->Initialize(&argc, &argv);
// When using MPI, the number of processes is determined
// by the external program which launches this application.
// However, when using threads, we need to set it ourselves.
if (controller->IsA("vtkThreadedController"))
{
// Set the number of processes to 2 for this example.
controller->SetNumberOfProcesses(2);
}
int numProcs = controller->GetNumberOfProcesses();
if (numProcs != 2)
{
cerr << "This example requires two processes." << endl;
controller->Finalize();
controller->Delete();
return 1;
}
// Execute the function named "process" on both processes
controller->SetSingleMethod(process, 0);
controller->SingleMethodExecute();
// Clean-up and exit
controller->Finalize();
controller->Delete();
return 0;
}
| 29.138298 | 76 | 0.619204 | esean |
b84757937bcb1064675cd86e3362120718882383 | 3,240 | cpp | C++ | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | //연구소 3 다시풀기 8시 40분
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
#define debug 0
int dx[4] ={ -1, 0, 1, 0};
int dy[4] ={ 0, 1, 0, -1 };
class lab
{
public:
int n, m;
vector<int> t;
vector<int> vis;
int blac=0;
int time;
void input()
{
cin>>n >> m;
t= vector<int>(n*n);
for(int i=0; i<n*n; i++){
cin>> t[i];
if(t[i]==2) vis.push_back(i);
if(t[i]==0) blac++;
}
}
int spread(vector<int> selected)
{
vector<int> nt =t; //퍼진 후 멥
queue<int> q_vis;
vector<int> sp_t(n*n); //각 칸에 퍼진 시간을 기록
int spread_time=0;
int sp_area=0;
#if debug
cout<<"\n selected :" ;
#endif
for(int i: selected) //활성 비이러스로 바꾸기, 활성 바이러스는 4로 표시
{
nt[i] = 4;
q_vis.push(i);
#if debug
cout<<i<<" ";
#endif
}
while(!q_vis.empty())
{
int cur = q_vis.front();
q_vis.pop();
int x = cur%n;
int y = cur/n;
for(int j=0; j<4 ;j++)//현재 위치를 기준으로 4방향 조사
{
int nx= x+dx[j];
int ny= y+dy[j];
if(nx>=n || nx<0 || ny>=n || ny<0 ) continue; //큐에 넣을 필요 없는놈들
if(nt[ny*n+nx]==1 || nt[ny*n+nx]==4) continue;
if(t[ny*n+nx]==0) sp_area++;
sp_t[ny*n+nx] = sp_t[cur]+1; // 이 칸에 최초로 퍼진 시간은, 이칸을 퍼트린 놈의 시간 +1
if( spread_time < sp_t[cur]+1 && t[ny*n+nx]==0 ) spread_time = sp_t[cur]+1 ;
// 저 조건들을 제외하면 0 또는 2(비 활성 바이러스)
nt[ny*n+nx] = 4; //활성 시켜주고
q_vis.push(ny*n+nx); //다음에 여기서부터 뻗어가도록 추가
}
#if debug
cout<<endl;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
char a;
if(t[i*n+j]==1) a='-';
else if(t[i*n+j]==2) a='*';
else a= to_string(sp_t[i*n+j])[0];
cout<< a<<" ";
}
cout<<endl;
}
cout<<endl;
#endif
}
if(sp_area == blac)
return spread_time;
else
return -1;
}
int sol()
{
input();
// if(vis.size()==0 && blac !=0) return -1;
if(blac ==0) return 0;
//vis 중에 m개를 선택
int min_time=999999;
int time;
vector<int> selected;
vector<bool> combintaion;
for(int i=0; i<m; i++)
combintaion.push_back(1);
while(combintaion.size() < vis.size()) combintaion.push_back(0);
sort(combintaion.begin(), combintaion.end());
do
{
for(int i=0; i<combintaion.size(); i++)
if(combintaion[i]) selected.push_back(vis[i]);
time= spread(selected);
if(time <min_time && time != -1) min_time=time;
selected.clear();
selected.resize(0);
}while(next_permutation(combintaion.begin(), combintaion.end()));
if(min_time != 999999)
return min_time;
else
return -1;
}
};
int main()
{
lab l;
cout<<l.sol();
return 0;
} | 21.315789 | 100 | 0.437346 | goongg |
b8478a49f898e10c0bb161004640961b96364e04 | 1,492 | cpp | C++ | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 5 | 2019-12-02T07:13:06.000Z | 2019-12-02T14:34:36.000Z | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2021-05-28T03:48:40.000Z | 2021-05-28T03:48:40.000Z | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2020-02-12T14:00:22.000Z | 2020-02-12T14:00:22.000Z | #include "glfw_renderer_frontend.hpp"
#include <mbgl/renderer/renderer.hpp>
#include <mbgl/gfx/backend_scope.hpp>
GLFWRendererFrontend::GLFWRendererFrontend(std::unique_ptr<mbgl::Renderer> renderer_, GLFWView& glfwView_)
: glfwView(glfwView_)
, renderer(std::move(renderer_)) {
glfwView.setRenderFrontend(this);
}
GLFWRendererFrontend::~GLFWRendererFrontend() = default;
void GLFWRendererFrontend::reset() {
assert(renderer);
renderer.reset();
}
void GLFWRendererFrontend::setObserver(mbgl::RendererObserver& observer) {
assert(renderer);
renderer->setObserver(&observer);
}
void GLFWRendererFrontend::update(std::shared_ptr<mbgl::UpdateParameters> params) {
updateParameters = std::move(params);
glfwView.invalidate();
}
void GLFWRendererFrontend::render() {
assert(renderer);
if (!updateParameters) return;
mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit };
// onStyleImageMissing might be called during a render. The user implemented method
// could trigger a call to MGLRenderFrontend#update which overwrites `updateParameters`.
// Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is
// still using them.
auto updateParameters_ = updateParameters;
renderer->render(*updateParameters_);
}
mbgl::Renderer* GLFWRendererFrontend::getRenderer() {
assert(renderer);
return renderer.get();
}
| 31.083333 | 114 | 0.735925 | gomapi |
b8484451cf9ee98b67f41ee32d67249456d1ea73 | 5,912 | cpp | C++ | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | 1 | 2020-06-15T01:44:13.000Z | 2020-06-15T01:44:13.000Z | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | null | null | null | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | null | null | null | #include "application.h"
#include "game/brick.h"
#include "game/paddle.h"
#include "game/platform.h"
#include "game/background.h"
#include "game/camera.h"
#include "game/ball.h"
//--------------------------------------------------------------
MiniVkApplication::MiniVkApplication()
: currentFrame(0)
, framebufferResized(false)
, m_window(nullptr)
{
}
//--------------------------------------------------------------
MiniVkApplication::~MiniVkApplication()
{
}
//--------------------------------------------------------------
void MiniVkApplication::run() {
initWindow();
initVulkan();
initScene();
mainLoop();
cleanup();
}
//--------------------------------------------------------------
void MiniVkApplication::initWindow()
{
glfwInit();
// dont create OGL context
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
// special case of resizing (disable for this time)
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
m_window = glfwCreateWindow(APP_WIDTH, APP_HEIGHT, "Brick Breaker with Vulkan", nullptr, nullptr);
glfwSetWindowUserPointer(m_window, this);
glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback);
}
//--------------------------------------------------------------
void MiniVkApplication::framebufferResizeCallback(GLFWwindow* window, int /*width*/, int /*height*/)
{
auto app = reinterpret_cast<MiniVkApplication*>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
//--------------------------------------------------------------
void MiniVkApplication::initVulkan()
{
m_gcore = new GraphicsCore(m_window);
m_gcore->initialize();
m_swapchain = new SwapChainResources(m_gcore->device(), m_gcore->surface());
m_swapchain->initialize();
m_descpool = new DescriptorPool(m_gcore->device(), m_swapchain->count(), 10);
m_pipeline = new ShaderPipeline(m_gcore->device(), m_swapchain->getRenderPass(), m_swapchain->getSwapChain()->getExtent());
m_drawcmd = new DrawCommandBuffer(m_swapchain, m_pipeline->pipeline());
m_drawcmd->initialize();
m_sync = new Synchronization(m_gcore->device());
m_sync->initialize();
}
//--------------------------------------------------------------
void MiniVkApplication::initScene()
{
m_assets = new AssetsLoader(m_gcore->device(), m_descpool, m_pipeline->layout());
m_drawables = new DrawableAllocator(m_gcore->device(), m_swapchain, m_pipeline->layout(), m_descpool);
Camera* cam = new Camera(30.0, m_gcore->device(), m_descpool, m_pipeline->layout(), m_swapchain);
m_sceneObjects.setView(cam);
Paddle* paddle = new Paddle();
paddle->position.y = -6.0;
m_sceneObjects.add(paddle);
m_collisions.setPaddle(paddle);
std::srand(0);
float depf = 1.4;
for(int x=0;x<20;++x) for(int y=0;y<5;++y)
{
float xf = float(x) * depf - 13.0;
float yf = float(y) * depf + 3.5;
Brick* brick = new Brick();
brick->position.x = xf;
brick->position.y = yf;
brick->color.x = float(std::rand())/RAND_MAX;
brick->color.y = float(std::rand())/RAND_MAX;
brick->color.z = float(std::rand())/RAND_MAX;
brick->m_timeOffset = float(std::rand());
m_sceneObjects.add(brick);
m_collisions.addBrick(brick);
}
Platform* platform = new Platform();
platform->position.y = -10.0;
m_sceneObjects.add(platform);
m_collisions.setPlatform(platform);
Background* background = new Background();
background->position.z = -2.0;
m_sceneObjects.add(background);
Ball* ball = new Ball();
m_sceneObjects.add(ball);
m_collisions.setBall(ball);
}
//--------------------------------------------------------------
void MiniVkApplication::mainLoop()
{
while (!glfwWindowShouldClose(m_window))
{
glfwPollEvents();
drawFrame();
}
vkDeviceWaitIdle(m_gcore->device()->get());
}
//--------------------------------------------------------------
void MiniVkApplication::drawFrame()
{
m_sync->waitForFence();
uint32_t imageIndex = m_swapchain->getSwapChain()->acquireNextImage(m_sync->getImgAvailableSemaphore());
m_sceneObjects.updateState(m_window);
m_sceneObjects.animateScene();
m_collisions.checkCollisions();
m_sceneObjects.updateUniform(imageIndex);
m_drawcmd->beginDraw(imageIndex);
m_drawcmd->drawScene(&m_sceneObjects);
m_drawcmd->endDraw();
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = {m_sync->getImgAvailableSemaphore()};
VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_drawcmd->get(imageIndex)->get();
VkSemaphore signalSemaphores[] = {m_sync->getRenderFinishedSemaphore()};
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
m_sync->resetFence();
if (vkQueueSubmit(m_gcore->device()->getGraphicQueue()->get(), 1, &submitInfo, m_sync->getFence()) != VK_SUCCESS)
{
throw std::runtime_error("failed to submit draw command buffer!");
}
m_gcore->device()->getPresentQueue()->present(m_sync->getRenderFinishedSemaphore(), m_swapchain->getSwapChain(), imageIndex);
m_sync->nextFrame();
m_gcore->device()->getPresentQueue()->wait();
}
//--------------------------------------------------------------
void MiniVkApplication::cleanup()
{
glfwDestroyWindow(m_window);
glfwTerminate();
}
| 30.791667 | 130 | 0.594384 | Lut1n |
b84b2061b6d35ec21dc7194e137c0044517a953f | 4,840 | cpp | C++ | kjvm/kjvm.cpp | kuasha/jvm | e2244e6ac985fd299db742c8a7bb90893885c20d | [
"MIT"
] | 8 | 2020-10-15T05:35:09.000Z | 2021-06-06T17:53:18.000Z | kjvm/kjvm.cpp | kuasha/jvm | e2244e6ac985fd299db742c8a7bb90893885c20d | [
"MIT"
] | null | null | null | kjvm/kjvm.cpp | kuasha/jvm | e2244e6ac985fd299db742c8a7bb90893885c20d | [
"MIT"
] | 2 | 2021-06-05T04:34:10.000Z | 2022-03-13T14:40:03.000Z | // kjvm.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "kjvm.h"
#include "JavaClass.h"
#include "ClassHeap.h"
#include "types.h"
#include "constants.h"
#include "ExecutionEngine.h"
#include "ObjectHeap.h"
JavaClass *LoadClass(std::string strClassPath)
{
JavaClass *pClass = new JavaClass();
if (!pClass->LoadClassFromFile(strClassPath))
{
delete pClass;
pClass = NULL;
}
return pClass;
}
void ShowClassInfo(JavaClass *pClass);
int Execute(std::string strClass)
{
std::string path = strClass;
ClassHeap heap;
JavaClass *pClass1, *pClass2, *pClass3;
pClass1 = new JavaClass();
pClass2 = new JavaClass();
heap.AddClassRoot("/home/boltu/workspaces/jvm/kjvm/lib");
bool bRet = heap.LoadClass(strClass, pClass1);
bRet = heap.LoadClass("java/lang/Object", pClass2);
ObjectHeap oheap;
Frame *pFrameStack = new Frame[20];
Frame::pBaseFrame = pFrameStack;
memset(pFrameStack, 0, sizeof(Frame) * 20);
Frame::pOpStack = new Variable[100];
memset(Frame::pOpStack, 0, sizeof(Variable) * 100);
ExecutionEngine ex;
ex.pClassHeap = &heap;
ex.pObjectHeap = &oheap;
int startFrame = 0;
Object object = oheap.CreateObject(pClass1);
JavaClass *pVirtualClass = pClass1;
int mindex = pClass1->GetMethodIndex("Entry", "()I", pVirtualClass);
pFrameStack[startFrame].pClass = pVirtualClass;
pFrameStack[startFrame].pMethod = &pVirtualClass->methods[mindex];
pFrameStack[startFrame].stack = Frame::pOpStack;
pFrameStack[startFrame].sp = pFrameStack[startFrame].pMethod->pCode_attr->max_locals;
pFrameStack[startFrame].stack[0].object = object;
ex.Execute(&pFrameStack[startFrame]);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
return -1;
}
return Execute(argv[1]);
}
void Test2()
{
std::string path = "Test";
std::string path2 = "java\\lang\\Object";
ClassHeap heap;
JavaClass *pClass1, *pClass2, *pClass3;
pClass1 = new JavaClass();
pClass2 = new JavaClass();
bool bRet = heap.LoadClass(path, pClass1);
bRet = heap.LoadClass(path2, pClass2);
pClass3 = heap.GetClass("Test");
for (int i = 0; pClass3 && i < pClass3->interfaces_count; i++)
{
u2 intr = pClass3->interfaces[i];
std::string name;
cp_info *pi = pClass3->constant_pool[intr];
assert(pi->tag == CONSTANT_Class);
char *p = (char *)pi;
int ni = getu2((char *)(&p[1]));
pClass3->GetStringFromConstPool(ni, name);
printf("Loading Interface %s\n", name);
JavaClass *pClass4 = new JavaClass();
bRet = heap.LoadClass(name.c_str(), pClass4);
if (bRet)
ShowClassInfo(pClass4);
}
}
void ShowClassInfo(JavaClass *pClass)
{
if (!pClass)
return;
std::string name = pClass->GetName();
printf("Class Name = [%s]\n", name.c_str());
name = pClass->GetSuperClassName();
printf("Super Class Name = [%s]\n", name.c_str());
printf("Object Size = [%lu]\n", pClass->GetObjectSize());
for (int i = 1; i < pClass->constant_pool_count - 1; i++)
{
std::string strRetVal;
printf("Pool %d Type = %d ", i, pClass->constant_pool[i]->tag);
if (1 != pClass->constant_pool[i]->tag)
continue;
pClass->GetStringFromConstPool(i, strRetVal);
printf("String at %d [%s]\n", i, strRetVal.c_str());
}
for (int i = 0; i < pClass->methods_count; i++)
{
std::cout << "Method " << i << ":" << std::endl;
std::cout << "Access flags: " << pClass->methods[i].access_flags << std::endl;
if (pClass->methods[i].pCode_attr != NULL)
{
printf("ode Length= %d\n", pClass->methods[i].pCode_attr->code_length);
printf("Max stack = %d, Max Locals = %d, Exception table length= %d\nCODE\n", pClass->methods[i].pCode_attr->max_stack, pClass->methods[i].pCode_attr->max_locals, pClass->methods[i].pCode_attr->exception_table_length);
for (u4 j = 0; j < pClass->methods[i].pCode_attr->code_length; j++)
printf("%d ", pClass->methods[i].pCode_attr->code[j]);
printf("\nENDCODE\n");
}
else if (pClass->methods[i].access_flags && ACC_NATIVE)
{
printf("Method %d is native\n", i);
}
}
for (int i = 0; i < pClass->fields_count; i++)
{
std::string name, desc;
pClass->GetStringFromConstPool(pClass->fields[i].name_index, name);
pClass->GetStringFromConstPool(pClass->fields[i].descriptor_index, desc);
printf("Filed %d: Name: %s Type: %s\n", i, name, desc);
}
for (int i = 0; i < pClass->interfaces_count; i++)
{
u2 intr = pClass->interfaces[i];
std::string name;
cp_info *pi = pClass->constant_pool[intr];
assert(pi->tag == CONSTANT_Class);
char *p = (char *)pi;
int ni = getu2((char *)(&p[1]));
pClass->GetStringFromConstPool(ni, name);
printf("Interface %d: Name %s\n", i, name);
}
}
| 27.344633 | 222 | 0.648347 | kuasha |
b84c5b8194f8d705b07ce95ab810647313f3ac03 | 1,064 | cpp | C++ | Easy/38 - Count and Say.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 11 | 2015-08-06T15:43:48.000Z | 2022-02-16T01:30:24.000Z | Easy/38 - Count and Say.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 1 | 2015-08-17T13:33:55.000Z | 2015-08-27T03:43:47.000Z | Easy/38 - Count and Say.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 2 | 2021-09-30T14:39:05.000Z | 2021-10-02T11:02:20.000Z | /*
Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
@author Zixuan
@date 2015/8/12
*/
#include <string>
using namespace std;
class Solution
{
public:
string countAndSay(int n)
{
string sequence("1");
for (int i = 1; i < n; ++i)
{
string temp = sequence;
sequence.clear();
//It is sure temp.length() >= 1.
//Initalization.
char thisDigit = temp[0];
int thisTime = 0;
for (char j : temp)
{
if (j == thisDigit)
++thisTime;
else
{
sequence += (thisTime + '0');
sequence += thisDigit;
//Reconfigure thisDigit and thisTime;
thisDigit = j;
thisTime = 1;
}
}
//There must be an end.
sequence += (thisTime + '0');
sequence += thisDigit;
}
return sequence;
}
};
| 16.888889 | 76 | 0.607143 | WangZixuan |
b84d05416a4b47afcb3ba24dd7e08de57c80ed39 | 658 | cpp | C++ | exam-1/fall-2018/9.cpp | lherman-cs/cs4160 | abcc582e59f139ba8d8e74600ee028f321b308fd | [
"Apache-2.0"
] | 2 | 2019-04-18T21:28:18.000Z | 2019-04-18T21:28:52.000Z | exam-1/fall-2018/9.cpp | lherman-cs/cs4160 | abcc582e59f139ba8d8e74600ee028f321b308fd | [
"Apache-2.0"
] | null | null | null | exam-1/fall-2018/9.cpp | lherman-cs/cs4160 | abcc582e59f139ba8d8e74600ee028f321b308fd | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <list>
const int MAX = 20;
const int MAX_NUMBER = 101;
void eraseLessThan(std::list<int> &l, int max) {
std::cout << "removing all less than " << max << std::endl;
auto it = l.begin();
while (it != l.end()) {
if (*it < max) {
it = l.erase(it);
} else {
it++;
}
}
}
void init(std::list<int> &l) {
for (auto i = 0; i < MAX; i++) l.emplace_back(rand() % MAX_NUMBER);
}
void print(std::list<int> &l) {
for (auto el : l) std::cout << el << ' ';
std::cout << std::endl;
}
int main() {
std::list<int> l;
init(l);
print(l);
eraseLessThan(l, rand() % 50 + 50 - rand() % 30);
print(l);
} | 19.939394 | 69 | 0.534954 | lherman-cs |
b85420fdf60791b0a6e3b9d29c2984bd67cf6921 | 2,214 | cc | C++ | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | 1 | 2020-09-10T16:47:09.000Z | 2020-09-10T16:47:09.000Z | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | // test_fseek.cc
#include "menon/io.hh"
#include <boost/core/lightweight_test.hpp>
#include <cstddef>
#include <vector>
#include <fstream>
// テストデータの作成
long long make_test_file(char const* path)
{
std::vector<std::byte> v(256, std::byte(123));
if (auto stream = std::fopen(path, "wb"))
{
std::fwrite(v.data(), 1, v.size(), stream);
std::fclose(stream);
}
return static_cast<long long>(v.size());
}
int main()
{
char const* path = "test.data";
[[maybe_unused]] auto n = make_test_file(path);
{ // fseek/ftell関数の基本的な使い方
auto stream = std::fopen(path, "rb");
menon::fseek(stream, 100, SEEK_SET);
BOOST_TEST_EQ(std::ftell(stream), 100);
BOOST_TEST_EQ(std::ftell(stream), menon::ftell(stream));
std::fclose(stream);
}
{ // fseek/ftell関数とfsetpos/fgetpos関数の混在
auto stream = std::fopen(path, "rb");
menon::fpos_t pos;
menon::fseek(stream, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(stream, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(stream, &pos), 0);
BOOST_TEST_EQ(std::ftell(stream), 100);
std::fclose(stream);
}
{ // istream版のfseek関数
std::ifstream ifs(path);
menon::fseek(ifs, 100, SEEK_SET);
BOOST_TEST_EQ(ifs.tellg(), 100);
}
{ // istream版のfseek関数とfsetpos/fgetos関数の混在
std::ifstream ifs(path);
menon::fpos_t pos;
menon::fseek(ifs, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(ifs, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(ifs, &pos), 0);
BOOST_TEST_EQ(ifs.tellg(), 100);
}
{ // iostream版のfseek関数
std::fstream fs(path);
menon::fseek(fs, 100, SEEK_SET);
BOOST_TEST_EQ(fs.tellp(), 100);
BOOST_TEST_EQ(fs.tellg(), 100);
}
{ // ostream版のfseek関数
std::ofstream ofs(path);
menon::fseek(ofs, 100, SEEK_SET);
BOOST_TEST_EQ(ofs.tellp(), 100);
}
{ // ostream版のfseek関数とfsetpos/fgetpos関数の混在
std::ofstream ofs(path);
menon::fpos_t pos;
menon::fseek(ofs, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(ofs, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(ofs, &pos), 0);
BOOST_TEST_EQ(ofs.tellp(), 100);
}
std::remove(path);
return boost::report_errors();
}
| 25.744186 | 60 | 0.644986 | menonfled |
b854ce1b6c524e8dc9fdf931860abf58d57a087a | 6,084 | cpp | C++ | lc7/src/CLC7NavBar.cpp | phixion/l0phtcrack | 48ee2f711134e178dbedbd925640f6b3b663fbb5 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-10-20T00:25:39.000Z | 2021-11-08T12:52:42.000Z | lc7/src/CLC7NavBar.cpp | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
] | null | null | null | lc7/src/CLC7NavBar.cpp | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-14T06:41:16.000Z | 2022-03-14T06:41:16.000Z | #include"stdafx.h"
CLC7NavBar::CLC7NavBar(QStackedWidget *stackedwidget):QScrollArea(NULL), m_buttongroup(this)
{
TR;
m_stackedwidget=stackedwidget;
installEventFilter(this);
ILC7ColorManager *colman = CLC7App::getInstance()->GetMainWindow()->GetColorManager();
m_buttongroup.setExclusive(true);
m_groupwidget=new CLC7NavBarWidget(this);
setWidget(m_groupwidget);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setWidgetResizable(true);
m_scrollupbutton=new QPushButton(this);
m_scrollupbutton->setFixedHeight(16*colman->GetSizeRatio());
m_scrollupbutton->setObjectName("scroll-up-button");
m_scrollupbutton->setIcon(colman->GetMonoColorIcon(":/qss_icons/rc/up_arrow_disabled.png"));
m_scrolldownbutton=new QPushButton(this);
m_scrolldownbutton->setFixedHeight(16 * colman->GetSizeRatio());
m_scrolldownbutton->setObjectName("scroll-down-button");
m_scrolldownbutton->setIcon(colman->GetMonoColorIcon(":/qss_icons/rc/down_arrow_disabled.png"));
m_scrollupbutton->setVisible(false);
m_scrolldownbutton->setVisible(false);
connect(m_scrollupbutton, &QAbstractButton::pressed, this, &CLC7NavBar::slot_scrollUpButtonPressed);
connect(m_scrolldownbutton, &QAbstractButton::pressed, this, &CLC7NavBar::slot_scrollDownButtonPressed);
connect(m_scrollupbutton, &QAbstractButton::released, this, &CLC7NavBar::slot_scrollUpButtonReleased);
connect(m_scrolldownbutton, &QAbstractButton::released, this, &CLC7NavBar::slot_scrollDownButtonReleased);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(slot_doScrolling()));
m_scrolling_up=false;
m_scrolling_down=false;
}
void CLC7NavBar::slot_doScrolling(void)
{TR;
if (m_scrolling_up)
{
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - 5);
}
if (m_scrolling_down)
{
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + 5);
}
}
void CLC7NavBar::slot_scrollUpButtonPressed(void)
{TR;
m_scrolling_up = true;
m_timer->start(20);
}
void CLC7NavBar::slot_scrollDownButtonPressed(void)
{TR;
m_scrolling_down = true;
m_timer->start(20);
}
void CLC7NavBar::slot_scrollUpButtonReleased(void)
{TR;
m_timer->stop();
m_scrolling_up = false;
}
void CLC7NavBar::slot_scrollDownButtonReleased(void)
{TR;
m_timer->stop();
m_scrolling_down = false;
}
void CLC7NavBar::resizeEvent(QResizeEvent *evt)
{TR;
QSize sz=evt->size();
m_scrollupbutton->resize(200,16);
m_scrollupbutton->move(0,0);
m_scrolldownbutton->resize(200, 16);
m_scrolldownbutton->move(0,sz.height()-3);
}
bool CLC7NavBar::eventFilter(QObject *object, QEvent *event)
{
if(object==this && event->type()==QEvent::Enter)
{
QSize sz=size();
if(sz.height()<m_groupwidget->height())
{
m_scrollupbutton->setVisible(true);
m_scrolldownbutton->setVisible(true);
}
return true;
}
else if(object==this && event->type()==QEvent::Leave)
{
m_scrollupbutton->setVisible(false);
m_scrolldownbutton->setVisible(false);
return true;
}
return QScrollArea::eventFilter(object,event);
}
CLC7NavBarGroup *CLC7NavBar::addGroup(QString groupname)
{TR;
CLC7NavBarGroup *group=new CLC7NavBarGroup(this);
if(!groupname.isEmpty())
{
m_groups_by_name[groupname]=group;
}
m_groups.append(group);
QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout());
layout->insertWidget(-1,group);
hide();
show();
return group;
}
CLC7NavBarGroup *CLC7NavBar::insertGroup(int pos, QString groupname)
{TR;
CLC7NavBarGroup *group=new CLC7NavBarGroup(this);
if(!groupname.isEmpty())
{
m_groups_by_name[groupname]=group;
}
m_groups.insert(pos,group);
QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout());
layout->insertWidget(pos,group);
hide();
show();
return group;
}
void CLC7NavBar::removeGroup(int pos)
{TR;
CLC7NavBarGroup *group=m_groups[pos];
QString key=m_groups_by_name.key(group);
if(!key.isEmpty())
{
m_groups_by_name.remove(key);
}
m_groups.removeAt(pos);
QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout());
layout->removeWidget(group);
delete group;
hide();
show();
}
void CLC7NavBar::removeGroup(CLC7NavBarGroup *group)
{TR;
int pos=m_groups.indexOf(group);
QString key=m_groups_by_name.key(group);
if(!key.isEmpty())
{
m_groups_by_name.remove(key);
}
m_groups.removeAt(pos);
QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout());
layout->removeWidget(group);
delete group;
hide();
show();
}
void CLC7NavBar::removeGroup(QString groupname)
{TR;
if(m_groups_by_name.contains(groupname))
{
CLC7NavBarGroup *group=m_groups_by_name[groupname];
int pos=m_groups.indexOf(group);
QString key=m_groups_by_name.key(group);
if(!key.isEmpty())
{
m_groups_by_name.remove(key);
}
m_groups.removeAt(pos);
QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout());
layout->removeWidget(group);
delete group;
hide();
show();
}
}
CLC7NavBarGroup *CLC7NavBar::group(QString groupname)
{TR;
if(m_groups_by_name.contains(groupname))
{
CLC7NavBarGroup *group=m_groups_by_name[groupname];
return group;
}
return NULL;
}
CLC7NavBarGroup *CLC7NavBar::group(int pos)
{TR;
return m_groups[pos];
}
int CLC7NavBar::indexOf(CLC7NavBarGroup *group)
{TR;
return m_groups.indexOf(group);
}
int CLC7NavBar::indexOf(QString groupname)
{TR;
if(m_groups_by_name.contains(groupname))
{
CLC7NavBarGroup *group=m_groups_by_name[groupname];
return m_groups.indexOf(group);
}
return -1;
}
CLC7NavBarItem *CLC7NavBar::item(QWidget *buddy)
{TR;
foreach(CLC7NavBarGroup *group, m_groups)
{
CLC7NavBarItem *item=group->item(buddy);
if(item)
{
return item;
}
}
return NULL;
}
int CLC7NavBar::count()
{TR;
return m_groups.count();
}
QStackedWidget *CLC7NavBar::stackedwidget()
{
return m_stackedwidget;
} | 23.4 | 108 | 0.716798 | phixion |
b855805b1278fab0d5d3267d2e813e5f401fa998 | 2,589 | hpp | C++ | include/src/Extra/SOC/SOCLaw.impl.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | 1 | 2021-11-03T11:30:05.000Z | 2021-11-03T11:30:05.000Z | include/src/Extra/SOC/SOCLaw.impl.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | include/src/Extra/SOC/SOCLaw.impl.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | /*
* This file is part of So-bogus, a C++ sparse block matrix library and
* Second Order Cone solver.
*
* Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
*
* So-bogus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
* So-bogus 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 So-bogus. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BOGUS_SOCLAW_IMPL_HPP
#define BOGUS_SOCLAW_IMPL_HPP
#include "SOCLaw.hpp"
#include "../../Core/Utils/NumTraits.hpp"
#include "FischerBurmeister.hpp"
#include "LocalSOCSolver.hpp"
#include "LocalSOCSolver.impl.hpp"
namespace bogus {
template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat >
SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::SOCLaw(const unsigned n, const double *mu )
: m_mu(mu), m_n(n), m_localTol( std::pow( NumTraits< Scalar >::epsilon(), .75 ) )
{
}
template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat >
bool SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::solveLocal(const unsigned problemIndex,
const typename Traits::Matrix &A,
const typename Traits::Vector &b,
typename Traits::Vector &xm , const Scalar scaling ) const
{
typedef LocalSOCSolver< Traits::dimension, typename Traits::Scalar, DeSaxceCOV, Strat > LocalSolver ;
return m_localTol > LocalSolver::solve( A, b, xm, m_mu[ problemIndex ], m_localTol, scaling ) ;
}
template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat >
void SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::projectOnConstraint(
const unsigned problemIndex, typename Traits::Vector &x ) const
{
const Scalar nxt = Traits::tp( x ).norm() ;
const Scalar mu = m_mu[ problemIndex ] ;
const Scalar xn = Traits::np( x ) ;
if( mu < 0 ){ x.setZero() ; return ; }
// x inside cone
if ( nxt <= mu * xn ) return ;
// x inside dual cone
if( mu * nxt <= -xn ) {
x.setZero() ;
return ;
}
const Scalar den2 = ( 1 + mu * mu ) ;
const Scalar proj = ( xn + mu * nxt ) / den2 ;
Traits::np( x ) = proj ;
Traits::tp( x ) *= proj * mu / nxt ;
}
}
#endif
| 31.573171 | 105 | 0.70954 | sjokic |
b857437f1b00b85fe95cd917783c18cdff9f528a | 7,806 | cpp | C++ | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | 1 | 2020-10-29T07:39:00.000Z | 2020-10-29T07:39:00.000Z | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | null | null | null | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | null | null | null | /**
* @file fwf - Firewall filter test (also regression test for MXS-683 "qc_mysqlembedded reports as-name
* instead of original-name")
* - setup Firewall filter to use rules from rule file fw/ruleXX, where XX - number of sub-test
* - execute queries for fw/passXX file, expect OK
* - execute queries from fw/denyXX, expect Access Denied error (mysql_error 1141)
* - repeat for all XX
* - setup Firewall filter to block queries next 2 minutes using 'at_time' statement (see template
* fw/rules_at_time)
* - start sending queries, expect Access Denied now and OK after two mintes
* - setup Firewall filter to limit a number of queries during certain time
* - start sending queries as fast as possible, expect OK for N first quries and Access Denied for next
* queries
* - wait, start sending queries again, but only one query per second, expect OK
* - try to load rules with syntax error, expect failure for all sessions and queries
*/
#include <iostream>
#include <ctime>
#include <maxtest/testconnections.hh>
#include <maxtest/sql_t1.hh>
#include <maxtest/fw_copy_rules.hh>
int main(int argc, char* argv[])
{
TestConnections::skip_maxscale_start(true);
TestConnections* Test = new TestConnections(argc, argv);
int local_result;
char str[4096];
char sql[4096];
char pass_file[4096];
char deny_file[4096];
char rules_dir[4096];
FILE* file;
sprintf(rules_dir, "%s/fw/", test_dir);
int N = 19;
int i;
for (i = 1; i < N + 1; i++)
{
Test->set_timeout(180);
local_result = 0;
sprintf(str, "rules%d", i);
copy_rules(Test, str, rules_dir);
Test->maxscales->restart_maxscale(0);
Test->maxscales->connect_rwsplit(0);
sprintf(pass_file, "%s/fw/pass%d", test_dir, i);
sprintf(deny_file, "%s/fw/deny%d", test_dir, i);
if (Test->verbose)
{
Test->tprintf("Pass file: %s", pass_file);
Test->tprintf("Deny file: %s", deny_file);
}
file = fopen(pass_file, "r");
if (file != NULL)
{
if (Test->verbose)
{
Test->tprintf("********** Trying queries that should be OK ********** ");
}
while (fgets(sql, sizeof(sql), file))
{
if (strlen(sql) > 1)
{
if (Test->verbose)
{
Test->tprintf("%s", sql);
}
int rv = execute_query(Test->maxscales->conn_rwsplit[0], "%s", sql);
Test->add_result(rv, "Query should succeed: %s", sql);
local_result += rv;
}
}
fclose(file);
}
else
{
Test->add_result(1, "Error opening query file");
}
file = fopen(deny_file, "r");
if (file != NULL)
{
if (Test->verbose)
{
Test->tprintf("********** Trying queries that should FAIL ********** ");
}
while (fgets(sql, sizeof(sql), file))
{
Test->set_timeout(180);
if (strlen(sql) > 1)
{
if (Test->verbose)
{
Test->tprintf("%s", sql);
}
execute_query_silent(Test->maxscales->conn_rwsplit[0], sql);
if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141)
{
Test->tprintf("Expected 1141, Access Denied but got %d, %s instead: %s",
mysql_errno(Test->maxscales->conn_rwsplit[0]),
mysql_error(Test->maxscales->conn_rwsplit[0]),
sql);
local_result++;
}
}
}
fclose(file);
}
else
{
Test->add_result(1, "Error opening query file");
}
if (local_result)
{
Test->add_result(1, "********** rules%d test FAILED", i);
}
else
{
Test->tprintf("********** rules%d test PASSED", i);
}
mysql_close(Test->maxscales->conn_rwsplit[0]);
}
Test->set_timeout(180);
// Test for at_times clause
if (Test->verbose)
{
Test->tprintf("Trying at_times clause");
}
copy_rules(Test, (char*) "rules_at_time", rules_dir);
if (Test->verbose)
{
Test->tprintf("DELETE quries without WHERE clause will be blocked during the 30 seconds");
Test->tprintf("Put time to rules.txt: %s", str);
}
Test->maxscales->ssh_node_f(0,
false,
"start_time=`date +%%T`;"
"stop_time=` date --date \"now +30 secs\" +%%T`;"
"%s sed -i \"s/###time###/$start_time-$stop_time/\" %s/rules/rules.txt",
Test->maxscales->access_sudo(0),
Test->maxscales->access_homedir(0));
Test->maxscales->restart_maxscale(0);
Test->maxscales->connect_rwsplit(0);
sleep(10);
Test->tprintf("Trying 'DELETE FROM t1' and expecting FAILURE");
execute_query_silent(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1");
if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141)
{
Test->add_result(1,
"Query succeded, but fail expected, error is %d",
mysql_errno(Test->maxscales->conn_rwsplit[0]));
}
Test->tprintf("Waiting 30 seconds and trying 'DELETE FROM t1', expecting OK");
Test->stop_timeout();
sleep(30);
Test->set_timeout(180);
Test->try_query(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1");
mysql_close(Test->maxscales->conn_rwsplit[0]);
Test->maxscales->stop_maxscale(0);
Test->tprintf("Trying limit_queries clause");
Test->tprintf("Copying rules to Maxscale machine: %s", str);
copy_rules(Test, (char*) "rules_limit_queries", rules_dir);
Test->maxscales->start_maxscale(0);
Test->maxscales->connect_rwsplit(0);
Test->tprintf("Trying 10 quries as fast as possible");
for (i = 0; i < 10; i++)
{
Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"),
"%d -query failed",
i);
}
Test->tprintf("Expecting failures during next 5 seconds");
time_t start_time_clock = time(NULL);
timeval t1, t2;
double elapsedTime;
gettimeofday(&t1, NULL);
do
{
gettimeofday(&t2, NULL);
elapsedTime = (t2.tv_sec - t1.tv_sec);
elapsedTime += (double) (t2.tv_usec - t1.tv_usec) / 1000000.0;
}
while ((execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1") != 0)
&& (elapsedTime < 10));
Test->tprintf("Quries were blocked during %f (using clock_gettime())", elapsedTime);
Test->tprintf("Quries were blocked during %lu (using time())", time(NULL) - start_time_clock);
if ((elapsedTime > 6) or (elapsedTime < 4))
{
Test->add_result(1, "Queries were blocked during wrong time");
}
Test->set_timeout(180);
Test->tprintf("Trying 12 quries, 1 query / second");
for (i = 0; i < 12; i++)
{
sleep(1);
Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"),
"query failed");
if (Test->verbose)
{
Test->tprintf("%d ", i);
}
}
int rval = Test->global_result;
delete Test;
return rval;
}
| 32.798319 | 104 | 0.532667 | 2733284198 |
b85d97e3f1be1f2f02837d347e42ce6731c58414 | 2,956 | cc | C++ | lite/kernels/x86/search_grnn_compute_test.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | 1 | 2020-03-09T03:51:31.000Z | 2020-03-09T03:51:31.000Z | lite/kernels/x86/search_grnn_compute_test.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | null | null | null | lite/kernels/x86/search_grnn_compute_test.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle 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 "lite/kernels/x86/search_grnn_compute.h"
#include <gtest/gtest.h>
#include <memory>
#include <utility>
#include <vector>
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace x86 {
TEST(search_grnn_x86, retrive_op) {
auto kernel =
KernelRegistry::Global().Create<TARGET(kX86), PRECISION(kFloat)>(
"search_grnn");
ASSERT_FALSE(kernel.empty());
ASSERT_TRUE(kernel.front());
}
TEST(search_grnn_x86, init) {
SearchGrnnCompute<float> ssdc;
ASSERT_EQ(ssdc.precision(), PRECISION(kFloat));
ASSERT_EQ(ssdc.target(), TARGET(kX86));
}
TEST(search_grnn_x86, run_test) {
int num_input = 128;
int num_hidden = 128;
int num_batch = 3;
lite::Tensor x, wi, wh, out, idx_sorted_by_width, layout_input, tmp_buffer;
x.Resize({num_batch, num_input});
wi.Resize({3, num_hidden, num_input});
wh.Resize({3, num_hidden, num_hidden});
// out.Resize({num_batch, num_hidden});
LoD x_lod{};
x_lod.push_back({0, 1, 3});
x.set_lod(x_lod);
auto* x_data = x.mutable_data<float>();
for (int64_t i = 0; i < x.numel(); i++) {
x_data[i] = static_cast<float>(i);
}
auto* wi_data = wi.mutable_data<float>();
for (int64_t i = 0; i < wi.numel(); i++) {
wi_data[i] = static_cast<float>(i);
}
auto* wh_data = wh.mutable_data<float>();
for (int64_t i = 0; i < wh.numel(); i++) {
wh_data[i] = static_cast<float>(i);
}
std::unique_ptr<KernelContext> ctx(new KernelContext);
ctx->As<X86Context>();
operators::SearchGrnnParam param;
param.x = &x;
param.wi = &wi;
param.wh = &wh;
param.out = &out;
param.idx_sorted_by_width = &idx_sorted_by_width;
param.layout_input = &layout_input;
param.tmp_buffer = &tmp_buffer;
param.num_input = num_input;
param.num_hidden = num_hidden;
SearchGrnnCompute<float> sgc;
sgc.SetContext(std::move(ctx));
sgc.SetParam(param);
sgc.Run();
// std::vector<float> ref_results = {0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19};
auto* out_data = out.mutable_data<float>();
LOG(INFO) << out.numel();
for (int i = 0; i < out.numel(); i++) {
// EXPECT_NEAR(out_data[i], ref_results[i], 1e-3);
LOG(INFO) << out_data[i];
}
}
} // namespace x86
} // namespace kernels
} // namespace lite
} // namespace paddle
USE_LITE_KERNEL(search_grnn, kX86, kFloat, kNCHW, def);
| 29.267327 | 79 | 0.679296 | jameswu2014 |
b85eaa44ffdcdb3de29aefc2c6da4dd85d35dd17 | 64 | hh | C++ | RAVL2/MSVC/include/Ravl/Image/GrabfileReader.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/Image/GrabfileReader.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/Image/GrabfileReader.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null |
#include "../.././Contrib/RawVidFileFormat/GrabfileReader.hh"
| 16 | 61 | 0.71875 | isuhao |
b85ef9a5b75347f0b4343e4ded5b180cc0544bda | 3,180 | cc | C++ | lullaby/tools/common/file_utils.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 1,198 | 2017-06-09T08:10:52.000Z | 2022-03-21T13:39:50.000Z | lullaby/tools/common/file_utils.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 14 | 2017-06-10T00:47:46.000Z | 2020-12-31T05:19:55.000Z | lullaby/tools/common/file_utils.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 183 | 2017-06-09T22:19:20.000Z | 2022-02-23T03:31:35.000Z | /*
Copyright 2017-2019 Google Inc. 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 "lullaby/tools/common/file_utils.h"
#if defined(_MSC_VER)
#include <direct.h> // Windows functions for directory creation.
#else
#include <sys/stat.h>
#endif
#include <fstream>
#include <string>
namespace lull {
namespace tool {
bool DefaultLoadFile(const char* filename, bool binary, std::string* out);
static LoadFileFunction g_load_file_fn = DefaultLoadFile;
void SetLoadFileFunction(LoadFileFunction fn) {
if (fn) {
g_load_file_fn = fn;
} else {
g_load_file_fn = DefaultLoadFile;
}
}
bool FileExists(const char* filename) {
std::ifstream file(filename, std::ios::binary);
return file ? true : false;
}
bool DefaultLoadFile(const char* filename, bool binary, std::string* out) {
std::ifstream file(filename, binary ? std::ios::binary : std::ios::in);
if (!file) {
return false;
}
file.seekg(0, std::ios::end);
out->resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(const_cast<char*>(out->c_str()), out->size());
return true;
}
bool LoadFile(const char* filename, bool binary, std::string* out) {
return g_load_file_fn(filename, binary, out);
}
bool SaveFile(const void* bytes, size_t num_bytes, const char* filename,
bool binary) {
std::ofstream file(filename, binary ? std::ios::binary : std::ios::out);
if (!file) {
return false;
}
file.write(reinterpret_cast<const char*>(bytes), num_bytes);
file.close();
return true;
}
bool CopyFile(const char* dst, const char* src) {
std::ifstream srcfile(src, std::ios::binary);
std::ofstream dstfile(dst, std::ios::binary);
if (srcfile.is_open() && dstfile.is_open()) {
dstfile << srcfile.rdbuf();
return true;
}
return false;
}
static int MakeDir(const char* sub_dir) {
#if defined(_MSC_VER)
return _mkdir(sub_dir);
#else
static const mode_t kDirectoryMode = 0755;
return mkdir(sub_dir, kDirectoryMode);
#endif
}
bool CreateFolder(const char* directory) {
if (directory == nullptr || *directory == 0) {
return true;
}
std::string dir = directory;
for (size_t slash = 0; slash != std::string::npos;) {
// Find the next sub-directory (after the last one we just created).
slash = dir.find_first_of("\\/", slash + 1);
// If slash is npos, we take the entire `dir` and create it.
const std::string sub_dir = dir.substr(0, slash);
// Create the sub-directory (or continue if the directory already exists).
const int result = MakeDir(sub_dir.c_str());
if (result != 0 && errno != EEXIST) {
return false;
}
}
return true;
}
} // namespace tool
} // namespace lull
| 26.722689 | 78 | 0.691824 | dherbst |
b863500d594a9420bc294d29a2c88d0c2c8f0895 | 1,393 | cc | C++ | 算法导论/educoder/sort/heap_sort.cc | wine99/hfut-cs-assignments | 77ebe4b5fe613f90eb54b8bdcfd1d8afbbd321da | [
"MIT"
] | 56 | 2020-05-28T15:21:47.000Z | 2022-03-29T08:54:55.000Z | 算法导论/educoder/sort/heap_sort.cc | wine99/hfut-cs-assignments | 77ebe4b5fe613f90eb54b8bdcfd1d8afbbd321da | [
"MIT"
] | 2 | 2020-05-29T03:49:05.000Z | 2021-08-04T00:43:26.000Z | 算法导论/educoder/sort/heap_sort.cc | wine99/hfut-cs-assignments | 77ebe4b5fe613f90eb54b8bdcfd1d8afbbd321da | [
"MIT"
] | 14 | 2021-05-22T04:52:47.000Z | 2022-03-29T08:55:00.000Z | #include <cstdio>
#include <iostream>
using namespace std;
void print_array(int* arr, int n)
// 打印数组
{
if (n == 0) {
printf("ERROR: Array length is ZERO\n");
return;
}
printf("%d", arr[0]);
for (int i = 1; i < n; i++) {
printf(" %d", arr[i]);
}
printf("\n");
}
void adjustHeap(int* arr, int start, int end)
// 编程实现堆的调整
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
// When this function is called,
// the two subtrees should already be heaps.
for (int parent = start, son = start * 2 + 1;
son <= end;
parent = son, son = son * 2 + 1
) {
// The parent should swap with the bigger son (if it's going to swap)
if (son + 1 <= end && arr[son] < arr[son + 1])
son = son + 1;
if (arr[parent] >= arr[son]) return;
swap(arr[parent], arr[son]);
}
/********** End **********/
}
int* heap_sort(int* arr, int n)
// 基于adjustHeap函数编程实现堆排序
// 函数参数:无序数组arr 数组长度n
// 函数返回值:返回从小到大排序后的数组
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
// Build a heap.
for (int i = (n - 2) / 2; i >= 0; --i)
adjustHeap(arr, i, n - 1);
// Remove the max of arr, which is the top of heap.
for (int i = n - 1; i > 0; --i) {
swap(arr[0], arr[i]);
adjustHeap(arr, 0, i - 1);
}
return arr;
/********** End **********/
}
| 24.017241 | 77 | 0.480258 | wine99 |
b864112cd5544b5d4e68be3887738c1bc9a43f2f | 2,297 | cc | C++ | chrome/browser/ui/app_list/search/ranking/score_normalizing_ranker.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/ui/app_list/search/ranking/score_normalizing_ranker.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/ui/app_list/search/ranking/score_normalizing_ranker.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 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/app_list/search/ranking/score_normalizing_ranker.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/ui/app_list/search/chrome_search_result.h"
#include "chrome/browser/ui/app_list/search/search_controller.h"
namespace app_list {
namespace {
// Prefix added to the name of each score normalizer, which is used for prefs
// storage.
constexpr char kNormalizerPrefix[] = "categorical_search_normalizer_";
// Returns true if results from this provider should not have their result
// scores normalized. This is to prevent creating an unnecessary number of
// normalizers.
bool ShouldIgnoreProvider(ProviderType type) {
switch (type) {
// Deprecated types:
case ProviderType::kLauncher:
case ProviderType::kAnswerCard:
// Types not associated with a provider:
case ProviderType::kFileChip:
case ProviderType::kDriveChip:
// Types that only create suggestion chips:
case ProviderType::kAssistantChip:
// Types that only ever create one result:
case ProviderType::kPlayStoreReinstallApp:
// Internal types:
case ProviderType::kUnknown:
case ProviderType::kInternalPrivacyInfo:
return true;
default:
return false;
}
}
} // namespace
ScoreNormalizingRanker::ScoreNormalizingRanker(Profile* profile) {
static constexpr int kProviderMin = static_cast<int>(ProviderType::kUnknown);
static constexpr int kProviderMax = static_cast<int>(ProviderType::kMaxValue);
for (int provider_int = kProviderMin; provider_int <= kProviderMax;
++provider_int) {
const ProviderType provider = static_cast<ProviderType>(provider_int);
if (ShouldIgnoreProvider(provider))
continue;
const std::string name =
base::StrCat({kNormalizerPrefix, base::NumberToString(provider_int)});
}
}
ScoreNormalizingRanker::~ScoreNormalizingRanker() {}
void ScoreNormalizingRanker::Rank(ResultsMap& results,
CategoriesMap& categories,
ProviderType provider) {}
} // namespace app_list
| 34.283582 | 80 | 0.730083 | zealoussnow |
b86635f2d1fb465311fb8c1e568bf312e7cece9d | 2,517 | cpp | C++ | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 1 | 2019-12-30T13:23:30.000Z | 2019-12-30T13:23:30.000Z | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 11 | 2019-12-02T20:47:52.000Z | 2020-02-04T23:19:31.000Z | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 1 | 2020-11-17T19:18:58.000Z | 2020-11-17T19:18:58.000Z | #include "segment_accessor.hpp"
#include "resolve_type.hpp"
namespace opossum::detail {
template <typename T>
std::unique_ptr<AbstractSegmentAccessor<T>> CreateSegmentAccessor<T>::create(
const std::shared_ptr<const BaseSegment>& segment) {
std::unique_ptr<AbstractSegmentAccessor<T>> accessor;
resolve_segment_type<T>(*segment, [&](const auto& typed_segment) {
using SegmentType = std::decay_t<decltype(typed_segment)>;
if constexpr (std::is_same_v<SegmentType, ReferenceSegment>) {
const auto& pos_list = *typed_segment.pos_list();
if (pos_list.references_single_chunk() && !pos_list.empty()) {
// If the pos list stores a NULL value, its chunk_id references a non-existing chunk. If all entries reference
// the same chunk_id, we can safely assume that all other entries are also NULL. Instead of using an accessor
// that checks for the reference being NULL, we can simply use the NullAccessor, which always returns nullopt,
// i.e., the accessors representation of NULL values.
// Note that this is independent of the row being pointed to holding a NULL value.
if (pos_list[ChunkOffset{0}].is_null()) {
accessor = std::make_unique<NullAccessor<T>>();
} else {
auto chunk_id = pos_list[ChunkOffset{0}].chunk_id;
auto referenced_segment =
typed_segment.referenced_table()->get_chunk(chunk_id)->get_segment(typed_segment.referenced_column_id());
// If only a single segment is referenced, we can resolve it once and avoid some more expensive
// virtual method calls later.
resolve_segment_type<T>(*referenced_segment, [&](const auto& typed_referenced_segment) {
using ReferencedSegment = std::decay_t<decltype(typed_referenced_segment)>;
if constexpr (!std::is_same_v<ReferencedSegment, ReferenceSegment>) {
accessor = std::make_unique<SingleChunkReferenceSegmentAccessor<T, ReferencedSegment>>(
pos_list, chunk_id, typed_referenced_segment);
} else {
Fail("Encountered nested ReferenceSegments");
}
});
}
} else {
accessor = std::make_unique<MultipleChunkReferenceSegmentAccessor<T>>(typed_segment);
}
} else {
accessor = std::make_unique<SegmentAccessor<T, SegmentType>>(typed_segment);
}
});
return accessor;
}
EXPLICITLY_INSTANTIATE_DATA_TYPES(CreateSegmentAccessor);
} // namespace opossum::detail
| 50.34 | 119 | 0.688915 | dey4ss |
b86685f9997fc8e9371a9d5a24e56d36000d0f9e | 2,535 | cpp | C++ | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | #include "kernsem.h"
#include "asystem.h"
KernelSem::KernelSem(int init, Semaphore *initSemph) :
count(init), semph(initSemph) {
System::semaphores.add(this);
}
KernelSem::~KernelSem() {
while (count < 0)
signal();
}
int KernelSem::val() const {
return count;
}
int KernelSem::wait(Time maxTimeToWait) {
lock
if (count-- > 0) {
unlock
return 1;
}
System::runningPcb->state = PCB::BLOCKED;
if (maxTimeToWait == 0) {
// Cisto blokiranje do nekog signal()-a
blockedThreads.add((PCB*) System::runningPcb);
} else {
// Vremensko blokiranje, novi SemaphoredThread se ubacuje na pravo mesto u nizu tako da poredak vremena budjenja ostane rastuci
SemaphoredThread st = SemaphoredThread((PCB*) System::runningPcb,
System::bootTimeDelta + maxTimeToWait);
if (timeBlocked.empty()) {
// Nema sta da se pretrazuje
timeBlocked.add(st);
} else {
Iterator<SemaphoredThread> t = timeBlocked.iterStart(), rightPlace = timeBlocked.iterEnd();
while (t != timeBlocked.iterEnd()
&& st.futureWakeupTime < t.current->data.futureWakeupTime) {
rightPlace = t;
t++;
}
if (rightPlace != timeBlocked.iterEnd()) {
// Nadjena je vrednost posle koje treba ubaciti ovu novu
timeBlocked.insert(rightPlace, st);
} else {
// rightPlace je ostao kraj niza, znaci da nema onog elementa POSLE koga bi ovo trebalo ubaciti
// To znaci da su svi VECI od ovog novog, i on onda ide pre svih njih
timeBlocked.addToFront(st);
}
}
}
unlock
dispatch();
// Mozda je isteklo vreme?
if (!System::runningPcb->semphTimeExceeded) {
System::runningPcb->semphTimeExceeded = false;
return 0;
}
return 1;
}
void KernelSem::releaseBlocked() {
PCB *pcb = blockedThreads.front();
blockedThreads.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = true; //?
Scheduler::put(pcb);
}
void KernelSem::releaseTimed() {
PCB *pcb = timeBlocked.front().myPCB;
timeBlocked.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = true;
Scheduler::put(pcb);
}
void KernelSem::signal() {
lock
if (count++ < 0) {
if (!blockedThreads.empty()) {
releaseBlocked();
} else if (!timeBlocked.empty()) {
releaseTimed();
}
}
unlock
}
void KernelSem::timerCleanup() {
lock
while (!timeBlocked.empty()) {
if (timeBlocked.front().futureWakeupTime > System::bootTimeDelta)
break;
PCB *pcb = timeBlocked.front().myPCB;
timeBlocked.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = false;
Scheduler::put(pcb);
}
unlock
}
| 20.778689 | 129 | 0.677712 | aleksamagicka |
b8678d33d9523e9b130d6bf78609589644ae8809 | 20 | cpp | C++ | Lidar_Lane_Separator_Detection/src/Segment.cpp | michaellengyel/Lidar_Lane_Separator_Detection | 1d099501f5498fb3f9f998fab8b2737e6c624def | [
"Apache-2.0"
] | null | null | null | Lidar_Lane_Separator_Detection/src/Segment.cpp | michaellengyel/Lidar_Lane_Separator_Detection | 1d099501f5498fb3f9f998fab8b2737e6c624def | [
"Apache-2.0"
] | null | null | null | Lidar_Lane_Separator_Detection/src/Segment.cpp | michaellengyel/Lidar_Lane_Separator_Detection | 1d099501f5498fb3f9f998fab8b2737e6c624def | [
"Apache-2.0"
] | null | null | null | #include "Segment.h" | 20 | 20 | 0.75 | michaellengyel |
b8690a1397fcea3fa74496c86685c051198079f6 | 4,735 | hpp | C++ | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | // Copyright Eric Niebler 2013-2015
// Copyright 2015-2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
//
// This was modeled after the code available in the Range v3 library
#pragma once
#include <hpx/config.hpp>
#include <hpx/assert.hpp>
#include <hpx/datastructures/tagged.hpp>
#include <hpx/datastructures/tuple.hpp>
#include <hpx/type_support/decay.hpp>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace hpx { namespace util {
///////////////////////////////////////////////////////////////////////////
template <typename F, typename S>
struct tagged_pair
: tagged<std::pair<typename detail::tag_elem<F>::type,
typename detail::tag_elem<S>::type>,
typename detail::tag_spec<F>::type,
typename detail::tag_spec<S>::type>
{
typedef tagged<std::pair<typename detail::tag_elem<F>::type,
typename detail::tag_elem<S>::type>,
typename detail::tag_spec<F>::type,
typename detail::tag_spec<S>::type>
base_type;
template <typename... Ts>
tagged_pair(Ts&&... ts)
: base_type(std::forward<Ts>(ts)...)
{
}
};
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(std::pair<T1, T2>&& p)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(std::move(p));
}
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(std::pair<T1, T2> const& p)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(p);
}
template <typename Tag1, typename Tag2, typename... Ts>
constexpr HPX_FORCEINLINE tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
make_tagged_pair(hpx::tuple<Ts...>&& p)
{
static_assert(
sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements");
typedef tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
result_type;
return result_type(std::move(get<0>(p)), std::move(get<1>(p)));
}
template <typename Tag1, typename Tag2, typename... Ts>
constexpr HPX_FORCEINLINE tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
make_tagged_pair(hpx::tuple<Ts...> const& p)
{
static_assert(
sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements");
typedef tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
result_type;
return result_type(get<0>(p), get<1>(p));
}
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(T1&& t1, T2&& t2)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(std::forward<T1>(t1), std::forward<T2>(t2));
}
}} // namespace hpx::util
namespace hpx {
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2>
struct tuple_size<util::tagged_pair<Tag1, Tag2>>
: std::integral_constant<std::size_t, 2>
{
};
template <std::size_t N, typename Tag1, typename Tag2>
struct tuple_element<N, util::tagged_pair<Tag1, Tag2>>
: hpx::tuple_element<N,
std::pair<typename util::detail::tag_elem<Tag1>::type,
typename util::detail::tag_elem<Tag2>::type>>
{
};
} // namespace hpx
| 35.601504 | 80 | 0.577191 | AnshMishra2001 |
b86b0d4762b5df97d94954219dcdb26dd59f2e86 | 17,882 | cpp | C++ | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 27 | 2020-04-16T22:24:47.000Z | 2022-01-12T08:23:43.000Z | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 2 | 2020-08-11T07:03:35.000Z | 2021-02-05T06:43:26.000Z | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 6 | 2020-04-16T21:49:50.000Z | 2022-01-26T15:38:47.000Z | #include "d3d/voxel/voxelize.h"
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <vector>
#include <iostream>
#include <limits>
using namespace std;
using namespace at;
using namespace pybind11::literals;
template <typename T> using toptional = torch::optional<T>;
typedef tuple<int, int, int> coord_t;
struct coord_hash : public std::unary_function<coord_t, std::size_t>
{
std::size_t operator()(const coord_t& k) const
{
constexpr int p = 997; // match this to the range of k
size_t ret = std::get<0>(k);
ret = ret * p + std::get<1>(k);
ret = ret * p + std::get<2>(k);
return ret;
}
};
struct coord_equal : public std::binary_function<coord_t, coord_t, bool>
{
bool operator()(const coord_t& v0, const coord_t& v1) const
{
return (
std::get<0>(v0) == std::get<0>(v1) &&
std::get<1>(v0) == std::get<1>(v1) &&
std::get<2>(v0) == std::get<2>(v1)
);
}
};
typedef unordered_map<coord_t, int, coord_hash, coord_equal> coord_m; // XXX: Consider use robin-map
template <ReductionType Reduction>
py::dict voxelize_3d_dense_templated(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const int max_points, const int max_voxels
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_shape_ = voxel_shape.accessor<int, 1>();
auto voxel_bound_ = voxel_bound.accessor<float, 1>();
Tensor voxels = torch::zeros({max_voxels, max_points, points_.size(1)}, torch::dtype(torch::kFloat32));
Tensor coords = torch::empty({max_voxels, 3}, torch::dtype(torch::kLong));
Tensor voxel_pmask = torch::empty({max_voxels, max_points}, torch::dtype(torch::kBool));
Tensor voxel_npoints = torch::zeros(max_voxels, torch::dtype(torch::kInt32));
auto voxels_ = voxels.accessor<float, 3>();
auto coords_ = coords.accessor<int64_t, 2>();
auto voxel_pmask_ = voxel_pmask.accessor<bool, 2>();
auto voxel_npoints_ = voxel_npoints.accessor<int, 1>();
// initialize aggregated values
Tensor aggregates;
switch(Reduction)
{
case ReductionType::NONE:
aggregates = torch::empty({0, 0});
break;
case ReductionType::MEAN:
aggregates = torch::zeros({max_voxels, points_.size(1)}, torch::dtype(torch::kFloat32));
break;
case ReductionType::MAX:
aggregates = torch::full({max_voxels, points_.size(1)}, -numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32));
break;
case ReductionType::MIN:
aggregates = torch::full({max_voxels, points_.size(1)}, numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32));
break;
}
auto aggregates_ = aggregates.accessor<float, 2>();
// calculate voxel sizes and other variables
float voxel_size_[3];
for (int d = 0; d < 3; ++d)
voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d];
auto npoints = points_.size(0);
auto nfeatures = points_.size(1);
coord_m voxel_idmap;
int coord_temp[3];
int nvoxels = 0;
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
bool out_of_range = false;
for (int d = 0; d < 3; ++d)
{
int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]);
if (idx < 0 || idx >= voxel_shape_[d])
{
out_of_range = true;
break;
}
coord_temp[d] = idx;
}
if (out_of_range) continue;
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
if (nvoxels >= max_voxels)
continue;
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
for (int d = 0; d < 3; ++d)
coords_[voxel_idx][d] = coord_temp[d];
}
else
voxel_idx = voxel_iter->second;
// assign voxel mask and original features
int n = voxel_npoints_[voxel_idx]++;
if (n < max_points)
{
voxel_pmask_[voxel_idx][n] = true;
for (int d = 0; d < nfeatures; ++d)
voxels_[voxel_idx][n][d] = points_[i][d];
}
// reduce features
for (int d = 0; d < nfeatures; ++d)
{
switch (Reduction)
{
case ReductionType::MEAN: // mean
aggregates_[voxel_idx][d] += points_[i][d];
break;
case ReductionType::MAX: // max, aggregates should be initialized as positive huge numbers
aggregates_[voxel_idx][d] = max(aggregates_[voxel_idx][d], points_[i][d]);
break;
case ReductionType::MIN: // min, aggregates should be initialized as negative huge numbers
aggregates_[voxel_idx][d] = min(aggregates_[voxel_idx][d], points_[i][d]);
break;
case ReductionType::NONE:
default:
break;
}
}
}
// if aggregate is mean, divide them by the numbers now
if (Reduction == ReductionType::MEAN)
for (int i = 0; i < nvoxels; i++)
for (int d = 0; d < nfeatures; d++)
aggregates_[i][d] /= voxel_npoints_[i];
// remove unused voxel entries
if (Reduction != ReductionType::NONE)
return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels),
"coords"_a=coords.slice(0, 0, nvoxels),
"voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels),
"voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels),
"aggregates"_a=aggregates.slice(0, 0, nvoxels)
);
else
return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels),
"coords"_a=coords.slice(0, 0, nvoxels),
"voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels),
"voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels)
);
}
py::dict voxelize_3d_dense(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const int max_points, const int max_voxels, const ReductionType reduction_type
)
{
#define _VOXELIZE_3D_REDUCTION_TYPE_CASE(n) case n: \
return voxelize_3d_dense_templated<n>(points, voxel_shape, voxel_bound, max_points, max_voxels)
switch (reduction_type)
{
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::NONE);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MEAN);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MIN);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MAX);
default:
throw py::value_error("Unsupported reduction type in voxelization!");
}
#undef _VOXELIZE_3D_REDUCTION_TYPE_CASE
}
py::dict voxelize_3d_sparse(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const toptional<int> max_points, const toptional<int> max_voxels
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_shape_ = voxel_shape.accessor<int, 1>();
auto voxel_bound_ = voxel_bound.accessor<float, 1>();
// fill points mapping with -1 (unassigned)
Tensor points_mapping = torch::full(points_.size(0), -1, torch::dtype(torch::kLong));
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
// calculate voxel sizes and other variables
float voxel_size_[3];
for (int d = 0; d < 3; ++d)
voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d];
auto npoints = points_.size(0);
auto nfeatures = points_.size(1);
coord_m voxel_idmap;
vector<int> voxel_npoints;
vector<Tensor> coords_list;
int coord_temp[3];
int nvoxels = 0;
bool need_mask = false;
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
bool out_of_range = false;
for (int d = 0; d < 3; ++d)
{
int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]);
if (idx < 0 || idx >= voxel_shape_[d])
{
out_of_range = true;
break;
}
coord_temp[d] = idx;
}
if (out_of_range)
{
need_mask = true;
continue;
}
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
voxel_npoints.push_back(1);
coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong));
}
else
{
voxel_idx = voxel_iter->second;
voxel_npoints[voxel_idx] += 1;
}
points_mapping_[i] = voxel_idx;
}
// process mask
Tensor points_filtered = points;
Tensor masked;
if (need_mask)
{
masked = torch::where(points_mapping >= 0)[0];
points_filtered = torch::index_select(points, 0, masked);
points_mapping = torch::index_select(points_mapping, 0, masked);
}
else
{
masked = torch::arange(npoints);
}
return py::dict(
"points"_a=points_filtered,
"points_mask"_a=masked,
"points_mapping"_a=points_mapping,
"coords"_a=torch::stack(coords_list),
"voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32));
}
py::dict voxelize_sparse(
const Tensor points, const Tensor voxel_size, const toptional<int> ndim
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_size_ = voxel_size.accessor<float, 1>();
int ndim_ = ndim.value_or(3);
auto npoints = points_.size(0);
Tensor points_mapping = torch::empty(npoints, torch::dtype(torch::kLong));
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
coord_m voxel_idmap; // coord to voxel id
vector<int> voxel_npoints; // number of points per voxel
vector<Tensor> coords_list; // list of coordinates
int coord_temp[ndim_]; // array to store temporary coordinate
int nvoxels = 0; // number of total voxels
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
for (int d = 0; d < ndim_; ++d)
coord_temp[d] = floor(points_[i][d] / voxel_size_[d]);
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
voxel_npoints.push_back(1);
coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong));
}
else
{
voxel_idx = voxel_iter->second;
voxel_npoints[voxel_idx] += 1;
}
points_mapping_[i] = voxel_idx;
}
return py::dict(
"points_mapping"_a=points_mapping,
"coords"_a=torch::stack(coords_list),
"voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32)
);
}
py::dict voxelize_filter(
const Tensor feats, const Tensor points_mapping,
const Tensor coords, const Tensor voxel_npoints, const toptional<Tensor> coords_bound,
const toptional<int> min_points, const toptional<int> max_points, const toptional<int> max_voxels,
const toptional<MaxPointsFilterType> max_points_filter, const toptional<MaxVoxelsFilterType> max_voxels_filter
)
{
auto feats_ = feats.accessor<float, 2>();
auto coords_ = coords.accessor<int64_t, 2>();
auto voxel_npoints_ = voxel_npoints.accessor<int, 1>();
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
Tensor coord_bound_default = coords_bound.value_or(torch::empty({0, 0}, torch::dtype(torch::kFloat)));
auto coords_bound_ = coord_bound_default.accessor<int64_t, 2>();
int nvoxels = coords_.size(0);
int ndim = coords_.size(1);
int npoints = feats_.size(0);
int nfeats = feats_.size(1);
// default values
MaxPointsFilterType max_points_filter_ = max_points_filter.value_or(MaxPointsFilterType::NONE);
MaxVoxelsFilterType max_voxels_filter_ = max_voxels_filter.value_or(MaxVoxelsFilterType::NONE);
if (max_voxels_filter != MaxVoxelsFilterType::NONE && !max_voxels.has_value())
throw py::value_error("Must specify maximum voxel count to filter voxels!");
int max_voxels_ = max_voxels.value();
if (max_points_filter != MaxPointsFilterType::NONE && !max_points.has_value())
throw py::value_error("Must specify maximum points per voxel to filter points!");
int max_points_ = max_points.value();
int min_points_ = min_points.value_or(0);
// filter out voxels at first
std::unordered_map<int, int> voxel_indices;
int nvoxel_filtered = 0;
auto test_bound = [&](int i) -> bool{
bool out_of_range = false;
for (int d = 0; d < ndim; d++)
if (coords_[i][d] < coords_bound_[d][0] ||
coords_[i][d] >= coords_bound_[d][1])
{
out_of_range = true;
break;
}
return out_of_range;
};
switch (max_voxels_filter_)
{
case MaxVoxelsFilterType::NONE:
for (int i = 0; i < nvoxels; i++)
{
if (voxel_npoints_[i] < min_points_) // skip voxels with few points
continue;
if (coords_bound.has_value() && test_bound(i))
continue;
voxel_indices[i] = nvoxel_filtered++;
}
break;
case MaxVoxelsFilterType::TRIM:
cout << "In trim" << endl;
for (int i = 0; i < nvoxels; i++)
{
if (nvoxel_filtered >= max_voxels_)
break;
if (voxel_npoints_[i] < min_points_) // skip voxels with few points
continue;
if (coords_bound.has_value() && test_bound(i))
continue;
voxel_indices[i] = nvoxel_filtered++;
}
break;
case MaxVoxelsFilterType::DESCENDING:
auto order = torch::argsort(voxel_npoints, 0, true);
auto ordered_ = order.accessor<long, 1>();
for (int i = 0; i < nvoxels; i++)
{
if (nvoxel_filtered >= max_voxels_)
break;
if (voxel_npoints_[ordered_[i]] < min_points_)
break; // skip voxels with few points
if (coords_bound.has_value() && test_bound(ordered_[i]))
continue;
voxel_indices[ordered_[i]] = nvoxel_filtered++;
}
break;
}
// filter coordinates
Tensor coords_filtered = torch::empty({nvoxel_filtered, ndim}, coords.options());
auto coords_filtered_ = coords_filtered.accessor<int64_t, 2>();
for (auto iter = voxel_indices.begin(); iter != voxel_indices.end(); iter++)
for (int d = 0; d < ndim; d++)
coords_filtered_[iter->second][d] = coords_[iter->first][d];
// filter out points, first create output tensors
Tensor points_mapping_filtered = torch::empty_like(points_mapping);
Tensor voxel_npoints_filtered = torch::zeros({nvoxel_filtered}, voxel_npoints.options());
auto points_mapping_filtered_ = points_mapping_filtered.accessor<int64_t, 1>();
auto voxel_npoints_filtered_ = voxel_npoints_filtered.accessor<int, 1>();
switch(max_points_filter_)
{
case MaxPointsFilterType::NONE:
for (int i = 0; i < npoints; i++)
{
auto new_id = voxel_indices.find(points_mapping_[i]);
if (new_id != voxel_indices.end())
{
int vid = new_id->second;
points_mapping_filtered_[i] = vid;
voxel_npoints_filtered_[vid]++;
}
else points_mapping_filtered_[i] = -1;
}
break;
case MaxPointsFilterType::TRIM:
for (int i = 0; i < npoints; i++)
{
auto new_id = voxel_indices.find(points_mapping_[i]);
if (new_id != voxel_indices.end())
{
int vid = new_id->second;
if (voxel_npoints_filtered_[vid] >= max_points_)
{
points_mapping_filtered_[i] = -1;
continue;
}
points_mapping_filtered_[i] = vid;
voxel_npoints_filtered_[vid]++;
}
else points_mapping_filtered_[i] = -1;
}
break;
case MaxPointsFilterType::FARTHEST_SAMPLING:
throw py::value_error("Farthest Sampling not implemented!");
break;
}
Tensor masked = torch::where(points_mapping_filtered >= 0)[0];
Tensor feats_filtered = torch::index_select(feats, 0, masked);
points_mapping_filtered = torch::index_select(points_mapping_filtered, 0, masked);
return py::dict(
"points"_a=feats_filtered, // FIXME: use consistent name for point features (`points` or `feats`)
"points_mask"_a=masked,
"points_mapping"_a=points_mapping_filtered,
"voxel_npoints"_a=voxel_npoints_filtered,
"coords"_a=coords_filtered
);
} | 36.946281 | 135 | 0.593054 | minghanz |
b86e2bcff4598d6cb3e50c8a2895af98d6312f0e | 7,608 | cc | C++ | diagnostics/cros_healthd/events/bluetooth_events_impl_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/events/bluetooth_events_impl_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/events/bluetooth_events_impl_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include <utility>
#include <base/bind.h>
#include <base/check.h>
#include <base/run_loop.h>
#include <base/test/task_environment.h>
#include <dbus/object_path.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <mojo/core/embedder/embedder.h>
#include <mojo/public/cpp/bindings/pending_receiver.h>
#include <mojo/public/cpp/bindings/receiver.h>
#include "diagnostics/common/system/bluetooth_client.h"
#include "diagnostics/common/system/fake_bluetooth_client.h"
#include "diagnostics/cros_healthd/events/bluetooth_events_impl.h"
#include "diagnostics/cros_healthd/system/mock_context.h"
#include "diagnostics/mojom/public/cros_healthd_events.mojom.h"
namespace diagnostics {
namespace {
namespace mojo_ipc = ::chromeos::cros_healthd::mojom;
using ::testing::Invoke;
using ::testing::StrictMock;
void PropertyChanged(const std::string& property_name) {}
std::unique_ptr<BluetoothClient::AdapterProperties> CreateAdapterProperties() {
auto properties = std::make_unique<BluetoothClient::AdapterProperties>(
nullptr, base::Bind(&PropertyChanged));
properties->name.ReplaceValue("hci0");
properties->address.ReplaceValue("aa:bb:cc:dd:ee:ff");
properties->powered.ReplaceValue(true);
return properties;
}
std::unique_ptr<BluetoothClient::DeviceProperties> CreateDeviceProperties() {
auto properties = std::make_unique<BluetoothClient::DeviceProperties>(
nullptr, base::Bind(&PropertyChanged));
properties->name.ReplaceValue("keyboard");
properties->address.ReplaceValue("70:88:6B:92:34:70");
properties->connected.ReplaceValue(true);
properties->adapter.ReplaceValue(dbus::ObjectPath("/org/bluez/hci0"));
return properties;
}
class MockCrosHealthdBluetoothObserver
: public mojo_ipc::CrosHealthdBluetoothObserver {
public:
MockCrosHealthdBluetoothObserver(
mojo::PendingReceiver<mojo_ipc::CrosHealthdBluetoothObserver> receiver)
: receiver_{this /* impl */, std::move(receiver)} {
DCHECK(receiver_.is_bound());
}
MockCrosHealthdBluetoothObserver(const MockCrosHealthdBluetoothObserver&) =
delete;
MockCrosHealthdBluetoothObserver& operator=(
const MockCrosHealthdBluetoothObserver&) = delete;
MOCK_METHOD(void, OnAdapterAdded, (), (override));
MOCK_METHOD(void, OnAdapterRemoved, (), (override));
MOCK_METHOD(void, OnAdapterPropertyChanged, (), (override));
MOCK_METHOD(void, OnDeviceAdded, (), (override));
MOCK_METHOD(void, OnDeviceRemoved, (), (override));
MOCK_METHOD(void, OnDevicePropertyChanged, (), (override));
private:
mojo::Receiver<mojo_ipc::CrosHealthdBluetoothObserver> receiver_;
};
// Tests for the BluetoothEventsImpl class.
class BluetoothEventsImplTest : public testing::Test {
protected:
BluetoothEventsImplTest() = default;
BluetoothEventsImplTest(const BluetoothEventsImplTest&) = delete;
BluetoothEventsImplTest& operator=(const BluetoothEventsImplTest&) = delete;
void SetUp() override {
// Before any observers have been added, we shouldn't have subscribed to
// BluetoothClient.
ASSERT_FALSE(fake_bluetooth_client()->HasObserver(&bluetooth_events_impl_));
mojo::PendingRemote<mojo_ipc::CrosHealthdBluetoothObserver> observer;
mojo::PendingReceiver<mojo_ipc::CrosHealthdBluetoothObserver>
observer_receiver(observer.InitWithNewPipeAndPassReceiver());
observer_ = std::make_unique<StrictMock<MockCrosHealthdBluetoothObserver>>(
std::move(observer_receiver));
bluetooth_events_impl_.AddObserver(std::move(observer));
// Now that an observer has been added, we should have subscribed to
// BluetoothClient.
ASSERT_TRUE(fake_bluetooth_client()->HasObserver(&bluetooth_events_impl_));
}
BluetoothEventsImpl* bluetooth_events_impl() {
return &bluetooth_events_impl_;
}
FakeBluetoothClient* fake_bluetooth_client() {
return mock_context_.fake_bluetooth_client();
}
MockCrosHealthdBluetoothObserver* mock_observer() { return observer_.get(); }
dbus::ObjectPath adapter_path() {
return dbus::ObjectPath("/org/bluez/hci0");
}
dbus::ObjectPath device_path() {
return dbus::ObjectPath("/org/bluez/hci0/dev_70_88_6B_92_34_70");
}
void DestroyMojoObserver() {
observer_.reset();
// Make sure |bluetooth_events_impl_| gets a chance to observe the
// connection error.
task_environment_.RunUntilIdle();
}
private:
base::test::TaskEnvironment task_environment_;
MockContext mock_context_;
BluetoothEventsImpl bluetooth_events_impl_{&mock_context_};
std::unique_ptr<StrictMock<MockCrosHealthdBluetoothObserver>> observer_;
};
// Test that we can receive an adapter added event.
TEST_F(BluetoothEventsImplTest, ReceiveAdapterAddedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnAdapterAdded()).WillOnce(Invoke([&]() {
run_loop.Quit();
}));
fake_bluetooth_client()->EmitAdapterAdded(adapter_path(),
*CreateAdapterProperties());
run_loop.Run();
}
// Test that we can receive an adapter removed event.
TEST_F(BluetoothEventsImplTest, ReceiveAdapterRemovedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnAdapterRemoved()).WillOnce(Invoke([&]() {
run_loop.Quit();
}));
fake_bluetooth_client()->EmitAdapterRemoved(adapter_path());
run_loop.Run();
}
// Test that we can receive an adapter property changed event.
TEST_F(BluetoothEventsImplTest, ReceiveAdapterPropertyChangedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnAdapterPropertyChanged())
.WillOnce(Invoke([&]() { run_loop.Quit(); }));
fake_bluetooth_client()->EmitAdapterPropertyChanged(
adapter_path(), *CreateAdapterProperties());
run_loop.Run();
}
// Test that we can receive a device added event.
TEST_F(BluetoothEventsImplTest, ReceiveDeviceAddedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnDeviceAdded()).WillOnce(Invoke([&]() {
run_loop.Quit();
}));
fake_bluetooth_client()->EmitDeviceAdded(device_path(),
*CreateDeviceProperties());
run_loop.Run();
}
// Test that we can receive a device removed event.
TEST_F(BluetoothEventsImplTest, ReceiveDeviceRemovedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnDeviceRemoved()).WillOnce(Invoke([&]() {
run_loop.Quit();
}));
fake_bluetooth_client()->EmitDeviceRemoved(device_path());
run_loop.Run();
}
// Test that we can receive a device property changed event.
TEST_F(BluetoothEventsImplTest, ReceiveDevicePropertyChangedEvent) {
base::RunLoop run_loop;
EXPECT_CALL(*mock_observer(), OnDevicePropertyChanged())
.WillOnce(Invoke([&]() { run_loop.Quit(); }));
fake_bluetooth_client()->EmitDevicePropertyChanged(device_path(),
*CreateDeviceProperties());
run_loop.Run();
}
// Test that BluetoothEvents unsubscribes from BluetoothClient when
// BluetoothEvents loses all of its Mojo observers.
TEST_F(BluetoothEventsImplTest,
UnsubscribeFromBluetoothClientWhenAllObserversLost) {
DestroyMojoObserver();
// Emit an event so that BluetoothEventsImpl has a chance to check for any
// remaining Mojo observers.
fake_bluetooth_client()->EmitAdapterRemoved(adapter_path());
EXPECT_FALSE(fake_bluetooth_client()->HasObserver(bluetooth_events_impl()));
}
} // namespace
} // namespace diagnostics
| 33.813333 | 80 | 0.744479 | Toromino |
b86fdf20471ea8badf2b98ef3174f590d96188a9 | 6,852 | cpp | C++ | Mario_Game/title.cpp | Rossterrrr/Qt | 3e5c2934ce19675390d2ad6d513a14964d8cbe50 | [
"MIT"
] | 3 | 2019-09-02T05:17:08.000Z | 2021-01-07T11:21:34.000Z | QtMario_Youtube-master/QtMario_Original Code/title.cpp | Jhongesell/Qt | 3fc548731435d3f6fffbaec1bdfd19371232088e | [
"MIT"
] | null | null | null | QtMario_Youtube-master/QtMario_Original Code/title.cpp | Jhongesell/Qt | 3fc548731435d3f6fffbaec1bdfd19371232088e | [
"MIT"
] | null | null | null | #include "title.h"
#include "loginwindow.h"
#include <QMessageBox>
Title::Title(View *view, QWidget *parent) : QGraphicsScene(parent){
viewer = view;
scroll = new QScrollBar;
scroll = viewer->horizontalScrollBar();
background = new AnimatedGraphicsItem;
background->setPixmap(QPixmap(":/images/background.png"));
foreground = new QGraphicsPixmapItem(QPixmap(":/images/title.png"));
//cursor = new QGraphicsPixmapItem(QPixmap(":/images/cursor.png"));
logo = new QGraphicsPixmapItem(QPixmap(":/images/logo.png"));
animation = new QPropertyAnimation(background, "pos");
animation->setLoopCount(-1);
animation->setDuration(150000);
animation->setStartValue(QPoint(-width,0));
animation->setEndValue(QPoint(0,0));
animation->start();
logo->setPos((width - logo->boundingRect().width()) / 2, height / 12);
addItem(background);
addItem(foreground);
addItem(logo);
this->setFocus();
this->setSceneRect(0,0,1280,720);
view->sceneSet(this);
//Push Button for login
loginButton = new QPushButton(viewer);
loginButton->setText("Login");
loginButton->setObjectName(QString("loginButton"));
loginButton->setToolTip("Click to login");
loginButton->setGeometry(QRect(540, 500, 100, 32));
connect(loginButton, SIGNAL(clicked()), this, SLOT(login()));
//Push Button for developer login
developerButton = new QPushButton(viewer);
developerButton->setText("Guest Login");
developerButton->setObjectName(QString("developerButton"));
developerButton->setToolTip("Login as a guest");
developerButton->setGeometry(QRect(540, 535, 100, 32));
connect(developerButton, SIGNAL(clicked()), this, SLOT(developerLogin()));
//Push Button to quit
quitButton = new QPushButton(viewer);
quitButton->setText("Quit");
quitButton->setObjectName(QString("quitButton"));
quitButton->setToolTip("Quit program");
quitButton->setGeometry(QRect(642, 535, 100, 32));
connect(quitButton, SIGNAL(clicked()), this, SLOT(quitProgram()));
//Push Button for new user
newUserButton = new QPushButton(viewer);
newUserButton->setText("New User");
newUserButton->setObjectName(QString("newUserButton"));
newUserButton->setToolTip("Click to create a login");
newUserButton->setGeometry(QRect(642, 500, 100, 32));
connect(newUserButton, SIGNAL(clicked()), this, SLOT(newUser()));
//Add line edit for username, set tooltip
userLine = new QLineEdit(viewer);
//userLine->setObjectName(QString("userLine"));
userLine->setToolTip("Enter an email address");
userLine->setGeometry(QRect(540, 420, 200, 25));
//Add Label for username
QFont font("MV Boli", 15, QFont::Bold);
userName = new QLabel(viewer);
userName->setFont(font);
userName->setText("Username");
userName->setObjectName(QString("username"));
userName->setGeometry(QRect(430, 420, 100, 25));
//Add line edit for password, set tooltip
passLine = new QLineEdit(viewer);
passLine->setEchoMode(QLineEdit::Password);
passLine->setObjectName(QString("passLine"));
passLine->setToolTip("Enter password");
passLine->setGeometry(QRect(540, 450, 200, 25));
//Add Label For password
password = new QLabel(viewer);
password->setFont(font);
password->setText("Password");
password->setObjectName(QString("password"));
password->setGeometry(QRect(430, 450, 100, 25));
//Add radio button and connect signal to slot,set tooltip
radioButton = new QRadioButton(viewer);
radioButton->setObjectName(QString("radioButton"));
radioButton->setToolTip("Click to show password text");
radioButton->setGeometry(QRect(760, 450, 100, 25));
connect(radioButton, SIGNAL(toggled(bool)), this, SLOT(on_radioButton_toggled(bool)));
//add radio button text
radioText = new QLabel(viewer);
radioText->setText("Show Password");
radioText->setToolTip("Click to show password text");
radioText->setGeometry(QRect(780, 450, 100, 25));
}
bool Title::regExUserTest(){
bool accessGranted = false;
usernameRegEx = new QRegularExpression("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$");
usernamenameMatch = new QRegularExpressionMatch(usernameRegEx->match(userLine->text()));
accessGranted = usernamenameMatch->hasMatch();
if(accessGranted){
return true;
}
else
return false;
}
void Title::on_radioButton_toggled(bool checked)
{
if(checked){
passLine->setEchoMode(QLineEdit::Normal);
}
else{
passLine->setEchoMode(QLineEdit::Password);
}
}
void Title::quitProgram(){
qApp->quit();
}
void Title::login(){
//Connect to Database
DataB::DBConnect(DBase);
//Error for lack of input
if(userLine->text().isEmpty()){
QMessageBox msgBox;
msgBox.setText("You must enter a username. ");
msgBox.setWindowTitle("Warning");
msgBox.exec();
return;
}
if(regExUserTest()== false){
QMessageBox msgBoxFail;
msgBoxFail.setText("That is not a valid email address. ");
msgBoxFail.setWindowTitle("Warning");
msgBoxFail.exec();
return;
}
if(passLine->text().isEmpty()){
QMessageBox msgBox2;
msgBox2.setText("You must enter a password. ");
msgBox2.setWindowTitle("Warning");
msgBox2.exec();
return;
}
//Gather Input
Query uInput;
uInput.uName=userLine->text();
uInput.pass=passLine->text();
qDebug() << uInput.uName;
qDebug() << uInput.pass;
//Try to check User
if(DataB::cUsrPas(uInput,DBase.db)){
//Then it worked
loginButton->close();
newUserButton->close();
passLine->close();
userLine->close();
userName->close();
password->close();
radioButton->close();
radioText->close();
developerButton->close();
quitButton->close();
scene = new MyScene(scroll,this);
viewer->sceneSet(scene);
}
else{
//Then it didnt
QMessageBox msgBox3;
msgBox3.setText(" Combination of username and/or password incorrect. ");
msgBox3.setWindowTitle("Warning");
msgBox3.exec();
return;
}
}
void Title::newUser(){
loginWindow = new LoginWindow();
loginWindow->exec();
}
void Title::developerLogin(){
loginButton->close();
newUserButton->close();
passLine->close();
userLine->close();
userName->close();
password->close();
radioButton->close();
radioText->close();
developerButton->close();
quitButton->close();
scene = new MyScene(scroll,this);
viewer->sceneSet(scene);
}
| 31.004525 | 95 | 0.641419 | Rossterrrr |
b87257a0c6a1ce5e74afdffa0ffd25ad460441fa | 8,899 | cpp | C++ | inetsrv/iis/admin/migrtool/ui/postprocessadd.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/admin/migrtool/ui/postprocessadd.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/admin/migrtool/ui/postprocessadd.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "stdafx.h"
#include "WizardSheet.h"
#include "CommandDlg.h"
CPostProcessAdd::CPostProcessAdd( CWizardSheet* pTheSheet ) :
m_pTheSheet( pTheSheet )
{
m_strTitle.LoadString( IDS_TITLE_POSTPROCESS );
m_strSubTitle.LoadString( IDS_SUBTITLE_POSTPROCESS );
SetHeaderTitle( m_strTitle );
SetHeaderSubTitle( m_strSubTitle );
}
LRESULT CPostProcessAdd::OnAddFile( WORD wNotifyCode, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled )
{
CString strFilter;
UIUtils::LoadOFNFilterFromRes( IDS_FILTER_POSTPROCESSFILES, /*r*/strFilter );
CFileDialog dlg( TRUE,
NULL,
NULL,
OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOREADONLYRETURN | OFN_FILEMUSTEXIST,
strFilter,
m_hWnd );
if ( dlg.DoModal() == IDCANCEL ) return 0;
// File names must be unique as the path is not preserved
// Check if there is already a file with the same name
WCHAR wszNew[ MAX_PATH + 1 ];
::wcscpy( wszNew, dlg.m_szFileName );
::PathStripPath( wszNew );
for ( TStringList::const_iterator it = m_Files.begin();
it != m_Files.end();
++it )
{
WCHAR wszCurrent[ MAX_PATH + 1 ];
::wcscpy( wszCurrent, it->c_str() );
::PathStripPathW( wszCurrent );
if ( ::_wcsicmp( wszCurrent, wszNew ) == 0 )
{
UIUtils::MessageBox( m_hWnd, IDS_E_PPFILENOTUNIQUE, IDS_APPTITLE, MB_OK | MB_ICONSTOP );
return 0 ;
}
}
m_Files.push_back( std::wstring( dlg.m_szFileName ) );
::wcscpy( wszNew, dlg.m_szFileName );
UIUtils::PathCompatCtrlWidth( GetDlgItem( IDC_FILES ), wszNew, ::GetSystemMetrics( SM_CXVSCROLL ) );
ListBox_AddString( GetDlgItem( IDC_FILES ), wszNew );
return 0;
}
LRESULT CPostProcessAdd::OnDelFile( WORD wNotifyCode, WORD /*wID*/, HWND hWndCtl, BOOL& bHandled )
{
HWND hwndFiles = GetDlgItem( IDC_FILES );
int nCurSel = ListBox_GetCurSel( hwndFiles );
_ASSERT( nCurSel != LB_ERR );
ListBox_DeleteString( hwndFiles, nCurSel );
if ( ListBox_GetCount( hwndFiles ) > 0 )
{
ListBox_SetCurSel( hwndFiles, max( nCurSel - 1, 0 ) );
}
else
{
::EnableWindow( hWndCtl, FALSE );
}
return 0;
}
LRESULT CPostProcessAdd::LBSelChanged( WORD /*wNotifyCode*/, WORD wID, HWND hWndCtl, BOOL& /*bHandled*/ )
{
// If selection is not changed - do nothing
if ( ListBox_GetCurSel( hWndCtl ) == LB_ERR ) return 0;
if ( wID == IDC_FILES )
{
::EnableWindow( GetDlgItem( IDC_DELFILE ), TRUE );
}
else if ( wID == IDC_COMMANDS )
{
::EnableWindow( GetDlgItem( IDC_DELCMD ), TRUE );
::EnableWindow( GetDlgItem( IDC_EDITCMD ), TRUE );
int iLastEl = ListBox_GetCount( hWndCtl ) - 1;
int iCurSel = ListBox_GetCurSel( hWndCtl );
_ASSERT( iCurSel != LB_ERR );
// Enable / Disable the MoveUp and MoveDown Btns
::EnableWindow( GetDlgItem( IDC_MOVEUP ), iCurSel > 0 );
::EnableWindow( GetDlgItem( IDC_MOVEDOWN ), iCurSel < iLastEl );
}
return 0;
}
LRESULT CPostProcessAdd::OnAddCmd( WORD wNotifyCode, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled )
{
CCommandDlg dlg;
if ( dlg.DoModal() != IDOK ) return 0;
CmdInfo Cmd;
Cmd.bIgnoreErrors = dlg.m_bIgnoreErrors;
Cmd.dwTimeout = dlg.m_dwTimeout;
Cmd.strText = dlg.m_strText;
m_Commands.push_back( Cmd );
UIUtils::TrimTextToCtrl( GetDlgItem( IDC_COMMANDS ),
dlg.m_strText.GetBuffer( dlg.m_strText.GetLength() ),
::GetSystemMetrics( SM_CXVSCROLL ) );
dlg.m_strText.ReleaseBuffer();
BOOL bUnused = FALSE;;
ListBox_InsertString( GetDlgItem( IDC_COMMANDS ), -1, dlg.m_strText );
LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused );
return 0;
}
LRESULT CPostProcessAdd::OnDelCmd( WORD wNotifyCode, WORD /*wID*/, HWND hWndCtl, BOOL& bHandled )
{
HWND hwndCmds = GetDlgItem( IDC_COMMANDS );
int nCurSel = ListBox_GetCurSel( hwndCmds );
_ASSERT( nCurSel != LB_ERR );
ListBox_DeleteString( hwndCmds, nCurSel );
m_Commands.erase( m_Commands.begin() + nCurSel );
if ( ListBox_GetCount( hwndCmds ) > 0 )
{
BOOL bUnused = FALSE;
ListBox_SetCurSel( hwndCmds, max( nCurSel - 1, 0 ) );
LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused );
}
else
{
::EnableWindow( hWndCtl, FALSE );
::EnableWindow( GetDlgItem( IDC_EDITCMD ), FALSE );
}
return 0;
}
LRESULT CPostProcessAdd::OnEditCmd( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ )
{
HWND hwndCmds = GetDlgItem( IDC_COMMANDS );
int iCmd = ListBox_GetCurSel( hwndCmds );
if ( LB_ERR == iCmd ) return 0;
CCommandDlg dlg;
dlg.m_bIgnoreErrors = m_Commands[ iCmd ].bIgnoreErrors;
dlg.m_dwTimeout = m_Commands[ iCmd ].dwTimeout;
dlg.m_strText = m_Commands[ iCmd ].strText;
if ( dlg.DoModal() != IDOK ) return 0;
m_Commands[ iCmd ].bIgnoreErrors = dlg.m_bIgnoreErrors;
m_Commands[ iCmd ].dwTimeout = dlg.m_dwTimeout;
m_Commands[ iCmd ].strText = dlg.m_strText;
UIUtils::TrimTextToCtrl( hwndCmds,
dlg.m_strText.GetBuffer( dlg.m_strText.GetLength() ),
::GetSystemMetrics( SM_CXVSCROLL ) );
dlg.m_strText.ReleaseBuffer();
ListBox_InsertString( hwndCmds, iCmd, dlg.m_strText );
ListBox_DeleteString( hwndCmds, iCmd + 1 );
ListBox_SetCurSel( hwndCmds, iCmd );
return 0;
}
LRESULT CPostProcessAdd::LBDoubleClick( WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/ )
{
if ( wID != IDC_COMMANDS ) return 0;
BOOL bUnused = FALSE;
OnEditCmd( BN_CLICKED, IDC_EDITCMD, GetDlgItem( IDC_EDITCMD ), bUnused );
return 0;
}
LRESULT CPostProcessAdd::OnMoveUp( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ )
{
HWND hwndCmds = GetDlgItem( IDC_COMMANDS );
int iSel = ListBox_GetCurSel( hwndCmds );
_ASSERT( ( iSel != LB_ERR ) && ( iSel > 0 ) );
LBSwapElements( hwndCmds, iSel, iSel - 1 );
ListBox_SetCurSel( hwndCmds, iSel - 1 );
BOOL bUnused = FALSE;
LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused );
CmdInfo cmdTemp = m_Commands[ iSel ];
m_Commands[ iSel ] = m_Commands[ iSel - 1 ];
m_Commands[ iSel - 1 ] = cmdTemp;
return 0;
}
LRESULT CPostProcessAdd::OnMoveDown( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ )
{
HWND hwndCmds = GetDlgItem( IDC_COMMANDS );
int iSel = ListBox_GetCurSel( hwndCmds );
_ASSERT( ( iSel != LB_ERR ) && ( iSel < ( ListBox_GetCount( hwndCmds ) - 1 ) ) );
LBSwapElements( hwndCmds, iSel, iSel + 1 );
ListBox_SetCurSel( hwndCmds, iSel + 1 );
BOOL bUnused = FALSE;
LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused );
CmdInfo cmdTemp = m_Commands[ iSel ];
m_Commands[ iSel ] = m_Commands[ iSel + 1 ];
m_Commands[ iSel + 1 ] = cmdTemp;
return 0;
}
void CPostProcessAdd::LBSwapElements( HWND hwndLB, int iSrc, int iTarget )
{
_ASSERT( hwndLB != NULL );
_ASSERT( iSrc != iTarget );
CString strSrc;
CString strTarget;
ListBox_GetText( hwndLB, iSrc, strSrc.GetBuffer( ListBox_GetTextLen( hwndLB, iSrc ) + 1 ) );
ListBox_GetText( hwndLB, iTarget, strTarget.GetBuffer( ListBox_GetTextLen( hwndLB, iTarget ) + 1 ) );
strSrc.ReleaseBuffer();
strTarget.ReleaseBuffer();
ListBox_InsertString( hwndLB, iTarget, strSrc );
ListBox_DeleteString( hwndLB, iTarget + 1 );
ListBox_InsertString( hwndLB, iSrc, strTarget );
ListBox_DeleteString( hwndLB, iSrc + 1 );
}
int CPostProcessAdd::OnWizardNext()
{
int nRet = 0; // Goto next page
int nMsgRes = 0;
// Check if there are files, but no commands
if ( m_Commands.empty() && !m_Files.empty() )
{
nMsgRes = UIUtils::MessageBox( m_hWnd, IDS_W_NOCMDS, IDS_APPTITLE, MB_YESNO | MB_ICONWARNING );
// User wants to continue and ignore the files
if ( IDYES == nMsgRes )
{
m_Files.clear();
ListBox_ResetContent( GetDlgItem( IDC_FILES ) );
}
else
{
nRet = -1; // Stay on this page
}
}
return nRet;
} | 29.369637 | 112 | 0.602315 | npocmaka |
b87258732d44223afa72a788f2950b11b3939e65 | 35,929 | cc | C++ | plugins/experimental/cookie_remap/cookie_remap.cc | cmcfarlen/trafficserver | 2aa1d3106398eb082e5a454212b0273c63d5f69d | [
"Apache-2.0"
] | 1,351 | 2015-01-03T08:25:40.000Z | 2022-03-31T09:14:08.000Z | plugins/experimental/cookie_remap/cookie_remap.cc | cmcfarlen/trafficserver | 2aa1d3106398eb082e5a454212b0273c63d5f69d | [
"Apache-2.0"
] | 7,009 | 2015-01-14T16:22:45.000Z | 2022-03-31T17:18:04.000Z | plugins/experimental/cookie_remap/cookie_remap.cc | cmcfarlen/trafficserver | 2aa1d3106398eb082e5a454212b0273c63d5f69d | [
"Apache-2.0"
] | 901 | 2015-01-11T19:21:08.000Z | 2022-03-18T18:21:33.000Z | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
////////////////////////////////////////////////////////////////////////////////
// cookie_remap: ATS plugin to do (simple) cookie based remap rules
// To use this plugin, configure a remap.config rule like
// map http://foo.com http://bar.com @plugin=.../libexec/cookie_remap.so
// @pparam=maps.reg
#include "cookiejar.h"
#include <ts/ts.h>
#include <pcre.h>
#include <ts/remap.h>
#include <yaml-cpp/yaml.h>
#include <string>
#include <vector>
#include <string_view>
#include <cstddef>
#include "hash.h"
#undef FMT_SV
#define FMT_SV(SV) static_cast<int>((SV).size()), (SV).data()
using namespace std;
#define MY_NAME "cookie_remap"
const int OVECCOUNT = 30; // We support $1 - $9 only, and this needs to be 3x that
class UrlComponents
{
public:
UrlComponents(TSRemapRequestInfo *rri, TSHttpTxn txn) : _rri(rri), _txn(txn) {}
std::string const &
path(bool pre_remap)
{
if (_d[pre_remap].path_str.empty()) {
auto urlh = _get_url(pre_remap);
// based on RFC2396, matrix params are part of path segments so
// we will just
// append them to the path
_d[pre_remap].path_str = _get_url_comp(urlh, TSUrlPathGet);
auto matrix = _get_url_comp(urlh, TSUrlHttpParamsGet);
if (!matrix.empty()) {
_d[pre_remap].path_str.append(";", 1).append(matrix);
}
}
return _d[pre_remap].path_str;
}
std::string_view
query(bool pre_remap)
{
if (_d[pre_remap].query.empty()) {
_d[pre_remap].query = _get_url_comp(_get_url(pre_remap), TSUrlHttpQueryGet);
}
return _d[pre_remap].query;
}
std::string_view
from_path()
{
if (_from_path.empty()) {
_UrlHandle urlh{_rri->requestBufp, _rri->mapFromUrl};
_from_path = _get_url_comp(urlh, TSUrlPathGet);
}
return _from_path;
}
std::string_view
url(bool pre_remap)
{
if (_d[pre_remap].url.empty()) {
auto urlh = _get_url(pre_remap);
int length;
auto data = TSUrlStringGet(urlh.bufp, urlh.urlp, &length);
_d[pre_remap].url = std::string_view(data, length);
}
return _d[pre_remap].url;
}
// No copying/moving.
//
UrlComponents(UrlComponents const &) = delete;
UrlComponents &operator=(UrlComponents const &) = delete;
~UrlComponents()
{
// Not calling TSHandleMLocRelease() for the URL TSMLoc pointers because it doesn't do anything.
if (_d[0].url.data() != nullptr) {
TSfree(const_cast<char *>(_d[0].url.data()));
}
if (_d[1].url.data() != nullptr) {
TSfree(const_cast<char *>(_d[1].url.data()));
}
}
private:
TSRemapRequestInfo *_rri;
TSHttpTxn _txn;
struct _UrlHandle {
TSMBuffer bufp = nullptr;
TSMLoc urlp;
};
// Buffer any data that's likely to be used more than once.
struct _Data {
_UrlHandle urlh;
std::string path_str;
std::string_view url;
std::string_view query;
};
// index 0 - remapped
// index 1 - pre-remap
//
_Data _d[2];
std::string_view _from_path;
_UrlHandle
_get_url(bool pre_remap)
{
_UrlHandle h = _d[pre_remap].urlh;
if (!h.bufp) {
if (pre_remap) {
if (TSHttpTxnPristineUrlGet(_txn, &h.bufp, &h.urlp) != TS_SUCCESS) {
TSError("%s: Plugin is unable to get pristine url", MY_NAME);
return _UrlHandle();
}
} else {
h.bufp = _rri->requestBufp;
h.urlp = _rri->requestUrl;
}
_d[pre_remap].urlh = h;
}
return h;
}
static std::string_view
_get_url_comp(_UrlHandle urlh, char const *(*comp_func)(TSMBuffer, TSMLoc, int *))
{
int length;
auto data = comp_func(urlh.bufp, urlh.urlp, &length);
return std::string_view(data, length);
}
};
enum operation_type { UNKNOWN = -1, EXISTS = 1, NOTEXISTS, REGEXP, STRING, BUCKET };
enum target_type {
COOKIE = 1,
URI, // URI = PATH + QUERY
PRE_REMAP_URI,
UNKNOWN_TARGET
};
/***************************************************************************************
Decimal to Hex
converter
This is a template function which returns a char* array filled with hex digits
when
passed to it a number(can work as a decimal to hex conversion)and will work for
signed
and unsigned: char, short, and integer(long) type parameters passed to it.
Shortcomings:It won't work for decimal numbers because of presence of
bitshifting in its algorithm.
Arguments:
* _num is the number to convert to hex
* hdigits two-byte character array, will be populated with the hex number
***************************************************************************************/
template <class type> // template usage to allow multiple types of parameters
void
dec_to_hex(type _num, char *hdigits)
{
const char *hlookup = "0123456789ABCDEF"; // lookup table stores the hex digits into their
// corresponding index.
if (_num < 0) {
_num *= -1; // and make _num positive to clear(zero) the sign bit
}
char mask = 0x000f; // mask will clear(zero) out all the bits except lowest 4
// which represent a single hex digit
hdigits[1] = hlookup[mask & _num];
hdigits[0] = hlookup[mask & (_num >> 4)];
return;
}
void
urlencode(std::string &str)
{
auto orig = str.size();
auto enc = orig;
for (auto c : str) {
if (!isalnum(c)) {
enc += 2;
}
}
if (enc == orig) {
// No changes needed.
return;
}
str.resize(enc);
while (orig--) {
if (!isalnum(str[orig])) {
enc -= 3;
dec_to_hex(str[orig], &(str[enc + 1]));
str[enc] = '%';
} else {
str[--enc] = str[orig];
}
}
}
//----------------------------------------------------------------------------
class subop
{
public:
subop()
: cookie(""),
operation(""),
str_match(""),
bucket("")
{
TSDebug(MY_NAME, "subop constructor called");
}
~subop()
{
TSDebug(MY_NAME, "subop destructor called");
if (regex) {
pcre_free(regex);
}
if (regex_extra) {
pcre_free(regex_extra);
}
}
bool
empty() const
{
return (cookie == "" && operation == "" && op_type == UNKNOWN);
}
void
setCookieName(const std::string &s)
{
cookie = s;
}
const std::string &
getCookieName() const
{
return cookie;
}
const std::string &
getOperation() const
{
return operation;
}
operation_type
getOpType() const
{
return op_type;
}
target_type
getTargetType() const
{
return target;
}
void
setOperation(const std::string &s)
{
operation = s;
if (operation == "string") {
op_type = STRING;
}
if (operation == "regex") {
op_type = REGEXP;
}
if (operation == "exists") {
op_type = EXISTS;
}
if (operation == "not exists") {
op_type = NOTEXISTS;
}
if (operation == "bucket") {
op_type = BUCKET;
}
}
void
setTarget(const std::string &s)
{
if (s == "uri") {
target = URI;
} else if (s == "puri") {
target = PRE_REMAP_URI;
} else {
target = COOKIE;
}
}
void
setStringMatch(const std::string &s)
{
op_type = STRING;
str_match = s;
}
const std::string &
getStringMatch() const
{
return str_match;
}
void
setBucket(const std::string &s)
{
int start_pos = s.find('/');
op_type = BUCKET;
bucket = s;
how_many = atoi(bucket.substr(0, start_pos).c_str());
out_of = atoi(bucket.substr(start_pos + 1).c_str());
}
int
bucketGetTaking() const
{
return how_many;
}
int
bucketOutOf() const
{
return out_of;
}
bool
setRegexMatch(const std::string &s)
{
const char *error_comp = nullptr;
const char *error_study = nullptr;
int erroffset;
op_type = REGEXP;
regex_string = s;
regex = pcre_compile(regex_string.c_str(), 0, &error_comp, &erroffset, nullptr);
if (regex == nullptr) {
return false;
}
regex_extra = pcre_study(regex, 0, &error_study);
if ((regex_extra == nullptr) && (error_study != nullptr)) {
return false;
}
if (pcre_fullinfo(regex, regex_extra, PCRE_INFO_CAPTURECOUNT, ®ex_ccount) != 0) {
return false;
}
return true;
}
const std::string &
getRegexString() const
{
return regex_string;
}
int
getRegexCcount() const
{
return regex_ccount;
}
int
regexMatch(const char *str, int len, int ovector[]) const
{
return pcre_exec(regex, // the compiled pattern
regex_extra, // Extra data from study (maybe)
str, // the subject std::string
len, // the length of the subject
0, // start at offset 0 in the subject
0, // default options
ovector, // output vector for substring information
OVECCOUNT); // number of elements in the output vector
};
void
printSubOp() const
{
TSDebug(MY_NAME, "\t+++subop+++");
TSDebug(MY_NAME, "\t\tcookie: %s", cookie.c_str());
TSDebug(MY_NAME, "\t\toperation: %s", operation.c_str());
if (str_match.size() > 0) {
TSDebug(MY_NAME, "\t\tmatching: %s", str_match.c_str());
}
if (regex) {
TSDebug(MY_NAME, "\t\tregex: %s", regex_string.c_str());
}
if (bucket.size() > 0) {
TSDebug(MY_NAME, "\t\tbucket: %s", bucket.c_str());
TSDebug(MY_NAME, "\t\ttaking: %d", how_many);
TSDebug(MY_NAME, "\t\tout of: %d", out_of);
}
}
private:
std::string cookie;
std::string operation;
enum operation_type op_type = UNKNOWN;
enum target_type target = UNKNOWN_TARGET;
std::string str_match;
pcre *regex = nullptr;
pcre_extra *regex_extra = nullptr;
std::string regex_string;
int regex_ccount = 0;
std::string bucket;
unsigned int how_many = 0;
unsigned int out_of = 0;
};
using SubOpQueue = std::vector<const subop *>;
//----------------------------------------------------------------------------
class op
{
public:
op() { TSDebug(MY_NAME, "op constructor called"); }
~op()
{
TSDebug(MY_NAME, "op destructor called");
for (auto &subop : subops) {
delete subop;
}
}
void
addSubOp(const subop *s)
{
subops.push_back(s);
}
void
setSendTo(const std::string &s)
{
sendto = s;
}
const std::string &
getSendTo() const
{
return sendto;
}
void
setElseSendTo(const std::string &s)
{
else_sendto = s;
}
void
setStatus(const std::string &s)
{
if (else_sendto.size() > 0) {
else_status = static_cast<TSHttpStatus>(atoi(s.c_str()));
} else {
status = static_cast<TSHttpStatus>(atoi(s.c_str()));
}
}
void
setElseStatus(const std::string &s)
{
else_status = static_cast<TSHttpStatus>(atoi(s.c_str()));
}
void
printOp() const
{
TSDebug(MY_NAME, "++++operation++++");
TSDebug(MY_NAME, "sending to: %s", sendto.c_str());
TSDebug(MY_NAME, "if these operations match: ");
for (auto subop : subops) {
subop->printSubOp();
}
if (else_sendto.size() > 0) {
TSDebug(MY_NAME, "else: %s", else_sendto.c_str());
}
}
bool
process(CookieJar &jar, std::string &dest, TSHttpStatus &retstat, TSRemapRequestInfo *rri, UrlComponents &req_url) const
{
if (sendto == "") {
return false; // guessing every operation must have a
// sendto url???
}
int retval = 1;
bool cookie_found = false;
std::string c;
std::string cookie_data;
std::string object_name; // name of the thing being processed,
// cookie, or
// request url
TSDebug(MY_NAME, "starting to process a new operation");
for (auto subop : subops) {
// subop* s = *it;
int subop_type = subop->getOpType();
target_type target = subop->getTargetType();
c = subop->getCookieName();
if (c.length()) {
TSDebug(MY_NAME, "processing cookie: %s", c.c_str());
size_t period_pos = c.find_first_of('.');
if (period_pos == std::string::npos) { // not a sublevel
// cookie name
TSDebug(MY_NAME, "processing non-sublevel cookie");
cookie_found = jar.get_full(c, cookie_data);
TSDebug(MY_NAME, "full cookie: %s", cookie_data.c_str());
object_name = c;
} else { // is in the format FOO.BAR
std::string cookie_main = c.substr(0, period_pos);
std::string cookie_subkey = c.substr(period_pos + 1);
TSDebug(MY_NAME, "processing sublevel cookie");
TSDebug(MY_NAME, "c key: %s", cookie_main.c_str());
TSDebug(MY_NAME, "c subkey: %s", cookie_subkey.c_str());
cookie_found = jar.get_part(cookie_main, cookie_subkey, cookie_data);
object_name = cookie_main + " . " + cookie_subkey;
}
// invariant: cookie name is in object_name and
// cookie data (if any) is
// in cookie_data
if (cookie_found == false) { // cookie name or sub-key not found
// inside cookies
if (subop_type == NOTEXISTS) {
TSDebug(MY_NAME,
"cookie %s was not "
"found (and we wanted "
"that)",
object_name.c_str());
continue; // we can short
// circuit more
// testing
}
TSDebug(MY_NAME, "cookie %s was not found", object_name.c_str());
retval &= 0;
break;
} else {
// cookie exists
if (subop_type == NOTEXISTS) { // we found the cookie
// but are asking
// for non existence
TSDebug(MY_NAME,
"cookie %s was found, "
"but operation "
"requires "
"non-existence",
object_name.c_str());
retval &= 0;
break;
}
if (subop_type == EXISTS) {
TSDebug(MY_NAME, "cookie %s was found", object_name.c_str()); // got what
// we were
// looking
// for
continue; // we can short
// circuit more
// testing
}
} // handled EXISTS / NOTEXISTS subops
TSDebug(MY_NAME, "processing cookie data: \"%s\"", cookie_data.c_str());
} else if (target != PRE_REMAP_URI) {
target = URI;
}
// INVARIANT: we now have the data from the cookie (if
// any) inside
// cookie_data and we are here because we need
// to continue processing this suboperation in some way
if (!rri) { // too dangerous to continue without the
// rri; hopefully that
// never happens
TSDebug(MY_NAME, "request info structure is "
"empty; can't continue "
"processing this subop");
retval &= 0;
break;
}
// If the user has specified a cookie in his
// suboperation, use the cookie
// data for matching;
// otherwise, use the request uri (path + query)
std::string request_uri; // only set the value if we
// need it; we might
// match the cookie data instead
bool use_url = (target == URI) || (target == PRE_REMAP_URI);
const std::string &string_to_match(use_url ? request_uri : cookie_data);
if (use_url) {
request_uri = req_url.path(target == PRE_REMAP_URI);
TSDebug(MY_NAME, "process req_url.path = %s", request_uri.c_str());
if (request_uri.length() && request_uri[0] != '/') {
request_uri.insert(0, 1, '/');
}
auto query = req_url.query(target == PRE_REMAP_URI);
if (query.size() > 0) {
request_uri += '?';
request_uri += query;
}
object_name = "request uri";
}
// invariant: we've decided at this point what string
// we'll match, if we
// do matching
// OPERATION::string matching
if (subop_type == STRING) {
if (string_to_match == subop->getStringMatch()) {
TSDebug(MY_NAME, "string match succeeded");
continue;
} else {
TSDebug(MY_NAME, "string match failed");
retval &= 0;
break;
}
}
// OPERATION::regex matching
if (subop_type == REGEXP) {
int ovector[OVECCOUNT];
int ret = subop->regexMatch(string_to_match.c_str(), string_to_match.length(), ovector);
if (ret >= 0) {
std::string::size_type pos = sendto.find('$');
std::string::size_type ppos = 0;
dest.erase(); // we only reset dest if
// there is a successful
// regex
// match
dest.reserve(sendto.size() * 2); // Wild guess at this
// time ... is
// sucks we can't precalculate this
// like regex_remap.
TSDebug(MY_NAME, "found %d matches", ret);
TSDebug(MY_NAME,
"successful regex "
"match of: %s with %s "
"rewriting string: %s",
string_to_match.c_str(), subop->getRegexString().c_str(), sendto.c_str());
// replace the $(1-9) in the sendto url
// as necessary
const size_t LAST_IDX_TO_SEARCH(sendto.length() - 2); // otherwise the below loop can
// access "sendto" out of range
while (pos <= LAST_IDX_TO_SEARCH) {
if (isdigit(sendto[pos + 1])) {
int ix = sendto[pos + 1] - '0';
if (ix <= subop->getRegexCcount()) { // Just skip an illegal regex group
dest += sendto.substr(ppos, pos - ppos);
dest += string_to_match.substr(ovector[ix * 2], ovector[ix * 2 + 1] - ovector[ix * 2]);
ppos = pos + 2;
} else {
TSDebug(MY_NAME,
"bad "
"rewriting "
"string, "
"for group "
"%d: %s",
ix, sendto.c_str());
}
}
pos = sendto.find('$', pos + 1);
}
dest += sendto.substr(ppos);
continue; // next subop, please
} else {
TSDebug(MY_NAME,
"could not match "
"regular expression "
"%s to %s",
subop->getRegexString().c_str(), string_to_match.c_str());
retval &= 0;
break;
}
}
// OPERATION::bucket ranges
if (subop_type == BUCKET) {
unsigned int taking = subop->bucketGetTaking();
unsigned int out_of = subop->bucketOutOf();
uint32_t hash;
if (taking == 0 || out_of == 0) {
TSDebug(MY_NAME,
"taking %d out of %d "
"makes no sense?!",
taking, out_of);
retval &= 0;
break;
}
hash = hash_fnv32_buckets(cookie_data.c_str(), cookie_data.size(), out_of);
TSDebug(MY_NAME,
"we hashed this to bucket: %u "
"taking: %u out of: %u",
hash, taking, out_of);
if (hash < taking) {
TSDebug(MY_NAME, "we hashed in the range, yay!");
continue; // we hashed in the range
} else {
TSDebug(MY_NAME, "we didn't hash in the "
"range requested, so "
"sad");
retval &= 0;
break;
}
}
}
if (retval == 1) {
if (dest.size() == 0) { // Unless already set by one of
// the operators (e.g. regex)
dest = sendto;
}
if (status > 0) {
retstat = status;
}
return true;
} else if (else_sendto.size() > 0 && retval == 0) {
dest = else_sendto;
if (else_status > 0) {
retstat = else_status;
}
return true;
} else {
dest = "";
return false;
}
}
private:
SubOpQueue subops{};
std::string sendto{""};
std::string else_sendto{""};
TSHttpStatus status = TS_HTTP_STATUS_NONE;
TSHttpStatus else_status = TS_HTTP_STATUS_NONE;
};
using StringPair = std::pair<std::string, std::string>;
using OpMap = std::vector<StringPair>;
//----------------------------------------------------------------------------
static bool
build_op(op &o, OpMap const &q)
{
subop *sub = new subop();
// loop through the array of key->value pairs
for (auto const &pr : q) {
std::string const &key = pr.first;
std::string const &val = pr.second;
TSDebug(MY_NAME, "build_op: key=%s val=%s", key.c_str(), val.c_str());
if (key == "cookie") {
if (!sub->empty()) {
TSDebug(MY_NAME, "ERROR: you need to define a connector");
goto error;
}
sub->setCookieName(val);
}
if (key == "sendto" || key == "url") {
o.setSendTo(val);
}
if (key == "else") {
o.setElseSendTo(val);
}
if (key == "status") {
o.setStatus(val);
}
if (key == "operation") {
sub->setOperation(val);
}
if (key == "target") {
sub->setTarget(val);
}
if (key == "match") {
sub->setStringMatch(val);
}
if (key == "regex") {
bool ret = sub->setRegexMatch(val);
if (!ret) {
goto error;
}
}
if (key == "bucket" || key == "hash") {
sub->setBucket(val);
}
if (key == "connector") {
o.addSubOp(sub);
sub = new subop();
}
}
o.addSubOp(sub);
return true;
error:
TSDebug(MY_NAME, "error building operation");
return false;
}
using OpsQueue = std::vector<const op *>;
//----------------------------------------------------------------------------
// init
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
{
return TS_SUCCESS;
}
//----------------------------------------------------------------------------
// initialization of structures from config parameters
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size)
{
if (argc != 3) {
TSError("arguments not equal to 3: %d", argc);
TSDebug(MY_NAME, "arguments not equal to 3: %d", argc);
return TS_ERROR;
}
std::string filename(argv[2]);
try {
YAML::Node config = YAML::LoadFile(filename);
std::unique_ptr<OpsQueue> ops(new OpsQueue);
OpMap op_data;
for (YAML::const_iterator it = config.begin(); it != config.end(); ++it) {
const string &name = it->first.as<std::string>();
YAML::NodeType::value type = it->second.Type();
if (name != "op" || type != YAML::NodeType::Map) {
const string reason = "Top level nodes must be named op and be of type map";
TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str());
return TS_ERROR;
}
for (YAML::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
const YAML::Node first = it2->first;
const YAML::Node second = it2->second;
if (second.IsScalar() == false) {
const string reason = "All op nodes must be of type scalar";
TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str());
return TS_ERROR;
}
const string &key = first.as<std::string>();
const string &value = second.as<std::string>();
op_data.emplace_back(key, value);
}
if (op_data.size()) {
op *o = new op();
if (!build_op(*o, op_data)) {
delete o;
TSError("building operation, check configuration file: %s", filename.c_str());
return TS_ERROR;
} else {
ops->push_back(o);
}
o->printOp();
op_data.clear();
}
}
TSDebug(MY_NAME, "# of ops: %d", static_cast<int>(ops->size()));
*ih = static_cast<void *>(ops.release());
} catch (const YAML::Exception &e) {
TSError("YAML::Exception %s when parsing YAML config file %s for cookie_remap", e.what(), filename.c_str());
return TS_ERROR;
}
return TS_SUCCESS;
}
namespace
{
std::string
unmatched_path(UrlComponents &req_url, bool pre_remap)
{
std::string path = req_url.path(pre_remap);
std::string_view from_path = req_url.from_path();
std::size_t pos = path.find(from_path);
if (pos != std::string::npos) {
path.erase(pos, from_path.size());
}
TSDebug(MY_NAME, "from_path: %*s", FMT_SV(from_path));
TSDebug(MY_NAME, "%s: %s", pre_remap ? "unmatched_ppath" : "unmatched_path", path.c_str());
return path;
}
int const sub_req_url_id = 0;
int const sub_req_purl_id = -1;
int const sub_path_id = -2;
int const sub_ppath_id = -3;
int const sub_unmatched_path_id = -4;
int const sub_unmatched_ppath_id = -5;
int const sub_url_encode_id = -6;
struct CompNext {
std::string_view const comp;
int const *const next;
CompNext(std::string_view p, int const *n) : comp(p), next(n) {}
};
struct SubUnmatched {
SubUnmatched() = default; // Work-around for Intel compiler problem.
int count = 2;
CompNext o1{"ath", &sub_unmatched_path_id};
CompNext o2{"path", &sub_unmatched_ppath_id};
};
SubUnmatched const sub_unmatched;
struct SubP {
SubP() = default; // Work-around for Intel compiler problem.
int count = 2;
CompNext o1{"ath", &sub_path_id};
CompNext o2{"path", &sub_ppath_id};
};
SubP const sub_p;
struct SubCrReq {
SubCrReq() = default; // Work-around for Intel compiler problem.
int count = 2;
CompNext o1{"url", &sub_req_url_id};
CompNext o2{"purl", &sub_req_purl_id};
};
SubCrReq const sub_cr_req;
struct SubCr {
SubCr() = default; // Work-around for Intel compiler problem.
int count = 2;
CompNext o1{"req_", &sub_cr_req.count};
CompNext o2{"urlencode(", &sub_url_encode_id};
};
SubCr const sub_cr;
struct Sub {
Sub() = default; // Work-around for Intel compiler problem.
int count = 3;
CompNext o1{"cr_", &sub_cr.count};
CompNext o2{"p", &sub_p.count};
CompNext o3{"unmatched_p", &sub_unmatched.count};
};
Sub const sub;
int
sub_lookup(char const *targ, int targ_len)
{
int count = sub.count;
auto opt = &sub.o1;
for (;;) {
while ((targ_len < static_cast<int>(opt->comp.size())) || (std::string_view(targ, opt->comp.size()) != opt->comp)) {
if (!--count) {
return 1; // Failed lookup, return some positive number.
}
++opt;
}
count = *opt->next;
if (count <= 0) {
break;
}
targ += opt->comp.size();
targ_len -= opt->comp.size();
opt = reinterpret_cast<CompNext const *>(reinterpret_cast<char const *>(opt->next) + offsetof(decltype(sub), o1));
}
return count;
}
} // end anonymous namespace
//----------------------------------------------------------------------------
// called whenever we need to perform substitutions on a string; used to replace
// things like
// $path, $ppath, $unmatched_path, $unmatched_ppath, $cr_req_url, $cr_req_purl, and $cr_url_encode
void
cr_substitutions(std::string &obj, UrlComponents &req_url)
{
{
auto path = req_url.path(false);
TSDebug(MY_NAME, "x req_url.path: %*s %d", FMT_SV(path), static_cast<int>(path.size()));
auto url = req_url.url(false);
TSDebug(MY_NAME, "x req_url.url: %*s %d", FMT_SV(url), static_cast<int>(url.size()));
}
auto npos = std::string::npos;
std::string tmp;
std::size_t pos = 0;
for (;;) {
pos = obj.find('$', pos);
if (npos == pos) {
break;
}
std::string_view variable, value;
switch (sub_lookup(obj.data() + pos + 1, static_cast<int>(obj.size()) - pos - 1)) {
case sub_req_url_id: {
variable = "$cr_req_url";
value = req_url.url(false);
} break;
case sub_req_purl_id: {
variable = "$cr_req_purl";
value = req_url.url(true);
} break;
case sub_path_id: {
variable = "$path";
value = req_url.path(false);
} break;
case sub_ppath_id: {
variable = "$ppath";
value = req_url.path(true);
} break;
case sub_unmatched_path_id: {
variable = "$unmatched_path";
tmp = unmatched_path(req_url, false);
value = tmp;
} break;
case sub_unmatched_ppath_id: {
variable = "$unmatched_ppath";
tmp = unmatched_path(req_url, true);
value = tmp;
} break;
case sub_url_encode_id: {
std::size_t bpos = pos + sizeof("cr_urlencode(") - 1;
std::size_t epos = obj.find(')', bpos);
if (npos == epos) {
variable = "$";
value = variable;
} else {
variable = std::string_view(obj.data() + pos, epos + 1 - pos);
tmp = obj.substr(bpos, epos - bpos);
cr_substitutions(tmp, req_url);
urlencode(tmp);
value = tmp;
}
} break;
default: {
variable = "$";
value = variable;
} break;
} // end switch
TSDebug(MY_NAME, "%*s => %*s", FMT_SV(variable), FMT_SV(value));
obj.replace(pos, variable.size(), value);
pos += value.size();
} // end for (;;)
}
//----------------------------------------------------------------------------
// called on each request
// returns 0 on error or failure to match rules, 1 on a match
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
{
OpsQueue *ops = static_cast<OpsQueue *>(ih);
TSHttpStatus status = TS_HTTP_STATUS_NONE;
UrlComponents req_url{rri, txnp};
if (ops == (OpsQueue *)nullptr) {
TSError("serious error with encountered while attempting to "
"cookie_remap");
TSDebug(MY_NAME, "serious error with encountered while attempting to remap");
return TSREMAP_NO_REMAP;
}
// get any query params..we will append that to the answer (possibly)
std::string client_req_query_params;
auto query = req_url.query(false);
if (!query.empty()) {
client_req_query_params = "?";
client_req_query_params += query;
}
TSDebug(MY_NAME, "Query Parameters: %s", client_req_query_params.c_str());
std::string rewrite_to;
char cookie_str[] = "Cookie";
TSMLoc field = TSMimeHdrFieldFind(rri->requestBufp, rri->requestHdrp, cookie_str, sizeof(cookie_str) - 1);
// cookie header doesn't exist
if (field == nullptr) {
TSDebug(MY_NAME, "no cookie header");
// return TSREMAP_NO_REMAP;
}
const char *cookie = nullptr;
int cookie_len = 0;
if (field != nullptr) {
cookie = TSMimeHdrFieldValueStringGet(rri->requestBufp, rri->requestHdrp, field, -1, &cookie_len);
}
std::string temp_cookie(cookie, cookie_len);
CookieJar jar;
jar.create(temp_cookie);
for (auto &op : *ops) {
TSDebug(MY_NAME, ">>> processing new operation");
if (op->process(jar, rewrite_to, status, rri, req_url)) {
cr_substitutions(rewrite_to, req_url);
size_t pos = 7; // 7 because we want to ignore the // in
// http:// :)
size_t tmp_pos = rewrite_to.find('?', pos); // we don't want to alter the query string
do {
pos = rewrite_to.find("//", pos);
if (pos < tmp_pos) {
rewrite_to.erase(pos, 1); // remove one '/'
}
} while (pos <= rewrite_to.length() && pos < tmp_pos);
// Add Query Parameters if not already present
if (!client_req_query_params.empty() && rewrite_to.find('?') == std::string::npos) {
rewrite_to.append(client_req_query_params);
}
TSDebug(MY_NAME, "rewriting to: %s", rewrite_to.c_str());
// Maybe set the return status
if (status > TS_HTTP_STATUS_NONE) {
TSDebug(MY_NAME, "Setting return status to %d", status);
TSHttpTxnStatusSet(txnp, status);
if ((status == TS_HTTP_STATUS_MOVED_PERMANENTLY) || (status == TS_HTTP_STATUS_MOVED_TEMPORARILY)) {
if (rewrite_to.size() > 8192) {
TSError("Redirect in target "
"URL too long");
TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_REQUEST_URI_TOO_LONG);
} else {
const char *start = rewrite_to.c_str();
int dest_len = rewrite_to.size();
if (TS_PARSE_ERROR == TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + dest_len)) {
TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
TSError("can't parse "
"substituted "
"URL string");
} else {
rri->redirect = 1;
}
}
}
if (field != nullptr) {
TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
}
if (rri->redirect) {
return TSREMAP_DID_REMAP;
} else {
return TSREMAP_NO_REMAP;
}
}
const char *start = rewrite_to.c_str();
// set the new url
if (TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + rewrite_to.length()) == TS_PARSE_ERROR) {
TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
TSError("can't parse substituted URL string");
goto error;
} else {
if (field != nullptr) {
TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
}
return TSREMAP_DID_REMAP;
}
// Cleanup
error:
if (field != nullptr) {
TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
}
return TSREMAP_NO_REMAP;
}
}
TSDebug(MY_NAME, "could not execute ANY of the cookie remap operations... "
"falling back to default in remap.config");
if (field != nullptr) {
TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
}
return TSREMAP_NO_REMAP;
}
//----------------------------------------------------------------------------
// unload
void
TSRemapDeleteInstance(void *ih)
{
OpsQueue *ops = static_cast<OpsQueue *>(ih);
TSDebug(MY_NAME, "deleting loaded operations");
for (auto &op : *ops) {
delete op;
}
delete ops;
return;
}
| 27.57406 | 122 | 0.550419 | cmcfarlen |
b876f4e871d4aeba187eb19460307071bc5eadea | 12,190 | hpp | C++ | overlapping_wfc.hpp | xyproto/fast-wfc-cxx | 4511f71218bf5b422a70f2539912311ad9126e24 | [
"MIT"
] | null | null | null | overlapping_wfc.hpp | xyproto/fast-wfc-cxx | 4511f71218bf5b422a70f2539912311ad9126e24 | [
"MIT"
] | null | null | null | overlapping_wfc.hpp | xyproto/fast-wfc-cxx | 4511f71218bf5b422a70f2539912311ad9126e24 | [
"MIT"
] | null | null | null | #ifndef FAST_WFC_OVERLAPPING_WFC_HPP_
#define FAST_WFC_OVERLAPPING_WFC_HPP_
#include <unordered_map>
#include <vector>
#include "array2D.hpp"
#include "wfc.hpp"
/**
* Options needed to use the overlapping wfc.
*/
struct OverlappingWFCOptions {
bool periodic_input; // True if the input is toric.
bool periodic_output; // True if the output is toric.
unsigned out_height; // The height of the output in pixels.
unsigned out_width; // The width of the output in pixels.
unsigned symmetry; // The number of symmetries (the order is defined in wfc).
bool ground; // True if the ground needs to be set (see init_ground).
unsigned pattern_size; // The width and height in pixel of the patterns.
/**
* Get the wave height given these options.
*/
unsigned get_wave_height() const noexcept
{
return periodic_output ? out_height : out_height - pattern_size + 1;
}
/**
* Get the wave width given these options.
*/
unsigned get_wave_width() const noexcept
{
return periodic_output ? out_width : out_width - pattern_size + 1;
}
};
/**
* Class generating a new image with the overlapping WFC algorithm.
*/
template <typename T> class OverlappingWFC {
private:
/**
* The input image. T is usually a color.
*/
Array2D<T> input;
/**
* Options needed by the algorithm.
*/
OverlappingWFCOptions options;
/**
* The array of the different patterns extracted from the input.
*/
std::vector<Array2D<T>> patterns;
/**
* The underlying generic WFC algorithm.
*/
WFC wfc;
/**
* Constructor initializing the wfc.
* This constructor is called by the other constructors.
* This is necessary in order to initialize wfc only once.
*/
OverlappingWFC(const Array2D<T>& input, const OverlappingWFCOptions& options, const int& seed,
const std::pair<std::vector<Array2D<T>>, std::vector<double>>& patterns,
const std::vector<std::array<std::vector<unsigned>, 4>>& propagator) noexcept
: input(input)
, options(options)
, patterns(patterns.first)
, wfc(options.periodic_output, seed, patterns.second, propagator,
options.get_wave_height(), options.get_wave_width())
{
// If necessary, the ground is set.
if (options.ground) {
init_ground(wfc, input, patterns.first, options);
}
}
/**
* Constructor used only to call the other constructor with more computed
* parameters.
*/
OverlappingWFC(const Array2D<T>& input, const OverlappingWFCOptions& options, const int& seed,
const std::pair<std::vector<Array2D<T>>, std::vector<double>>& patterns) noexcept
: OverlappingWFC(input, options, seed, patterns, generate_compatible(patterns.first))
{
}
/**
* Init the ground of the output image.
* The lowest middle pattern is used as a floor (and ceiling when the input is
* toric) and is placed at the lowest possible pattern position in the output
* image, on all its width. The pattern cannot be used at any other place in
* the output image.
*/
static void init_ground(WFC& wfc, const Array2D<T>& input,
const std::vector<Array2D<T>>& patterns, const OverlappingWFCOptions& options) noexcept
{
unsigned ground_pattern_id = get_ground_pattern_id(input, patterns, options);
// Place the pattern in the ground.
for (unsigned j = 0; j < options.get_wave_width(); j++) {
for (unsigned p = 0; p < patterns.size(); p++) {
if (ground_pattern_id != p) {
wfc.remove_wave_pattern(options.get_wave_height() - 1, j, p);
}
}
}
// Remove the pattern from the other positions.
for (unsigned i = 0; i < options.get_wave_height() - 1; i++) {
for (unsigned j = 0; j < options.get_wave_width(); j++) {
wfc.remove_wave_pattern(i, j, ground_pattern_id);
}
}
// Propagate the information with wfc.
wfc.propagate();
}
/**
* Return the id of the lowest middle pattern.
*/
static unsigned get_ground_pattern_id(const Array2D<T>& input,
const std::vector<Array2D<T>>& patterns, const OverlappingWFCOptions& options) noexcept
{
// Get the pattern.
Array2D<T> ground_pattern = input.get_sub_array(
input.height - 1, input.width / 2, options.pattern_size, options.pattern_size);
// Retrieve the id of the pattern.
for (unsigned i = 0; i < patterns.size(); i++) {
if (ground_pattern == patterns[i]) {
return i;
}
}
// The pattern exists.
assert(false);
return 0;
}
/**
* Return the list of patterns, as well as their probabilities of apparition.
*/
static std::pair<std::vector<Array2D<T>>, std::vector<double>> get_patterns(
const Array2D<T>& input, const OverlappingWFCOptions& options) noexcept
{
std::unordered_map<Array2D<T>, unsigned> patterns_id;
std::vector<Array2D<T>> patterns;
// The number of time a pattern is seen in the input image.
std::vector<double> patterns_weight;
std::vector<Array2D<T>> symmetries(
8, Array2D<T>(options.pattern_size, options.pattern_size));
unsigned max_i
= options.periodic_input ? input.height : input.height - options.pattern_size + 1;
unsigned max_j
= options.periodic_input ? input.width : input.width - options.pattern_size + 1;
for (unsigned i = 0; i < max_i; i++) {
for (unsigned j = 0; j < max_j; j++) {
// Compute the symmetries of every pattern in the image.
symmetries[0].data
= input.get_sub_array(i, j, options.pattern_size, options.pattern_size).data;
symmetries[1].data = symmetries[0].reflected().data;
symmetries[2].data = symmetries[0].rotated().data;
symmetries[3].data = symmetries[2].reflected().data;
symmetries[4].data = symmetries[2].rotated().data;
symmetries[5].data = symmetries[4].reflected().data;
symmetries[6].data = symmetries[4].rotated().data;
symmetries[7].data = symmetries[6].reflected().data;
// The number of symmetries in the option class define which symetries
// will be used.
for (unsigned k = 0; k < options.symmetry; k++) {
auto res = patterns_id.insert(std::make_pair(symmetries[k], patterns.size()));
// If the pattern already exist, we just have to increase its number
// of appearance.
if (!res.second) {
patterns_weight[res.first->second] += 1;
} else {
patterns.push_back(symmetries[k]);
patterns_weight.push_back(1);
}
}
}
}
return { patterns, patterns_weight };
}
/**
* Return true if the pattern1 is compatible with pattern2
* when pattern2 is at a distance (dy,dx) from pattern1.
*/
static bool agrees(
const Array2D<T>& pattern1, const Array2D<T>& pattern2, int dy, int dx) noexcept
{
unsigned xmin = dx < 0 ? 0 : dx;
unsigned xmax = dx < 0 ? dx + pattern2.width : pattern1.width;
unsigned ymin = dy < 0 ? 0 : dy;
unsigned ymax = dy < 0 ? dy + pattern2.height : pattern1.width;
// Iterate on every pixel contained in the intersection of the two pattern.
for (unsigned y = ymin; y < ymax; y++) {
for (unsigned x = xmin; x < xmax; x++) {
// Check if the color is the same in the two patterns in that pixel.
if (pattern1.get(y, x) != pattern2.get(y - dy, x - dx)) {
return false;
}
}
}
return true;
}
/**
* Precompute the function agrees(pattern1, pattern2, dy, dx).
* If agrees(pattern1, pattern2, dy, dx), then compatible[pattern1][direction]
* contains pattern2, where direction is the direction defined by (dy, dx)
* (see direction.hpp).
*/
static std::vector<std::array<std::vector<unsigned>, 4>> generate_compatible(
const std::vector<Array2D<T>>& patterns) noexcept
{
std::vector<std::array<std::vector<unsigned>, 4>> compatible
= std::vector<std::array<std::vector<unsigned>, 4>>(patterns.size());
// Iterate on every dy, dx, pattern1 and pattern2
for (unsigned pattern1 = 0; pattern1 < patterns.size(); pattern1++) {
for (unsigned direction = 0; direction < 4; direction++) {
for (unsigned pattern2 = 0; pattern2 < patterns.size(); pattern2++) {
if (agrees(patterns[pattern1], patterns[pattern2], directions_y[direction],
directions_x[direction])) {
compatible[pattern1][direction].push_back(pattern2);
}
}
}
}
return compatible;
}
/**
* Transform a 2D array containing the patterns id to a 2D array containing
* the pixels.
*/
Array2D<T> to_image(const Array2D<unsigned>& output_patterns) const noexcept
{
Array2D<T> output = Array2D<T>(options.out_height, options.out_width);
if (options.periodic_output) {
for (unsigned y = 0; y < options.get_wave_height(); y++) {
for (unsigned x = 0; x < options.get_wave_width(); x++) {
output.get(y, x) = patterns[output_patterns.get(y, x)].get(0, 0);
}
}
} else {
for (unsigned y = 0; y < options.get_wave_height(); y++) {
for (unsigned x = 0; x < options.get_wave_width(); x++) {
output.get(y, x) = patterns[output_patterns.get(y, x)].get(0, 0);
}
}
for (unsigned y = 0; y < options.get_wave_height(); y++) {
const Array2D<T>& pattern
= patterns[output_patterns.get(y, options.get_wave_width() - 1)];
for (unsigned dx = 1; dx < options.pattern_size; dx++) {
output.get(y, options.get_wave_width() - 1 + dx) = pattern.get(0, dx);
}
}
for (unsigned x = 0; x < options.get_wave_width(); x++) {
const Array2D<T>& pattern
= patterns[output_patterns.get(options.get_wave_height() - 1, x)];
for (unsigned dy = 1; dy < options.pattern_size; dy++) {
output.get(options.get_wave_height() - 1 + dy, x) = pattern.get(dy, 0);
}
}
const Array2D<T>& pattern = patterns[output_patterns.get(
options.get_wave_height() - 1, options.get_wave_width() - 1)];
for (unsigned dy = 1; dy < options.pattern_size; dy++) {
for (unsigned dx = 1; dx < options.pattern_size; dx++) {
output.get(
options.get_wave_height() - 1 + dy, options.get_wave_width() - 1 + dx)
= pattern.get(dy, dx);
}
}
}
return output;
}
public:
/**
* The constructor used by the user.
*/
OverlappingWFC(
const Array2D<T>& input, const OverlappingWFCOptions& options, int seed) noexcept
: OverlappingWFC(input, options, seed, get_patterns(input, options))
{
}
/**
* Run the WFC algorithm, and return the result if the algorithm succeeded.
*/
std::optional<Array2D<T>> run() noexcept
{
std::optional<Array2D<unsigned>> result = wfc.run();
if (result.has_value()) {
return to_image(*result);
}
return std::nullopt;
}
};
#endif // FAST_WFC_WFC_HPP_
| 37.623457 | 98 | 0.57219 | xyproto |
b877694b3d7bd62ad48f6b1322df50f0986b90b5 | 3,721 | cpp | C++ | example-Basic/src/ofApp.cpp | thorikawa/ofxSyphon | 83cca453ba6d6359923a5871bfdbf9a68ef65d99 | [
"BSD-2-Clause"
] | 118 | 2015-01-19T04:54:18.000Z | 2021-09-29T07:36:06.000Z | example-Basic/src/ofApp.cpp | thorikawa/ofxSyphon | 83cca453ba6d6359923a5871bfdbf9a68ef65d99 | [
"BSD-2-Clause"
] | 33 | 2015-01-30T21:36:42.000Z | 2022-02-10T11:47:14.000Z | example-Basic/src/ofApp.cpp | thorikawa/ofxSyphon | 83cca453ba6d6359923a5871bfdbf9a68ef65d99 | [
"BSD-2-Clause"
] | 28 | 2015-01-21T05:26:47.000Z | 2021-06-05T14:30:28.000Z | #include "ofApp.h"
const int width = 800;
const int height = 600;
//--------------------------------------------------------------
void ofApp::setup(){
counter = 0;
ofSetCircleResolution(50);
//ofBackground(0,0,0);
bSmooth = false;
ofSetWindowTitle("ofxSyphon Example");
mainOutputSyphonServer.setName("Screen Output");
individualTextureSyphonServer.setName("Texture Output");
mClient.setup();
//using Syphon app Simple Server, found at http://syphon.v002.info/
mClient.set("","Simple Server");
tex.allocate(200, 100, GL_RGBA);
ofSetFrameRate(60); // if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps.
}
//--------------------------------------------------------------
void ofApp::update(){
counter = counter + 0.033f;
}
//--------------------------------------------------------------
void ofApp::draw(){
// Clear with alpha, so we can capture via syphon and composite elsewhere should we want.
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//--------------------------- circles
//let's draw a circle:
ofSetColor(255,130,0);
float radius = 50 + 10 * sin(counter);
ofFill(); // draw "filled shapes"
ofDrawCircle(100,400,radius);
// now just an outline
ofNoFill();
ofSetHexColor(0xCCCCCC);
ofDrawCircle(100,400,80);
// use the bitMap type
// note, this can be slow on some graphics cards
// because it is using glDrawPixels which varies in
// speed from system to system. try using ofTrueTypeFont
// if this bitMap type slows you down.
ofSetHexColor(0x000000);
ofDrawBitmapString("circle", 75,500);
//--------------------------- rectangles
ofFill();
for (int i = 0; i < 200; i++){
ofSetColor((int)ofRandom(0,255),(int)ofRandom(0,255),(int)ofRandom(0,255));
ofDrawRectangle(ofRandom(250,350),ofRandom(350,450),ofRandom(10,20),ofRandom(10,20));
}
ofSetHexColor(0x000000);
ofDrawBitmapString("rectangles", 275,500);
//--------------------------- transparency
ofSetHexColor(0x00FF33);
ofDrawRectangle(100,150,100,100);
// alpha is usually turned off - for speed puposes. let's turn it on!
ofEnableAlphaBlending();
ofSetColor(255,0,0,127); // red, 50% transparent
ofDrawRectangle(150,230,100,33);
ofSetColor(255,0,0,(int)(counter * 10.0f) % 255); // red, variable transparent
ofDrawRectangle(150,170,100,33);
ofDisableAlphaBlending();
ofSetHexColor(0x000000);
ofDrawBitmapString("transparency", 110,300);
//--------------------------- lines
// a bunch of red lines, make them smooth if the flag is set
if (bSmooth){
ofEnableSmoothing();
}
ofSetHexColor(0xFF0000);
for (int i = 0; i < 20; i++){
ofDrawLine(300,100 + (i*5),500, 50 + (i*10));
}
if (bSmooth){
ofDisableSmoothing();
}
ofSetColor(255,255,255);
ofDrawBitmapString("lines\npress 's' to toggle smoothness", 300,300);
// draw static into our one texture.
unsigned char pixels[200*100*4];
for (int i = 0; i < 200*100*4; i++)
{
pixels[i] = (int)(255 * ofRandomuf());
}
tex.loadData(pixels, 200, 100, GL_RGBA);
ofSetColor(255, 255, 255);
ofEnableAlphaBlending();
tex.draw(50, 50);
// Syphon Stuff
mClient.draw(50, 50);
mainOutputSyphonServer.publishScreen();
individualTextureSyphonServer.publishTexture(&tex);
ofDrawBitmapString("Note this text is not captured by Syphon since it is drawn after publishing.\nYou can use this to hide your GUI for example.", 150,500);
}
//--------------------------------------------------------------
void ofApp::keyPressed (int key){
if (key == 's'){
bSmooth = !bSmooth;
}
}
| 26.963768 | 164 | 0.601182 | thorikawa |
b87aa314e26331d69774bef6858d817ed0087130 | 2,801 | hpp | C++ | src/rp/intelbeaengine.hpp | clayne/rp | 5cf489872a7f31c5688e55b99cd41b586a1006e3 | [
"MIT"
] | 1 | 2022-01-17T17:40:29.000Z | 2022-01-17T17:40:29.000Z | src/rp/intelbeaengine.hpp | clayne/rp | 5cf489872a7f31c5688e55b99cd41b586a1006e3 | [
"MIT"
] | null | null | null | src/rp/intelbeaengine.hpp | clayne/rp | 5cf489872a7f31c5688e55b99cd41b586a1006e3 | [
"MIT"
] | null | null | null | // Axel '0vercl0k' Souchet - January 12 2022
#pragma once
#include "disassenginewrapper.hpp"
#include <beaengine/BeaEngine.h>
class IntelBeaEngine : public DisassEngineWrapper {
public:
/*! The different architectures BeaRopGadgetFinder handles */
enum E_Arch { x86 = 32, x64 = 64 };
explicit IntelBeaEngine(const E_Arch arch) : m_arch(uint32_t(arch)) {
// those options are mostly display option for the disassembler engine
m_disasm.Options = PrefixedNumeral + NasmSyntax;
// this one is to precise what architecture we'll disassemble
m_disasm.Archi = m_arch;
}
InstructionInformation disass(const uint8_t *data, uint64_t len,
const uint64_t vaddr,
DisassEngineReturn &ret) override {
InstructionInformation instr;
m_disasm.EIP = UIntPtr(data);
m_disasm.VirtualAddr = vaddr;
m_disasm.SecurityBlock = uint32_t(len);
const int len_instr = Disasm(&m_disasm);
if (len_instr == OUT_OF_BLOCK) {
ret = OutOfBlock;
return instr;
}
// OK this one is an unknow opcode, goto the next one
if (len_instr == UNKNOWN_OPCODE) {
ret = UnknownInstruction;
return instr;
}
ret = AllRight;
instr.address = m_disasm.EIP;
instr.virtual_address_in_memory = uintptr_t(m_disasm.VirtualAddr);
instr.disassembly = m_disasm.CompleteInstr;
instr.mnemonic = m_disasm.Instruction.Mnemonic;
instr.size = len_instr;
const auto branch_type = m_disasm.Instruction.BranchType;
const auto addr_value = m_disasm.Instruction.AddrValue;
const char *mnemonic_s = m_disasm.Instruction.Mnemonic;
const char *disass_s = instr.disassembly.c_str();
instr.is_branch = branch_type != 0;
const bool is_good_branch_type =
// We accept all the ret type instructions (except retf/iret)
(branch_type == RetType && (strncmp(mnemonic_s, "retf", 4) != 0) &&
(strncmp(mnemonic_s, "iretd", 5) != 0)) ||
// call reg32 / call [reg32]
(branch_type == CallType && addr_value == 0) ||
// jmp reg32 / jmp [reg32]
(branch_type == JmpType && addr_value == 0) ||
// int 0x80 & int 0x2e
((strncmp(disass_s, "int 0x80", 8) == 0) ||
(strncmp(disass_s, "int 0x2e", 8) == 0) ||
(strncmp(disass_s, "syscall", 7) == 0));
instr.is_valid_ending_instr =
is_good_branch_type &&
// Yeah, we don't accept jmp far/call far
instr.disassembly.find("far") == std::string::npos;
return instr;
}
uint32_t get_size_biggest_instruction() const override { return 15; }
uint32_t get_alignement() const override { return 1; }
private:
uint32_t m_arch = 0; /*!< architecture the BeaEngine will use to disassemble*/
DISASM m_disasm = {};
};
| 33.345238 | 80 | 0.653695 | clayne |
b87b3292e0d300a7a0f343d67544309a72d3470b | 2,005 | cc | C++ | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | null | null | null | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 2 | 2021-12-15T10:51:15.000Z | 2022-01-26T17:03:16.000Z | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <iostream>
#include <vector>
using namespace std;
/**
* This file is generated by leetcode_add.py
*
* 1288.
* Remove Covered Intervals
*
* ––––––––––––––––––––––––––––– Description –––––––––––––––––––––––––––––
*
* Given an array ‘intervals’ where ‘intervals[i] = [lᵢ, rᵢ]’ represent
* the interval ‘[lᵢ, rᵢ)’ , remove all intervals that are covered by
* another interval in the
* The interval ‘[a, b)’ is covered by the interval ‘[c, d)’ if and only
* if ‘c ≤ a’ and ‘b ≤ d’
* Return “the number of remaining intervals” .
*
* ––––––––––––––––––––––––––––– Constraints –––––––––––––––––––––––––––––
*
* • ‘1 ≤ intervals.length ≤ 1000’
* • ‘intervals[i].length = 2’
* • ‘0 ≤ lᵢ ≤ rᵢ ≤ 10⁵’
* • All the given intervals are “unique” .
*
*/
struct q1288 : public ::testing::Test {
// Leetcode answer here
class Solution {
public:
int removeCoveredIntervals(vector<vector<int>> &intervals) {
sort(intervals.begin(), intervals.end(), [](const vector<int> &x, const vector<int> &y) {
return x[0] == y[0] ? x[1] > y[1] : x[0] < y[0];
});
int res = intervals.size();
vector<int> curr = intervals.front();
for (auto it = intervals.begin() + 1; it != intervals.end(); ++it) {
int l = curr[0],
r = curr[1];
if (l <= (*it)[0] && r >= (*it)[1]) {
--res;
} else {
curr = *it;
}
}
return res;
}
};
class Solution *solution;
};
TEST_F(q1288, sample_input01) {
solution = new Solution();
vector<vector<int>> intervals = {{1, 4}, {3, 6}, {2, 8}};
int exp = 2;
int act = solution->removeCoveredIntervals(intervals);
EXPECT_EQ(act, exp);
delete solution;
}
TEST_F(q1288, sample_input02) {
solution = new Solution();
vector<vector<int>> intervals = {{1, 4}, {2, 3}};
int exp = 1;
int act = solution->removeCoveredIntervals(intervals);
EXPECT_EQ(act, exp);
delete solution;
} | 27.465753 | 95 | 0.539651 | vNaonLu |
b87bb4b690d2dc5869d77c3611bc2783a0266475 | 6,024 | cc | C++ | media/cast/test/receiver/framer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | media/cast/test/receiver/framer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | media/cast/test/receiver/framer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/cast/test/receiver/framer.h"
#include "base/logging.h"
#include "media/cast/constants.h"
namespace media {
namespace cast {
Framer::Framer(const base::TickClock* clock,
RtpPayloadFeedback* incoming_payload_feedback,
uint32_t ssrc,
bool decoder_faster_than_max_frame_rate,
int max_unacked_frames)
: decoder_faster_than_max_frame_rate_(decoder_faster_than_max_frame_rate),
cast_msg_builder_(clock,
incoming_payload_feedback,
this,
ssrc,
decoder_faster_than_max_frame_rate,
max_unacked_frames),
waiting_for_key_(true),
last_released_frame_(FrameId::first() - 1),
newest_frame_id_(FrameId::first() - 1) {
DCHECK(incoming_payload_feedback) << "Invalid argument";
}
Framer::~Framer() = default;
bool Framer::InsertPacket(const uint8_t* payload_data,
size_t payload_size,
const RtpCastHeader& rtp_header,
bool* duplicate) {
*duplicate = false;
if (rtp_header.is_key_frame && waiting_for_key_) {
last_released_frame_ = rtp_header.frame_id - 1;
waiting_for_key_ = false;
}
VLOG(1) << "InsertPacket frame:" << rtp_header.frame_id
<< " packet:" << static_cast<int>(rtp_header.packet_id)
<< " max packet:" << static_cast<int>(rtp_header.max_packet_id);
if ((rtp_header.frame_id <= last_released_frame_) && !waiting_for_key_) {
// Packet is too old.
return false;
}
// Update the last received frame id.
if (rtp_header.frame_id > newest_frame_id_) {
newest_frame_id_ = rtp_header.frame_id;
}
// Insert packet.
const auto it = frames_.find(rtp_header.frame_id);
FrameBuffer* buffer;
if (it == frames_.end()) {
buffer = new FrameBuffer();
frames_.insert(std::make_pair(rtp_header.frame_id,
std::unique_ptr<FrameBuffer>(buffer)));
} else {
buffer = it->second.get();
}
if (!buffer->InsertPacket(payload_data, payload_size, rtp_header)) {
VLOG(3) << "Packet already received, ignored: frame " << rtp_header.frame_id
<< ", packet " << rtp_header.packet_id;
*duplicate = true;
return false;
}
return buffer->Complete();
}
// This does not release the frame.
bool Framer::GetEncodedFrame(EncodedFrame* frame,
bool* next_frame,
bool* have_multiple_decodable_frames) {
*have_multiple_decodable_frames = HaveMultipleDecodableFrames();
// Find frame id.
FrameBuffer* buffer = FindNextFrameForRelease();
if (buffer) {
// We have our next frame.
*next_frame = true;
} else {
// Check if we can skip frames when our decoder is too slow.
if (!decoder_faster_than_max_frame_rate_)
return false;
buffer = FindOldestDecodableFrame();
if (!buffer)
return false;
*next_frame = false;
}
return buffer->AssembleEncodedFrame(frame);
}
void Framer::AckFrame(FrameId frame_id) {
VLOG(2) << "ACK frame " << frame_id;
cast_msg_builder_.CompleteFrameReceived(frame_id);
}
void Framer::ReleaseFrame(FrameId frame_id) {
const auto it = frames_.begin();
const bool skipped_old_frame = it->first < frame_id;
frames_.erase(it, frames_.upper_bound(frame_id));
last_released_frame_ = frame_id;
if (skipped_old_frame)
cast_msg_builder_.UpdateCastMessage();
}
bool Framer::TimeToSendNextCastMessage(base::TimeTicks* time_to_send) {
return cast_msg_builder_.TimeToSendNextCastMessage(time_to_send);
}
void Framer::SendCastMessage() {
cast_msg_builder_.UpdateCastMessage();
}
FrameBuffer* Framer::FindNextFrameForRelease() {
for (const auto& entry : frames_) {
if (entry.second->Complete() && IsNextFrameForRelease(*entry.second))
return entry.second.get();
}
return nullptr;
}
FrameBuffer* Framer::FindOldestDecodableFrame() {
for (const auto& entry : frames_) {
if (entry.second->Complete() && IsDecodableFrame(*entry.second))
return entry.second.get();
}
return nullptr;
}
bool Framer::HaveMultipleDecodableFrames() const {
bool found_one = false;
for (const auto& entry : frames_) {
if (entry.second->Complete() && IsDecodableFrame(*entry.second)) {
if (found_one)
return true; // Found another.
else
found_one = true; // Found first one. Continue search for another.
}
}
return false;
}
bool Framer::Empty() const {
return frames_.empty();
}
int Framer::NumberOfCompleteFrames() const {
int count = 0;
for (const auto& entry : frames_) {
if (entry.second->Complete())
++count;
}
return count;
}
bool Framer::FrameExists(FrameId frame_id) const {
return frames_.end() != frames_.find(frame_id);
}
void Framer::GetMissingPackets(FrameId frame_id,
bool last_frame,
PacketIdSet* missing_packets) const {
const auto it = frames_.find(frame_id);
if (it == frames_.end())
return;
it->second->GetMissingPackets(last_frame, missing_packets);
}
bool Framer::IsNextFrameForRelease(const FrameBuffer& buffer) const {
if (waiting_for_key_ && !buffer.is_key_frame())
return false;
return (last_released_frame_ + 1) == buffer.frame_id();
}
bool Framer::IsDecodableFrame(const FrameBuffer& buffer) const {
if (buffer.is_key_frame())
return true;
if (waiting_for_key_)
return false;
// Self-reference?
if (buffer.last_referenced_frame_id() == buffer.frame_id())
return true;
// Current frame is not necessarily referencing the last frame.
// Has the reference frame been released already?
return buffer.last_referenced_frame_id() <= last_released_frame_;
}
} // namespace cast
} // namespace media
| 29.674877 | 80 | 0.663845 | zealoussnow |
b87df593d29beba63e7f8814d90b2a0fed8249cd | 580 | hpp | C++ | config/src/vespa/config/helper/configpoller.hpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-06-02T13:28:29.000Z | 2020-06-02T13:28:29.000Z | config/src/vespa/config/helper/configpoller.hpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-03-31T22:24:20.000Z | 2021-03-31T22:24:20.000Z | config/src/vespa/config/helper/configpoller.hpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-12-08T19:56:35.000Z | 2020-12-08T19:56:35.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
namespace config {
template <typename ConfigType>
void
ConfigPoller::subscribe(const std::string & configId, IFetcherCallback<ConfigType> * callback, milliseconds subscribeTimeout)
{
std::unique_ptr<ConfigHandle<ConfigType> > handle(_subscriber.subscribe<ConfigType>(configId, subscribeTimeout));
_handleList.emplace_back(std::make_unique<GenericHandle<ConfigType>>(std::move(handle)));
_callbackList.push_back(callback);
}
} // namespace config
| 38.666667 | 125 | 0.786207 | amahussein |
b87e7b45c29c66f4617b070f238fa2f3faff4415 | 2,943 | cpp | C++ | hotspot/src/os/solaris/vm/threadCritical_solaris.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | hotspot/src/os/solaris/vm/threadCritical_solaris.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | hotspot/src/os/solaris/vm/threadCritical_solaris.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadCritical.hpp"
// OS-includes here
#include <thread.h>
#include <synch.h>
//
// See threadCritical.hpp for details of this class.
//
// For some reason, we don't do locking until the
// os::init() call completes. I'm not sure why this
// is, and have left it that way for now. This should
// be reviewed later.
static mutex_t global_mut;
static thread_t global_mut_owner = -1;
static int global_mut_count = 0;
static bool initialized = false;
ThreadCritical::ThreadCritical() {
if (initialized) {
thread_t owner = thr_self();
if (global_mut_owner != owner) {
if (os::Solaris::mutex_lock(&global_mut))
fatal(err_msg("ThreadCritical::ThreadCritical: mutex_lock failed (%s)",
strerror(errno)));
assert(global_mut_count == 0, "must have clean count");
assert(global_mut_owner == -1, "must have clean owner");
}
global_mut_owner = owner;
++global_mut_count;
} else {
assert (Threads::number_of_threads() == 0, "valid only during initialization");
}
}
ThreadCritical::~ThreadCritical() {
if (initialized) {
assert(global_mut_owner == thr_self(), "must have correct owner");
assert(global_mut_count > 0, "must have correct count");
--global_mut_count;
if (global_mut_count == 0) {
global_mut_owner = -1;
if (os::Solaris::mutex_unlock(&global_mut))
fatal(err_msg("ThreadCritical::~ThreadCritical: mutex_unlock failed "
"(%s)", strerror(errno)));
}
} else {
assert (Threads::number_of_threads() == 0, "valid only during initialization");
}
}
void ThreadCritical::initialize() {
// This method is called at the end of os::init(). Until
// then, we don't do real locking.
initialized = true;
}
void ThreadCritical::release() {
}
| 33.827586 | 83 | 0.692491 | dbac |
b87f61a901338830bacddd80b689d591cb5bddb3 | 25,904 | cpp | C++ | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2019 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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 llpcBuilder.cpp
* @brief LLPC source file: implementation of Llpc::Builder
***********************************************************************************************************************
*/
#include "llpcBuilderImpl.h"
#include "llpcPipelineState.h"
#include "llpcContext.h"
#include "llpcInternal.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/CommandLine.h"
#include <set>
#define DEBUG_TYPE "llpc-builder"
using namespace Llpc;
using namespace llvm;
// -use-builder-recorder
static cl::opt<uint32_t> UseBuilderRecorder("use-builder-recorder",
cl::desc("Do lowering via recording and replaying LLPC builder:\n"
"0: Generate IR directly; no recording\n"
"1: Do lowering via recording and replaying LLPC builder (default)\n"
"2: Do lowering via recording; no replaying"),
cl::init(1));
// =====================================================================================================================
// Create a Builder object
// If -use-builder-recorder is 0, this creates a BuilderImpl. Otherwise, it creates a BuilderRecorder.
Builder* Builder::Create(
LLVMContext& context) // [in] LLVM context
{
if (UseBuilderRecorder == 0)
{
// -use-builder-recorder=0: generate LLVM IR directly without recording
return CreateBuilderImpl(context);
}
// -use-builder-recorder=1: record with BuilderRecorder and replay with BuilderReplayer
// -use-builder-recorder=2: record with BuilderRecorder and do not replay
return CreateBuilderRecorder(context, UseBuilderRecorder == 1 /*wantReplay*/);
}
// =====================================================================================================================
// Create a BuilderImpl object
Builder* Builder::CreateBuilderImpl(
LLVMContext& context) // [in] LLVM context
{
return new BuilderImpl(context);
}
// =====================================================================================================================
Builder::Builder(
LLVMContext& context) // [in] LLPC context
:
IRBuilder<>(context)
{
m_pPipelineState = new PipelineState(&context);
}
// =====================================================================================================================
Builder::~Builder()
{
delete m_pPipelineState;
}
// =====================================================================================================================
// Get the type pElementTy, turned into a vector of the same vector width as pMaybeVecTy if the latter
// is a vector type.
Type* Builder::GetConditionallyVectorizedTy(
Type* pElementTy, // [in] Element type
Type* pMaybeVecTy) // [in] Possible vector type to get number of elements from
{
if (auto pVecTy = dyn_cast<VectorType>(pMaybeVecTy))
{
return VectorType::get(pElementTy, pVecTy->getNumElements());
}
return pElementTy;
}
// =====================================================================================================================
// Set the resource mapping nodes for the given shader stage.
// This stores the nodes as IR metadata.
void Builder::SetUserDataNodes(
ArrayRef<ResourceMappingNode> nodes, // The resource mapping nodes
ArrayRef<DescriptorRangeValue> rangeValues) // The descriptor range values
{
m_pPipelineState->SetUserDataNodes(nodes, rangeValues);
}
// =====================================================================================================================
// Base implementation of linking shader modules into a pipeline module.
Module* Builder::Link(
ArrayRef<Module*> modules, // Array of modules indexed by shader stage, with nullptr entry
// for any stage not present in the pipeline
bool linkNativeStages) // Whether to link native shader stage modules
{
// Add IR metadata for the shader stage to each function in each shader, and rename the entrypoint to
// ensure there is no clash on linking.
if (linkNativeStages)
{
uint32_t metaKindId = getContext().getMDKindID(LlpcName::ShaderStageMetadata);
for (uint32_t stage = 0; stage < modules.size(); ++stage)
{
Module* pModule = modules[stage];
if (pModule == nullptr)
{
continue;
}
auto pStageMetaNode = MDNode::get(getContext(), { ConstantAsMetadata::get(getInt32(stage)) });
for (Function& func : *pModule)
{
if (func.isDeclaration() == false)
{
func.setMetadata(metaKindId, pStageMetaNode);
if (func.getLinkage() != GlobalValue::InternalLinkage)
{
func.setName(Twine(LlpcName::EntryPointPrefix) +
GetShaderStageAbbreviation(static_cast<ShaderStage>(stage), true) +
"." +
func.getName());
}
}
}
}
}
// If there is only one shader, just change the name on its module and return it.
Module* pPipelineModule = nullptr;
for (auto pModule : modules)
{
if (pPipelineModule == nullptr)
{
pPipelineModule = pModule;
}
else if (pModule != nullptr)
{
pPipelineModule = nullptr;
break;
}
}
if (pPipelineModule != nullptr)
{
pPipelineModule->setModuleIdentifier("llpcPipeline");
// Record pipeline state into IR metadata.
if (m_pPipelineState != nullptr)
{
m_pPipelineState->RecordState(pPipelineModule);
}
}
else
{
// Create an empty module then link each shader module into it. We record pipeline state into IR
// metadata before the link, to avoid problems with a Constant for an immutable descriptor value
// disappearing when modules are deleted.
bool result = true;
pPipelineModule = new Module("llpcPipeline", getContext());
static_cast<Llpc::Context*>(&getContext())->SetModuleTargetMachine(pPipelineModule);
Linker linker(*pPipelineModule);
if (m_pPipelineState != nullptr)
{
m_pPipelineState->RecordState(pPipelineModule);
}
for (int32_t shaderIndex = 0; shaderIndex < modules.size(); ++shaderIndex)
{
if (modules[shaderIndex] != nullptr)
{
// NOTE: We use unique_ptr here. The shader module will be destroyed after it is
// linked into pipeline module.
if (linker.linkInModule(std::unique_ptr<Module>(modules[shaderIndex])))
{
result = false;
}
}
}
if (result == false)
{
delete pPipelineModule;
pPipelineModule = nullptr;
}
}
return pPipelineModule;
}
// =====================================================================================================================
// Create a map to i32 function. Many AMDGCN intrinsics only take i32's, so we need to massage input data into an i32
// to allow us to call these intrinsics. This helper takes a function pointer, massage arguments, and passthrough
// arguments and massages the mappedArgs into i32's before calling the function pointer. Note that all massage
// arguments must have the same type.
Value* Builder::CreateMapToInt32(
PFN_MapToInt32Func pfnMapFunc, // [in] The function to call on each provided i32.
ArrayRef<Value*> mappedArgs, // The arguments to be massaged into i32's and passed to function.
ArrayRef<Value*> passthroughArgs) // The arguments to be passed through as is (no massaging).
{
// We must have at least one argument to massage.
LLPC_ASSERT(mappedArgs.size() > 0);
Type* const pType = mappedArgs[0]->getType();
// Check the massage types all match.
for (uint32_t i = 1; i < mappedArgs.size(); i++)
{
LLPC_ASSERT(mappedArgs[i]->getType() == pType);
}
if (mappedArgs[0]->getType()->isVectorTy())
{
// For vectors we extract each vector component and map them individually.
const uint32_t compCount = pType->getVectorNumElements();
SmallVector<Value*, 4> results;
for (uint32_t i = 0; i < compCount; i++)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateExtractElement(pMappedArg, i));
}
results.push_back(CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs));
}
Value* pResult = UndefValue::get(VectorType::get(results[0]->getType(), compCount));
for (uint32_t i = 0; i < compCount; i++)
{
pResult = CreateInsertElement(pResult, results[i], i);
}
return pResult;
}
else if (pType->isIntegerTy() && pType->getIntegerBitWidth() == 1)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateZExt(pMappedArg, getInt32Ty()));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateTrunc(pResult, getInt1Ty());
}
else if (pType->isIntegerTy() && pType->getIntegerBitWidth() < 32)
{
SmallVector<Value*, 4> newMappedArgs;
Type* const pVectorType = VectorType::get(pType, (pType->getPrimitiveSizeInBits() == 16) ? 2 : 4);
Value* const pUndef = UndefValue::get(pVectorType);
for (Value* const pMappedArg : mappedArgs)
{
Value* const pNewMappedArg = CreateInsertElement(pUndef, pMappedArg, static_cast<uint64_t>(0));
newMappedArgs.push_back(CreateBitCast(pNewMappedArg, getInt32Ty()));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateExtractElement(CreateBitCast(pResult, pVectorType), static_cast<uint64_t>(0));
}
else if (pType->getPrimitiveSizeInBits() == 64)
{
SmallVector<Value*, 4> castMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
castMappedArgs.push_back(CreateBitCast(pMappedArg, VectorType::get(getInt32Ty(), 2)));
}
Value* pResult = UndefValue::get(castMappedArgs[0]->getType());
for (uint32_t i = 0; i < 2; i++)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pCastMappedArg : castMappedArgs)
{
newMappedArgs.push_back(CreateExtractElement(pCastMappedArg, i));
}
Value* const pResultComp = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
pResult = CreateInsertElement(pResult, pResultComp, i);
}
return CreateBitCast(pResult, pType);
}
else if (pType->isFloatingPointTy())
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateBitCast(pMappedArg, getIntNTy(pMappedArg->getType()->getPrimitiveSizeInBits())));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateBitCast(pResult, pType);
}
else if (pType->isIntegerTy(32))
{
return pfnMapFunc(*this, mappedArgs, passthroughArgs);
}
else
{
LLPC_NEVER_CALLED();
return nullptr;
}
}
// =====================================================================================================================
// Gets new matrix type after doing matrix transposing.
Type* Builder::GetTransposedMatrixTy(
Type* const pMatrixType // [in] The matrix type to get the transposed type from.
) const
{
LLPC_ASSERT(pMatrixType->isArrayTy());
Type* const pColumnVectorType = pMatrixType->getArrayElementType();
LLPC_ASSERT(pColumnVectorType->isVectorTy());
const uint32_t columnCount = pMatrixType->getArrayNumElements();
const uint32_t rowCount = pColumnVectorType->getVectorNumElements();
return ArrayType::get(VectorType::get(pColumnVectorType->getVectorElementType(), columnCount), rowCount);
}
// =====================================================================================================================
// Get the LLPC context. This overrides the IRBuilder method that gets the LLVM context.
Context& Builder::getContext() const
{
return *static_cast<Llpc::Context*>(&IRBuilder<>::getContext());
}
// =====================================================================================================================
// Get the type of pointer returned by CreateLoadBufferDesc.
PointerType* Builder::GetBufferDescTy(
Type* pPointeeTy) // [in] Type that the returned pointer should point to.
{
return PointerType::get(pPointeeTy, ADDR_SPACE_BUFFER_FAT_POINTER);
}
// =====================================================================================================================
// Get the type of an image descriptor
VectorType* Builder::GetImageDescTy()
{
return VectorType::get(getInt32Ty(), 8);
}
// =====================================================================================================================
// Get the type of an fmask descriptor
VectorType* Builder::GetFmaskDescTy()
{
return VectorType::get(getInt32Ty(), 8);
}
// =====================================================================================================================
// Get the type of a texel buffer descriptor
VectorType* Builder::GetTexelBufferDescTy()
{
return VectorType::get(getInt32Ty(), 4);
}
// =====================================================================================================================
// Get the type of a sampler descriptor
VectorType* Builder::GetSamplerDescTy()
{
return VectorType::get(getInt32Ty(), 4);
}
// =====================================================================================================================
// Get the type of pointer to image descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetImageDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetImageDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to fmask descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetFmaskDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetFmaskDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to texel buffer descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetTexelBufferDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetTexelBufferDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to sampler descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetSamplerDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetSamplerDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of a built-in. Where the built-in has a shader-defined array size (ClipDistance,
// CullDistance, SampleMask), inOutInfo.GetArraySize() is used as the array size.
Type* Builder::GetBuiltInTy(
BuiltInKind builtIn, // Built-in kind
InOutInfo inOutInfo) // Extra input/output info (shader-defined array size)
{
enum TypeCode: uint32_t
{
a2f32,
a4f32,
af32,
ai32,
f32,
i1,
i32,
i64,
mask,
v2f32,
v3f32,
v3i32,
v4f32,
v4i32,
a4v3f32
};
uint32_t arraySize = inOutInfo.GetArraySize();
TypeCode typeCode = TypeCode::i32;
switch (builtIn)
{
#define BUILTIN(name, number, out, in, type) \
case BuiltIn ## name: \
typeCode = TypeCode:: type; \
break;
#include "llpcBuilderBuiltIns.h"
#undef BUILTIN
default:
LLPC_NEVER_CALLED();
break;
}
switch (typeCode)
{
case TypeCode::a2f32: return ArrayType::get(getFloatTy(), 2);
case TypeCode::a4f32: return ArrayType::get(getFloatTy(), 4);
// For ClipDistance and CullDistance, the shader determines the array size.
case TypeCode::af32: return ArrayType::get(getFloatTy(), arraySize);
// For SampleMask, the shader determines the array size.
case TypeCode::ai32: return ArrayType::get(getInt32Ty(), arraySize);
case TypeCode::f32: return getFloatTy();
case TypeCode::i1: return getInt1Ty();
case TypeCode::i32: return getInt32Ty();
case TypeCode::i64: return getInt64Ty();
case TypeCode::v2f32: return VectorType::get(getFloatTy(), 2);
case TypeCode::v3f32: return VectorType::get(getFloatTy(), 3);
case TypeCode::v4f32: return VectorType::get(getFloatTy(), 4);
case TypeCode::v3i32: return VectorType::get(getInt32Ty(), 3);
case TypeCode::v4i32: return VectorType::get(getInt32Ty(), 4);
case TypeCode::a4v3f32: return ArrayType::get(VectorType::get(getFloatTy(), 3), 4);
default:
LLPC_NEVER_CALLED();
return nullptr;
}
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type from the given APFloat, converting APFloat semantics where necessary
Constant* Builder::GetFpConstant(
Type* pTy, // [in] FP scalar or vector type
APFloat value) // APFloat value
{
const fltSemantics* pSemantics = &APFloat::IEEEdouble();
Type* pScalarTy = pTy->getScalarType();
if (pScalarTy->isHalfTy())
{
pSemantics = &APFloat::IEEEhalf();
}
else if (pScalarTy->isFloatTy())
{
pSemantics = &APFloat::IEEEsingle();
}
bool ignored = true;
value.convert(*pSemantics, APFloat::rmNearestTiesToEven, &ignored);
return ConstantFP::get(pTy, value);
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value PI/180, for converting radians to degrees.
Constant* Builder::GetPiOver180(
Type* pTy) // [in] FP scalar or vector type
{
// PI/180, 0.017453292
// TODO: Use a value that works for double as well.
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x3F91DF46A0000000)));
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value 180/PI, for converting degrees to radians.
Constant* Builder::Get180OverPi(
Type* pTy) // [in] FP scalar or vector type
{
// 180/PI, 57.29577951308232
// TODO: Use a value that works for double as well.
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x404CA5DC20000000)));
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value 1/(2^n - 1)
Constant* Builder::GetOneOverPower2MinusOne(
Type* pTy, // [in] FP scalar or vector type
uint32_t n) // Power of two to use
{
// We could calculate this here, using knowledge that 1(2^n - 1) in binary has a repeating bit pattern
// of {n-1 zeros, 1 one}. But instead we just special case the values of n that we know are
// used from the frontend.
uint64_t bits = 0;
switch (n) {
case 7: // 1/127
bits = 0x3F80204081020408;
break;
case 8: // 1/255
bits = 0x3F70101010101010;
break;
case 15: // 1/32767
bits = 0x3F00002000400080;
break;
case 16: // 1/65535
bits = 0x3EF0001000100010;
break;
default:
LLPC_NEVER_CALLED();
}
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, bits)));
}
// =====================================================================================================================
// Create a call to the specified intrinsic with one operand, mangled on its type.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateUnaryIntrinsic(
Intrinsic::ID id, // Intrinsic ID
Value* pValue, // [in] Input value
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& instName) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateUnaryIntrinsic(id, pValue, pFmfSource, instName);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
// There are certain intrinsics with an FP result that we do not want FMF on.
switch (id)
{
case Intrinsic::amdgcn_wqm:
case Intrinsic::amdgcn_wwm:
break;
default:
pResult->setFastMathFlags(getFastMathFlags());
break;
}
}
return pResult;
}
// =====================================================================================================================
// Create a call to the specified intrinsic with two operands of the same type, mangled on that type.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateBinaryIntrinsic(
Intrinsic::ID id, // Intrinsic ID
Value* pValue1, // [in] Input value 1
Value* pValue2, // [in] Input value 2
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& name) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateBinaryIntrinsic(id, pValue1, pValue2, pFmfSource, name);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
pResult->setFastMathFlags(getFastMathFlags());
}
return pResult;
}
// =====================================================================================================================
// Create a call to the specified intrinsic with the specified operands, mangled on the specified types.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateIntrinsic(
Intrinsic::ID id, // Intrinsic ID
ArrayRef<Type*> types, // [in] Types
ArrayRef<Value*> args, // [in] Input values
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& name) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateIntrinsic(id, types, args, pFmfSource, name);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
pResult->setFastMathFlags(getFastMathFlags());
}
return pResult;
}
| 40.72956 | 123 | 0.552617 | hustwarhd |
b8820d698f9791ef3cae05f9ed6ee384fa697210 | 4,324 | tcc | C++ | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 6 | 2019-07-01T03:21:02.000Z | 2021-09-13T17:15:01.000Z | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 3 | 2019-07-01T03:53:56.000Z | 2020-06-17T09:14:27.000Z | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 1 | 2019-07-23T12:28:30.000Z | 2019-07-23T12:28:30.000Z | /*
This file is part of the Tweeny library.
Copyright (c) 2016-2018 Leonardo G. Lucena de Freitas
Copyright (c) 2016 Guilherme R. Costa
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.
*/
/*
* This file implements the tweenpoint class
*/
#ifndef TWEENY_TWEENPOINT_TCC
#define TWEENY_TWEENPOINT_TCC
#include <algorithm>
#include <type_traits>
#include "tweenpoint.h"
#include "tweentraits.h"
#include "easing.h"
#include "easingresolve.h"
#include "int2type.h"
namespace tweeny {
namespace detail {
template<typename TypeTupleT, typename EasingCollectionT, typename EasingT, size_t I>
void easingfill(EasingCollectionT &f, EasingT easing, int2type<I>) {
easingresolve<I, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing);
easingfill<TypeTupleT, EasingCollectionT, EasingT>(f, easing, int2type<I - 1>{});
}
template<typename TypeTupleT, typename EasingCollectionT, typename EasingT>
void easingfill(EasingCollectionT &f, EasingT easing, int2type<0>) {
easingresolve<0, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing);
}
template<class ...T>
struct are_same;
template<class A, class B, class ...T>
struct are_same<A, B, T...> {
static const bool value = std::is_same<A, B>::value && are_same<B, T...>::value;
};
template<class A>
struct are_same<A> {
static const bool value = true;
};
template<typename... Ts>
inline tweenpoint<Ts...>::tweenpoint(Ts... vs) : values{vs...} {
during(static_cast<uint16_t>(0));
via(easing::linear);
}
template<typename... Ts>
template<typename D>
inline void tweenpoint<Ts...>::during(D milis) {
for (uint16_t &t : durations) { t = static_cast<uint16_t>(milis); }
}
template<typename... Ts>
template<typename... Ds>
inline void tweenpoint<Ts...>::during(Ds... milis) {
static_assert(sizeof...(Ds) == sizeof...(Ts),
"Amount of durations should be equal to the amount of values in a currentPoint");
std::array<int, sizeof...(Ts)> list = {{milis...}};
std::copy(list.begin(), list.end(), durations.begin());
}
template<typename... Ts>
template<typename... Fs>
inline void tweenpoint<Ts...>::via(Fs... fs) {
static_assert(sizeof...(Fs) == sizeof...(Ts),
"Number of functions passed to via() must be equal the number of values.");
detail::easingresolve<0, std::tuple<Ts...>, typename traits::easingCollection, Fs...>::impl(easings, fs...);
}
template<typename... Ts>
template<typename F>
inline void tweenpoint<Ts...>::via(F f) {
easingfill<typename traits::valuesType>(easings, f, int2type<sizeof...(Ts) - 1>{});
}
template<typename... Ts>
inline uint16_t tweenpoint<Ts...>::duration() const {
return *std::max_element(durations.begin(), durations.end());
}
template<typename... Ts>
inline uint16_t tweenpoint<Ts...>::duration(size_t i) const {
return durations.at(i);
}
}
}
#endif //TWEENY_TWEENPOINT_TCC
| 37.275862 | 120 | 0.641304 | minkcv |
b882ee10eca24255a32735d5f932e10d4224b817 | 9,142 | cpp | C++ | Core/fbp/bp_all.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 1 | 2018-11-09T11:58:32.000Z | 2018-11-09T11:58:32.000Z | Core/fbp/bp_all.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 8 | 2018-05-22T12:58:27.000Z | 2020-10-15T14:54:04.000Z | Core/fbp/bp_all.cpp | vais-ral/CCPi-Reconstruction | 6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd | [
"Apache-2.0"
] | 1 | 2019-01-11T12:04:53.000Z | 2019-01-11T12:04:53.000Z | #include "defs.h"
bool fbp_gpu_20_fs(allData *aD){
unsigned int onx, ony, wo, ho, obnx, obny, nx, ny, wh, wh2, wu, vH;
float sx, sy, ps;
double angleStart, angleStep;
Ipp32f *vux, *vuy, *v;
Ipp64f *v1, *v2, *v3, *v4;
xFBP_gpu *fg;
gpu_info *gi;
xData *xd;
xRoi *xr;
fg = aD->fg;
gi = aD->gi;
xd = aD->data;
xr = aD->hms->fbp->backprojection->roi;
nx = aD->ta_nx;
ny = aD->ta_ny;
wh = gi->ho * gi->wo;
wh2 = wh/2;
wu = ny/wh2;
onx = gi->mxo;
ony = gi->myo;
wo = gi->wo;
ho = gi->ho;
obnx = onx/wo;
obny = ony/ho;
ps = gi->outputPixelSize;
angleStart = pi*double(xr->angle)/180.0;
angleStep = double(gi->rotAngleStep);
v1 = ippsMalloc_64f(ny);
v2 = ippsMalloc_64f(ny);
v3 = ippsMalloc_64f(ny);
v4 = ippsMalloc_64f(2*ny);
xd->vecCS = ippsMalloc_32f(2*ny);
ippsVectorSlope_64f(v1,ny,angleStart,angleStep);
ippsCos_64f_A53(v1,v2,ny);
ippsSin_64f_A53(v1,v3,ny);
ippsRealToCplx_64f(v2, v3, (Ipp64fc *)v4, ny);
ippsConvert_64f32f(v4,xd->vecCS,2*ny);
ippsFree(v1); v1 = NULL;
ippsFree(v2); v2 = NULL;
ippsFree(v3); v3 = NULL;
ippsFree(v4); v4 = NULL;
sx = 0.5f*ps * float(onx - 1);
sy = 0.5f*ps * float(ony - 1);
aD->roiRadius = sqrt(sx*sx+sy*sy);
aD->to_nx = onx;
aD->to_ny = ony;
vux = ippsMalloc_32f(onx);
vuy = ippsMalloc_32f(onx);
if(vux == NULL || vuy == NULL){
printError(aD,"can not allocate memory (fbp, ux, uy)");
return false;
}
xd->vecXY_block = ippsMalloc_32f(2*wo*ho);
xd->vecXY = ippsMalloc_32f(2*onx*ony);
xd->vecRA = ippsMalloc_32f(2*onx*ony);
xd->vecbXY = ippsMalloc_32f(2*obnx*obny);
if(xd->vecXY == NULL || xd->vecbXY == NULL || xd->vecRA == NULL){
printError(aD, "can not allocate memory (FBP, vecXY, vecbXY, vecRA)");
return false;
}
ippsVectorSlope_32f(vux,wo,-0.5f*ps*(wo-1),ps);
for(unsigned int i=0; i<ho; i++){
ippsSet_32f(-0.5f*ps*(ho-1)+float(i)*ps,vuy,wo);
ippsRealToCplx_32f(vux,vuy,(Ipp32fc*)(xd->vecXY_block)+i*wo,wo);
}
ippsVectorSlope_32f(vux,onx,-0.5f*ps*(onx-1),ps);
for(unsigned int i=0; i<ony; i++){
ippsSet_32f(-0.5f*ps*(ony-1)+float(i)*ps,vuy,onx);
ippsRealToCplx_32f(vux,vuy,(Ipp32fc*)(xd->vecXY)+i*onx,onx);
}
ippsCartToPolar_32fc((Ipp32fc *)xd->vecXY, xd->vecRA, xd->vecRA+onx*ony, onx*ony);
v = xd->vecRA+onx*ony;
for(unsigned int i=0; i<onx*ony; i++){
if(v[i]<0.0f) v[i] += (2.0f*pif);
}
ippsMulC_32f_I(float(aD->ta_ny_13-1)/pif,v,onx*ony);
ippsThreshold_LTValGTVal_32f_I(v, onx*ony, 0.0f, 0.0f, float(2*aD->ta_ny_13-2), float(2*aD->ta_ny_13-2));
ippsFree(vux); vux = NULL;
ippsFree(vuy); vuy = NULL;
xd->vecAT = ippsMalloc_32f(onx*ony);
ippsPhase_32fc((Ipp32fc*)xd->vecXY, xd->vecAT, onx*ony);
ippsAddC_32f_I(pif,xd->vecAT,onx*ony);
ippsMulC_32f_I(float(aD->ta_ny_13)/pif,xd->vecAT,onx*ony);
for(unsigned int i=0; i<obny; i++){
for(unsigned int j=0; j<obnx; j++){
xd->vecbXY[2*(i*obnx+j)] = 0.5f * (xd->vecXY[2*(i*ho*onx+j*wo)] + xd->vecXY[2*(((i+1)*ho-1)*onx+(j+1)*wo-1)]);
xd->vecbXY[2*(i*obnx+j)+1] = 0.5f * (xd->vecXY[2*(i*ho*onx+j*wo)+1] + xd->vecXY[2*(((i+1)*ho-1)*onx+(j+1)*wo-1)+1]);
}
}
xd->vto = ippsMalloc_32f(onx*ony);
if(xd->vto == NULL){
printError(aD, "can not allocate memory (output matrix)");
return false;
}
if(!form_filter(aD))return false;
vH = gi->vertH;
xd->veccF = ippsMalloc_32fc(nx*vH);
Ipp32f *vz = ippsMalloc_32f(nx);
ippsZero_32f(vz, nx);
ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx);
for(unsigned int i=1; i<vH; i++){
ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx);
}
ippsFree(vz); vz = NULL;
return true;
}
bool fbp_gpu_fs(allData *aD){
xData *xd;
xFBP_gpu *fg;
gpu_info *gi;
xRoi *xr;
unsigned int onx, ony, wo, ho, ny, nx;
double angleStart, angleStep;
unsigned int ont;
unsigned int ndiam, ndiameter, nleft;
unsigned int vH;
float sx, sy, ps;
double dps, xmin, ymin, yval;
double rat;
Ipp64f *v1, *v2, *v3, *v4;
xd = aD->data;
fg = aD->fg;
gi = aD->gi;
fg->nx = aD->ta_nx;
fg->ny = aD->ta_ny;
fg->nxo = gi->mxo;
fg->nyo = gi->myo;
fg->blockWidth = gi->wo;
fg->blockHeight = gi->ho;
fg->vH = gi->vertH;
nx = aD->ta_nx;
ny = aD->ta_ny;
xr = aD->hms->fbp->backprojection->roi;
ps = gi->outputPixelSize;
angleStart = pi*double(xr->angle)/180.0;
angleStep = double(gi->rotAngleStep);
v1 = ippsMalloc_64f(ny);
v2 = ippsMalloc_64f(ny);
v3 = ippsMalloc_64f(ny);
v4 = ippsMalloc_64f(2*ny);
xd->vecCS = ippsMalloc_32f(2*ny);
ippsVectorSlope_64f(v1,ny,angleStart,angleStep);
ippsCos_64f_A53(v1,v2,ny);
ippsSin_64f_A53(v1,v3,ny);
ippsRealToCplx_64f(v2, v3, (Ipp64fc *)v4, ny);
ippsConvert_64f32f(v4,xd->vecCS,2*ny);
ippsFree(v1); v1 = NULL;
ippsFree(v2); v2 = NULL;
ippsFree(v3); v3 = NULL;
ippsFree(v4); v4 = NULL;
onx = gi->mxo;
ony = gi->myo;
ont = onx*ony;
wo = gi->wo;
ho = gi->ho;
sx = 0.5f*ps * float(onx - 1);
sy = 0.5f*ps * float(ony - 1);
aD->roiRadius = sqrt(sx*sx+sy*sy);
ndiam = __min(nx,(unsigned int)(ceil(2.0f*aD->roiRadius))+2);
int_ratio(ndiam,wo,&ndiameter);
fg->chunkWidth = ndiameter;
nleft = (unsigned int)(floor(aD->new_xc - 0.5f*float(ndiameter) - 1.0f));
if (nleft + fg->chunkWidth > nx){
nleft = nx - fg->chunkWidth;
}
fg->chunkLeft = nleft;
fg->xc = aD->new_xc - float(nleft);
fg->numChunks = fg->ny/fg->vH;
aD->to_nx = onx;
aD->to_ny = ony;
xd->vecX = ippsMalloc_32f(ont);
xd->vecY = ippsMalloc_32f(ont);
dps = double(ps);
xmin = -0.5 * double(onx-1) * dps;
ymin = -0.5 * double(ony-1) * dps;
v1 = ippsMalloc_64f(onx);
v2 = ippsMalloc_64f(onx);
ippsVectorSlope_64f(v1,onx,xmin,dps);
rat = double(aD->ta_ny_13-1)/pi;
for(unsigned int i = 0; i<ony; i++){
yval = ymin + double(i)*dps;
ippsSet_64f(yval,v2,onx);
ippsConvert_64f32f(v1,xd->vecX+i*onx,onx);
ippsConvert_64f32f(v2,xd->vecY+i*onx,onx);
}
ippsFree(v1); v1 = NULL;
ippsFree(v2); v2 = NULL;
xd->vto = ippsMalloc_32f(onx*ony);
if(xd->vto == NULL){
printError(aD, "can not allocate memory (output matrix)");
return false;
}
vH = gi->vertH;
if(!form_filter(aD))return false;
xd->veccF = ippsMalloc_32fc(nx*vH);
Ipp32f *vz = ippsMalloc_32f(nx);
ippsZero_32f(vz, nx);
ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx);
for(unsigned int i=1; i<vH; i++){
ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx);
}
ippsFree(vz); vz = NULL;
return true;
}
bool fbp_gpu_cpu2_fs(allData *aD){
xData *xd;
xFBP_gpu *fg;
gpu_info *gi;
xRoi *xr;
unsigned int onx, ony, wo, ho, ny, nx;
double angleStart, angleStep;
unsigned int ont;
unsigned int ndiam, ndiameter, nleft;
unsigned int vH;
float sx, sy, ps;
double dps, xmin, ymin, yval;
double rat;
Ipp64f *v1, *v2, *v3, *v4;
xd = aD->data;
fg = aD->fg;
gi = aD->gi;
fg->nx = aD->ta_nx;
fg->ny = aD->ta_ny;
fg->nxo = gi->mxo;
fg->nyo = gi->myo;
fg->blockWidth = gi->wo;
fg->blockHeight = gi->ho;
fg->vH = gi->vertH;
nx = aD->ta_nx;
ny = aD->ta_ny;
xr = aD->hms->fbp->backprojection->roi;
ps = gi->outputPixelSize;
unsigned int na, nr, pol_a, pol_r;
wo = gi->wo;
ho = gi->ho;
na = 2*aD->ta_ny_13 -1;
int_ratio(na,wo,&pol_a);
angleStart = pi*double(xr->angle)/180.0;
angleStep = double(gi->rotAngleStep);
v1 = ippsMalloc_64f(ny);
v2 = ippsMalloc_64f(ny);
xd->vecCos = ippsMalloc_32f(aD->ta_ny_13);
ippsVectorSlope_64f(v1,ny,angleStart,angleStep);
ippsCos_64f_A53(v1,v2,aD->ta_ny_13);
ippsConvert_64f32f(v2,xd->vecCos,aD->ta_ny_13);
ippsFree(v1); v1 = NULL;
ippsFree(v2); v2 = NULL;
onx = gi->mxo;
ony = gi->myo;
sx = 0.5f*ps * float(onx - 1);
sy = 0.5f*ps * float(ony - 1);
aD->roiRadius = sqrt(sx*sx+sy*sy);
nr = (unsigned int)(ceil(aD->roiRadius/ps)+1.0f);
int_ratio(nr,ho,&pol_r);
xd->vecPol = ippsMalloc_32f(pol_r*pol_a);
gi->pol_r = pol_r;
gi->pol_a = pol_a;
onx = gi->mxo;
ony = gi->myo;
xd->vto = ippsMalloc_32f(onx*ony);
if(xd->vto == NULL){
printError(aD, "can not allocate memory (output matrix)");
return false;
}
vH = gi->vertH;
if(!form_filter(aD))return false;
xd->veccF = ippsMalloc_32fc(nx*vH);
Ipp32f *vz = ippsMalloc_32f(nx);
ippsZero_32f(vz, nx);
ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx);
for(unsigned int i=1; i<vH; i++){
ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx);
}
ippsFree(vz); vz = NULL;
return true;
}
bool fbp_gpu(allData *aD){
printTagStart(aD,"FilteredBackprojectionGPU");
#ifdef _ALGORITHM2
if(aD->isFirstSlice){
if(!fbp_gpu_20_fs(aD))return false;
}
if(!fbp_cuda_20(aD))return false;
#elif _ALGORITHM_CPU_2
if(aD->isFirstSlice){
if(!fbp_gpu_cpu2_fs(aD))return false;
}
if(!fbp_cuda_cpu2(aD))return false;
#else
if(aD->isFirstSlice){
if(!fbp_gpu_fs(aD))return false;
}
if(!fbp_cuda(aD))return false;
#endif
printTagEnd(aD);
return true;
}
| 22.352078 | 120 | 0.607963 | vais-ral |
b88562691a6bf5d67067985a8f47ede759226625 | 3,316 | cc | C++ | cpp/src/pegasus/parquet/parquet_reader_test.cc | jerrychenhf/pegasus | be7b75c86649836589009a7469e2cf249caab5a1 | [
"Apache-2.0"
] | 3 | 2020-11-02T02:32:21.000Z | 2022-01-01T08:02:32.000Z | cpp/src/pegasus/parquet/parquet_reader_test.cc | jerrychenhf/pegasus | be7b75c86649836589009a7469e2cf249caab5a1 | [
"Apache-2.0"
] | null | null | null | cpp/src/pegasus/parquet/parquet_reader_test.cc | jerrychenhf/pegasus | be7b75c86649836589009a7469e2cf249caab5a1 | [
"Apache-2.0"
] | 2 | 2021-12-31T08:37:13.000Z | 2021-12-31T11:05:47.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <gtest/gtest.h>
#include "arrow/util/uri.h"
#include "parquet/parquet_reader.h"
#include "storage/storage.h"
#include "storage/storage_factory.h"
#include "test/gtest-util.h"
namespace pegasus {
TEST(ParquetReaderTest, Unit) {
std::string partition_path =
"hdfs://10.239.47.55:9000/genData1000/customer/part-00005-f6fb1ced-d4d4-4dac-a584-02e398d988b4-c000.snappy.parquet";
std::shared_ptr<StorageFactory> worker_storage_factory(
new StorageFactory());
std::shared_ptr<Storage> worker_storage;
ASSERT_OK(worker_storage_factory->GetStorage(partition_path, &worker_storage));
ASSERT_NE(nullptr, worker_storage);
ASSERT_EQ(Storage::HDFS, worker_storage->GetStorageType());
std::shared_ptr<HdfsReadableFile> file;
ASSERT_OK(std::dynamic_pointer_cast<HDFSStorage>(worker_storage)
->GetReadableFile(partition_path, &file));
parquet::ArrowReaderProperties properties = parquet::default_arrow_reader_properties();
// static parquet::ArrowReaderProperties properties;
arrow::MemoryPool *pool = arrow::default_memory_pool();
std::unique_ptr<ParquetReader> parquet_reader(new ParquetReader(file, pool, properties));
std::shared_ptr<arrow::Schema> schema;
ASSERT_OK(parquet_reader->GetSchema(&schema));
ASSERT_EQ(18, schema->num_fields());
std::shared_ptr<arrow::Table> table1;
ASSERT_OK(parquet_reader->ReadParquetTable(&table1));
ASSERT_NE(nullptr, table1);
ASSERT_EQ(18, table1->num_columns());
// ASSERT_EQ(144000, table1->num_rows());
std::shared_ptr<arrow::Table> table2;
std::vector<int> column_indices;
column_indices.push_back(0);
ASSERT_OK(parquet_reader->ReadParquetTable(column_indices, &table2));
ASSERT_NE(nullptr, table2);
ASSERT_EQ(1, table2->num_columns());
// ASSERT_EQ(144000, table2->num_rows());
std::shared_ptr<arrow::ChunkedArray> chunked_out1;
ASSERT_OK(parquet_reader->ReadColumnChunk(0, 0, &chunked_out1));
// ASSERT_EQ(144000, chunked_out1->length());
// ASSERT_EQ(1, chunked_out1->num_chunks());
std::shared_ptr<arrow::ChunkedArray> chunked_out2;
ASSERT_OK(parquet_reader->ReadColumnChunk(0, &chunked_out2, 2));
ASSERT_EQ(2, chunked_out2->length());
ASSERT_EQ(1, chunked_out2->num_chunks());
std::shared_ptr<arrow::ChunkedArray> chunked_out3;
ASSERT_OK(parquet_reader->ReadColumnChunk(0, &chunked_out3));
// ASSERT_EQ(144000, chunked_out3->length());
// ASSERT_EQ(1, chunked_out3->num_chunks());
}
}
PEGASUS_TEST_MAIN(); | 38.114943 | 122 | 0.75573 | jerrychenhf |
b888b9126c171245de259d7cefe90c151647eead | 4,532 | cpp | C++ | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 8 | 2019-06-18T14:38:56.000Z | 2020-09-14T07:23:08.000Z | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 1 | 2019-06-26T09:10:21.000Z | 2019-06-26T09:10:21.000Z | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 3 | 2019-06-27T00:49:48.000Z | 2020-04-17T02:21:50.000Z | //
// Created by ZL on 2019-06-13.
//
#include "zqcnn_mtcnn_nchwc4.h"
#include <android/log.h>
#include <jni.h>
#include <string>
#include <vector>
#include <imgproc/types_c.h>
#define TAG "ZQCNN"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
using namespace std;
using namespace cv;
using namespace ZQ;
static MTCNNNCHWC *mtcnnnchwc;
extern "C" {
JNIEXPORT jboolean JNICALL
Java_com_zl_demo_MTCNNNCHWC_initModelPath(JNIEnv *env, jobject instance, jstring modelPath_) {
if (NULL == modelPath_) {
return false;
}
//获取MTCNN模型的绝对路径的目录(不是/aaa/bbb.bin这样的路径,是/aaa/)
const char *modelPath = env->GetStringUTFChars(modelPath_, 0);
if (NULL == modelPath) {
return false;
}
string tFaceModelDir = modelPath;
string tLastChar = tFaceModelDir.substr(tFaceModelDir.length() - 1, 1);
//目录补齐/
if ("\\" == tLastChar) {
tFaceModelDir = tFaceModelDir.substr(0, tFaceModelDir.length() - 1) + "/";
} else if (tLastChar != "/") {
tFaceModelDir += "/";
}
LOGD("init, tFaceModelDir=%s", tFaceModelDir.c_str());
mtcnnnchwc = new MTCNNNCHWC(tFaceModelDir);
return true;
}
JNIEXPORT jfloatArray JNICALL
Java_com_zl_demo_MTCNNNCHWC_detectFace(JNIEnv *env, jobject instance, jstring imgPath_) {
const char *imgPath = env->GetStringUTFChars(imgPath_, 0);
vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detect(imgPath);
int32_t num_face = static_cast<int32_t>(faceInfo.size());
LOGD("检测到的人脸数目:%d\n", num_face);
int out_size = 1 + num_face * 29;
float *faces = new float[out_size];
faces[0] = num_face;
for (int i = 0; i < num_face; i++) {
float score = faceInfo[i].score;
int row1 = faceInfo[i].row1;
int col1 = faceInfo[i].col1;
int row2 = faceInfo[i].row2;
int col2 = faceInfo[i].col2;
LOGD("faceInfo:score=%.3f;row1=%d,col1=%d,row2=%d,col2=%d\n", score, row1, col1, row2,
col2);
}
jfloatArray tFaces = env->NewFloatArray(out_size);
env->SetFloatArrayRegion(tFaces, 0, out_size, faces);
return tFaces;
}
JNIEXPORT jobjectArray JNICALL
Java_com_zl_demo_MTCNNNCHWC_detect(JNIEnv *env, jobject instance, jbyteArray yuv, jint width,
jint height) {
jobjectArray faceArgs = nullptr;
jbyte *pBuf = (jbyte *) env->GetByteArrayElements(yuv, 0);
Mat image(height + height / 2, width, CV_8UC1, (unsigned char *) pBuf);
Mat mBgr;
cvtColor(image, mBgr, CV_YUV2BGR_NV21);
vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detectMat(mBgr);
int32_t num_face = static_cast<int32_t>(faceInfo.size());
/**
* 获取Face类以及其对于参数的签名
*/
jclass faceClass = env->FindClass("com/zl/demo/FaceInfo");//获取Face类
jmethodID faceClassInitID = (env)->GetMethodID(faceClass, "<init>", "()V");
jfieldID faceScore = env->GetFieldID(faceClass, "score",
"F");//获取int类型参数confidence
jfieldID faceRect = env->GetFieldID(faceClass, "faceRect",
"Landroid/graphics/Rect;");//获取faceRect的签名
/**
* 获取RECT类以及对应参数的签名
*/
jclass rectClass = env->FindClass("android/graphics/Rect");//获取到RECT类
jmethodID rectClassInitID = (env)->GetMethodID(rectClass, "<init>", "()V");
jfieldID rect_left = env->GetFieldID(rectClass, "left", "I");//获取x的签名
jfieldID rect_top = env->GetFieldID(rectClass, "top", "I");//获取y的签名
jfieldID rect_right = env->GetFieldID(rectClass, "right", "I");//获取width的签名
jfieldID rect_bottom = env->GetFieldID(rectClass, "bottom", "I");//获取height的签名
faceArgs = (env)->NewObjectArray(num_face, faceClass, 0);
LOGD("检测到的人脸数目:%d\n", num_face);
for (int i = 0; i < num_face; i++) {
float score = faceInfo[i].score;
int row1 = faceInfo[i].row1;
int col1 = faceInfo[i].col1;
int row2 = faceInfo[i].row2;
int col2 = faceInfo[i].col2;
jobject newFace = (env)->NewObject(faceClass, faceClassInitID);
jobject newRect = (env)->NewObject(rectClass, rectClassInitID);
(env)->SetIntField(newRect, rect_left, row1);
(env)->SetIntField(newRect, rect_top, col1);
(env)->SetIntField(newRect, rect_right, row2);
(env)->SetIntField(newRect, rect_bottom, col2);
(env)->SetObjectField(newFace, faceRect, newRect);
(env)->SetFloatField(newFace, faceScore, score);
(env)->SetObjectArrayElement(faceArgs, i, newFace);
}
free(pBuf);
return faceArgs;
}
} | 36.845528 | 94 | 0.644748 | zhu260824 |
b88c66d7cf69b1a9011829927330aa1b86ce3c8a | 1,980 | cpp | C++ | UVa 11620 - City of Egocentrics/sample/11620 - City of Egocentrics.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 11620 - City of Egocentrics/sample/11620 - City of Egocentrics.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 11620 - City of Egocentrics/sample/11620 - City of Egocentrics.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <algorithm>
using namespace std;
const int MAXN = 128;
int A[MAXN][MAXN], B[MAXN][MAXN], n;
int mark[MAXN][MAXN];
void print(char c) {
printf("%c\n", c);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
if (mark[i][j])
printf("%d %d\n", i, j);
}
}
void solve() {
for (int i = 0; i < n; i++) {
int sum = 0, l, r;
for (int j = 0; j < n; j++)
sum += A[i][j];
l = 0, r = sum;
for (int j = 0; j < n; j++) {
r -= A[i][j];
mark[i][j] = (l == r);
l += A[i][j];
}
}
print('H');
for (int i = 0; i < n; i++) {
int sum = 0, l, r;
for (int j = 0; j < n; j++)
sum += A[j][i];
l = 0, r = sum;
for (int j = 0; j < n; j++) {
r -= A[j][i];
mark[j][i] = (l == r);
l += A[j][i];
}
}
print('V');
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i-1 >= 0 && j-1 >= 0)
B[i][j] = B[i-1][j-1] + A[i][j];
else
B[i][j] = A[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int l = 0, r = 0;
if (i-1 >= 0 && j-1 >= 0)
l = B[i-1][j-1];
int ex, ey;
ex = i + min(n-1-i, n-1-j), ey = j + min(n-1-i, n-1-j);
r = B[ex][ey] - l - A[i][j];
mark[i][j] = (l == r);
}
}
print('D');
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i-1 >= 0 && j+1 < n)
B[i][j] = B[i-1][j+1] + A[i][j];
else
B[i][j] = A[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int l = 0, r = 0;
if (i-1 >= 0 && j+1 < n)
l = B[i-1][j+1];
int ex, ey;
ex = i + min(n-1-i, j), ey = j - min(n-1-i, j);
r = B[ex][ey] - l - A[i][j];
mark[i][j] = (l == r);
}
}
print('A');
}
int main() {
int testcase;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d", &n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &A[i][j]);
solve();
}
return 0;
}
/*
3
3
1 2 3
4 5 6
7 8 9
3
1 1 1
1 1 1
1 1 1
4
5 7 7 6
2 4 0 8
6 1 0 7
6 8 7 5
*/
| 17.068966 | 58 | 0.378788 | tadvi |
b88d01986d5ec067a1ae8b6d269fd6015928f63b | 481 | cpp | C++ | src/Functions/ilike.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 8,629 | 2016-06-14T21:03:01.000Z | 2019-09-23T07:46:38.000Z | src/Functions/ilike.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 4,335 | 2016-06-15T12:58:31.000Z | 2019-09-23T11:18:43.000Z | src/Functions/ilike.cpp | zzachimed/ClickHouse | a403f1cd1b2655a60ca196d209ef443ef6d91b39 | [
"Apache-2.0"
] | 1,700 | 2016-06-15T09:25:11.000Z | 2019-09-23T11:16:38.000Z | #include "FunctionsStringSearch.h"
#include "FunctionFactory.h"
#include "MatchImpl.h"
namespace DB
{
namespace
{
struct NameILike
{
static constexpr auto name = "ilike";
};
using ILikeImpl = MatchImpl<NameILike, MatchTraits::Syntax::Like, MatchTraits::Case::Insensitive, MatchTraits::Result::DontNegate>;
using FunctionILike = FunctionsStringSearch<ILikeImpl>;
}
void registerFunctionILike(FunctionFactory & factory)
{
factory.registerFunction<FunctionILike>();
}
}
| 18.5 | 131 | 0.767152 | zzachimed |
b8912f7577b1ff9fb94ab1de217144dd547167b8 | 2,449 | cpp | C++ | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | null | null | null | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | 1 | 2017-01-26T04:11:23.000Z | 2017-02-03T01:14:41.000Z | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | null | null | null | // 00000011111111112222222222333333333344444444445555555555666666666677777777778
// 45678901234567890123456789012345678901234567890123456789012345678901234567890
//
// File Name : addStrings.cpp
// File Type : Source code
// Purpose : Main program (Adding two strings).
//
// Date : 2017-02-23
// Version : 1.0.0
// Copyrights : FRCC
//
// Author : Mohammad Huwaidi
// E-Mail : Mohammad.Huwaidi@frontrange.edu
// Style : http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
// Document : http://www.stack.nl/~dimitri/doxygen/index.html
//
// 00000011111111112222222222333333333344444444445555555555666666666677777777778
// 45678901234567890123456789012345678901234567890123456789012345678901234567890
//
//
// Define the PAUSE depending on the operating system:
// Do not worry about this code until where HERE is written
#if defined(_WIN32) || defined(WIN32) // Windows machine
#include <windows.h>
#define PAUSE "pause" // The pause command for DOS window.
#else // Unix-based machines
// Following is the pause command for the BASH script that runs on UNIX:
#define PAUSE "read -p 'Press [Enter] key to continue ...'"
#endif
// HERE
// C++ include files:
#include <iostream> // I/O manipulation; e.g., cout.
#include <string> // String types and operations.
using namespace std;
// 0000001111111111222222222233333333334444444444555555555566666666667777777777
// 4567890123456789012345678901234567890123456789012345678901234567890123456789
//
// The main function that is invoked by the operating system.
//
int main(int argc, char * argv[])
{
// Define some variables. It is a good idea to make them constants if they
// will not be modified later in the program.
string fname;
string lname;
cout << "What is your first name?" << endl;
cin >> fname;
cout << "Now your last name." << endl;
cin >> lname;
const string first_name = fname; // Define and initialize the 1st name.
const string last_name = lname; // Define and initialize the last name.
const string full_name = first_name + string(" ") + last_name; // Combine the two names
cout << "Your name is " << first_name + last_name << endl;
cout << "Full name is " << full_name << endl;
//system(PAUSE); // Pause for the user so the window doesn't disappear.
return 0; // Since nothing went wrong, go back to the OS normally.
}
| 38.265625 | 92 | 0.705186 | DaveKerk |
b892545b8861da99b61befca57cb6746ced83e6c | 648 | cpp | C++ | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "isBalanced.hpp"
namespace BT = BinaryTreeUnique;
TEST_CASE("isBalanced test", "[isBalanced]") {
auto tree = BT::create("[]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,2]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,null,2]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,2,3]");
REQUIRE(isBalanced(tree) == false);
tree = BT::create("[1,2,3,null,null,4]");
REQUIRE(isBalanced(tree) == false);
tree = BT::create("[1,2,3,null,null,null,4]");
REQUIRE(isBalanced(tree) == true);
}
| 23.142857 | 48 | 0.617284 | longztian |
b89400e94f3467a599d91ccfb19b79fe41f67548 | 2,901 | hpp | C++ | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | #ifndef ENGINE_HPP
#define ENGINE_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include "Command.hpp"
#include "Argument.hpp"
namespace gtp {
/**
* Defines a function that may be registered to the GTP Engine.
* When an engine recives the corresponding Command, the registered
* function will be called. This function should return the string
* representing the result of the function, it will then be output by the
* Engine (including any additional data needed by the controller).
*/
typedef std::string (*ProcCmd)(const ARG_LIST&);
/**
* An engine for the Go Text Protocol.
* An instance of this class may be used to communicate between
* with the go server that maintains the current game.
*/
class Engine {
public:
/**
* Constructs an Engine by registering the default implementation
* for each supported command.
*/
Engine();
/**
* Main game loop for the engine.
* This will read and execute commands from the given input stream
* until either an EOF is sent or the 'quit' command is given.
* \param is Input stream to read commands from.
*/
void play(std::istream &is);
/**
* Read and execute a single command from the input stream.
* \param is Input stream to read a command from.
*/
void proc_command(std::istream &is);
/**
* Registers the input proc to the given command.
* Whenever that command is received from the controller,
* the proc function will be executed with the arguments
* as supplied by the controller.
* If a proccess is already registered to the input Command,
* that process will be overridden.
* \param cmd Command to register the input proc to.
* \param proc The process to execute on receiving the given command.
*/
void register_proc(Command cmd, const ProcCmd &proc);
private:
std::map<Command,ProcCmd> commands;
/**
* Parse all arguments from the input line, given the type of argument that will be parsed.
* \param cmd Type of command to parse arguments for.
* \param iss Input string stream of the line being parsed.
* \return Array of pointers to argument objects.
*/
ARG_LIST args_for_cmd(const Command &cmd, std::istringstream &iss);
/**
* Performs preprocessing on a line of text.
* The following operation are performed in accordance with the GTP specification.
* 1. Remove all occurences of CR and other control characters except for HT and LF.
* 2. For each line with a hash sign (#), remove all text following and including this characeter.
* 3. Convert all occurences of HT to SPACE.
* 4. Discard any empty or white-space only lines.
* \param line to the line to be processed.
* \return Processed version of the input string.
*/
std::string preproc_line(const std::string &line);
/**
* \param The line in question.
* \return Should this line be ignored?
*/
bool ignore_line(const std::string &line);
};
}
#endif
| 30.536842 | 99 | 0.722509 | imalerich |
b895c774ee235f0a32ab770b51cc581514e2e94f | 4,524 | cpp | C++ | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | //#include "Triangle.hpp"
//#include "rasterizer.hpp"
//#include <eigen3/Eigen/Eigen>
//#include <iostream>
//#include <opencv2/opencv.hpp>
///*
//constexpr double MY_PI = 3.1415926;
//
//Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
//{
// Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
//
// Eigen::Matrix4f translate;
// translate << 1, 0, 0, -eye_pos[0],
// 0, 1, 0, -eye_pos[1],
// 0, 0, 1, -eye_pos[2],
// 0, 0, 0, 1;
//
// view = translate * view;
//
// return view;
//}
//
//Eigen::Matrix4f get_model_matrix(float rotation_angle)
//{
// Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
//
// // TODO: Implement this function
// // Create the model matrix for rotating the triangle around the Z axis.
// // Then return it.
// double theta = rotation_angle / 180.0 * MY_PI;
//
// model << std::cos(theta), std::sin(theta), 0, 0,
// -std::sin(theta), std::cos(theta), 0, 0,
// 0, 0, 1, 0,
// 0, 0, 0, 1;
//
// return model;
//}
//
//Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
// float zNear, float zFar)
//{
// // Students will implement this function
//
// Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
//
// // TODO: Implement this function
// // Create the projection matrix for the given parameters.
// // Then return it.
//
// // Transformation matrix of perspective projection to orthographic projection
// Eigen::Matrix4f PerspToOrth;
// PerspToOrth << zNear, 0, 0, 0,
// 0, zNear, 0, 0,
// 0, 0, zNear + zFar, -zNear * zFar,
// 0, 0, 0, 1;
//
// // Tan(fov/2) = height/2, aspect = weight / height
// float Height = std::atan(eye_fov / 2 / 180 * MY_PI) * 2;
// float Width = aspect_ratio * Height;
//
// Eigen::Matrix4f ViewPort;
// ViewPort << Width / 2, 0, 0, Width / 2,
// 0, Height / 2, 0, Height / 2,
// 0, 0, 1, 0,
// 0, 0, 0, 1;
//
// projection = ViewPort * PerspToOrth;
//
// return projection;
//}
//
//Eigen::Matrix4f get_rotation(Vector3f axis, float angle)
//{
// // https://www.bilibili.com/read/cv11925407
// Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
// angle = angle / 180.f * MY_PI;
// axis.normalize();
// /*
// float = square = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
// axis[0] /= std::sqrt(square);
// axis[1] /= std::sqrt(square);
// axis[2] /= std::sqrt(square);
//
// Eigen::Matrix3f k;
// k << 0.f, -axis[2], axis[1],
// axis[2], 0.f, -axis[0],
// -axis[1], axis[0], 0.f;
// Eigen::Matrix3f E = Eigen::Matrix3f::Identity();
// Eigen::Matrix3f rotation_matrix;
// rotation_matrix = E * std::cos(angle) + std::sin(angle) * k + (1 - std::cos(angle)) * axis * axis.transpose();
//
// model.block<3, 3>(0, 0) = rotation_matrix;
// return model;
//
//}
//
//
//int main(int argc, const char** argv)
//{
// float angle = 45.0f;
// Eigen::Vector3f axis(0, 0, 1);
// bool command_line = false;
// std::string filename = "output.png";
//
// if (argc >= 3) {
// command_line = true;
// angle = std::stof(argv[2]); // -r by default
// if (argc == 4) {
// filename = std::string(argv[3]);
// }
// }
//
// rst::rasterizer r(700, 700);
//
// Eigen::Vector3f eye_pos = { 0, 0, 5 };
//
// std::vector<Eigen::Vector3f> pos{ {2, 0, -2}, {0, 2, -2}, {-2, 0, -2} };
//
// std::vector<Eigen::Vector3i> ind{ {0, 1, 2} };
//
// auto pos_id = r.load_positions(pos);
// auto ind_id = r.load_indices(ind);
//
// int key = 0;
// int frame_count = 0;
//
// if (command_line) {
// r.clear(rst::Buffers::Color | rst::Buffers::Depth);
//
// r.set_model(get_model_matrix(angle));
// r.set_view(get_view_matrix(eye_pos));
// r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
//
// r.draw(pos_id, ind_id, rst::Primitive::Triangle);
// cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
// image.convertTo(image, CV_8UC3, 1.0f);
//
// cv::imwrite(filename, image);
//
// return 0;
// }
//
// while (key != 27) {
// r.clear(rst::Buffers::Color | rst::Buffers::Depth);
//
// //r.set_model(get_rotation(axis, angle));
//
// r.set_model(get_model_matrix(angle));
// r.set_view(get_view_matrix(eye_pos));
// r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
//
// r.draw(pos_id, ind_id, rst::Primitive::Triangle);
//
// cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
// image.convertTo(image, CV_8UC3, 1.0f);
// cv::imshow("image", image);
// key = cv::waitKey(10);
//
// std::cout << "frame count: " << frame_count++ << '\n';
//
// if (key == 'a') {
// angle += 10;
// }
// else if (key == 'd') {
// angle -= 10;
// }
// }
//
// return 0;
//}
//*/
| 26 | 113 | 0.596596 | xiliangjianke |
b897659ed171f916cfb637567e47fb13868eff3c | 2,040 | cpp | C++ | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | #include "SpriteBatch.h"
namespace prb {
void SpriteBatch::init() {
vao = { { { {}, 4 } } }; //this probably leaks memory if you reinitialize the spritebatch
sh = { "assets/shaders/spritebatch.vert", "assets/shaders/spritebatch.frag" };
}
SpriteBatch::SpriteBatch() {}
SpriteBatch::SpriteBatch(Sprite const& atlas) : atlas(atlas) { init(); }
void SpriteBatch::draw(Sprite const& s, vec2 const& txmin, vec2 const& txmax, mat3 const& transform) {
if (s.tex.texID != atlas.tex.texID) flushAndClear();
vec2 v0 = transform * vec2(-1.f, -1.f);
vec2 v1 = transform * vec2(-1.f, 1.f);
vec2 v2 = transform * vec2(1.f, 1.f);
vec2 v3 = transform * vec2(1.f, -1.f);
if (data.size() < curFloat + 3 * 2 * 4) data.resize(curFloat + 3 * 2 * 4);
data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y;
data[curFloat++] = v1.x; data[curFloat++] = v1.y; data[curFloat++] = txmin.x; data[curFloat++] = txmax.y;
data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y;
data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y;
data[curFloat++] = v3.x; data[curFloat++] = v3.y; data[curFloat++] = txmax.x; data[curFloat++] = txmin.y;
data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y;
}
void SpriteBatch::draw(Sprite const& s, Sprite::AnimationPlayer const& sa, mat3 const& transform) { vec2 offset = s.getOffset(sa) / s.tex.size; draw(s, offset, offset + s.size / s.tex.size, transform); }
void SpriteBatch::draw(Sprite const& s, mat3 const& transform) { draw(s, 0.f, 1.f, transform); }
void SpriteBatch::flush() {
vao.vbos[0].setData(data, curFloat);
sh.use();
sh.setUniform("transform", transform);
sh.setUniform("tex", 0);
util::bindTexture(0, atlas.tex.texID);
vao.draw();
sh.release();
}
void SpriteBatch::clear() { curFloat = 0; }
void SpriteBatch::flushAndClear() { flush(); clear(); }
}
| 43.404255 | 204 | 0.640686 | AlessandroParrotta |
b897bc9be34af804432b95d2f473110d244472a5 | 11,701 | cpp | C++ | test/virtual_float.cpp | johnmcfarlane/dsp | a62d7acc69a96b5cf770ea74b03034798cd4577f | [
"BSL-1.0"
] | null | null | null | test/virtual_float.cpp | johnmcfarlane/dsp | a62d7acc69a96b5cf770ea74b03034798cd4577f | [
"BSL-1.0"
] | null | null | null | test/virtual_float.cpp | johnmcfarlane/dsp | a62d7acc69a96b5cf770ea74b03034798cd4577f | [
"BSL-1.0"
] | 1 | 2018-04-30T07:45:20.000Z | 2018-04-30T07:45:20.000Z | // Copyright Heikki Berg 2017 - 2018
// 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 <random>
#include <gtest/gtest.h>
#include <dsp/complex.h>
#include <dsp/dsp_types.h>
#include <dsp/virtual_float.h>
TEST(virtual_float, creation)
{
{
cnl::dsp::virtual_float<float> val{1.0f};
float val_float = static_cast<float>(val);
EXPECT_EQ(val_float, 1.0f);
}
{
cnl::dsp::virtual_float<float> val{7.0f};
float val_float = static_cast<float>(val);
EXPECT_EQ(val_float, 7.0f);
}
{
q4_20 val{2.0f};
cnl::dsp::virtual_float<q4_20> valvf{val};
EXPECT_EQ(static_cast<float>(valvf), 2.0f);
EXPECT_EQ(static_cast<float>(valvf.mantissa()), 2.0f);
EXPECT_EQ(valvf.exponent(), 0);
}
{
q4_20 val{7.0f};
cnl::dsp::virtual_float<q4_20> valvf{val};
EXPECT_EQ(static_cast<float>(valvf), 7.0f);
EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.5f);
EXPECT_EQ(valvf.exponent(), 1);
}
{
q8_40 val{7.0f};
cnl::dsp::virtual_float<q8_40> valvf{val};
EXPECT_EQ(static_cast<float>(valvf), 7.0f);
EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.5f);
EXPECT_EQ(valvf.exponent(), 1);
}
{
cnl::dsp::virtual_float<q4_20> val{3.0f};
cnl::dsp::virtual_float<q4_20> valvf{val};
EXPECT_EQ(static_cast<float>(valvf), 3.0f);
EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.0f);
EXPECT_EQ(valvf.exponent(), 0);
}
{
cnl::dsp::virtual_float<q4_20> val{3.0f};
cnl::dsp::virtual_float<q4_20> valvf{std::move(val)};
EXPECT_EQ(static_cast<float>(valvf), 3.0f);
EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.0f);
EXPECT_EQ(valvf.exponent(), 0);
}
}
TEST(virtual_float, sum)
{
{
cnl::dsp::virtual_float<float> f1(1.0f);
cnl::dsp::virtual_float<float> f2(2.0f);
cnl::dsp::virtual_float<float> f = f1 + f2;
EXPECT_EQ(static_cast<float>(f), 3.0f);
}
{
cnl::dsp::virtual_float<q4_20> f1{1.0f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 + f2;
EXPECT_EQ(static_cast<float>(f1), 1.0f);
EXPECT_EQ(static_cast<float>(f2), 2.0f);
EXPECT_EQ(static_cast<float>(f), 3.0f);
}
{
cnl::dsp::virtual_float<q8_40> f1{1.0f};
cnl::dsp::virtual_float<q8_40> f2{2.0f};
cnl::dsp::virtual_float<q8_40> f = f1 + f2;
EXPECT_EQ(static_cast<float>(f1), 1.0f);
EXPECT_EQ(static_cast<float>(f2), 2.0f);
EXPECT_EQ(static_cast<float>(f), 3.0f);
}
}
TEST(virtual_float, subtract)
{
{
cnl::dsp::virtual_float<float> f1(1.0f);
cnl::dsp::virtual_float<float> f2(2.0f);
cnl::dsp::virtual_float<float> f = f1 - f2;
EXPECT_EQ(static_cast<float>(f), -1.0f);
}
{
cnl::dsp::virtual_float<q4_20> f1{1.0f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 - f2;
EXPECT_EQ(static_cast<float>(f), -1.0f);
}
{
cnl::dsp::virtual_float<q8_40> f1{1.0f};
cnl::dsp::virtual_float<q8_40> f2{2.0f};
cnl::dsp::virtual_float<q8_40> f = f1 - f2;
EXPECT_EQ(static_cast<float>(f), -1.0f);
}
}
TEST(virtual_float, negate)
{
{
cnl::dsp::virtual_float<q4_20> f1{1.0f};
cnl::dsp::virtual_float<q4_20> f = -f1;
EXPECT_EQ(static_cast<float>(f), -1.0f);
}
{
cnl::dsp::virtual_float<q8_40> f1{1.0f};
cnl::dsp::virtual_float<q8_40> f = -f1;
EXPECT_EQ(static_cast<float>(f), -1.0f);
}
}
TEST(virtual_float, multiply)
{
{
cnl::dsp::virtual_float<q4_20> f1{1.0f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 * f2;
EXPECT_EQ(static_cast<float>(f), 2.0f);
}
{
cnl::dsp::virtual_float<q4_20> f1{0.125f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 * f2;
EXPECT_EQ(static_cast<float>(f), 0.250f);
}
{
cnl::dsp::virtual_float<q4_20> f1{0.34561825f};
cnl::dsp::virtual_float<q4_20> f2{1.5678196f};
cnl::dsp::virtual_float<q4_20> f = f1 * f2;
EXPECT_FLOAT_EQ(static_cast<float>(f), 0.54186706f);
}
{
cnl::dsp::virtual_float<q8_40> f1{1.0f};
cnl::dsp::virtual_float<q8_40> f2{2.0f};
cnl::dsp::virtual_float<q8_40> f = f1 * f2;
EXPECT_EQ(static_cast<float>(f), 2.0f);
}
{
cnl::dsp::virtual_float<q8_40> f1{0.34561825f};
cnl::dsp::virtual_float<q8_40> f2{1.5678196f};
cnl::dsp::virtual_float<q8_40> f = f1 * f2;
EXPECT_FLOAT_EQ(static_cast<float>(f), 0.54186706f);
}
}
TEST(virtual_float, division)
{
{
cnl::dsp::virtual_float<q4_20> f1{1.0f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 / f2;
EXPECT_EQ(static_cast<float>(f), 0.5f);
}
{
cnl::dsp::virtual_float<q4_20> f1{0.125f};
cnl::dsp::virtual_float<q4_20> f2{2.0f};
cnl::dsp::virtual_float<q4_20> f = f1 / f2;
EXPECT_EQ(static_cast<float>(f), 0.0625f);
}
{
cnl::dsp::virtual_float<q4_20> f1{0.34561825f};
cnl::dsp::virtual_float<q4_20> f2{1.5678196f};
cnl::dsp::virtual_float<q4_20> f = f1 / f2;
EXPECT_FLOAT_EQ(static_cast<float>(f), 0.22044516f);
}
{
cnl::dsp::virtual_float<q8_40> f1{0.34561825f};
cnl::dsp::virtual_float<q8_40> f2{1.5678196f};
cnl::dsp::virtual_float<q8_40> f = f1 / f2;
EXPECT_FLOAT_EQ(static_cast<float>(f), 0.22044516f);
}
}
TEST(virtual_float, assignment)
{
{
cnl::dsp::virtual_float<float> e = 2.0f;
EXPECT_EQ(static_cast<float>(e), 2.0f);
}
{
cnl::dsp::virtual_float<q4_20> e = q4_20{3.0f};
EXPECT_EQ(static_cast<float>(e), 3.0f);
}
{
cnl::dsp::virtual_float<q4_20> f = q4_20{3.0f};
cnl::dsp::virtual_float<q8_40> e = f;
EXPECT_EQ(static_cast<float>(e), 3.0f);
}
{
cnl::dsp::virtual_float<q8_40> f = q8_40{3.0f};
cnl::dsp::virtual_float<q4_20> e = f;
EXPECT_EQ(static_cast<float>(e), 3.0f);
}
}
TEST(virtual_float, comparison)
{
{
cnl::dsp::virtual_float<float> a{1.0f};
cnl::dsp::virtual_float<float> b{0.0f};
EXPECT_TRUE(a > b);
EXPECT_TRUE(a >= b);
EXPECT_FALSE(b > a);
EXPECT_FALSE(b >= a);
EXPECT_TRUE(b < a);
EXPECT_TRUE(b <= a);
EXPECT_FALSE(a < b);
EXPECT_FALSE(a <= b);
EXPECT_FALSE(a < a);
EXPECT_FALSE(a > a);
EXPECT_TRUE(a >= a);
EXPECT_TRUE(a <= a);
EXPECT_TRUE(a == a);
EXPECT_FALSE(a != a);
EXPECT_TRUE(a != b);
EXPECT_TRUE(b != a);
}
{
cnl::dsp::virtual_float<q4_20> a{2.0f};
cnl::dsp::virtual_float<q4_20> b{1.0f};
EXPECT_TRUE(a > b);
EXPECT_TRUE(a >= b);
EXPECT_FALSE(b > a);
EXPECT_FALSE(b >= a);
EXPECT_TRUE(b < a);
EXPECT_TRUE(b <= a);
EXPECT_FALSE(a < b);
EXPECT_FALSE(a <= b);
EXPECT_FALSE(a < a);
EXPECT_FALSE(a > a);
EXPECT_TRUE(a >= a);
EXPECT_TRUE(a <= a);
EXPECT_TRUE(a == a);
EXPECT_FALSE(a != a);
EXPECT_TRUE(a != b);
EXPECT_TRUE(b != a);
}
{
cnl::dsp::virtual_float<q8_40> a{2.0f};
cnl::dsp::virtual_float<q8_40> b{1.0f};
EXPECT_TRUE(a > b);
EXPECT_TRUE(a >= b);
EXPECT_FALSE(b > a);
EXPECT_FALSE(b >= a);
EXPECT_TRUE(b < a);
EXPECT_TRUE(b <= a);
EXPECT_FALSE(a < b);
EXPECT_FALSE(a <= b);
EXPECT_FALSE(a < a);
EXPECT_FALSE(a > a);
EXPECT_TRUE(a >= a);
EXPECT_TRUE(a <= a);
EXPECT_TRUE(a == a);
EXPECT_FALSE(a != a);
EXPECT_TRUE(a != b);
EXPECT_TRUE(b != a);
}
}
TEST(virtual_float, square_root)
{
{
cnl::dsp::virtual_float<float> a{1.0f};
cnl::dsp::virtual_float<float> b = sqrt(a);
EXPECT_EQ(static_cast<float>(b), 1.0f);
}
{
cnl::dsp::virtual_float<float> a{2.0f};
cnl::dsp::virtual_float<float> b = sqrt(a);
EXPECT_EQ(static_cast<float>(b), std::sqrt(2.0f));
}
{
cnl::dsp::virtual_float<q4_20> a{2.0f};
EXPECT_EQ(static_cast<float>(a), 2.0f);
cnl::dsp::virtual_float<q4_20> b = sqrt(a);
EXPECT_FLOAT_EQ(static_cast<float>(b), std::sqrt(2.0f));
}
{
cnl::dsp::virtual_float<q4_20> a{3.5783958f};
EXPECT_FLOAT_EQ(static_cast<float>(a), 3.5783958f);
cnl::dsp::virtual_float<q4_20> b = sqrt(a);
EXPECT_FLOAT_EQ(static_cast<float>(b), std::sqrt(3.5783958f));
}
{
cnl::dsp::virtual_float<q4_20> a{1.349885940551758f};
EXPECT_FLOAT_EQ(static_cast<float>(a), 1.349885940551758f);
cnl::dsp::virtual_float<q4_20> b = sqrt(a);
EXPECT_NEAR(static_cast<float>(b), std::sqrt(1.349885940551758f), 0.00001);
}
#if defined(CNL_INT128_ENABLED)
{
cnl::dsp::virtual_float<q8_40> a{1.349885940551758f};
EXPECT_FLOAT_EQ(static_cast<float>(a), 1.349885940551758f);
cnl::dsp::virtual_float<q8_40> b = sqrt(a);
EXPECT_NEAR(static_cast<float>(b), std::sqrt(1.349885940551758f), 0.00001);
}
#endif
}
TEST(virtual_float, from_virtual_float)
{
{
cnl::dsp::virtual_float<q4_20> a{2.0f};
q4_20 b = static_cast<q4_20>(a);
EXPECT_EQ(static_cast<float>(b), 2.0f);
}
{
cnl::dsp::virtual_float<q8_40> a{2.0f};
q8_40 b = static_cast<q8_40>(a);
EXPECT_EQ(static_cast<float>(b), 2.0f);
}
{
cnl::dsp::virtual_float<q8_40> a{2.0f};
q4_20 b = static_cast<q4_20>(a);
EXPECT_EQ(static_cast<float>(b), 2.0f);
}
{
cnl::dsp::virtual_float<q8_40> a{2.0f};
cnl::dsp::virtual_float<q4_20> b = static_cast<q4_20>(a);
EXPECT_EQ(static_cast<float>(b), 2.0f);
}
}
TEST(virtual_float, cumulative_sum_q4_20)
{
std::mt19937 mt(91);
std::uniform_real_distribution<float> fdist(-0.5, 0.5);
double float_sum(0);
cnl::dsp::virtual_float<q4_20> vf_sum(0.0);
for (unsigned int loop = 0; loop < 1000; loop++)
{
q4_20 efxp_num = static_cast<q4_20>(fdist(mt));
double float_num = static_cast<double>(efxp_num);
cnl::dsp::virtual_float<q4_20> vfe_num = efxp_num;
ASSERT_FLOAT_EQ(static_cast<float>(vfe_num), static_cast<float>(float_num));
float_sum += float_num;
vf_sum += vfe_num;
EXPECT_NEAR(static_cast<float>(float_sum), static_cast<float>(vf_sum), 5e-4f);
}
}
TEST(virtual_float, cumulative_sum_q8_40)
{
std::mt19937 mt(91);
std::uniform_real_distribution<float> fdist(-0.5, 0.5);
double float_sum(0);
cnl::dsp::virtual_float<q8_40> vf_sum(0.0);
for (unsigned int loop = 0; loop < 1000000; loop++)
{
q8_40 efxp_num = static_cast<q8_40>(fdist(mt));
double float_num = static_cast<double>(efxp_num);
cnl::dsp::virtual_float<q8_40> vfe_num = efxp_num;
ASSERT_FLOAT_EQ(static_cast<float>(vfe_num), static_cast<float>(float_num));
float_sum += float_num;
vf_sum += vfe_num;
EXPECT_NEAR(static_cast<float>(float_sum), static_cast<float>(vf_sum), 1e-7f);
}
}
| 31.286096 | 86 | 0.576276 | johnmcfarlane |
b897df97da696e9b310e69ff5d44eb8b892d1cac | 11,993 | cpp | C++ | to/lang/OpenCV-2.2.0/samples/gpu/hog.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | null | null | null | to/lang/OpenCV-2.2.0/samples/gpu/hog.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | 14 | 2016-11-24T10:46:39.000Z | 2016-12-10T07:24:15.000Z | to/lang/OpenCV-2.2.0/samples/gpu/hog.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
/** Contains all properties of application (including those which can be
changed by user in runtime) */
class Settings
{
public:
/** Sets default values */
Settings();
/** Reads settings from command args */
static Settings Read(int argc, char** argv);
string src;
bool src_is_video;
bool make_gray;
bool resize_src;
double resize_src_scale;
double scale;
int nlevels;
int gr_threshold;
double hit_threshold;
int win_width;
int win_stride_width;
int win_stride_height;
bool gamma_corr;
};
/** Describes aplication logic */
class App
{
public:
/** Initializes application */
App(const Settings& s);
/** Runs demo using OpenCV highgui module for GUI building */
void RunOpencvGui();
/** Processes user keybord input */
void HandleKey(char key);
void HogWorkBegin();
void HogWorkEnd();
double HogWorkFps() const;
void WorkBegin();
void WorkEnd();
double WorkFps() const;
const string GetPerformanceSummary() const;
private:
App operator=(App&);
Settings settings;
bool running;
bool use_gpu;
bool make_gray;
double scale;
int gr_threshold;
int nlevels;
double hit_threshold;
bool gamma_corr;
int64 hog_work_begin;
double hog_work_fps;
int64 work_begin;
double work_fps;
};
int main(int argc, char** argv)
{
try
{
if (argc < 2)
{
cout << "Usage:\nsample_hog\n"
<< " -src <path_to_the_source>\n"
<< " [-src_is_video <true/false>] # says to interp. src as img or as video\n"
<< " [-make_gray <true/false>] # convert image to gray one or not\n"
<< " [-resize_src <true/false>] # do resize of the source image or not\n"
<< " [-resize_src_scale <double>] # preprocessing image scale factor\n"
<< " [-hit_threshold <double>] # classifying plane dist. threshold (0.0 usually)\n"
<< " [-scale <double>] # HOG window scale factor\n"
<< " [-nlevels <int>] # max number of HOG window scales\n"
<< " [-win_width <int>] # width of the window (48 or 64)\n"
<< " [-win_stride_width <int>] # distance by OX axis between neighbour wins\n"
<< " [-win_stride_height <int>] # distance by OY axis between neighbour wins\n"
<< " [-gr_threshold <int>] # merging similar rects constant\n"
<< " [-gamma_corr <int>] # do gamma correction or not\n";
return 1;
}
App app(Settings::Read(argc, argv));
app.RunOpencvGui();
}
catch (const Exception& e) { return cout << "Error: " << e.what() << endl, 1; }
catch (const exception& e) { return cout << "Error: " << e.what() << endl, 1; }
catch(...) { return cout << "Unknown exception" << endl, 1; }
return 0;
}
Settings::Settings()
{
src_is_video = false;
make_gray = false;
resize_src = true;
resize_src_scale = 1.5;
scale = 1.05;
nlevels = 13;
gr_threshold = 8;
hit_threshold = 1.4;
win_width = 48;
win_stride_width = 8;
win_stride_height = 8;
gamma_corr = true;
}
Settings Settings::Read(int argc, char** argv)
{
cout << "Parsing command args" << endl;
Settings settings;
for (int i = 1; i < argc - 1; i += 2)
{
string key = argv[i];
string val = argv[i + 1];
if (key == "-src") settings.src = val;
else if (key == "-src_is_video") settings.src_is_video = (val == "true");
else if (key == "-make_gray") settings.make_gray = (val == "true");
else if (key == "-resize_src") settings.resize_src = (val == "true");
else if (key == "-resize_src_scale") settings.resize_src_scale = atof(val.c_str());
else if (key == "-hit_threshold") settings.hit_threshold = atof(val.c_str());
else if (key == "-scale") settings.scale = atof(val.c_str());
else if (key == "-nlevels") settings.nlevels = atoi(val.c_str());
else if (key == "-win_width") settings.win_width = atoi(val.c_str());
else if (key == "-win_stride_width") settings.win_stride_width = atoi(val.c_str());
else if (key == "-win_stride_height") settings.win_stride_height = atoi(val.c_str());
else if (key == "-gr_threshold") settings.gr_threshold = atoi(val.c_str());
else if (key == "-gamma_corr") settings.gamma_corr = atoi(val.c_str()) != 0;
else throw runtime_error((string("Unknown key: ") + key));
}
cout << "Command args are parsed\n";
return settings;
}
App::App(const Settings &s)
{
settings = s;
cout << "\nControls:\n"
<< "\tESC - exit\n"
<< "\tm - change mode GPU <-> CPU\n"
<< "\tg - convert image to gray or not\n"
<< "\t1/q - increase/decrease HOG scale\n"
<< "\t2/w - increase/decrease levels count\n"
<< "\t3/e - increase/decrease HOG group threshold\n"
<< "\t4/r - increase/decrease hit threshold\n"
<< endl;
use_gpu = true;
make_gray = settings.make_gray;
scale = settings.scale;
gr_threshold = settings.gr_threshold;
nlevels = settings.nlevels;
hit_threshold = settings.hit_threshold;
gamma_corr = settings.gamma_corr;
if (settings.win_width != 64 && settings.win_width != 48)
settings.win_width = 64;
cout << "Scale: " << scale << endl;
cout << "Group threshold: " << gr_threshold << endl;
cout << "Levels number: " << nlevels << endl;
cout << "Win width: " << settings.win_width << endl;
cout << "Win stride: (" << settings.win_stride_width << ", " << settings.win_stride_height << ")\n";
cout << "Hit threshold: " << hit_threshold << endl;
cout << "Gamma correction: " << gamma_corr << endl;
cout << endl;
}
void App::RunOpencvGui()
{
running = true;
Size win_size(settings.win_width, settings.win_width * 2); //(64, 128) or (48, 96)
Size win_stride(settings.win_stride_width, settings.win_stride_height);
vector<float> detector;
if (win_size == Size(64, 128))
detector = cv::gpu::HOGDescriptor::getPeopleDetector_64x128();
else
detector = cv::gpu::HOGDescriptor::getPeopleDetector_48x96();
// GPU's HOG classifier
cv::gpu::HOGDescriptor gpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9,
cv::gpu::HOGDescriptor::DEFAULT_WIN_SIGMA, 0.2, gamma_corr,
cv::gpu::HOGDescriptor::DEFAULT_NLEVELS);
gpu_hog.setSVMDetector(detector);
// CPU's HOG classifier
cv::HOGDescriptor cpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9, 1, -1,
HOGDescriptor::L2Hys, 0.2, gamma_corr, cv::HOGDescriptor::DEFAULT_NLEVELS);
cpu_hog.setSVMDetector(detector);
// Make endless cycle from video (if src is video)
while (running)
{
VideoCapture vc;
Mat frame;
if (settings.src_is_video)
{
vc.open(settings.src.c_str());
if (!vc.isOpened())
throw runtime_error(string("Can't open video file: " + settings.src));
vc >> frame;
}
else
{
frame = imread(settings.src);
if (frame.empty())
throw runtime_error(string("Can't open image file: " + settings.src));
}
Mat img_aux, img, img_to_show;
gpu::GpuMat gpu_img;
// Iterate over all frames
while (running && !frame.empty())
{
WorkBegin();
vector<Rect> found;
// Change format of the image (input must be 8UC3)
if (make_gray)
cvtColor(frame, img_aux, CV_BGR2GRAY);
else if (use_gpu)
cvtColor(frame, img_aux, CV_BGR2BGRA);
else
img_aux = frame;
// Resize image
if (settings.resize_src)
resize(img_aux, img, Size(int(frame.cols * settings.resize_src_scale), int(frame.rows * settings.resize_src_scale)));
else
img = img_aux;
img_to_show = img;
gpu_hog.nlevels = nlevels;
cpu_hog.nlevels = nlevels;
// Perform HOG classification
HogWorkBegin();
if (use_gpu)
{
gpu_img = img;
gpu_hog.detectMultiScale(gpu_img, found, hit_threshold, win_stride, Size(0, 0), scale, gr_threshold);
}
else
cpu_hog.detectMultiScale(img, found, hit_threshold, win_stride, Size(0, 0), scale, gr_threshold);
HogWorkEnd();
// Draw positive classified windows
for (size_t i = 0; i < found.size(); i++)
{
Rect r = found[i];
rectangle(img_to_show, r.tl(), r.br(), CV_RGB(0, 255, 0), 3);
}
WorkEnd();
// Show results
putText(img_to_show, GetPerformanceSummary(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2);
imshow("opencv_gpu_hog", img_to_show);
HandleKey((char)waitKey(3));
if (settings.src_is_video)
{
vc >> frame;
}
}
}
}
void App::HandleKey(char key)
{
switch (key)
{
case 27:
running = false;
break;
case 'm':
case 'M':
use_gpu = !use_gpu;
cout << "Switched to " << (use_gpu ? "CUDA" : "CPU") << " mode\n";
break;
case 'g':
case 'G':
make_gray = !make_gray;
cout << "Convert image to gray: " << (make_gray ? "YES" : "NO") << endl;
break;
case '1':
scale *= 1.05;
cout << "Scale: " << scale << endl;
break;
case 'q':
case 'Q':
scale /= 1.05;
cout << "Scale: " << scale << endl;
break;
case '2':
nlevels++;
cout << "Levels number: " << nlevels << endl;
break;
case 'w':
case 'W':
nlevels = max(nlevels - 1, 1);
cout << "Levels number: " << nlevels << endl;
break;
case '3':
gr_threshold++;
cout << "Group threshold: " << gr_threshold << endl;
break;
case 'e':
case 'E':
gr_threshold = max(0, gr_threshold - 1);
cout << "Group threshold: " << gr_threshold << endl;
break;
case '4':
hit_threshold+=0.25;
cout << "Hit threshold: " << hit_threshold << endl;
break;
case 'r':
case 'R':
hit_threshold = max(0.0, hit_threshold - 0.25);
cout << "Hit threshold: " << hit_threshold << endl;
break;
case 'c':
case 'C':
gamma_corr = !gamma_corr;
cout << "Gamma correction: " << gamma_corr << endl;
break;
}
}
inline void App::HogWorkBegin() { hog_work_begin = getTickCount(); }
inline void App::HogWorkEnd()
{
int64 delta = getTickCount() - hog_work_begin;
double freq = getTickFrequency();
hog_work_fps = freq / delta;
}
inline double App::HogWorkFps() const { return hog_work_fps; }
inline void App::WorkBegin() { work_begin = getTickCount(); }
inline void App::WorkEnd()
{
int64 delta = getTickCount() - work_begin;
double freq = getTickFrequency();
work_fps = freq / delta;
}
inline double App::WorkFps() const { return work_fps; }
inline const string App::GetPerformanceSummary() const
{
stringstream ss;
ss << (use_gpu ? "GPU" : "CPU") << " HOG FPS: " << setiosflags(ios::left) << setprecision(4) <<
setw(7) << HogWorkFps() << " Total FPS: " << setprecision(4) << setw(7) << WorkFps();
return ss.str();
}
| 29.685644 | 133 | 0.560744 | eirTony |
b89902749f712e950284009eaa76065c5224362f | 2,160 | cpp | C++ | windows/src/test/cpp/ClientExtensionTest.cpp | ane-community/cryptopp-ane | 1c2550b0e2ee85503d94b8292a588430d94de706 | [
"MIT"
] | 3 | 2015-06-16T18:56:29.000Z | 2019-03-06T03:18:33.000Z | windows/src/test/cpp/ClientExtensionTest.cpp | ane-community/cryptopp-ane | 1c2550b0e2ee85503d94b8292a588430d94de706 | [
"MIT"
] | null | null | null | windows/src/test/cpp/ClientExtensionTest.cpp | ane-community/cryptopp-ane | 1c2550b0e2ee85503d94b8292a588430d94de706 | [
"MIT"
] | null | null | null | /*
* =BEGIN MIT LICENSE
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Andras Csizmadia
* http://www.vpmedia.hu
*
* 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.
*
* =END MIT LICENSE
*
*/
/**
* ClientExtensionTest
* ClientExtensionTest.cpp
* Purpose: Test for ClientExtension
*
* @author Andras Csizmadia (andras at vpmedia.hu)
* @version 1.0.0
*/
//----------------------------------
// Import Custom Headers
//----------------------------------
#include "ClientExtensionTest.h"
//----------------------------------
// Main
//----------------------------------
int main(int argc, char** argv)
{
printf("Testing Crypto\n");
CryptoPP::SHA512 hash;
byte digest[ CryptoPP::SHA512::DIGESTSIZE ];
std::string message = "HelloWorld";
hash.CalculateDigest( digest, (byte*) message.c_str(), message.length() );
CryptoPP::HexEncoder encoder;
std::string output;
encoder.Attach( new CryptoPP::StringSink( output ) );
encoder.Put( digest, sizeof(digest) );
encoder.MessageEnd();
std::cout << output << std::endl;
return EXIT_SUCCESS;
}
| 30.422535 | 80 | 0.657407 | ane-community |
b89a06c8554e9d0b604c6516bfd664f640294d99 | 1,413 | hpp | C++ | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | /** System that manages sound effects ****************************************
* *
* Copyright (c) 2016 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include <core/audio/audio_ctx.hpp>
#include <core/audio/sound.hpp>
#include <core/engine.hpp>
#include <core/utils/str_id.hpp>
#include <core/utils/messagebus.hpp>
#include <core/units.hpp>
#include <core/ecs/ecs.hpp>
namespace lux {
namespace renderer {
struct Animation_event;
}
namespace sys {
namespace sound {
struct Sound_mappings;
class Sound_sys {
public:
Sound_sys(Engine&, ecs::Entity_manager& ecs);
~Sound_sys();
void update(Time dt);
private:
struct Sound_effect {
audio::Sound_ptr sound;
bool loop = false;
};
audio::Audio_ctx& _audio_ctx;
asset::Asset_manager& _assets;
ecs::Entity_manager& _ecs;
asset::Ptr<Sound_mappings> _mappings;
util::Mailbox_collection _mailbox;
int _last_rev = 0;
std::unordered_map<util::Str_id, Sound_effect> _event_sounds;
void _reload();
void _on_anim_event(const renderer::Animation_event& event);
};
}
}
}
| 23.55 | 79 | 0.55414 | lowkey42 |
b89a48069d6488ef09291eaf8d1e3f7a91b9fc26 | 608 | cpp | C++ | Interview Preparation Kit - CPP/06. Greedy Algorithms/001. Minimum Absolute Difference in an Array.cpp | Snehakri022/HackerrankPractice | 15c2da0bfb4bce744b345c4a3613ae9a769f2676 | [
"MIT"
] | 831 | 2018-05-12T19:06:09.000Z | 2022-03-31T19:33:54.000Z | Interview Preparation Kit - CPP/06. Greedy Algorithms/001. Minimum Absolute Difference in an Array.cpp | Snehakri022/HackerrankPractice | 15c2da0bfb4bce744b345c4a3613ae9a769f2676 | [
"MIT"
] | 2 | 2019-06-17T14:58:56.000Z | 2021-03-05T23:49:59.000Z | Interview Preparation Kit - CPP/06. Greedy Algorithms/001. Minimum Absolute Difference in an Array.cpp | Snehakri022/HackerrankPractice | 15c2da0bfb4bce744b345c4a3613ae9a769f2676 | [
"MIT"
] | 457 | 2018-06-11T07:01:57.000Z | 2022-03-28T11:08:34.000Z | // Problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem
// Score: 15
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++){
int tmp;
cin >> tmp;
arr.push_back(tmp);
}
sort(arr.begin(), arr.end());
int ans = abs(arr[0] - arr[1]);
for (int i = 1; i < arr.size(); i++){
if (abs(arr[i] - arr[i-1]) < ans){
ans = abs(arr[i] - arr[i-1]);
}
}
cout << ans;
return 0;
}
| 17.371429 | 97 | 0.509868 | Snehakri022 |
b89ae093da4b64b42052cfd2fe2ed5e50755dde3 | 8,152 | cpp | C++ | clients/cpp-restsdk/generated/model/GenericResource.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 23 | 2017-08-01T12:25:26.000Z | 2022-01-25T03:44:11.000Z | clients/cpp-restsdk/generated/model/GenericResource.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/cpp-restsdk/generated/model/GenericResource.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 11 | 2017-08-31T19:00:20.000Z | 2021-12-19T12:04:12.000Z | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "GenericResource.h"
namespace org {
namespace openapitools {
namespace client {
namespace model {
GenericResource::GenericResource()
{
m__class = utility::conversions::to_string_t("");
m__classIsSet = false;
m_DisplayName = utility::conversions::to_string_t("");
m_DisplayNameIsSet = false;
m_DurationInMillis = 0;
m_DurationInMillisIsSet = false;
m_Id = utility::conversions::to_string_t("");
m_IdIsSet = false;
m_Result = utility::conversions::to_string_t("");
m_ResultIsSet = false;
m_StartTime = utility::conversions::to_string_t("");
m_StartTimeIsSet = false;
}
GenericResource::~GenericResource()
{
}
void GenericResource::validate()
{
// TODO: implement validation
}
web::json::value GenericResource::toJson() const
{
web::json::value val = web::json::value::object();
if(m__classIsSet)
{
val[utility::conversions::to_string_t("_class")] = ModelBase::toJson(m__class);
}
if(m_DisplayNameIsSet)
{
val[utility::conversions::to_string_t("displayName")] = ModelBase::toJson(m_DisplayName);
}
if(m_DurationInMillisIsSet)
{
val[utility::conversions::to_string_t("durationInMillis")] = ModelBase::toJson(m_DurationInMillis);
}
if(m_IdIsSet)
{
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id);
}
if(m_ResultIsSet)
{
val[utility::conversions::to_string_t("result")] = ModelBase::toJson(m_Result);
}
if(m_StartTimeIsSet)
{
val[utility::conversions::to_string_t("startTime")] = ModelBase::toJson(m_StartTime);
}
return val;
}
void GenericResource::fromJson(web::json::value& val)
{
if(val.has_field(utility::conversions::to_string_t("_class")))
{
setClass(ModelBase::stringFromJson(val[utility::conversions::to_string_t("_class")]));
}
if(val.has_field(utility::conversions::to_string_t("displayName")))
{
setDisplayName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("displayName")]));
}
if(val.has_field(utility::conversions::to_string_t("durationInMillis")))
{
setDurationInMillis(ModelBase::int32_tFromJson(val[utility::conversions::to_string_t("durationInMillis")]));
}
if(val.has_field(utility::conversions::to_string_t("id")))
{
setId(ModelBase::stringFromJson(val[utility::conversions::to_string_t("id")]));
}
if(val.has_field(utility::conversions::to_string_t("result")))
{
setResult(ModelBase::stringFromJson(val[utility::conversions::to_string_t("result")]));
}
if(val.has_field(utility::conversions::to_string_t("startTime")))
{
setStartTime(ModelBase::stringFromJson(val[utility::conversions::to_string_t("startTime")]));
}
}
void GenericResource::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m__classIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("_class"), m__class));
}
if(m_DisplayNameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("displayName"), m_DisplayName));
}
if(m_DurationInMillisIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("durationInMillis"), m_DurationInMillis));
}
if(m_IdIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id));
}
if(m_ResultIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("result"), m_Result));
}
if(m_StartTimeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("startTime"), m_StartTime));
}
}
void GenericResource::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("_class")))
{
setClass(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("_class"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("displayName")))
{
setDisplayName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("displayName"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("durationInMillis")))
{
setDurationInMillis(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("durationInMillis"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("id")))
{
setId(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("result")))
{
setResult(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("result"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("startTime")))
{
setStartTime(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("startTime"))));
}
}
utility::string_t GenericResource::getClass() const
{
return m__class;
}
void GenericResource::setClass(utility::string_t value)
{
m__class = value;
m__classIsSet = true;
}
bool GenericResource::_classIsSet() const
{
return m__classIsSet;
}
void GenericResource::unset_class()
{
m__classIsSet = false;
}
utility::string_t GenericResource::getDisplayName() const
{
return m_DisplayName;
}
void GenericResource::setDisplayName(utility::string_t value)
{
m_DisplayName = value;
m_DisplayNameIsSet = true;
}
bool GenericResource::displayNameIsSet() const
{
return m_DisplayNameIsSet;
}
void GenericResource::unsetDisplayName()
{
m_DisplayNameIsSet = false;
}
int32_t GenericResource::getDurationInMillis() const
{
return m_DurationInMillis;
}
void GenericResource::setDurationInMillis(int32_t value)
{
m_DurationInMillis = value;
m_DurationInMillisIsSet = true;
}
bool GenericResource::durationInMillisIsSet() const
{
return m_DurationInMillisIsSet;
}
void GenericResource::unsetDurationInMillis()
{
m_DurationInMillisIsSet = false;
}
utility::string_t GenericResource::getId() const
{
return m_Id;
}
void GenericResource::setId(utility::string_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool GenericResource::idIsSet() const
{
return m_IdIsSet;
}
void GenericResource::unsetId()
{
m_IdIsSet = false;
}
utility::string_t GenericResource::getResult() const
{
return m_Result;
}
void GenericResource::setResult(utility::string_t value)
{
m_Result = value;
m_ResultIsSet = true;
}
bool GenericResource::resultIsSet() const
{
return m_ResultIsSet;
}
void GenericResource::unsetResult()
{
m_ResultIsSet = false;
}
utility::string_t GenericResource::getStartTime() const
{
return m_StartTime;
}
void GenericResource::setStartTime(utility::string_t value)
{
m_StartTime = value;
m_StartTimeIsSet = true;
}
bool GenericResource::startTimeIsSet() const
{
return m_StartTimeIsSet;
}
void GenericResource::unsetStartTime()
{
m_StartTimeIsSet = false;
}
}
}
}
}
| 26.640523 | 141 | 0.703876 | PankTrue |
b8a20d7bcb754876f1238a5299cb7c9ca05accdf | 5,970 | hpp | C++ | src/astrolabe_exception.hpp | jose-navarro/ASTROLABE | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | null | null | null | src/astrolabe_exception.hpp | jose-navarro/ASTROLABE | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | 3 | 2019-05-28T05:34:50.000Z | 2019-12-09T12:58:22.000Z | src/astrolabe_exception.hpp | jose-navarro/astrolabe | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | null | null | null | /** \file astrolabe_exception.hpp
\brief Definition of the topmost, general ASTROLABE exception.
\ingroup ASTROLABE_exceptions_group
*/
#ifndef ASTROLABE_EXCEPTION_HPP
#define ASTROLABE_EXCEPTION_HPP
#include <stdexcept>
#include <string>
using namespace std;
class astrolabe_time;
/**
\brief ASTROLABE's topmost, general exception.
\ingroup ASTROLABE_exceptions_group
*/
class astrolabe_exception : public exception
{
public:
/// \brief Default constructor.
astrolabe_exception (void);
/// \brief Copy constructor.
/**
\param other The other exception from which the values
will be copied.
*/
astrolabe_exception (const astrolabe_exception & other);
/// \brief Destructor.
virtual ~astrolabe_exception (void);
public:
/// \brief Print the exception.
/**
\param the_stream The stream to print the exception to.
*/
virtual void print (ostream & the_stream) const;
/// \brief Set the description of the exception.
/**
\param the_description The description of the exception.
*/
virtual void set_description (const string & the_description);
/// \brief Get the description of the exception.
/**
\return The description of the exception.
*/
virtual string _description (void) const;
/// \brief Set the name of the source file where the exception takes place.
/**
\param the_file The name of the file to set.
*/
virtual void set_file (const string & the_file);
/// \brief Get the name of the file where the exception takes place.
/**
\return The name of the file where the exception takes place.
*/
virtual string _file (void) const;
/// \brief Set the line number (in the source file) where the exception takes place.
/**
\param the_line The line number to set.
*/
virtual void set_line (int the_line);
/// \brief Ge the line number (in the source file) where the exception takes place.
/**
\return The line number (in the source file) where the exception takes place.
*/
virtual int _line (void) const;
/// \brief Set the name of the class where the exception takes place.
/**
\param the_class The name of the class to set.
*/
virtual void set_class_in (const string & the_class);
/// \brief Retrieve the name of the class where the exception takes place.
/**
\return The name of the class where the exception takes place.
*/
virtual string _class_in (void) const;
/// \brief Set the name of the method where the exception takes place.
/**
\param the_method The name of the method to set.
*/
virtual void set_method_in (const string & the_method);
/// \brief Retrieve the name of the method where the exception takes place.
/**
\return The name of the method where the exception takes place.
*/
virtual string _method_in (void) const;
/// \brief Set the severity level of the exception.
/**
\param The severity level to set. It must be coded as follows:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
virtual void set_severity (int the_sever);
/// \brief Retrieve the severity level of the exception.
/**
\return The severity level of the exception. The meaning of the
numerical code returned is:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
virtual string _severity (void) const;
/// \brief Set the time when the exception takes place.
/**
\param Time The time when the exception takes place.
*/
virtual void set_time (const astrolabe_time Time);
/// \brief Retrieve the time when the exception takes place.
/**
\param Time The object to which the time when the exception
takes placw will be copied.
*/
virtual void _time ( astrolabe_time & Time) const;
/// \brief Retrieve the exception's alphanumeric code.
/**
\return The exception's alphanumeric code.
*/
virtual string _name_code (void) const;
/// \brief Retrieve the exception's numeric code.
/**
\return The exception's numeric code.
*/
virtual int _num_code (void) const;
protected:
/// \brief Source file where the exception took place.
string file_;
/// \brief Line number within the source file where the exception took place.
int line_;
/// \brief Class of the object throwing the exception.
string class_;
/// \brief Method of the object throwing the exception.
string method_;
/// \brief Short description.
string description_;
/// \brief Error degree.
/**
Three severity levels are allowed:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
int severity_;
/// \brief Time of event: year.
int yy_;
/// \brief Time of event: month.
int mm_;
/// \brief Time of event: day.
int dd_;
/// \brief Time of event: hour.
int ho_;
/// \brief Time of event: minute.
int mi_;
/// \brief Time of event: second.
long double se_;
};
ostream & operator << (ostream & result, const astrolabe_exception & the_exception);
#endif
| 25.622318 | 90 | 0.627303 | jose-navarro |
b8a321eb384a8c56db31894ac2698db5a374dc2e | 1,990 | cpp | C++ | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 20 | 2019-12-22T20:40:22.000Z | 2021-07-06T00:23:45.000Z | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 32 | 2020-07-11T15:51:13.000Z | 2021-06-07T10:25:07.000Z | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 3 | 2019-12-19T17:04:04.000Z | 2021-05-17T01:49:59.000Z | #include "PathTree.h"
#include <sstream>
#include "StringUtil.h"
namespace ze::assetdatabase
{
void PathTree::add(const std::filesystem::path& path)
{
ZE_CHECK(path.is_relative());
/** Check if path already exists */
if (has_path(path))
return;
/** Insert the path in the map if it is a directory */
if (!path.has_extension())
paths.insert({ path, PathDirectory() });
/** Now scan each part to build a tree */
std::vector<std::string> tokens = stringutil::split(path.string(),
std::filesystem::path::preferred_separator);
/** Insert at root */
if (tokens.size() == 1)
{
paths[""].childs.insert(path);
}
else
{
std::filesystem::path final_path;
std::filesystem::path parent = "";
for (size_t i = 0; i < tokens.size() - 1; ++i)
{
const auto& token = tokens[i];
final_path = final_path / token;
if (paths[parent].childs.find(token) == paths[parent].childs.end())
{
paths[parent / token].parent = parent;
paths[parent].childs.insert(token);
}
/** Insert file */
if (i == tokens.size() - 2)
{
paths[parent / token].childs.insert(tokens[tokens.size() - 1]);
}
parent /= token;
}
}
}
std::vector<std::filesystem::path> PathTree::get_childs(const std::filesystem::path& path,
const bool& include_files)
{
std::vector<std::filesystem::path> childs;
if (paths.find(path) == paths.end())
return childs;
childs.reserve(paths[path].childs.size());
for (const auto& child : paths[path].childs)
{
if (!include_files && child.has_extension())
continue;
childs.emplace_back(child);
}
return childs;
}
bool PathTree::has_path(const std::filesystem::path& path) const
{
if (path.has_filename())
{
/** Check to the parent of the file */
auto parent_it = paths.find(path.parent_path());
if (parent_it != paths.end())
{
return parent_it->second.childs.find(path.filename()) != parent_it->second.childs.end();
}
return false;
}
else
{
return paths.find(path) != paths.end();
}
}
} | 21.170213 | 91 | 0.647236 | Zino2201 |
b8a79a4bbf613fa1c526f04b1ca6fcb0c4677904 | 520 | cpp | C++ | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | #include <iostream>
long Factorial(int no);
long nCr(int n, int r);
int main() {
int n, r;
std::cout << "Enter a value for n ";
std::cin >> n;
std::cout << "Enter a value for r ";
std::cin >> r;
std::cout << "nCr = ";
std::cout << nCr(n, r);
std::cout << std::endl;
return 0;
}
long Factorial(int no)
{
long sum;
int i;
sum = 1;
for (i = no; i >= 1; i--)
{
sum = i * sum;
}
return sum;
}
long nCr(int n, int r)
{
long ncr;
ncr = Factorial(n) / (Factorial(r) * Factorial((n-r)));
return ncr;
}
| 14.054054 | 56 | 0.546154 | SLIIT-FacultyOfComputing |
b8a928f4114f88c9dfe65711e92def42e79fc27b | 2,620 | cpp | C++ | cpp/daal/src/algorithms/adaboost/adaboost_predict_dense_default_batch_fpt_dispatcher.cpp | Pahandrovich/daal | 3310c7a9a41a2f0eb72082115c0db98484e4d58d | [
"Apache-2.0"
] | 1 | 2021-02-05T15:41:08.000Z | 2021-02-05T15:41:08.000Z | cpp/daal/src/algorithms/adaboost/adaboost_predict_dense_default_batch_fpt_dispatcher.cpp | Pahandrovich/daal | 3310c7a9a41a2f0eb72082115c0db98484e4d58d | [
"Apache-2.0"
] | null | null | null | cpp/daal/src/algorithms/adaboost/adaboost_predict_dense_default_batch_fpt_dispatcher.cpp | Pahandrovich/daal | 3310c7a9a41a2f0eb72082115c0db98484e4d58d | [
"Apache-2.0"
] | null | null | null | /* file: adaboost_predict_dense_default_batch_fpt_dispatcher.cpp */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* 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.
*******************************************************************************/
/*
//++
// Implementation of Ada Boost prediction algorithm container --
// a class that contains Fast Ada Boost kernels for supported architectures.
//--
*/
#include "algorithms/boosting/adaboost_predict.h"
#include "src/algorithms/adaboost/adaboost_predict_batch_container.h"
namespace daal
{
namespace algorithms
{
__DAAL_INSTANTIATE_DISPATCH_CONTAINER(adaboost::prediction::BatchContainer, batch, DAAL_FPTYPE, adaboost::prediction::defaultDense)
__DAAL_INSTANTIATE_DISPATCH_CONTAINER(adaboost::prediction::BatchContainer, batch, DAAL_FPTYPE, adaboost::prediction::sammeR)
namespace adaboost
{
namespace prediction
{
namespace interface2
{
template <>
Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>::Batch(size_t nClasses)
{
_par = new ParameterType(nClasses);
parameter().nClasses = nClasses;
initialize();
}
using BatchTypeDefault = Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>;
template <>
Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>::Batch(const BatchTypeDefault & other)
: classifier::prediction::Batch(other), input(other.input)
{
_par = new ParameterType(other.parameter());
initialize();
}
template <>
Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>::Batch(size_t nClasses)
{
_par = new ParameterType(nClasses);
parameter().nClasses = nClasses;
initialize();
}
using BatchTypeSammeR = Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>;
template <>
Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>::Batch(const BatchTypeSammeR & other) : classifier::prediction::Batch(other), input(other.input)
{
_par = new ParameterType(other.parameter());
initialize();
}
} // namespace interface2
} // namespace prediction
} // namespace adaboost
} // namespace algorithms
} // namespace daal
| 33.589744 | 145 | 0.708397 | Pahandrovich |
b8acd63d07bc0f2c52e871117bc6e61b11be11d0 | 5,655 | cpp | C++ | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 193 | 2015-01-05T08:48:05.000Z | 2022-01-31T22:04:01.000Z | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 135 | 2015-01-13T13:02:49.000Z | 2022-01-12T15:06:48.000Z | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 40 | 2015-01-21T16:37:30.000Z | 2022-01-25T15:54:04.000Z | #include <memory>
#include <src/recordbuf.hpp>
#include <gtest/gtest.h>
namespace blackhole {
inline namespace v1 {
namespace {
TEST(recordbuf_t, FromRecordMessage) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_pack pack;
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(string_view("GET"), result->into_view().message());
}
TEST(owned, FromRecordFormattedMessage) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET: {}");
const attribute_pack pack;
record_t record(0, message, pack);
record.activate("GET: 42");
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(string_view("GET: 42"), result->into_view().formatted());
}
TEST(owned, FromRecordSeverity) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_pack pack;
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(42, result->into_view().severity());
}
TEST(owned, FromRecordTimestamp) {
std::unique_ptr<recordbuf_t> result;
record_t::clock_type::time_point min = {};
record_t::clock_type::time_point max = {};
{
const string_view message("");
const attribute_pack pack;
min = record_t::clock_type::now();
record_t record(0, message, pack);
record.activate();
max = record_t::clock_type::now();
result.reset(new recordbuf_t(record));
}
EXPECT_TRUE(min <= result->into_view().timestamp());
EXPECT_TRUE(max >= result->into_view().timestamp());
}
TEST(owned, FromRecordThreadId) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_pack pack;
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(::pthread_self(), result->into_view().tid());
}
TEST(owned, FromRecordAttributes) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
const attribute_list attributes{{"key#1", "value#1"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveConstructor) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
recordbuf_t own(record);
result.reset(new recordbuf_t(std::move(own)));
}
EXPECT_EQ(string_view("GET"), result->into_view().message());
EXPECT_EQ(42, result->into_view().severity());
const attribute_list attributes{{"key#1", "value#1"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveAssignment) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
{
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf_t own(record);
*result = std::move(own);
}
EXPECT_EQ(string_view("POST"), result->into_view().message());
EXPECT_EQ(10, result->into_view().severity());
const attribute_list attributes{{"key#2", "value#2"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveAssignmentWithDifferentSizes) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
{
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf_t own(record);
*result = std::move(own);
}
EXPECT_EQ(string_view("POST"), result->into_view().message());
EXPECT_EQ(10, result->into_view().severity());
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(recordbuf_t, DefaultMove) {
recordbuf_t recordbuf;
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf = recordbuf_t(record);
recordbuf_t destroyer;
destroyer = std::move(recordbuf);
}
} // namespace
} // namespace v1
} // namespace blackhole
| 27.1875 | 84 | 0.640318 | JakariaBlaine |
b8adc7d8895a94058707a407ed9472316f79e0d6 | 128 | cpp | C++ | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | 2 | 2018-12-19T01:52:39.000Z | 2022-03-29T16:04:15.000Z | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | #include "../../include/core/Allocator.h"
using namespace PhysicsEngine;
Allocator::Allocator()
{
}
Allocator::~Allocator(){}; | 16 | 41 | 0.710938 | jsandham |
b8afaf9523b596a374f84040ad7f91f6b5cc68e1 | 495 | hpp | C++ | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | 3 | 2021-12-14T00:14:53.000Z | 2022-03-30T04:08:34.000Z | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | null | null | null | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | 1 | 2021-12-09T10:21:11.000Z | 2021-12-09T10:21:11.000Z | #ifndef TOTEM_HPP
#define TOTEM_HPP
#include "gameobject.hpp"
class Totem : public GameObject
{
public:
Totem(btVector3 origin, btDiscreteDynamicsWorld *dyn_world);
virtual bool collide(btManifoldPoint &cp,
const btCollisionObjectWrapper *obj1, int id1, int index1);
virtual void update(float dt);
GameObject *carried;
private:
btDiscreteDynamicsWorld *dyn_world;
btCollisionShape *ghost_shape;
btPairCachingGhostObject *ghost;
};
#endif
| 23.571429 | 84 | 0.723232 | Hazematman |
b8b3288e128db7300c87f650925b3f87918bb5fc | 3,840 | cpp | C++ | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 216 | 2015-01-20T17:14:01.000Z | 2022-03-05T16:14:25.000Z | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 12 | 2015-07-09T06:46:09.000Z | 2017-04-13T05:41:08.000Z | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 29 | 2015-03-14T03:19:52.000Z | 2021-01-29T13:43:51.000Z | /****************************************************************************
**This file is part of the Motorcar 3D windowing framework
**
**
**Copyright (C) 2014 Forrest Reiling
**
**
** You may use this file under the terms of the BSD license as follows:
**
** "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.
**
**
** 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 <scenegraph/input/singlebonetracker.h>
using namespace motorcar;
SingleBoneTracker::SingleBoneTracker(Bone *trackedBone, glm::mat4 boneTrackTransform, Skeleton *skeleton, PhysicalNode *parent, const glm::mat4 &transform)
:BoneSensor(skeleton, parent, transform)
,m_trackedBone(trackedBone)
,m_boneTrackTransform(boneTrackTransform)
{
}
glm::mat4 SingleBoneTracker::trackerParentSpaceToBoneParentSpaceTransform()
{
//define tracker parent space in bone space
glm::mat4 workingTransform = trackedBone()->inverseWorldTransform() * this->parentNode()->worldTransform();
//apply inverse bone track transform in the bone space
//this makes sure that the bone's orientation is taken into account when applying translation
workingTransform = glm::inverse(boneTrackTransform()) * workingTransform;
//bring into bone parent space
workingTransform = trackedBone()->transform() * workingTransform;
return workingTransform;
}
void SingleBoneTracker::setTransformFromTrackedBone()
{
this->setTransform(this->parentNode()->inverseWorldTransform() * trackedBone()->worldTransform() * boneTrackTransform());
}
void SingleBoneTracker::setPosition(const glm::vec3 &position)
{
glm::vec4 parentSpaceBonePos = trackerParentSpaceToBoneParentSpaceTransform() * glm::vec4(position, 1);
trackedBone()->setPosition(glm::vec3(parentSpaceBonePos));
setTransformFromTrackedBone();
}
void SingleBoneTracker::setOrientation(const glm::mat3 &orientation)
{
glm::mat4 orientation4X4 = glm::mat4(orientation);
glm::mat4 boneOrientation4X4 = trackerParentSpaceToBoneParentSpaceTransform() * orientation4X4 ;
trackedBone()->setOrientation(glm::mat3(boneOrientation4X4));
setTransformFromTrackedBone();
}
Bone *SingleBoneTracker::trackedBone() const
{
return m_trackedBone;
}
void SingleBoneTracker::setTrackedBone(Bone *trackedBone)
{
m_trackedBone = trackedBone;
}
glm::mat4 SingleBoneTracker::boneTrackTransform() const
{
return m_boneTrackTransform;
}
void SingleBoneTracker::setBoneTrackTransform(const glm::mat4 &boneTrackTransform)
{
m_boneTrackTransform = boneTrackTransform;
}
| 33.684211 | 155 | 0.732292 | Quora-Users |
b8b4c69573bb9151f2bc9c7f4a7039e88c727175 | 383 | cpp | C++ | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | 18 | 2018-03-22T14:33:14.000Z | 2021-11-07T07:05:32.000Z | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | null | null | null | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int t,i,j,k;
int sum;
char a,b;
cin >>t;
while(t--)
{
sum=0;
cin>>i>>a>>j>>b>>k;
if(a=='+')
sum = i+j;
else
sum = i-j;
if(b=='+')
sum = sum + k;
else
sum=sum-k;
cout <<sum<<endl;
}
return 0;
}
| 15.32 | 27 | 0.355091 | muinocriz |
b8bb0b7fef2d2a8eb1acaa5fe098070efa4cc796 | 13,125 | cpp | C++ | data/interactive_markers/src/tools.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | 2 | 2020-06-02T07:45:58.000Z | 2021-01-25T12:42:10.000Z | melodic/src/interactive_markers/src/tools.cpp | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | melodic/src/interactive_markers/src/tools.cpp | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | 7 | 2019-07-22T15:33:42.000Z | 2020-06-02T07:45:45.000Z | /*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "interactive_markers/tools.h"
#include <tf/LinearMath/Quaternion.h>
#include <tf/LinearMath/Matrix3x3.h>
#include <math.h>
#include <assert.h>
#include <set>
#include <sstream>
namespace interactive_markers
{
void autoComplete( visualization_msgs::InteractiveMarker &msg, bool enable_autocomplete_transparency )
{
// this is a 'delete' message. no need for action.
if ( msg.controls.empty() )
{
return;
}
// default size
if ( msg.scale == 0 )
{
msg.scale = 1;
}
// correct empty orientation, normalize
if ( msg.pose.orientation.w == 0 && msg.pose.orientation.x == 0 &&
msg.pose.orientation.y == 0 && msg.pose.orientation.z == 0 )
{
msg.pose.orientation.w = 1;
}
//normalize quaternion
tf::Quaternion int_marker_orientation( msg.pose.orientation.x, msg.pose.orientation.y,
msg.pose.orientation.z, msg.pose.orientation.w );
int_marker_orientation.normalize();
msg.pose.orientation.x = int_marker_orientation.x();
msg.pose.orientation.y = int_marker_orientation.y();
msg.pose.orientation.z = int_marker_orientation.z();
msg.pose.orientation.w = int_marker_orientation.w();
// complete the controls
for ( unsigned c=0; c<msg.controls.size(); c++ )
{
autoComplete( msg, msg.controls[c], enable_autocomplete_transparency);
}
uniqueifyControlNames( msg );
}
void uniqueifyControlNames( visualization_msgs::InteractiveMarker& msg )
{
int uniqueification_number = 0;
std::set<std::string> names;
for( unsigned c = 0; c < msg.controls.size(); c++ )
{
std::string name = msg.controls[c].name;
while( names.find( name ) != names.end() )
{
std::stringstream ss;
ss << name << "_u" << uniqueification_number++;
name = ss.str();
}
msg.controls[c].name = name;
names.insert( name );
}
}
void autoComplete( const visualization_msgs::InteractiveMarker &msg,
visualization_msgs::InteractiveMarkerControl &control, bool enable_autocomplete_transparency)
{
// correct empty orientation
if ( control.orientation.w == 0 && control.orientation.x == 0 &&
control.orientation.y == 0 && control.orientation.z == 0 )
{
control.orientation.w = 1;
}
// add default control handles if there are none
if ( control.markers.empty() )
{
switch ( control.interaction_mode )
{
case visualization_msgs::InteractiveMarkerControl::NONE:
break;
case visualization_msgs::InteractiveMarkerControl::MOVE_AXIS:
control.markers.reserve(2);
makeArrow( msg, control, 1.0 );
makeArrow( msg, control, -1.0 );
break;
case visualization_msgs::InteractiveMarkerControl::MOVE_PLANE:
case visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS:
case visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE:
makeDisc( msg, control );
break;
case visualization_msgs::InteractiveMarkerControl::BUTTON:
break;
case visualization_msgs::InteractiveMarkerControl::MENU:
makeViewFacingButton( msg, control, control.description );
break;
default:
break;
}
}
// get interactive marker pose for later
tf::Quaternion int_marker_orientation( msg.pose.orientation.x, msg.pose.orientation.y,
msg.pose.orientation.z, msg.pose.orientation.w );
tf::Vector3 int_marker_position( msg.pose.position.x, msg.pose.position.y, msg.pose.position.z );
// fill in missing pose information into the markers
for ( unsigned m=0; m<control.markers.size(); m++ )
{
visualization_msgs::Marker &marker = control.markers[m];
if ( marker.scale.x == 0 )
{
marker.scale.x = 1;
}
if ( marker.scale.y == 0 )
{
marker.scale.y = 1;
}
if ( marker.scale.z == 0 )
{
marker.scale.z = 1;
}
marker.ns = msg.name;
// correct empty orientation
if ( marker.pose.orientation.w == 0 && marker.pose.orientation.x == 0 &&
marker.pose.orientation.y == 0 && marker.pose.orientation.z == 0 )
{
marker.pose.orientation.w = 1;
}
//normalize orientation
tf::Quaternion marker_orientation( marker.pose.orientation.x, marker.pose.orientation.y,
marker.pose.orientation.z, marker.pose.orientation.w );
marker_orientation.normalize();
marker.pose.orientation.x = marker_orientation.x();
marker.pose.orientation.y = marker_orientation.y();
marker.pose.orientation.z = marker_orientation.z();
marker.pose.orientation.w = marker_orientation.w();
static volatile unsigned id = 0;
marker.id = id++;
marker.ns = msg.name;
// If transparency is disabled, set alpha to 1.0 for all semi-transparent markers
if ( !enable_autocomplete_transparency && marker.color.a > 0.0 )
{
marker.color.a = 1.0;
}
}
}
void makeArrow( const visualization_msgs::InteractiveMarker &msg,
visualization_msgs::InteractiveMarkerControl &control, float pos )
{
visualization_msgs::Marker marker;
// rely on the auto-completion for the correct orientation
marker.pose.orientation = control.orientation;
marker.type = visualization_msgs::Marker::ARROW;
marker.scale.x = msg.scale * 0.15; // aleeper: changed from 0.3 due to Rviz fix
marker.scale.y = msg.scale * 0.25; // aleeper: changed from 0.5 due to Rviz fix
marker.scale.z = msg.scale * 0.2;
assignDefaultColor(marker, control.orientation);
float dist = fabs(pos);
float dir = pos > 0 ? 1 : -1;
float inner = 0.5 * dist;
float outer = inner + 0.4;
marker.points.resize(2);
marker.points[0].x = dir * msg.scale * inner;
marker.points[1].x = dir * msg.scale * outer;
control.markers.push_back( marker );
}
void makeDisc( const visualization_msgs::InteractiveMarker &msg,
visualization_msgs::InteractiveMarkerControl &control, float width )
{
visualization_msgs::Marker marker;
// rely on the auto-completion for the correct orientation
marker.pose.orientation = control.orientation;
marker.type = visualization_msgs::Marker::TRIANGLE_LIST;
marker.scale.x = msg.scale;
marker.scale.y = msg.scale;
marker.scale.z = msg.scale;
assignDefaultColor(marker, control.orientation);
// compute points on a circle in the y-z plane
int steps = 36;
std::vector<geometry_msgs::Point> circle1, circle2;
circle1.reserve(steps);
circle2.reserve(steps);
geometry_msgs::Point v1,v2;
for ( int i=0; i<steps; i++ )
{
float a = float(i)/float(steps) * M_PI * 2.0;
v1.y = 0.5 * cos(a);
v1.z = 0.5 * sin(a);
v2.y = (1+width) * v1.y;
v2.z = (1+width) * v1.z;
circle1.push_back( v1 );
circle2.push_back( v2 );
}
marker.points.resize(6*steps);
std_msgs::ColorRGBA color;
color.r=color.g=color.b=color.a=1;
switch ( control.interaction_mode )
{
case visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS:
{
marker.colors.resize(2*steps);
std_msgs::ColorRGBA base_color = marker.color;
for ( int i=0; i<steps; i++ )
{
int i1 = i;
int i2 = (i+1) % steps;
int i3 = (i+2) % steps;
int p = i*6;
int c = i*2;
marker.points[p+0] = circle1[i1];
marker.points[p+1] = circle2[i2];
marker.points[p+2] = circle1[i2];
marker.points[p+3] = circle1[i2];
marker.points[p+4] = circle2[i2];
marker.points[p+5] = circle2[i3];
float t = 0.6 + 0.4 * (i%2);
color.r = base_color.r * t;
color.g = base_color.g * t;
color.b = base_color.b * t;
marker.colors[c] = color;
marker.colors[c+1] = color;
}
break;
}
case visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE:
{
marker.colors.resize(2*steps);
std_msgs::ColorRGBA base_color = marker.color;
for ( int i=0; i<steps-1; i+=2 )
{
int i1 = i;
int i2 = (i+1) % steps;
int i3 = (i+2) % steps;
int p = i * 6;
int c = i * 2;
marker.points[p+0] = circle1[i1];
marker.points[p+1] = circle2[i2];
marker.points[p+2] = circle1[i2];
marker.points[p+3] = circle1[i2];
marker.points[p+4] = circle2[i2];
marker.points[p+5] = circle1[i3];
color.r = base_color.r * 0.6;
color.g = base_color.g * 0.6;
color.b = base_color.b * 0.6;
marker.colors[c] = color;
marker.colors[c+1] = color;
p += 6;
c += 2;
marker.points[p+0] = circle2[i1];
marker.points[p+1] = circle2[i2];
marker.points[p+2] = circle1[i1];
marker.points[p+3] = circle2[i2];
marker.points[p+4] = circle2[i3];
marker.points[p+5] = circle1[i3];
marker.colors[c] = base_color;
marker.colors[c+1] = base_color;
}
break;
}
default:
for ( int i=0; i<steps; i++ )
{
int i1 = i;
int i2 = (i+1) % steps;
int p = i*6;
marker.points[p+0] = circle1[i1];
marker.points[p+1] = circle2[i1];
marker.points[p+2] = circle1[i2];
marker.points[p+3] = circle2[i1];
marker.points[p+4] = circle2[i2];
marker.points[p+5] = circle1[i2];
}
break;
}
control.markers.push_back(marker);
}
void makeViewFacingButton( const visualization_msgs::InteractiveMarker &msg,
visualization_msgs::InteractiveMarkerControl &control, std::string text )
{
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::VIEW_FACING;
control.independent_marker_orientation = false;
visualization_msgs::Marker marker;
float base_scale = 0.25 * msg.scale;
float base_z = 1.2 * msg.scale;
marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
marker.scale.x = base_scale;
marker.scale.y = base_scale;
marker.scale.z = base_scale;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
marker.pose.position.x = base_scale * -0.1;
marker.pose.position.z = base_z + base_scale * -0.1;
marker.text = text;
control.markers.push_back( marker );
}
void assignDefaultColor(visualization_msgs::Marker &marker, const geometry_msgs::Quaternion &quat )
{
geometry_msgs::Vector3 v;
tf::Quaternion bt_quat( quat.x, quat.y, quat.z, quat.w );
tf::Vector3 bt_x_axis = tf::Matrix3x3(bt_quat) * tf::Vector3(1,0,0);
float x,y,z;
x = fabs(bt_x_axis.x());
y = fabs(bt_x_axis.y());
z = fabs(bt_x_axis.z());
float max_xy = x>y ? x : y;
float max_yz = y>z ? y : z;
float max_xyz = max_xy > max_yz ? max_xy : max_yz;
marker.color.r = x / max_xyz;
marker.color.g = y / max_xyz;
marker.color.b = z / max_xyz;
marker.color.a = 0.5;
}
visualization_msgs::InteractiveMarkerControl makeTitle( const visualization_msgs::InteractiveMarker &msg )
{
visualization_msgs::Marker marker;
marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
marker.scale.x = msg.scale * 0.15;
marker.scale.y = msg.scale * 0.15;
marker.scale.z = msg.scale * 0.15;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
marker.pose.position.z = msg.scale * 1.4;
marker.text = msg.description;
visualization_msgs::InteractiveMarkerControl control;
control.interaction_mode = visualization_msgs::InteractiveMarkerControl::NONE;
control.orientation_mode = visualization_msgs::InteractiveMarkerControl::VIEW_FACING;
control.always_visible = true;
control.markers.push_back( marker );
autoComplete( msg, control );
return control;
}
}
| 29.428251 | 106 | 0.6592 | khairulislam |
b8bd27ca51efb91deee6403b18e3279bfbd28ce8 | 3,492 | cpp | C++ | ecal/core/src/ecal_process_stub.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | ecal/core/src/ecal_process_stub.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | ecal/core/src/ecal_process_stub.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | #include <sys/file.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include "ecal_process_stub.h"
int main(int argc, char** argv)
{
if (argc <= 1)
{
std::cout << "This program is part of eCAL and should not be launched manually." << std::endl;
return EXIT_FAILURE;
}
else if ((argc == 2) && (std::string(argv[1]) == "--version"))
{
// POSIX wants us to provide some output when launching with --version. We also use this to determine the correctnis of this application from other applications.
std::cout << ECAL_PROCESS_STUB_VERSION_STRING << std::endl;
return EXIT_SUCCESS;
}
else if (argc > 3)
{
char* fifo_name = argv[1];
char* lockfile_name = argv[2];
int process_args_start = 3;
// Create and lock the lockfile. The lockfile will automaticall be
// closed (and unlocked) when the execvp was successfull or the
// process exits.
// We have to do this BEFORE writing the FIFO, because after we have
// written the PID to the FIFO, the main process will also attempt
// to lock the lockfile.
int lockfile_fd = open(lockfile_name, O_RDWR | O_CREAT | O_CLOEXEC, 0666);
if (lockfile_fd)
{
if (flock(lockfile_fd, LOCK_EX) == -1)
std::cerr << "Error locking lockfile \"" << lockfile_name << "\": " << strerror(errno) << std::endl;
}
else
{
std::cerr << "Error creating lockfile \"" << lockfile_name << "\": " << strerror(errno) << std::endl;
}
// Open FIFO and send the PID to the eCAL. The other process will wait until
// we send the PID, here. It is important to know that although we have a
// valid PID, we cannot know whether the execvp will be successfull, yet.
// This is were the lockfile becomes important, as it will implicitely be
// unlocked when execvp is successfull.
pid_t process_id = getpid();
int fifo_fd = open(fifo_name, O_WRONLY);
if (fifo_fd >= 0)
{
if(write(fifo_fd, &process_id, sizeof(process_id)) <= 0)
{
std::cerr << "Error writing to FIFO \"" << fifo_name << "\": " << strerror(errno) << std::endl;
}
close(fifo_fd);
}
else
{
std::cerr << "Error opening FIFO \"" << fifo_name << "\": " << strerror(errno) << std::endl;
}
// Now call execvp, which will replace this process by the new one, if
// successfull. In that case, the lockfill will automatically be closed and
// unlocked.
const char** c_argv = new const char*[argc - process_args_start + 1];
for (int i = 0; i < argc - process_args_start; i++)
{
c_argv[i] = argv[i + process_args_start];
}
c_argv[argc - process_args_start] = nullptr;
execvp(c_argv[0], (char**)c_argv);
// ERROR! >> If we have ever reached this code, execvp has not succeeded.
// Now we have to tell the external main process via the lockfile. We simply
// write our errno to that file and then exit. This will release the lock
// and let the main process read the errno.
std::cerr << "Error executing process " << c_argv[0] << ": " << strerror(errno);
int errno_int = errno;
size_t written_bytes = write(lockfile_fd, &errno_int, sizeof(errno_int));
if(written_bytes == 0)
{
std::cerr << "Error writing errno to file \"" << lockfile_name << "\": " << strerror(errno);
}
delete c_argv;
return EXIT_FAILURE;
}
else
{
return EXIT_FAILURE;
}
}
| 34.92 | 165 | 0.625716 | jonico |
b8be8de72b7b10648fe75e002dc639285ea5ece9 | 4,978 | cpp | C++ | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "BoundingBox.h"
BoundingBox::BoundingBox(glm::vec3 min, glm::vec3 max)
{
m_Params[0] = min;
m_Params[1] = max;
m_Centre = (min + max) * 0.5f;
//Split(0);
}
BoundingBox::~BoundingBox()
{
}
void BoundingBox::Split(int level)
{
//if (level == MAX_DEPTH) return;
glm::vec3 min;
glm::vec3 max;
//if (m_Triangles.size() > MAX_TRIANGLES_PER_BOX)
//{
float epsilon = 1e-1;
BoundingBox* temp[NUMBER_OF_CHILDREN];
//Make children
temp[0]= new BoundingBox(this->m_Params[0] - epsilon, this->m_Centre + epsilon);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Centre.z + epsilon);
temp[1] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon);
temp[2] = new BoundingBox(min, max);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon);
temp[3] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z- epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon);
temp[4] = new BoundingBox(min, max);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon);
temp[5] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Centre.z - epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Params[1].z + epsilon);
temp[6] = new BoundingBox(min, max);
temp[7] = new BoundingBox(this->m_Centre - epsilon, this->m_Params[1] + epsilon);
//if (level < MAX_DEPTH) {
for (int i = 0; i < NUMBER_OF_CHILDREN; i++) {
for (int j = 0; j < m_Triangles.size(); j++) {
temp[i]->Add(m_Triangles[j]); //Try and add this triangle -> push_back(t)
if (j == m_Triangles.size() - 1) {
if (temp[i]->m_Triangles.size() <= 0) {
delete temp[i];
break;
}
if (temp[i]->m_Triangles.size() > MAX_TRIANGLES_PER_BOX)
{
temp[i]->Split(0);
temp[i]->m_Triangles.clear();
children.push_back(temp[i]);
break;
}
children.push_back(temp[i]);
}
}
}
//m_Triangles.clear();
/*for (int i = 0; i < NUMBER_OF_CHILDREN; i++) {
if()
}*/
/* for (int i = 0; i < children.size(); i++) {
if (this->children[i]->m_Triangles.size() > 0)
{
this->children[i]->Split(level + 1);
}
}*/
//}
//}
//else
//{
//// if (m_Triangles.size() == 0) delete this;
// WARN("Triangles On leaf: {0}", m_Triangles.size());
// isLeaf = true;
//}
}
bool BoundingBox::Intersect(Ray & ray)
{
float txmin, txmax, tymin, tymax, tzmin, tzmax;
txmin = (m_Params[ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x;
txmax = (m_Params[1 - ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x;
tymin = (m_Params[ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y;
tymax = (m_Params[1 - ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y;
if (txmin > txmax) swap(txmin, txmax);
if (tymin > tymax) swap(tymin, tymax);
if ((txmin > tymax) || (tymin > txmax))
return false;
if (tymin > txmin)
txmin = tymin;
if (tymax < txmax)
txmax = tymax;
tzmin = (m_Params[ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z;
tzmax = (m_Params[1 - ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z;
if (tzmin > tzmax) swap(tzmin, tzmax);
if ((txmin > tzmax) || (tzmin > txmax))
return false;
if (tzmin > txmin)
txmin = tzmin;
if (tzmax < txmax)
txmax = tzmax;
bool intersect = false;
if (children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
this->children[i]->Intersect(ray);
}
}
else
{
for (int i = 0; i < m_Triangles.size(); i++) {
if (m_Triangles[i]->Intersect(ray))
{
intersect = true;
}
}
}
return intersect;
}
void BoundingBox::swap(float& first, float& second)
{
float temp;
temp = first;
first = second;
second = temp;
}
void BoundingBox::Add(Triangle * t)
{
if (IsVertexInside(t->A()) || IsVertexInside(t->B()) || IsVertexInside(t->C()))
{
m_Triangles.push_back(t);
}
}
bool BoundingBox::IsVertexInside(const glm::vec3& vert)
{
if (vert.x >= m_Params[0].x &&
vert.y >= m_Params[0].y &&
vert.z >= m_Params[0].z &&
vert.x <= m_Params[1].x &&
vert.y <= m_Params[1].y &&
vert.z <= m_Params[1].z )
{
return true;
}
return false;
}
| 24.766169 | 108 | 0.608076 | cristi191096 |
b8bedb543fcb1bdf3fe9fd5f07c3dd18bbb41276 | 6,763 | cpp | C++ | pyschedcl/passes/feature_pass/tests/mv/src/main.cpp | sarthak-chakraborty/pyschedcl-concurrent | a9fe435b79ed429bfcbee27e6f90a2b67c3b41da | [
"MIT"
] | null | null | null | pyschedcl/passes/feature_pass/tests/mv/src/main.cpp | sarthak-chakraborty/pyschedcl-concurrent | a9fe435b79ed429bfcbee27e6f90a2b67c3b41da | [
"MIT"
] | null | null | null | pyschedcl/passes/feature_pass/tests/mv/src/main.cpp | sarthak-chakraborty/pyschedcl-concurrent | a9fe435b79ed429bfcbee27e6f90a2b67c3b41da | [
"MIT"
] | 1 | 2020-12-10T17:41:20.000Z | 2020-12-10T17:41:20.000Z | #include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include <string.h>
#include <stdio.h>
#include "Buffer.h"
#include "Device.h"
#include "Event.h"
#include "Kernel.h"
#include "Platform.h"
#include "Program.h"
#include "Queue.h"
#include "SystemConfiguration.h"
#include "bench_support.h"
//-----------------------------------------------------------------------------
constexpr int SIZE = 512;
std::vector<size_t> globalWorkSize = { SIZE };
std::vector<size_t> localWorkSize = { 128 };
const std::string kernelFileName = "mv.cl";
std::string kernelName = "";
//-----------------------------------------------------------------------------
void initialization(int argNumber, char **arguments);
void hostMemoryAlloc();
void deviceMemoryAlloc();
void setKernelArguments();
void enqueWriteCommands(Queue &queue);
void enqueReadCommands(Queue &queue);
void run(Queue &queue);
void freeMemory();
void setNDRangeSizes();
void verify();
//-----------------------------------------------------------------------------
// Runtime components.
Platform *platform;
Kernel *kernel;
// Host data.
std::vector<float> inputMatrixHost;
std::vector<float> inputVectorHost;
std::vector<float> outputVectorHost;
// Device data.
Buffer *inputMatrix = nullptr;
Buffer *inputVector = nullptr;
Buffer *outputVector = nullptr;
cl_int *width = nullptr;
cl_int *height = nullptr;
// Device.
int PLATFORM_ID = 0;
int DEVICE_ID = 0;
//-----------------------------------------------------------------------------
int main(int argNumber, char **arguments) {
initialization(argNumber, arguments);
getPlatformDevice(&PLATFORM_ID, &DEVICE_ID);
platform = new Platform(PLATFORM_ID);
Context *context = platform->getContext();
Device device = platform->getDevice(DEVICE_ID);
setNDRangeSizes();
std::cout << "Device name: " << device.getName() << "\n";
hostMemoryAlloc();
deviceMemoryAlloc();
std::string kernelFile = KERNEL_DIR + kernelFileName;
Program program(context, kernelFile);
Queue queue(*context, device, Queue::EnableProfiling);
enqueWriteCommands(queue);
if (!program.build(device)) {
std::cout << "Error building the program: \n";
std::cout << program.getBuildLog(device) << "\n";
return 1;
}
kernel = program.createKernel(kernelName.c_str());
setKernelArguments();
run(queue);
enqueReadCommands(queue);
verify();
freeMemory();
return 0;
}
//-----------------------------------------------------------------------------
void initialization(int argNumber, char **arguments) {
assert(globalWorkSize.size() == localWorkSize.size() &&
"Mismatching local and global work sizes");
if (argNumber != 2) {
std::cerr << "Must specify kernel name\n";
exit(1);
}
kernelName = std::string(arguments[1]);
}
//-----------------------------------------------------------------------------
void setNDRangeSizes() {
std::vector<size_t> newGlobalWorkSize(globalWorkSize.size(), 0);
std::vector<size_t> newLocalWorkSize(localWorkSize.size(), 0);
getNewSizes(globalWorkSize.data(), localWorkSize.data(),
newGlobalWorkSize.data(), newLocalWorkSize.data(),
kernelName.c_str(), globalWorkSize.size());
globalWorkSize.clear();
localWorkSize.clear();
std::copy(newGlobalWorkSize.begin(), newGlobalWorkSize.end(),
std::back_inserter(globalWorkSize));
std::copy(newLocalWorkSize.begin(), newLocalWorkSize.end(),
std::back_inserter(localWorkSize));
}
//-----------------------------------------------------------------------------
void freeMemory() {
delete kernel;
delete platform;
delete width;
delete height;
}
//-----------------------------------------------------------------------------
void hostMemoryAlloc() {
width = new cl_int(globalWorkSize[0]);
height = new cl_int(globalWorkSize[0]);
std::random_device randomDevice;
std::mt19937_64 gen(randomDevice());
std::uniform_real_distribution<float> distribution;
inputVectorHost.assign(*width, 0.f);
inputMatrixHost.assign(*width * (*height), 0.f);
outputVectorHost.assign(*height, 0.f);
std::generate_n(inputVectorHost.begin(), *width,
[&] { return (distribution(gen)); });
std::generate_n(inputMatrixHost.begin(), *width * (*height),
[&] { return (distribution(gen)); });
}
//-----------------------------------------------------------------------------
void deviceMemoryAlloc() {
inputVector = new Buffer(*(platform->getContext()), Buffer::ReadOnly,
inputVectorHost.size() * sizeof(float), nullptr);
inputMatrix = new Buffer(*(platform->getContext()), Buffer::ReadOnly,
inputMatrixHost.size() * sizeof(float), nullptr);
outputVector = new Buffer(*(platform->getContext()), Buffer::WriteOnly,
outputVectorHost.size() * sizeof(float), nullptr);
}
//-----------------------------------------------------------------------------
void enqueWriteCommands(Queue &queue) {
queue.writeBuffer(*inputVector, inputVectorHost.size() * sizeof(float),
(void *)inputVectorHost.data());
queue.writeBuffer(*inputMatrix, inputMatrixHost.size() * sizeof(float),
(void *)inputMatrixHost.data());
queue.finish();
}
//-----------------------------------------------------------------------------
void enqueReadCommands(Queue &queue) {
queue.readBuffer(*outputVector, outputVectorHost.size() * sizeof(float),
(void *)outputVectorHost.data());
queue.finish();
}
//-----------------------------------------------------------------------------
void setKernelArguments() {
kernel->setArgument(0, *inputMatrix);
kernel->setArgument(1, *inputVector);
kernel->setArgument(2, sizeof(cl_uint), (void *)width);
kernel->setArgument(3, sizeof(cl_uint), (void *)height);
kernel->setArgument(4, *outputVector);
if(kernelName == "MatVecMulCoalesced0") {
kernel->setArgument(5, localWorkSize[0] * sizeof(float), nullptr);
}
}
//-----------------------------------------------------------------------------
void run(Queue &queue) {
queue.run(*kernel, globalWorkSize.size(), 0, globalWorkSize.data(),
localWorkSize.data());
queue.finish();
}
//-----------------------------------------------------------------------------
void verify() {
for (int row = 0; row < 32; ++row) {
float result = 0.0f;
for (int column = 0; column < *width; ++column) {
result += inputMatrixHost[row * (*width) + column] * inputVectorHost[column];
}
std::cout << outputVectorHost[row] << " " << result << "\n";
// if (abs(outputVectorHost[row] - result) >= 0.001f) {
// std::cout << "Error\n";
// exit(1);
// }
}
}
| 32.204762 | 83 | 0.560698 | sarthak-chakraborty |
b8bf8b4ada3e129d4729be4ae6939433e0c5d4b3 | 216 | cpp | C++ | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | #include <negli/NeuralGliderGame.hpp>
#include <negli/ConsolePrint.hpp>
using namespace negli;
int main()
{
NeuralGliderGame game = NeuralGliderGame(20, 20, 5, 5);
negli::printGame(game);
return 0;
}
| 15.428571 | 59 | 0.699074 | DomonkosSuranyi |
b8bfb109ed59d7e98bbe354fd1fc27e4ab7e8636 | 4,611 | cpp | C++ | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | #include <iostream>
#include "util.hpp"
#include "tsp.hpp"
#include "nearest_neighbor.hpp"
#include "nearest_insertion.hpp"
#include "farthest_insertion.hpp"
#include "double_mst.hpp"
#include "greedy.hpp"
#include "quick_boruvka.hpp"
#include "two_opt.hpp"
// main routine
int main(int argc, char **argv){
if(argc<2){
std::cerr << "Error: need input filename." << std::endl;
return 1;
}
// input
{
std::string s(argv[1]);
s = "in/" + s + ".in";
TSP::input(s);
}
// nearest neighbor
{
Util::resettime();
Util::timestamp("Nearest Neighbor");
TSP::Tour tour_nn = TSP::NearestNeighbor::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_nn.out";
TSP::output(tour_nn,s);
tour_nn.clear();
}
// nearest insertion
{
Util::resettime();
Util::timestamp("Nearest Insertion");
TSP::Tour tour_ni = TSP::NearestInsertion::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_ni.out";
TSP::output(tour_ni,s);
tour_ni.clear();
}
// farthest insertion
{
Util::resettime();
Util::timestamp("Farthest Insertion");
TSP::Tour tour_fi = TSP::FarthestInsertion::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_fi.out";
TSP::output(tour_fi,s);
tour_fi.clear();
}
// double mst
{
Util::resettime();
Util::timestamp("Double Minimum Spanning Tree");
TSP::Tour tour_dmst = TSP::DoubleMST::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_dmst.out";
TSP::output(tour_dmst,s);
tour_dmst.clear();
}
// greedy
{
Util::resettime();
Util::timestamp("Greedy");
TSP::Tour tour_gr = TSP::Greedy::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_gr.out";
TSP::output(tour_gr,s);
tour_gr.clear();
}
// quick boruvka
{
Util::resettime();
Util::timestamp("Quick Boruvka");
TSP::Tour tour_qb = TSP::QuickBoruvka::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_qb.out";
TSP::output(tour_qb,s);
tour_qb.clear();
}
// nearest neighbor & 2-opt
{
Util::resettime();
Util::timestamp("Nearest Neighbor & 2-opt");
TSP::Tour tour_nn_2opt = TSP::NearestNeighbor::calc();
Util::timestamp("End(NN)");
TSP::TwoOpt::improve(tour_nn_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_nn_2opt.out";
TSP::output(tour_nn_2opt,s);
tour_nn_2opt.clear();
}
// nearest insertion & 2-opt
{
Util::resettime();
Util::timestamp("Nearest Insertion & 2-opt");
TSP::Tour tour_ni_2opt = TSP::NearestInsertion::calc();
Util::timestamp("End(NI)");
TSP::TwoOpt::improve(tour_ni_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_ni_2opt.out";
TSP::output(tour_ni_2opt,s);
tour_ni_2opt.clear();
}
// farthest insertion & 2-opt
{
Util::resettime();
Util::timestamp("Farthest Insertion & 2-opt");
TSP::Tour tour_fi_2opt = TSP::FarthestInsertion::calc();
Util::timestamp("End(FI)");
TSP::TwoOpt::improve(tour_fi_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_fi_2opt.out";
TSP::output(tour_fi_2opt,s);
tour_fi_2opt.clear();
}
// double mst & 2-opt
{
Util::resettime();
Util::timestamp("Double Minimum Spanning Tree & 2-opt");
TSP::Tour tour_dmst_2opt = TSP::DoubleMST::calc();
Util::timestamp("End(DMST)");
TSP::TwoOpt::improve(tour_dmst_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_dmst_2opt.out";
TSP::output(tour_dmst_2opt,s);
tour_dmst_2opt.clear();
}
// greedy & 2-opt
{
Util::resettime();
Util::timestamp("Greedy & 2-opt");
TSP::Tour tour_gr_2opt = TSP::Greedy::calc();
Util::timestamp("End(GR)");
TSP::TwoOpt::improve(tour_gr_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_gr_2opt.out";
TSP::output(tour_gr_2opt,s);
tour_gr_2opt.clear();
}
// quick boruvka & 2-opt
{
Util::resettime();
Util::timestamp("Quick Boruvka & 2-opt");
TSP::Tour tour_qb_2opt = TSP::QuickBoruvka::calc();
Util::timestamp("End(QB)");
TSP::TwoOpt::improve(tour_qb_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_qb_2opt.out";
TSP::output(tour_qb_2opt,s);
tour_qb_2opt.clear();
}
TSP::halt();
return 0;
}
| 24.657754 | 60 | 0.589243 | n-ari |
b8c1d6eaf8bd946b16d2f0fffc01aea65bc662a3 | 370 | hpp | C++ | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** rtype
** File description:
** Created by seb,
*/
#pragma once
namespace ecs {namespace component {
struct Drawable {
Drawable() {
this->layer = 0;
this->visible = false;
}
Drawable(unsigned int layer, bool visible) {
this->layer = layer;
this->visible = visible;
}
unsigned int layer;
bool visible;
};
}} | 16.086957 | 46 | 0.627027 | Pierre-Narcisi |
fef74a3ee35c0682f94ffc385d97330afa35efc7 | 3,442 | cpp | C++ | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | 2 | 2021-07-29T02:02:33.000Z | 2022-03-02T08:56:52.000Z | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | null | null | null | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include "test_op.h"
int create_test_clip_node(graph_t graph, const char* input_name, const char* node_name, int data_type, int layout, int n, int c, int h, int w)
{
(void)layout;
(void)n;
(void)c;
(void)h;
(void)w;
/* create the test node */
struct node* test_node = (struct node*)create_graph_node(graph, node_name, "Clip");
tensor_t input_tensor = get_graph_tensor(graph, input_name);
if (NULL == input_tensor)
{
fprintf(stderr, "create test node failed.\n");
return -1;
}
/* input tensors of test node */
set_node_input_tensor(test_node, 0, input_tensor);
/* output tensors of test node */
tensor_t output_tensor = create_graph_tensor(graph, node_name, data_type);
set_node_output_tensor(test_node, 0, output_tensor, TENSOR_TYPE_VAR);
return 0;
}
float input_fp32[5] = {-3.0f, 3.0f, 8.0f, 1.0f, -2.0f};
float reference_out[5] = {0.0f, 3.0f, 6.0f, 1.0f, 0.0f};
int main(int argc, char* argv[])
{
int n = 1, c = 1, h = 5, w = 1;
const char* test_node_name = "clip";
int data_type = TENGINE_DT_FP32;
int layout = TENGINE_LAYOUT_NCHW;
// init
int ret = test_graph_init();
if (0 != ret)
fprintf(stderr, "Tengine init failed.\n");
// create
graph_t graph = create_tensorrt_test_graph(test_node_name, data_type, layout, n, c, h, w, &create_test_clip_node);
if (NULL == graph)
return -1;
set_log_level(LOG_INFO);
dump_graph(graph);
// set quantize params
struct tensor* input_tensor = (struct tensor*)get_graph_input_tensor(graph, 0, 0);
struct tensor* output_tensor = (struct tensor*)get_graph_output_tensor(graph, 0, 0);
// set input data
set_tensor_buffer(input_tensor, input_fp32, 5 * 4);
// graph run
ret = test_graph_run(graph);
if (0 != ret)
{
fprintf(stderr, "Run graph error. ERRNO: %d.\n", ret);
test_graph_release(graph);
return -1;
}
// get output and dequant
float* output_data = (float*)output_tensor->data;
int output_size = output_tensor->elem_num;
// check the result
ret = 0;
for (int i = 0; i < output_size; i++)
{
if (fabsf(output_data[i] - reference_out[i]) > 0.1)
{
fprintf(stderr, "index:%d, a:%f, b:%f\n", i, output_data[i], reference_out[i]);
ret = -1;
}
}
if (ret == 0)
fprintf(stderr, "test pass.\n");
else
fprintf(stderr, "test failed.\n");
// exit
test_graph_release(graph);
return ret;
}
| 28.446281 | 142 | 0.647298 | sunnycase |
fef932d3d5f0b6ea85389a95dfd62345c79ead4f | 1,368 | cpp | C++ | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | //No of islands (only 4 neighbours)
//Time: O(M*N)
//Space: O(M*N)
#include <bits/stdc++.h>
using namespace std;
bool isInside(int n, int m, int i, int j)
{
if(i<0||j<0||i>n-1||j>m-1) return false;
return true;
}
void dfs(vector<vector<char>>&grid, vector<vector<bool>>&vis, int n, int m, int i, int j)
{
vis[i][j]=true;
int dx[] = { 0, -1, 0, 1 };
int dy[] = { -1, 0, 1, 0 };
for(int k=0;k<4;k++)
{
int x=dx[k]+i;
int y=dy[k]+j;
if(isInside(n,m,x,y) && !vis[x][y] && grid[x][y]=='X') dfs(grid,vis,n,m,x,y);
}
return;
}
int solve(vector<vector<char>>& grid)
{
int n=grid.size();
int m=grid[0].size();
int ans=0;
vector<vector<bool>>vis(n,vector<bool>(m,false));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(!vis[i][j] && grid[i][j]=='X')
{
dfs(grid,vis,n,m,i,j);
ans++;
}
}
}
return ans;
}
int main()
{
int n,m;
cin>>n>>m;
vector<vector<char>>grid(n,vector<char>(m));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>grid[i][j];
}
}
int ans = solve(grid);
cout<<ans;
}
| 22.8 | 93 | 0.407164 | diivyya |
fefa85d9d309040b173f27a6da35461b91f70102 | 1,353 | hpp | C++ | adbase/Logging/AsyncLogging.hpp | weiboad/adbase | d37ed32b55da24f7799be286c860e280ee0c786a | [
"Apache-2.0"
] | 62 | 2017-02-15T11:36:46.000Z | 2022-03-14T09:11:10.000Z | adbase/Logging/AsyncLogging.hpp | AraHaan/adbase | d37ed32b55da24f7799be286c860e280ee0c786a | [
"Apache-2.0"
] | 5 | 2017-02-21T05:32:14.000Z | 2017-05-21T13:15:07.000Z | adbase/Logging/AsyncLogging.hpp | AraHaan/adbase | d37ed32b55da24f7799be286c860e280ee0c786a | [
"Apache-2.0"
] | 22 | 2017-02-16T02:11:25.000Z | 2020-02-12T18:12:44.000Z | #if !defined ADBASE_LOGGING_HPP_
# error "Not allow include this header."
#endif
#ifndef ADBASE_UTILITY_ASYNCLOGGING_HPP_
#define ADBASE_UTILITY_ASYNCLOGGING_HPP_
#include <thread>
#include <condition_variable>
#include <vector>
namespace adbase {
/**
* @addtogroup logging adbase::Logging
*/
/*@{*/
class AsyncLogging {
public:
AsyncLogging(const std::string& basename,
size_t rollSize,
int flushInterval = 3);
AsyncLogging(const AsyncLogging&) = delete;
void operator=(const AsyncLogging&) = delete;
~AsyncLogging() {
if (_running) {
stop();
}
}
void append(const char* logline, int len);
void start();
void stop() {
_running = false;
_cond.notify_one();
}
static void deleteThread(std::thread *t);
private:
void threadFunc(void *data);
typedef adbase::detail::FixedBuffer<adbase::detail::kLargeBuffer> Buffer;
typedef std::unique_ptr<Buffer> BufferPtr;
typedef std::vector<BufferPtr> BufferVector;
const int _flushInterval;
bool _running;
std::string _basename;
size_t _rollSize;
mutable std::mutex _mut;
std::condition_variable _cond;
BufferPtr _currentBuffer;
BufferPtr _nextBuffer;
BufferVector _buffers;
typedef std::unique_ptr<std::thread, decltype(&AsyncLogging::deleteThread)> ThreadPtr;
typedef std::vector<ThreadPtr> ThreadPool;
ThreadPool _threads;
};
/*@}*/
}
#endif
| 19.608696 | 87 | 0.733186 | weiboad |
fefece9337b6ae3bafc108b2e17cdbdebe7a00da | 4,485 | cpp | C++ | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 23 | 2020-11-18T00:27:57.000Z | 2022-03-20T17:50:14.000Z | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 37 | 2020-10-19T16:15:27.000Z | 2022-03-20T12:21:22.000Z | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 40 | 2020-10-14T15:26:13.000Z | 2022-02-21T12:41:44.000Z | /*
The MIT License (MIT)
Copyright (c) 2021 Lancaster University.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "MicroBit.h"
#include "Tests.h"
extern MicroBit uBit;
MicroBitUARTService *uart;
// we use events abd the 'connected' variable to keep track of the status of the Bluetooth connection
void onConnected(MicroBitEvent)
{
uBit.display.print("C");
}
void onDisconnected(MicroBitEvent)
{
uBit.display.print("D");
}
void onDelim(MicroBitEvent)
{
ManagedString r = uart->readUntil("\r\n");
uart->send(r);
}
void ble_test()
{
// Configuration Tips
//
// An example codal.json is provided in the root directory: codal.ble.json
// Rename codal.ble.json to codal.json to use this BLE sample
//
// codal.json contains various Bluetooth related properties some of which are explained here:
//
// "SOFTDEVICE_PRESENT": 1 Determines whether the build contains softdevice
// "DEVICE_BLE": 1 Determines whether BLE is enabled
// "MICROBIT_BLE_ENABLED" : 1 Determines whether BLE is enabled
// "MICROBIT_BLE_PAIRING_MODE": 1 Determines whether Pairing Mode is enabled
// "MICROBIT_BLE_DFU_SERVICE": 1 Determines whether the Nordic DFU Service is enabled
// "MICROBIT_BLE_DEVICE_INFORMATION_SERVICE": 1 Determines whether the DIS is enabled
// "MICROBIT_BLE_EVENT_SERVICE" : 1, Determines whether the Event Service is enabled
// "MICROBIT_BLE_PARTIAL_FLASHING" : 0 Determines whether Partial Flashing is enabled (Needs MakeCode/Python)
// "MICROBIT_BLE_SECURITY_LEVEL": "SECURITY_MODE_ENCRYPTION_WITH_MITM" Determines security mode
//
// Options for MICROBIT_BLE_SECURITY_LEVEL are:
// SECURITY_MODE_ENCRYPTION_WITH_MITM, enables pairing with a passcode
// SECURITY_MODE_ENCRYPTION_NO_MITM, enables pairing without a passcode
// SECURITY_MODE_ENCRYPTION_OPEN_LINK, pairing is no required
//
// A cunning code to indicate during start-up the particular Bluetooth configuration in the build
//
// SERVICE CODES
// A: Accelerometer Service
// B: Button Service
// D: Device Information Service
// E: Event Service
// F: DFU Service
// I: IO Pin Service
// L: LED Service
// M: Magnetometer Service
// T: Temperature Service
// U: UART Service
//
// P: PASSKEY
// J: Just Works
// N: No Pairing Required
// Services/Pairing Config/Power Level
uBit.display.scroll("BLE ABDILMTU/P");
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);
uBit.messageBus.listen(MICROBIT_ID_BLE_UART, MICROBIT_UART_S_EVT_DELIM_MATCH, onDelim);
new MicroBitAccelerometerService(*uBit.ble, uBit.accelerometer);
new MicroBitButtonService(*uBit.ble);
new MicroBitIOPinService(*uBit.ble, uBit.io);
new MicroBitLEDService(*uBit.ble, uBit.display);
new MicroBitMagnetometerService(*uBit.ble, uBit.compass);
new MicroBitTemperatureService(*uBit.ble, uBit.thermometer);
uart = new MicroBitUARTService(*uBit.ble, 32, 32);
uart->eventOn("\r\n");
// If main exits, there may still be other fibers running or registered event handlers etc.
// Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
// sit in the idle task forever, in a power efficient sleep.
release_fiber();
}
| 38.663793 | 113 | 0.733333 | danielstl |
feff010f88248ab5fc0827a993aeb88f49ad90ee | 438 | cpp | C++ | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | /*
* Copyright 2021 Marzocchi Alessandro
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "port.h"
using namespace HFMidi;
Port::Port()
{
}
void Port::sendEvent(const QByteArray &data)
{
sendData(data);
}
bool Port::sendData(const QByteArray &data)
{
Q_UNUSED(data);
return false;
}
void Port::receivedData(const QByteArray &data)
{
// qDebug()<<data.toHex();
emit midiEvent(data);
}
| 14.6 | 71 | 0.696347 | hefsoftware |
fefffc3af6d878593c69fee7959c556962f63749 | 660 | cpp | C++ | 02. Algorithms/09. Dynamic Programming/006. House Robber II/code.cpp | dr490n1s3d-3d8/Data-Structures-and-Algorithms | f2bba2d836f448cc0cd894c4e9791819910571d5 | [
"MIT"
] | 1 | 2022-03-06T13:58:27.000Z | 2022-03-06T13:58:27.000Z | 02. Algorithms/09. Dynamic Programming/006. House Robber II/code.cpp | dr490n1s3d-3d8/Data-Structures-and-Algorithms | f2bba2d836f448cc0cd894c4e9791819910571d5 | [
"MIT"
] | null | null | null | 02. Algorithms/09. Dynamic Programming/006. House Robber II/code.cpp | dr490n1s3d-3d8/Data-Structures-and-Algorithms | f2bba2d836f448cc0cd894c4e9791819910571d5 | [
"MIT"
] | 1 | 2022-03-24T15:25:34.000Z | 2022-03-24T15:25:34.000Z | class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size() ;
if(n==1)
return nums[0] ;
if(n==2)
return max(nums[0],nums[1]) ;
int dp1[n-1] ;
dp1[0] = nums[0] ;
dp1[1] = max(nums[0],nums[1]) ;
for(int i=2;i<n-1;i++) {
dp1[i] = max(dp1[i-1],nums[i]+dp1[i-2]);
}
int dp2[n-1] ;
dp2[0] = nums[1] ;
dp2[1] = max(nums[2],nums[1]) ;
for(int i=2;i<n-1;i++) {
dp2[i] = max(dp2[i-1],nums[i+1]+dp2[i-2]);
}
return max(dp1[n-2],dp2[n-2]) ;
}
}; | 23.571429 | 54 | 0.369697 | dr490n1s3d-3d8 |
3a0142aad30569e9bf55c812144b062b67a7119d | 15,475 | cc | C++ | Dependencies/Grpc/Cpp/proto/gRPCCommunication/GrpcStepInput.pb.cc | DNAI-io/RL-Agent | 0f4df4af4b7617bf010aafc3f40349db2d14d93e | [
"MIT"
] | null | null | null | Dependencies/Grpc/Cpp/proto/gRPCCommunication/GrpcStepInput.pb.cc | DNAI-io/RL-Agent | 0f4df4af4b7617bf010aafc3f40349db2d14d93e | [
"MIT"
] | null | null | null | Dependencies/Grpc/Cpp/proto/gRPCCommunication/GrpcStepInput.pb.cc | DNAI-io/RL-Agent | 0f4df4af4b7617bf010aafc3f40349db2d14d93e | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/gRPCCommunication/GrpcStepInput.proto
#include "proto/gRPCCommunication/GrpcStepInput.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
namespace gRPCCommunication {
class GrpcStepInputDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GrpcStepInput> _instance;
} _GrpcStepInput_default_instance_;
} // namespace gRPCCommunication
static void InitDefaultsscc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::gRPCCommunication::_GrpcStepInput_default_instance_;
new (ptr) ::gRPCCommunication::GrpcStepInput();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::gRPCCommunication::GrpcStepInput::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto[1];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::gRPCCommunication::GrpcStepInput, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::gRPCCommunication::GrpcStepInput, actions_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::gRPCCommunication::GrpcStepInput)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::gRPCCommunication::_GrpcStepInput_default_instance_),
};
const char descriptor_table_protodef_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto[] =
"\n+proto/gRPCCommunication/GrpcStepInput."
"proto\022\021gRPCCommunication\" \n\rGrpcStepInpu"
"t\022\017\n\007actions\030\001 \003(\002b\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_deps[1] = {
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_sccs[1] = {
&scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_once;
static bool descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = {
&descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_initialized, descriptor_table_protodef_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, "proto/gRPCCommunication/GrpcStepInput.proto", 106,
&descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_once, descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_sccs, descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto::offsets,
file_level_metadata_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, 1, file_level_enum_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, file_level_service_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto), true);
namespace gRPCCommunication {
// ===================================================================
void GrpcStepInput::InitAsDefaultInstance() {
}
class GrpcStepInput::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GrpcStepInput::kActionsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GrpcStepInput::GrpcStepInput()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:gRPCCommunication.GrpcStepInput)
}
GrpcStepInput::GrpcStepInput(const GrpcStepInput& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
actions_(from.actions_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:gRPCCommunication.GrpcStepInput)
}
void GrpcStepInput::SharedCtor() {
}
GrpcStepInput::~GrpcStepInput() {
// @@protoc_insertion_point(destructor:gRPCCommunication.GrpcStepInput)
SharedDtor();
}
void GrpcStepInput::SharedDtor() {
}
void GrpcStepInput::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const GrpcStepInput& GrpcStepInput::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto.base);
return *internal_default_instance();
}
void GrpcStepInput::Clear() {
// @@protoc_insertion_point(message_clear_start:gRPCCommunication.GrpcStepInput)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
actions_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* GrpcStepInput::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated float actions = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(mutable_actions(), ptr, ctx);
CHK_(ptr);
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13) {
add_actions(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr));
ptr += sizeof(float);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool GrpcStepInput::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:gRPCCommunication.GrpcStepInput)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated float actions = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive<
float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT>(
input, this->mutable_actions())));
} else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (13 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT>(
1, 10u, input, this->mutable_actions())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:gRPCCommunication.GrpcStepInput)
return true;
failure:
// @@protoc_insertion_point(parse_failure:gRPCCommunication.GrpcStepInput)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void GrpcStepInput::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:gRPCCommunication.GrpcStepInput)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated float actions = 1;
if (this->actions_size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(1, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_actions_cached_byte_size_.load(
std::memory_order_relaxed));
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatArray(
this->actions().data(), this->actions_size(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:gRPCCommunication.GrpcStepInput)
}
::PROTOBUF_NAMESPACE_ID::uint8* GrpcStepInput::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:gRPCCommunication.GrpcStepInput)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated float actions = 1;
if (this->actions_size() > 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray(
1,
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray(
_actions_cached_byte_size_.load(std::memory_order_relaxed),
target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
WriteFloatNoTagToArray(this->actions_, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:gRPCCommunication.GrpcStepInput)
return target;
}
size_t GrpcStepInput::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:gRPCCommunication.GrpcStepInput)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated float actions = 1;
{
unsigned int count = static_cast<unsigned int>(this->actions_size());
size_t data_size = 4UL * count;
if (data_size > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size));
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size);
_actions_cached_byte_size_.store(cached_size,
std::memory_order_relaxed);
total_size += data_size;
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void GrpcStepInput::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:gRPCCommunication.GrpcStepInput)
GOOGLE_DCHECK_NE(&from, this);
const GrpcStepInput* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GrpcStepInput>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:gRPCCommunication.GrpcStepInput)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:gRPCCommunication.GrpcStepInput)
MergeFrom(*source);
}
}
void GrpcStepInput::MergeFrom(const GrpcStepInput& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:gRPCCommunication.GrpcStepInput)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
actions_.MergeFrom(from.actions_);
}
void GrpcStepInput::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:gRPCCommunication.GrpcStepInput)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GrpcStepInput::CopyFrom(const GrpcStepInput& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:gRPCCommunication.GrpcStepInput)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GrpcStepInput::IsInitialized() const {
return true;
}
void GrpcStepInput::Swap(GrpcStepInput* other) {
if (other == this) return;
InternalSwap(other);
}
void GrpcStepInput::InternalSwap(GrpcStepInput* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
actions_.InternalSwap(&other->actions_);
}
::PROTOBUF_NAMESPACE_ID::Metadata GrpcStepInput::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace gRPCCommunication
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::gRPCCommunication::GrpcStepInput* Arena::CreateMaybeMessage< ::gRPCCommunication::GrpcStepInput >(Arena* arena) {
return Arena::CreateInternal< ::gRPCCommunication::GrpcStepInput >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 41.71159 | 236 | 0.765428 | DNAI-io |
3a020dd3dd9621e2d1d76204c4720f5446e4407f | 2,338 | cpp | C++ | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The WebNN-native Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "ops/Pad.h"
#include "Utils.h"
namespace node::op {
Napi::Value Pad::Build(const Napi::CallbackInfo& info, wnn::GraphBuilder builder) {
// Operand pad(Operand input, Operand padding, optional PadOptions options = {});
WEBNN_NODE_ASSERT(info.Length() == 2 || info.Length() == 3,
"The number of arguments is invalid.");
std::vector<napi_value> args;
wnn::Operand input;
WEBNN_NODE_ASSERT(GetOperand(info[0], input, args), "The input parameter is invalid.");
wnn::Operand padding;
WEBNN_NODE_ASSERT(GetOperand(info[1], padding, args), "The padding parameter is invalid.");
// dictionary PadOptions {
// PaddingMode mode;
// float value = false;
// };
wnn::PadOptions options;
if (info.Length() == 3 && !info[2].IsUndefined()) {
WEBNN_NODE_ASSERT(info[2].IsObject(), "The options must be an object.");
Napi::Object jsOptions = info[2].As<Napi::Object>();
if (HasOptionMember(jsOptions, "mode")) {
WEBNN_NODE_ASSERT(GetPaddingMode(jsOptions.Get("mode"), options.mode),
"The mode parameter is invalid.");
}
if (HasOptionMember(jsOptions, "value")) {
WEBNN_NODE_ASSERT(GetValue(jsOptions.Get("value"), options.value),
"The value parameter is invalid.");
}
}
Napi::Object object = Operand::constructor.New(args);
Operand* operand = Napi::ObjectWrap<Operand>::Unwrap(object);
operand->SetImpl(builder.Pad(input, padding, &options));
return object;
}
} // namespace node::op
| 41.017544 | 99 | 0.61976 | wangli69087 |
3a024a78147f0f1d108a91d8d73eb54493c718e8 | 1,259 | cpp | C++ | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | #include "ControlWindow.h"
void CreateControlWindow(WinDat& wd){
wd._handle = CreateWindowEx(0, wd._className, NULL, wd._style, wd._x, wd._y, wd._w, wd._h, wd._parent, 0, NULL, NULL);
HTREEITEM hRoot;
TV_INSERTSTRUCT tvins;
tvins = { 0 };
tvins.hInsertAfter = TVI_ROOT;
tvins.item.mask = TVIF_TEXT;
tvins.item.pszText = L"Root";
tvins.item.cchTextMax = 10;
hRoot = TreeView_InsertItem(wd._handle, &tvins);
//tvins.hInsertAfter = TVI_LAST;
//tvins.item.pszText = "Child";
//hChild = TreeView_InsertItem(hSidePanel, &tvins);
ListViewAddItem(wd._handle, hRoot, L"test");
ListViewAddItem(wd._handle, hRoot, L"cat");
ListViewAddItem(wd._handle, ListViewAddItem(wd._handle, hRoot, L"murder"), L"more");
tvins.hInsertAfter = TVI_ROOT;
tvins.item.mask = TVIF_TEXT;
tvins.item.pszText = L"Root2";
tvins.item.cchTextMax = 10;
hRoot = TreeView_InsertItem(wd._handle, &tvins);
}
HTREEITEM ListViewAddItem(HWND hWnd, HTREEITEM hItem, LPWSTR lpstr) {
TVINSERTSTRUCT insert;
insert = { 0 };
insert.hParent = hItem;
insert.hInsertAfter = TVI_LAST;
insert.item.mask = TVIF_TEXT;
insert.item.pszText = lpstr;
insert.item.cchTextMax = 10;
//HTREEITEM test = TVM_INSERTITEM(0, &insert);
return TreeView_InsertItem(hWnd, &insert);
} | 23.754717 | 119 | 0.72359 | pipmix |
3a03e0a95acfb6fce27ba7ae88db0f22d41f6946 | 5,339 | cpp | C++ | feature/vldsift.cpp | abhishek4747/imagenet2010-devkit | 6ad756179dc2f85aec65ee5ed3a94ef17f351d81 | [
"MIT"
] | 2 | 2017-11-28T14:58:46.000Z | 2020-05-05T04:43:43.000Z | feature/vldsift.cpp | abhishek4747/imagenet2010-devkit | 6ad756179dc2f85aec65ee5ed3a94ef17f351d81 | [
"MIT"
] | null | null | null | feature/vldsift.cpp | abhishek4747/imagenet2010-devkit | 6ad756179dc2f85aec65ee5ed3a94ef17f351d81 | [
"MIT"
] | 2 | 2020-05-05T04:43:47.000Z | 2021-11-27T16:49:35.000Z | extern "C" {
#include "vl/generic.h"
#include "vl/stringop.h"
#include "vl/pgm.h"
#include "vl/dsift.h"
#include "vl/sift.h"
#include "vl/getopt_long.h"
}
#include <errno.h>
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <iostream>
#include <sstream>
#include <cmath>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdarg>
#include "vldsift.hpp"
using namespace std;
enum { DEBUG = 0, INFO, WARN, ERROR, FATAL, SIGNAL }; // log levels
int loglevel = INFO;
#define verify(_x) \
do { \
if (!(_x)) { \
LOG(FATAL, "Assertion failure in %s line %d of %s: %s\n", \
__FUNCTION__, __LINE__, __FILE__, #_x); \
} \
} while (0)
void LOG(int level, const char *fmt, ...)
{
static const char *level_str[] = {
"DEBUG", "INFO", "WARN", "ERROR", "FATAL", "SIGNAL"
};
assert(loglevel >= DEBUG);
assert(loglevel <= SIGNAL);
if (level >= loglevel) {
va_list args;
fprintf(stderr, "[%s] ", level_str[level]);
if (level == ERROR) {
fprintf(stderr, "(errno: %s) ", strerror(errno));
}
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
if (level == FATAL) {
exit(1);
}
}
char* input_path = NULL;
int verbose = 0;
int step_size = 10;
int cur_scale = 0;
int flag_ascii = 1;
void printUsageAndExit() {
cerr << "vldsift [options] input_file" << endl
<< "-s stepsize , default 10" << endl
<< "-b output binary ( default ascii )" << endl
<< "-l current scale ( default 0, image is assumed to have been reduced by 2^l. position is for the original image)" << endl
<< "stdout: vldsift format" << endl;
exit(1);
}
bool parseArgs(int argc, char** argv) {
//get rid of program name
argc--; argv++;
while(argc > 0)
{
if(!strcmp(*argv, "-s")){
argc--; argv++;
if(argc == 0) {
fprintf(stderr, "must specify -s\n");
return false;
} else {
step_size = atoi(*argv);
}
}
if(!strcmp(*argv, "-l")){
argc--; argv++;
if(argc == 0) {
fprintf(stderr, "must specify -s\n");
return false;
} else {
cur_scale = atoi(*argv);
}
}
else if(!strcmp(*argv, "-b")){
flag_ascii=0;
}else {
input_path = *argv;
}
argc--; argv++;
}
if( input_path == NULL ) {
return false;
}
return true;
}
int main(int argc, char** argv ) {
if( !parseArgs(argc, argv) ) {
printUsageAndExit();
}
vl_uint8 *data = 0 ;
vl_sift_pix *fdata = 0 ;
int err;
VlPgmImage pim ;
FILE* in;
/* open input file */
if( !strcmp(input_path, "-" )) {
in = stdin;
} else {
in = fopen (input_path, "rb") ;
}
if (!in) {
LOG(FATAL, "cannot open file %s\n", input_path);
}
/* ...............................................................
* Read data
* ............................................................ */
/* read PGM header */
err = vl_pgm_extract_head (in, &pim) ;
if (err) {
switch (vl_err_no) {
case VL_ERR_PGM_IO :
/*
snprintf(err_msg, sizeof(err_msg),
"Cannot read from '%s'.", name) ;
*/
err = VL_ERR_IO ;
break ;
case VL_ERR_PGM_INV_HEAD :
/*
snprintf(err_msg, sizeof(err_msg),
*/
LOG(FATAL, "'%s' contains a malformed PGM header.", input_path);
err = VL_ERR_IO ;
}
}
if (verbose)
fprintf (stderr, "sift: image is %d by %d pixels\n",
pim. width,
pim. height) ;
/* allocate buffer */
data = (vl_uint8*)malloc(vl_pgm_get_npixels (&pim) *
vl_pgm_get_bpp (&pim) * sizeof (vl_uint8) ) ;
fdata = (float*)malloc(vl_pgm_get_npixels (&pim) *
vl_pgm_get_bpp (&pim) * sizeof (float)) ;
if (!data || !fdata) {
err = VL_ERR_ALLOC ;
/*
snprintf(err_msg, sizeof(err_msg),
"Could not allocate enough memory.") ;
*/
LOG(FATAL, "Could not allocate enough memory.") ;
}
/* read PGM body */
err = vl_pgm_extract_data (in, &pim, data) ;
if (err) {
/*
snprintf(err_msg, sizeof(err_msg), "PGM body malformed.") ;
*/
err = VL_ERR_IO ;
LOG(FATAL,"PGM body malformed.");
}
/* convert data type */
for (int q = 0 ; q < pim.width * pim.height ; ++q)
fdata [q] = data [q] ;
VlDsiftFilter* df = vl_dsift_new(pim.width, pim.height);
vl_dsift_set_steps(df, step_size, step_size);
vl_dsift_process(df, fdata);
int num_keypoints = vl_dsift_get_keypoint_num(df);
const VlDsiftKeypoint* points = vl_dsift_get_keypoints(df);
const float* descriptors = vl_dsift_get_descriptors(df);
int dim = vl_dsift_get_descriptor_size(df);
Points_vldsift mypoints;
verify(VLDSIFT_DIM==dim);
for( int i = 0 ;i< num_keypoints; i++ ) {
const VlDsiftKeypoint& p = points[i];
mypoints.vecs.push_back(Point_vldsift());
Point_vldsift& q = mypoints.vecs.back();
q.x = p.x / (float)pim.width;
q.y = p.y / (float)pim.height;
q.scale = cur_scale;
q.norm = p.norm;
for( int k = 0; k < dim; k++ ) {
q.desc[k] = descriptors[i*dim+k];
}
}
if( flag_ascii ) {
cout << mypoints.toASCII() << endl;
} else {
string s = mypoints.toBinary();
cout.write((char*)s.data(),s.length());
}
vl_dsift_delete(df);
return 0;
}
| 22.914163 | 131 | 0.554411 | abhishek4747 |
3a05ddb3d8d3e19c15db99ecac35e8450db1259a | 5,885 | cpp | C++ | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// MITK
#include "mitkUSDeviceReaderWriterConstants.h"
#include "mitkUSDeviceWriterXML.h"
#include <mitkIGTMimeTypes.h>
#include <mitkLocaleSwitch.h>
#include <mitkUSDevice.h>
// Third Party
#include <tinyxml.h>
#include <itksys/SystemTools.hxx>
#include <fstream>
#include <iostream>
mitk::USDeviceWriterXML::USDeviceWriterXML() : AbstractFileWriter(USDevice::GetStaticNameOfClass(),
mitk::IGTMimeTypes::USDEVICEINFORMATIONXML_MIMETYPE(),
"MITK USDevice Writer (XML)"), m_Filename("")
{
RegisterService();
}
mitk::USDeviceWriterXML::USDeviceWriterXML(const mitk::USDeviceWriterXML& other) : AbstractFileWriter(other)
{
}
mitk::USDeviceWriterXML::~USDeviceWriterXML()
{
}
mitk::USDeviceWriterXML* mitk::USDeviceWriterXML::Clone() const
{
return new USDeviceWriterXML(*this);
}
void mitk::USDeviceWriterXML::Write()
{
if (m_Filename == "")
{
MITK_WARN << "Cannot write to file - empty filename!";
return;
}
}
void mitk::USDeviceWriterXML::SetFilename(std::string filename)
{
m_Filename = filename;
}
bool mitk::USDeviceWriterXML::WriteUltrasoundVideoDeviceConfiguration(mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
TiXmlDocument document;
TiXmlDeclaration* xmlDeclaration = new TiXmlDeclaration("1.0", "", "");
document.LinkEndChild(xmlDeclaration);
//Create the xml information of the ULTRASOUNDDEVICE-Tag:
TiXmlElement *ultrasoundDeviceTag = new TiXmlElement(TAG_ULTRASOUNDDEVICE);
this->CreateXmlInformationOfUltrasoundDeviceTag(document, ultrasoundDeviceTag, config);
//Create the xml information of the GENERALSETTINGS-Tag:
TiXmlElement *generalSettingsTag = new TiXmlElement(TAG_GENERALSETTINGS);
this->CreateXmlInformationOfGeneralSettingsTag(ultrasoundDeviceTag, generalSettingsTag, config);
//Create the xml information of the PROBES-Tag:
this->CreateXmlInformationOfProbesTag(ultrasoundDeviceTag, config);
return document.SaveFile(m_Filename);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfUltrasoundDeviceTag(
TiXmlDocument &document, TiXmlElement * ultrasoundDeviceTag,
mitk::USDeviceReaderXML::USVideoDeviceConfigData &config)
{
ultrasoundDeviceTag->SetAttribute(ATTR_FILEVERS, config.fileversion);
ultrasoundDeviceTag->SetAttribute(ATTR_TYPE, config.deviceType);
ultrasoundDeviceTag->SetAttribute(ATTR_NAME, config.deviceName);
ultrasoundDeviceTag->SetAttribute(ATTR_MANUFACTURER, config.manufacturer);
ultrasoundDeviceTag->SetAttribute(ATTR_MODEL, config.model);
ultrasoundDeviceTag->SetAttribute(ATTR_COMMENT, config.comment);
ultrasoundDeviceTag->SetAttribute(ATTR_IMAGESTREAMS, config.numberOfImageStreams);
document.LinkEndChild(ultrasoundDeviceTag);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfGeneralSettingsTag(TiXmlElement *parentTag, TiXmlElement *generalSettingsTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
std::string value = config.useGreyscale ? "true" : "false";
generalSettingsTag->SetAttribute(ATTR_GREYSCALE, value);
value = config.useResolutionOverride ? "true" : "false";
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONOVERRIDE, value);
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONWIDTH, config.resolutionWidth);
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONHEIGHT, config.resolutionHeight);
generalSettingsTag->SetAttribute(ATTR_SOURCEID, config.sourceID);
generalSettingsTag->SetAttribute(ATTR_FILEPATH, config.filepathVideoSource);
generalSettingsTag->SetAttribute(ATTR_OPENCVPORT, config.opencvPort);
parentTag->LinkEndChild(generalSettingsTag);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfProbesTag(TiXmlElement * parentTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
if (config.probes.size() != 0)
{
TiXmlElement *probesTag = new TiXmlElement(TAG_PROBES);
parentTag->LinkEndChild(probesTag);
for (size_t index = 0; index < config.probes.size(); ++index)
{
TiXmlElement *probeTag = new TiXmlElement(TAG_PROBE);
probesTag->LinkEndChild(probeTag);
mitk::USProbe::Pointer probe = config.probes.at(index);
probeTag->SetAttribute(ATTR_NAME, probe->GetName());
std::map<int, mitk::Vector3D> depthsAndSpacing = probe->GetDepthsAndSpacing();
if (depthsAndSpacing.size() != 0)
{
TiXmlElement *depthsTag = new TiXmlElement(TAG_DEPTHS);
probeTag->LinkEndChild(depthsTag);
for (std::map<int, mitk::Vector3D>::iterator it = depthsAndSpacing.begin(); it != depthsAndSpacing.end(); it++)
{
TiXmlElement *depthTag = new TiXmlElement(TAG_DEPTH);
depthTag->SetAttribute(ATTR_DEPTH, it->first);
depthsTag->LinkEndChild(depthTag);
TiXmlElement *spacingTag = new TiXmlElement(TAG_SPACING);
spacingTag->SetDoubleAttribute(ATTR_X, it->second[0], 6);
spacingTag->SetDoubleAttribute(ATTR_Y, it->second[1], 6);
depthTag->LinkEndChild(spacingTag);
}
TiXmlElement *croppingTag = new TiXmlElement(TAG_CROPPING);
probeTag->LinkEndChild(croppingTag);
croppingTag->SetAttribute(ATTR_TOP, probe->GetProbeCropping().top);
croppingTag->SetAttribute(ATTR_BOTTOM, probe->GetProbeCropping().bottom);
croppingTag->SetAttribute(ATTR_LEFT, probe->GetProbeCropping().left);
croppingTag->SetAttribute(ATTR_RIGHT, probe->GetProbeCropping().right);
}
}
}
}
| 37.246835 | 188 | 0.746814 | wyyrepo |
3a087fceb1f9cb99e6e419ac33c956794e78c256 | 9,122 | cpp | C++ | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | null | null | null | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | 97 | 2021-08-30T13:35:39.000Z | 2022-03-31T02:51:47.000Z | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | 1 | 2021-10-29T19:09:33.000Z | 2021-10-29T19:09:33.000Z | /*******************************************************************************
* @file oled.cpp
* @brief File containing all OLED functions.
*******************************************************************************/
#ifndef oled_cpp // Start of precompiler check to avoid dupicate inclusion of this code block.
#define oled_cpp // Precompiler macro used for precompiler check.
#include <main.h> // Header file for all libraries needed by this program.
/**
* @brief Hardware Interrupt Service Routine for Button A on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonA_ISR()
{
buttonA_flag = true;
} // ButtonA_ISR()
/**
* @brief Hardware Interrupt Service Routine for Button B on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonB_ISR()
{
buttonB_flag = true;
} // ButtonB_ISR()
/**
* @brief Hardware Interrupt Service Routine for Button C on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonC_ISR()
{
buttonC_flag = true;
} // ButtonC_ISR()
/**
* @brief Places a text message centrered vertically and horizontally.
*
* @param msg A text message to be displayed.
* @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3.
* @param fontColour SH110X_WHITE is the usual choice here.
* ==========================================================================*/
void placeTextVHcentre(String msg, uint8_t fontSize, uint16_t fontColour)
{
display.setTextSize(fontSize);
display.setTextColor(fontColour);
uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2;
uint8_t y = (oledY - (textBaseY * fontSize)) / 2;
display.setCursor(x, y);
display.print(msg);
} // placeTextVHcentre
/**
* @brief Places a text message centrered horizontally.
*
* @param msg A text message to be displayed.
* @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3.
* @param fontColour SH110X_WHITE is the usual choice here.
* ==========================================================================*/
void placeTextHcentre(String msg, uint8_t fontSize, uint16_t fontColour)
{
display.setTextSize(fontSize);
display.setTextColor(fontColour);
uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2;
display.setCursor(x, display.getCursorY());
display.println(msg);
} // placeTextHcentre()
/**
* @brief Rotate the display.
* @details Does not rotate the current screen content but will affect all
* new content sent t the OLED. Note that the the setRotation() function
* orients the content displayed on the OLED screen using a 1 byte parameter
* which has does the following:
* 0 sets the orietation so that the top is where the buttons are.
* 1 rotates the top of the display 90 degrees clockwise from position 0.
* 2 rotates the top of the display 180 degrees clockwise from position 0.
* 3 rotates the top of the display 270 degrees clockwise from position 0.
* @param newOrientation which of the 4 valid orientations to use.
* ==========================================================================*/
void rotateDisplay(int8_t newOrientation)
{
switch(newOrientation)
{
case 0:
Log.verboseln("<rotateDisplay> OLED top is now where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 1:
Log.verboseln("<rotateDisplay> OLED top is now 90 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 2:
Log.verboseln("<rotateDisplay> OLED top is now 180 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 3:
Log.verboseln("<rotateDisplay> OLED top is now 270 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
default:
Log.errorln("<rotateDisplay> Invalid OLED orientation request of %d. Only values 0-3 are allowed.", newOrientation);
break;
} // switch
} // rotateDisplay()
/**
* @brief Display the splash screen.
* @details Clear the OLED display, set the orientation then display the
* splash screen. Note that the the setRotation() function orients the content
* displayed on the OLED screen using a 1 byte parameter which has does the
* following:
* 0 sets the orietation so that the top is where the buttons are.
* 1 rotates the top of the display 90 degrees clockwise from position 0.
* 2 rotates the top of the display 180 degrees clockwise from position 0.
* 3 rotates the top of the display 270 degrees clockwise from position 0.
* @param msg Text message to add as tag line to splash screen.
* ==========================================================================*/
void displaySplashScreen(String msg)
{
if(oledConnected == false)
{
Log.warningln("<displaySplashScreen> OLED missing. Message suppressed.");
return;
} // if
int8_t headingSize = 3;
int8_t subMsgSize = 1;
display.clearDisplay(); // Clear the buffer.
if(msg == "") // No sub heading message
{
placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE);
} // if
else
{
placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE);
placeTextHcentre(msg, subMsgSize, SH110X_WHITE);
} // else
delay(10); // Wait for buffer.
yield(); // Periodic yield call to avoid watchdog reset.
display.display(); // Actually display all of the above
} // displaySplashScreen()
/**
* @brief Display what the legs are doing.
* ==========================================================================*/
void displayStatusScreen()
{
if(oledConnected == false)
{
Log.warningln("<displayStatusScreen> OLED missing. Message suppressed.");
return;
} // if
display.clearDisplay();
display.setCursor(0, 0);
placeTextHcentre("Robot Status", 1, SH110X_WHITE);
display.print("\nWifi: ");
// Wifi status.
if(networkConnected == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// MQTT broker connection status.
display.print("MQTT: ");
if(mqttBrokerConnected == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// Mobility status (if leg servo controllers are detected on I2C).
display.print("Legs: ");
if(mobilityStatus == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// Current robot goal.
display.print("Goal: ");
display.println(legDirExpl[legDirIndex]);
delay(10);
yield();
display.display(); // actually display all of the above
} // displayStatusScreen()
/**
* @brief Check to see if any of the OLED buttons have been pressed.
* ==========================================================================*/
void checkOledButtons()
{
if(buttonA_flag == true)
{
buttonA_flag = false;
display.clearDisplay();
display.setCursor(0, 0);
placeTextHcentre("Configuration", 1, SH110X_WHITE);
display.print("\nRobot: ");
display.println(WiFi.localIP());
display.print("Broker: ");
display.println(getMqttBrokerIP());
delay(10);
yield();
display.display(); // actually display all of the above
} // if
if(buttonB_flag == true)
{
buttonB_flag = false;
displayStatusScreen();
} // if
if(buttonC_flag == true)
{
buttonC_flag = false;
displaySplashScreen("");
} // if
} // loop()
/**
* @brief Initiaize OLED display.
* ==========================================================================*/
void initOled()
{
if(oledConnected == false)
{
Log.warningln("<initOled> OLED missing. Skipping initialization.");
return;
} // if
Log.verboseln("<initOled> 128x64 OLED FeatherWing setup.");
display.begin(0x3C, true); // Address 0x3C default
Log.verboseln("<initOled> OLED begun.");
pinMode(G_BUTTON_A, INPUT_PULLUP); // Make button A pin input with weak pullup.
pinMode(G_BUTTON_B, INPUT_PULLUP); // Make button B pin input with weak pullup.
pinMode(G_BUTTON_C, INPUT_PULLUP); // Make button C pin input with weak pullup.
attachInterrupt(G_BUTTON_A, ButtonA_ISR, RISING); // Assign ISR for button A.
attachInterrupt(G_BUTTON_B, ButtonB_ISR, RISING); // Assign ISR for button B.
attachInterrupt(G_BUTTON_C, ButtonC_ISR, RISING); // Assign ISR for button C.
rotateDisplay(oledOrientation); // Orient OLED text.
displaySplashScreen("");
} // setup()
#endif // End of precompiler protected code block | 36.342629 | 125 | 0.60513 | va3wam |
3a0b9822633116707d1d816cfafc655726d16bd8 | 3,222 | hpp | C++ | tutorial-day-2/cpp-toolkit/02_normalization_component/solution/normalized.hpp | NERSC/timemory-tutorials | 06056bfad1599364d0f881d53f280b2308313e69 | [
"MIT"
] | 15 | 2020-08-10T11:42:30.000Z | 2021-07-29T06:18:41.000Z | tutorial-day-2/cpp-toolkit/02_normalization_component/solution/normalized.hpp | NERSC/timemory-tutorials | 06056bfad1599364d0f881d53f280b2308313e69 | [
"MIT"
] | 6 | 2020-07-13T16:37:34.000Z | 2021-05-20T10:50:01.000Z | tutorial-day-2/cpp-toolkit/02_normalization_component/solution/normalized.hpp | NERSC/timemory-tutorials | 06056bfad1599364d0f881d53f280b2308313e69 | [
"MIT"
] | 2 | 2020-10-22T19:22:19.000Z | 2021-04-19T15:36:10.000Z |
#include "timemory/mpl/math.hpp"
#include "timemory/mpl/stl.hpp"
#include <timemory/components.hpp>
#include <timemory/components/base.hpp>
#include <timemory/mpl/types.hpp>
// for overload resolution, e.g. foo.store(normalize_tag{}, size_t)
struct normalization
{};
namespace tim
{
namespace component
{
template <typename T>
struct normalized;
}
} // namespace tim
namespace tim
{
namespace trait
{
// set the derivation types
template <typename T>
struct derivation_types<component::normalized<T>>
{
using type = type_list<type_list<T>>;
};
//
template <typename T>
struct statistics<component::normalized<T>>
{
using type = typename statistics<T>::type;
};
//
template <typename T>
struct is_available<component::normalized<T>>
{
using type = typename is_available<T>::type;
static constexpr auto value = is_available<T>::value;
};
//
template <typename T>
struct base_has_accum<component::normalized<T>> : false_type
{};
//
template <typename T>
struct echo_enabled<component::normalized<T>> : false_type
{};
} // namespace trait
} // namespace tim
namespace tim
{
namespace component
{
template <typename T>
struct normalized : public base<normalized<T>, T>
{
using value_type = T;
using base_type = base<normalized<T>, value_type>;
using base_type::get_value;
static std::string label();
static std::string description();
static auto unit();
static auto display_unit();
static const std::ios::fmtflags format_flags =
std::ios_base::scientific | std::ios_base::dec | std::ios_base::showpoint;
void store(normalization&&, size_t _sz);
auto get() const;
auto get_display() const;
bool derive(T* comp);
private:
size_t data_size = 1;
};
template <typename T>
std::string
normalized<T>::label()
{
return TIMEMORY_JOIN("_", "normalized", T::label());
}
template <typename T>
std::string
normalized<T>::description()
{
return TIMEMORY_JOIN(" ", T::description(), "normalized to data size");
}
template <typename T>
auto
normalized<T>::unit()
{
return T::unit();
}
template <typename T>
auto
normalized<T>::display_unit()
{
return T::display_unit();
}
template <typename T>
void
normalized<T>::store(normalization&&, size_t _sz)
{
data_size = _sz;
}
template <typename T>
auto
normalized<T>::get() const
{
// below might not be valid for more complex components
return get_value().get() / data_size;
// this will be valid for more complex components
// auto _v = get_value().get();
// using compute_type = math::compute<decay_t<decltype(_v)>>;
// compute_type::divide(_v, data_size);
// return _v;
}
template <typename T>
auto
normalized<T>::get_display() const
{
auto _v = get_value();
// below might not be valid for more complex components
_v /= data_size;
// this will be valid for more complex components
// using compute_type = math::compute<T>;
// compute_type::divide(_v, data_size);
return _v.get_display();
}
template <typename T>
bool
normalized<T>::derive(T* comp)
{
if(comp)
base_type::value = *comp;
return (comp != nullptr);
}
} // namespace component
} // namespace tim
| 20.392405 | 82 | 0.676909 | NERSC |
3a0caed9c94a94401d720ac84ad4c0a9c8a26413 | 2,181 | cpp | C++ | src/effects/VST3/internal/x11/PlugFrame.cpp | sthagen/audacity-audacity | 2f7ef196221bc20e7bcaa079c4d7d471563151b2 | [
"CC-BY-3.0"
] | 1 | 2022-03-23T09:09:18.000Z | 2022-03-23T09:09:18.000Z | src/effects/VST3/internal/x11/PlugFrame.cpp | sthagen/audacity-audacity | 2f7ef196221bc20e7bcaa079c4d7d471563151b2 | [
"CC-BY-3.0"
] | null | null | null | src/effects/VST3/internal/x11/PlugFrame.cpp | sthagen/audacity-audacity | 2f7ef196221bc20e7bcaa079c4d7d471563151b2 | [
"CC-BY-3.0"
] | null | null | null | /**********************************************************************
Audacity: A Digital Audio Editor
@file PlugFrame.cpp
@author Vitaly Sverchinsky
@brief Part of Audacity VST3 module
**********************************************************************/
#include "PlugFrame.h"
using namespace internal::x11;
IMPLEMENT_REFCOUNT(PlugFrame)
Steinberg::tresult PlugFrame::queryInterface (const ::Steinberg::TUID _iid, void** obj)
{
QUERY_INTERFACE (_iid, obj, Steinberg::FUnknown::iid, Steinberg::IPlugFrame);
QUERY_INTERFACE (_iid, obj, Steinberg::IPlugFrame::iid, Steinberg::IPlugFrame);
//As VST3 documentation states, IPlugFrame also has to provide
//reference to the Steinberg::Linux::IRunLoop implementation.
if (mRunLoop && Steinberg::FUnknownPrivate::iidEqual (_iid, Steinberg::Linux::IRunLoop::iid))
{
mRunLoop->addRef();
*obj = static_cast<Steinberg::Linux::IRunLoop*>(mRunLoop.get());
return ::Steinberg::kResultOk;
}
*obj = nullptr;
return ::Steinberg::kNoInterface;
}
PlugFrame::PlugFrame(Steinberg::Linux::IRunLoop* runLoop, wxWindow* window)
: mWindow(window), mRunLoop(runLoop)
{
FUNKNOWN_CTOR;
}
PlugFrame::~PlugFrame()
{
FUNKNOWN_DTOR;
}
Steinberg::tresult PlugFrame::resizeView(Steinberg::IPlugView* view, Steinberg::ViewRect* newSize)
{
const auto fixedSize = view->canResize() == Steinberg::kResultFalse;
if(UpdateSize({newSize->getWidth(), newSize->getHeight()}, fixedSize))
return Steinberg::kResultTrue;
return Steinberg::kResultFalse;
}
bool PlugFrame::UpdateSize(const wxSize& newSize, bool fixed)
{
if(auto window = mWindow.get())
{
//Wrapper (x11::SocketWindow) geometry needs to be updated too
auto wrapper = window->GetChildren()[0];
if(fixed)
{
//Update min/max if plugin window has fixed size
//but for some reason resize was requested
window->SetMinSize(newSize);
window->SetMaxSize(newSize);
wrapper->SetMinSize(newSize);
wrapper->SetMaxSize(newSize);
}
window->SetSize(newSize);
wrapper->SetSize(newSize);
return true;
}
return false;
}
| 29.472973 | 98 | 0.644658 | sthagen |
3a0f2adc46d8eee62126b5f74997a8b066ebb1eb | 2,607 | cpp | C++ | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | #include "PanelAbout.h"
#include "Application.h"
#include "ModuleGui.h"
#include "Imgui/imgui.h"
#include "mmgr/mmgr.h"
PanelAbout::PanelAbout(char * name) : Panel(name)
{
}
PanelAbout::~PanelAbout()
{
}
bool PanelAbout::Draw()
{
ImGuiWindowFlags settingsFlags = 0;
settingsFlags = ImGuiWindowFlags_NoFocusOnAppearing;
if (ImGui::Begin(name, &enabled, settingsFlags))
{
// --- Introduction ---
ImGui::Separator();
ImGui::Text("SAD 3D");
ImGui::SameLine();
ImGui::Text("Version 2.0");
ImGui::SameLine();
if (ImGui::Button("GitHub")) { App->gui->RequestBrowser("https://github.com/t3m1X/SAD-3D"); }
ImGui::Text("A fork of Central 3D");
ImGui::Text("By: ");
ImGui::SameLine();
if (ImGui::Button("Sergi Parra")) { App->gui->RequestBrowser("https://github.com/t3m1X"); }
ImGui::Text("Central 3D by:");
ImGui::SameLine();
if (ImGui::Button("Aitor Simona")) { App->gui->RequestBrowser("https://github.com/AitorSimona"); }
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
// --- License ---
ImGui::TextWrapped("MIT License");
ImGui::TextWrapped("Copyright(c) 2019 Aitor Simona Bouzas");
ImGui::TextWrapped("Copyright (c) 2021 Sergi Parra Ramirez");
ImGui::TextWrapped("Copyright for portions of SAD 3D are held by Aitor Simona Bouzas, 2019 as part of project CENTRAL 3D (Version 2.0).");
ImGui::TextWrapped("All other copyright for project SAD 3D are held by Sergi Parra Ramirez, 2021.");
ImGui::TextWrapped("");
ImGui::TextWrapped("Permission is hereby granted, free of charge, to any person obtaining a copyof 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 : ");
ImGui::TextWrapped("The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.");
ImGui::TextWrapped("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.");
}
ImGui::End();
return true;
}
| 42.737705 | 485 | 0.726506 | t3m1X |
3a0fda872f54dd180b67600e81631493d6ff426c | 13,944 | cpp | C++ | Tools/EditorFramework/EngineProcess/Implementation/EngineProcessDocumentContext.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | null | null | null | Tools/EditorFramework/EngineProcess/Implementation/EngineProcessDocumentContext.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | null | null | null | Tools/EditorFramework/EngineProcess/Implementation/EngineProcessDocumentContext.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | 1 | 2020-03-08T04:55:16.000Z | 2020-03-08T04:55:16.000Z | #include <PCH.h>
#include <EditorFramework/EngineProcess/EngineProcessDocumentContext.h>
#include <EditorFramework/EngineProcess/EngineProcessMessages.h>
#include <EditorFramework/IPC/SyncObject.h>
#include <EditorFramework/EngineProcess/EngineProcessMessages.h>
#include <EditorFramework/EngineProcess/EngineProcessViewContext.h>
#include <Foundation/Reflection/ReflectionUtils.h>
#include <Foundation/Serialization/ReflectionSerializer.h>
#include <Foundation/Logging/Log.h>
#include <Gizmos/GizmoHandle.h>
#include <RendererCore/RenderContext/RenderContext.h>
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezEngineProcessDocumentContext, ezReflectedClass, 1, ezRTTINoAllocator);
EZ_END_DYNAMIC_REFLECTED_TYPE();
ezHashTable<ezUuid, ezEngineProcessDocumentContext*> ezEngineProcessDocumentContext::s_DocumentContexts;
ezEngineProcessDocumentContext* ezEngineProcessDocumentContext::GetDocumentContext(ezUuid guid)
{
ezEngineProcessDocumentContext* pResult = nullptr;
s_DocumentContexts.TryGetValue(guid, pResult);
return pResult;
}
void ezEngineProcessDocumentContext::AddDocumentContext(ezUuid guid, ezEngineProcessDocumentContext* pContext, ezProcessCommunication* pIPC)
{
EZ_ASSERT_DEV(!s_DocumentContexts.Contains(guid), "Cannot add a view with an index that already exists");
s_DocumentContexts[guid] = pContext;
pContext->Initialize(guid, pIPC);
}
void ezEngineProcessDocumentContext::DestroyDocumentContext(ezUuid guid)
{
ezEngineProcessDocumentContext* pContext = nullptr;
if (s_DocumentContexts.Remove(guid, &pContext))
{
pContext->Deinitialize();
pContext->GetDynamicRTTI()->GetAllocator()->Deallocate(pContext);
}
}
ezEngineProcessDocumentContext::ezEngineProcessDocumentContext()
{
m_pWorld = nullptr;
m_uiNextComponentPickingID = 1;
}
ezEngineProcessDocumentContext::~ezEngineProcessDocumentContext()
{
EZ_ASSERT_DEV(m_pWorld == nullptr, "World has not been deleted! Call 'ezEngineProcessDocumentContext::DestroyDocumentContext'");
}
void ezEngineProcessDocumentContext::Deinitialize()
{
ClearViewContexts();
OnDeinitialize();
CleanUpContextSyncObjects();
EZ_DEFAULT_DELETE(m_pWorld);
}
void ezEngineProcessDocumentContext::SendProcessMessage(ezProcessMessage* pMsg, bool bSuperHighPriority /*= false*/)
{
m_pIPC->SendMessage(pMsg, bSuperHighPriority);
}
void ezEngineProcessDocumentContext::HandleMessage(const ezEditorEngineDocumentMsg* pMsg)
{
EZ_LOCK(m_pWorld->GetWriteMarker());
if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEntityMsgToEngine>())
{
const ezEntityMsgToEngine* pMsg2 = static_cast<const ezEntityMsgToEngine*>(pMsg);
HandlerEntityMsg(pMsg2);
}
else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEditorEngineSyncObjectMsg>())
{
const ezEditorEngineSyncObjectMsg* pMsg2 = static_cast<const ezEditorEngineSyncObjectMsg*>(pMsg);
ProcessEditorEngineSyncObjectMsg(*pMsg2);
}
else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezObjectTagMsgToEngine>())
{
const ezObjectTagMsgToEngine* pMsg2 = static_cast<const ezObjectTagMsgToEngine*>(pMsg);
ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg2->m_ObjectGuid);
ezTag tag;
ezTagRegistry::GetGlobalRegistry().RegisterTag(pMsg2->m_sTag, &tag);
ezGameObject* pObject;
if (m_pWorld->TryGetObject(hObject, pObject))
{
if (pMsg2->m_bSetTag)
pObject->GetTags().Set(tag);
else
pObject->GetTags().Clear(tag);
}
}
if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEditorEngineViewMsg>())
{
if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewRedrawMsgToEngine>())
{
UpdateSyncObjects();
}
const ezEditorEngineViewMsg* pViewMsg = static_cast<const ezEditorEngineViewMsg*>(pMsg);
EZ_ASSERT_DEV(pViewMsg->m_uiViewID < 0xFFFFFFFF, "Invalid view ID in '%s'", pMsg->GetDynamicRTTI()->GetTypeName());
if (pViewMsg->m_uiViewID >= m_ViewContexts.GetCount())
m_ViewContexts.SetCount(pViewMsg->m_uiViewID + 1);
if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewDestroyedMsgToEngine>())
{
if (m_ViewContexts[pViewMsg->m_uiViewID] != nullptr)
{
DestroyViewContext(m_ViewContexts[pViewMsg->m_uiViewID]);
m_ViewContexts[pViewMsg->m_uiViewID] = nullptr;
ezLog::Info("Destroyed View %i", pViewMsg->m_uiViewID);
}
}
else
{
if (m_ViewContexts[pViewMsg->m_uiViewID] == nullptr)
m_ViewContexts[pViewMsg->m_uiViewID] = CreateViewContext();
m_ViewContexts[pViewMsg->m_uiViewID]->HandleViewMessage(pViewMsg);
}
return;
}
else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewHighlightMsgToEngine>())
{
const ezViewHighlightMsgToEngine* pMsg2 = static_cast<const ezViewHighlightMsgToEngine*>(pMsg);
ezUInt32 uiPickingID = m_OtherPickingMap.GetHandle(pMsg2->m_HighlightObject);
ezRenderContext::GetDefaultInstance()->SetMaterialParameter("PickingHighlightID", (ezInt32)uiPickingID);
}
}
void ezEngineProcessDocumentContext::Initialize(const ezUuid& DocumentGuid, ezProcessCommunication* pIPC)
{
m_DocumentGuid = DocumentGuid;
m_pIPC = pIPC;
m_pWorld = EZ_DEFAULT_NEW(ezWorld, ezConversionUtils::ToString(m_DocumentGuid));
OnInitialize();
}
void ezEngineProcessDocumentContext::AddSyncObject(ezEditorEngineSyncObject* pSync)
{
m_SyncObjects[pSync->GetGuid()] = pSync;
}
void ezEngineProcessDocumentContext::RemoveSyncObject(ezEditorEngineSyncObject* pSync)
{
m_SyncObjects.Remove(pSync->GetGuid());
}
ezEditorEngineSyncObject* ezEngineProcessDocumentContext::FindSyncObject(const ezUuid& guid)
{
auto it = m_SyncObjects.Find(guid);
if (it.IsValid())
return it.Value();
return nullptr;
}
void ezEngineProcessDocumentContext::ClearViewContexts()
{
for (auto* pContext : m_ViewContexts)
{
DestroyViewContext(pContext);
}
m_ViewContexts.Clear();
}
void ezEngineProcessDocumentContext::CleanUpContextSyncObjects()
{
while (!m_SyncObjects.IsEmpty())
{
auto it = m_SyncObjects.GetIterator();
it.Value()->GetDynamicRTTI()->GetAllocator()->Deallocate(it.Value());
}
}
void ezEngineProcessDocumentContext::ProcessEditorEngineSyncObjectMsg(const ezEditorEngineSyncObjectMsg& msg)
{
auto it = m_SyncObjects.Find(msg.m_ObjectGuid);
if (msg.m_sObjectType.IsEmpty())
{
// object has been deleted!
if (it.IsValid())
{
it.Value()->GetDynamicRTTI()->GetAllocator()->Deallocate(it.Value());
}
return;
}
const ezRTTI* pRtti = ezRTTI::FindTypeByName(msg.m_sObjectType);
ezEditorEngineSyncObject* pSyncObject = nullptr;
bool bSetOwner = false;
if (pRtti == nullptr)
{
ezLog::Error("Cannot sync object of type unknown '%s' to engine process", msg.m_sObjectType.GetData());
return;
}
if (!it.IsValid())
{
// object does not yet exist
EZ_ASSERT_DEV(pRtti->GetAllocator() != nullptr, "Sync object of type '%s' does not have a default allocator", msg.m_sObjectType.GetData());
void* pObject = pRtti->GetAllocator()->Allocate();
pSyncObject = static_cast<ezEditorEngineSyncObject*>(pObject);
bSetOwner = true;
}
else
{
pSyncObject = it.Value();
}
ezMemoryStreamStorage storage;
ezMemoryStreamWriter writer(&storage);
ezMemoryStreamReader reader(&storage);
writer.WriteBytes(msg.m_sObjectData.GetData(), msg.m_sObjectData.GetElementCount());
ezReflectionSerializer::ReadObjectPropertiesFromJSON(reader, *pRtti, pSyncObject);
if (bSetOwner)
pSyncObject->SetOwner(this);
pSyncObject->SetModified(true);
}
void ezEngineProcessDocumentContext::HandlerGameObjectMsg(const ezEntityMsgToEngine* pMsg, ezRTTI* pRtti)
{
switch (pMsg->m_iMsgType)
{
case ezEntityMsgToEngine::ObjectAdded:
{
ezGameObjectDesc d;
d.m_sName.Assign(ezConversionUtils::ToString(pMsg->m_ObjectGuid).GetData());
if (pMsg->m_NewParentGuid.IsValid())
d.m_hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid);
ezGameObjectHandle hObject = m_pWorld->CreateObject(d);
m_GameObjectMap.RegisterObject(pMsg->m_ObjectGuid, hObject);
ezGameObject* pObject;
if (m_pWorld->TryGetObject(hObject, pObject))
{
UpdateProperties(pMsg, pObject, ezGetStaticRTTI<ezGameObject>());
}
}
break;
case ezEntityMsgToEngine::ObjectMoved:
{
ezRTTI* pRtti = ezRTTI::FindTypeByName(pMsg->m_sObjectType);
if (pRtti == nullptr)
{
ezLog::Error("Cannot create object of type '%s', RTTI is unknown", pMsg->m_sObjectType.GetData());
break;
}
ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid);
ezGameObjectHandle hNewParent;
if (pMsg->m_NewParentGuid.IsValid())
hNewParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid);
ezGameObject* pObject = nullptr;
if (m_pWorld->TryGetObject(hObject, pObject))
{
pObject->SetParent(hNewParent);
}
else
ezLog::Error("Couldn't access game object object %s in world %p", ezConversionUtils::ToString(pMsg->m_ObjectGuid).GetData(), m_pWorld);
}
break;
case ezEntityMsgToEngine::ObjectRemoved:
{
m_pWorld->DeleteObject(m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid));
m_GameObjectMap.UnregisterObject(pMsg->m_ObjectGuid);
}
break;
case ezEntityMsgToEngine::PropertyChanged:
{
ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid);
ezGameObject* pObject;
if (m_pWorld->TryGetObject(hObject, pObject))
{
UpdateProperties(pMsg, pObject, ezGetStaticRTTI<ezGameObject>());
//pObject->UpdateGlobalTransform();
}
}
break;
}
}
void ezEngineProcessDocumentContext::HandleComponentMsg(const ezEntityMsgToEngine* pMsg, ezRTTI* pRtti)
{
ezComponentManagerBase* pMan = m_pWorld->GetComponentManager(pRtti);
if (pMan == nullptr)
{
ezLog::Error("Component of type '%s' cannot be created, no component manager is registered", pRtti->GetTypeName());
return;
}
switch (pMsg->m_iMsgType)
{
case ezEntityMsgToEngine::ObjectAdded:
{
ezComponentHandle hComponent = pMan->CreateComponent();
ezGameObjectHandle hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid);
ezGameObject* pParent;
if (!m_pWorld->TryGetObject(hParent, pParent))
break;
ezComponent* pComponent;
if (pMan->TryGetComponent(hComponent, pComponent))
{
m_ComponentMap.RegisterObject(pMsg->m_ObjectGuid, hComponent);
UpdateProperties(pMsg, pComponent, pComponent->GetDynamicRTTI());
pComponent->m_uiEditorPickingID = m_uiNextComponentPickingID++;
m_ComponentPickingMap.RegisterObject(pMsg->m_ObjectGuid, pComponent->m_uiEditorPickingID);
}
else
{
ezLog::Error("Component of type '%s' cannot be found after creation", pRtti->GetTypeName());
}
pParent->AddComponent(hComponent);
}
break;
case ezEntityMsgToEngine::ObjectMoved:
{
ezGameObjectHandle hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid);
ezGameObject* pParent;
if (!m_pWorld->TryGetObject(hParent, pParent))
break;
ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid);
ezComponent* pComponent;
if (pMan->TryGetComponent(hComponent, pComponent))
{
if (pComponent->GetOwner())
pComponent->GetOwner()->RemoveComponent(pComponent);
}
pParent->AddComponent(hComponent);
}
break;
case ezEntityMsgToEngine::ObjectRemoved:
{
ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid);
m_ComponentMap.UnregisterObject(pMsg->m_ObjectGuid);
m_ComponentPickingMap.UnregisterObject(pMsg->m_ObjectGuid);
pMan->DeleteComponent(hComponent);
}
break;
case ezEntityMsgToEngine::PropertyChanged:
{
ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid);
ezComponent* pComponent;
if (pMan->TryGetComponent(hComponent, pComponent))
{
UpdateProperties(pMsg, pComponent, pComponent->GetDynamicRTTI());
}
else
{
ezLog::Error("Component of type '%s' cannot be found", pRtti->GetTypeName());
}
}
break;
}
}
void ezEngineProcessDocumentContext::HandlerEntityMsg(const ezEntityMsgToEngine* pMsg)
{
ezRTTI* pRtti = ezRTTI::FindTypeByName(pMsg->m_sObjectType);
if (pRtti == nullptr)
{
ezLog::Error("Cannot create object of type '%s', RTTI is unknown", pMsg->m_sObjectType.GetData());
return;
}
if (pRtti == ezGetStaticRTTI<ezGameObject>())
{
HandlerGameObjectMsg(pMsg, pRtti);
}
if (pRtti->IsDerivedFrom<ezComponent>())
{
HandleComponentMsg(pMsg, pRtti);
}
}
void ezEngineProcessDocumentContext::UpdateSyncObjects()
{
for (auto* pSyncObject : m_SyncObjects)
{
if (pSyncObject->GetModified() && pSyncObject->GetDynamicRTTI()->IsDerivedFrom<ezGizmoHandle>())
{
// reset the modified state to make sure the object isn't updated unless a new sync messages comes in
pSyncObject->SetModified(false);
ezGizmoHandle* pGizmoHandle = static_cast<ezGizmoHandle*>(pSyncObject);
EZ_LOCK(m_pWorld->GetWriteMarker());
if (pGizmoHandle->SetupForEngine(m_pWorld, m_uiNextComponentPickingID))
{
m_OtherPickingMap.RegisterObject(pGizmoHandle->GetGuid(), m_uiNextComponentPickingID);
++m_uiNextComponentPickingID;
}
pGizmoHandle->UpdateForEngine(m_pWorld);
}
}
}
void ezEngineProcessDocumentContext::UpdateProperties(const ezEntityMsgToEngine* pMsg, void* pObject, const ezRTTI* pRtti)
{
ezMemoryStreamStorage storage;
ezMemoryStreamWriter writer(&storage);
ezMemoryStreamReader reader(&storage);
writer.WriteBytes(pMsg->m_sObjectData.GetData(), pMsg->m_sObjectData.GetElementCount());
ezReflectionSerializer::ReadObjectPropertiesFromJSON(reader, *pRtti, pObject);
}
| 29.110647 | 143 | 0.727625 | eltld |
3a1333267ba4408a140f01de409b239e004253b3 | 1,987 | cc | C++ | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tmp112.h"
#include <lib/fake_ddk/fake_ddk.h>
#include <lib/mock-i2c/mock-i2c.h>
#include <zxtest/zxtest.h>
namespace {
bool FloatNear(float a, float b) { return std::abs(a - b) < 0.001f; }
} // namespace
namespace temperature {
using TemperatureClient = fidl::WireSyncClient<fuchsia_hardware_temperature::Device>;
class Tmp112DeviceTest : public zxtest::Test {
public:
Tmp112DeviceTest() {}
void SetUp() override {
dev_ = std::make_unique<Tmp112Device>(fake_ddk::kFakeParent,
ddk::I2cChannel(mock_i2c_.GetProto()));
const auto message_op = [](void* ctx, fidl_incoming_msg_t* msg,
fidl_txn_t* txn) -> zx_status_t {
return static_cast<Tmp112Device*>(ctx)->DdkMessage(msg, txn);
};
ASSERT_OK(messenger_.SetMessageOp(dev_.get(), message_op));
}
protected:
mock_i2c::MockI2c mock_i2c_;
std::unique_ptr<Tmp112Device> dev_;
fake_ddk::FidlMessenger messenger_;
};
TEST_F(Tmp112DeviceTest, Init) {
uint8_t initial_config_val[2] = {kConfigConvertResolutionSet12Bit, 0};
mock_i2c_.ExpectWrite({kConfigReg}).ExpectReadStop({0x0, 0x0});
mock_i2c_.ExpectWriteStop({kConfigReg, initial_config_val[0], initial_config_val[1]});
dev_->Init();
mock_i2c_.VerifyAndClear();
}
TEST_F(Tmp112DeviceTest, GetTemperatureCelsius) {
mock_i2c_.ExpectWrite({kTemperatureReg}).ExpectReadStop({0x34, 0x12});
TemperatureClient client(std::move(messenger_.local()));
auto result = client.GetTemperatureCelsius();
EXPECT_OK(result->status);
EXPECT_TRUE(FloatNear(result->temp, dev_->RegToTemperatureCelsius(0x1234)));
mock_i2c_.VerifyAndClear();
}
TEST_F(Tmp112DeviceTest, RegToTemperature) {
EXPECT_TRUE(FloatNear(dev_->RegToTemperatureCelsius(0x1234), 52.0625));
}
} // namespace temperature
| 29.220588 | 88 | 0.717665 | csrpi |
3a14283ea57ebe466e1b4e7b69e3e3d93b97efbc | 1,186 | cc | C++ | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 102 | 2021-05-18T10:31:57.000Z | 2022-03-29T04:25:42.000Z | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 9 | 2021-06-02T06:44:30.000Z | 2022-03-14T07:52:34.000Z | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 23 | 2021-05-18T13:07:50.000Z | 2022-02-24T02:16:02.000Z | // NOLINT(namespace-quic)
//
// This file is part of the QUICHE platform implementation, and is not to be
// consumed or referenced directly by other Envoy code. It serves purely as a
// porting layer for QUICHE.
#include "platform/epoll_platform_impl/quic_epoll_clock.h"
namespace quic {
QuicEpollClock::QuicEpollClock(epoll_server::SimpleEpollServer* epoll_server)
: epoll_server_(epoll_server), largest_time_(QuicTime::Zero()) {}
QuicTime QuicEpollClock::ApproximateNow() const {
return CreateTimeFromMicroseconds(epoll_server_->ApproximateNowInUsec());
}
QuicTime QuicEpollClock::Now() const {
QuicTime now = CreateTimeFromMicroseconds(epoll_server_->NowInUsec());
if (now <= largest_time_) {
// Time not increasing, return |largest_time_|.
return largest_time_;
}
largest_time_ = now;
return largest_time_;
}
QuicWallTime QuicEpollClock::WallNow() const {
return QuicWallTime::FromUNIXMicroseconds(epoll_server_->ApproximateNowInUsec());
}
QuicTime QuicEpollClock::ConvertWallTimeToQuicTime(const QuicWallTime& walltime) const {
return QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(walltime.ToUNIXMicroseconds());
}
} // namespace quic
| 30.410256 | 93 | 0.77403 | MacroLau |
3a14418b5b63b643fa73d0de8cdf04438e409c98 | 12,922 | cpp | C++ | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | null | null | null | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | 5 | 2019-12-27T05:51:10.000Z | 2022-02-12T02:24:58.000Z | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | null | null | null | /*
* Copywrite 2014-2015 Krzysztof Stasik. All rights reserved.
*/
#include "monitor_plugin.h"
#include "base/io/base_file.h"
#include "common/json/json_writer.h"
#include "link/plugin_log.h"
#include "base/core/time_utils.h"
#include "base/core/assert.h"
#include <unistd.h>
namespace Link {
static const streamsize kProcBufferSize = 1024;
struct CPUSample {
u32 timestamp; // sample time.
u32 user; // normal processes executing in user mode.
u32 nice; // niced processes executing in user mode.
u32 system; // processes executing in krenel mode.
u32 idle; // twiddling thumbs.
u32 iowait; // waiting for I/O to complete.
u32 irq; // servicing interrupts.
u32 softirq; // servicing softirqs.
void InitMax() {
timestamp = (u32)-1;
user = (u32)-1;
nice = (u32)-1;
system = (u32)-1;
idle = (u32)-1;
iowait = (u32)-1;
irq = (u32)-1;
softirq = (u32)-1;
}
void GetMax(const CPUSample &a) {
if(a.timestamp > timestamp)
timestamp = a.timestamp;
if(a.user > user)
user = a.user;
if(a.nice > nice)
nice = a.nice;
if(a.system > system)
system = a.system;
if(a.idle > idle)
idle = a.idle;
if(a.iowait > iowait)
iowait = a.iowait;
if(a.irq > irq)
irq = a.irq;
if(a.softirq > softirq)
softirq = a.softirq;
}
void GetMin(const CPUSample &a) {
if(a.timestamp < timestamp)
timestamp = a.timestamp;
if(a.user < user)
user = a.user;
if(a.nice < nice)
nice = a.nice;
if(a.system < system)
system = a.system;
if(a.idle < idle)
idle = a.idle;
if(a.iowait < iowait)
iowait = a.iowait;
if(a.irq < irq)
irq = a.irq;
if(a.softirq < softirq)
softirq = a.softirq;
}
CPUSample &operator+=(const CPUSample &rhs) {
timestamp += rhs.timestamp;
user += rhs.user;
nice += rhs.nice;
system += rhs.system;
idle += rhs.idle;
iowait += rhs.iowait;
irq += rhs.irq;
softirq += rhs.softirq;
return *this;
}
};
struct ProcessSample {
u32 timestamp;
u32 user;
u32 system;
};
float ToPercent(u32 stat, u32 time, u32 hz) {
float dt_sec = static_cast<float>(time) * 0.001f;
float denom = dt_sec * static_cast<float>(hz);
if(denom == 0.f) {
return 0.f;
}
return static_cast<float>(stat) / denom;
}
struct ProcessPercent {
float user;
float system;
void Calculate(const ProcessSample &delta, u32 hz) {
user = ToPercent(delta.user, delta.timestamp, hz);
system = ToPercent(delta.system, delta.timestamp, hz);
}
};
template <> inline void JsonWriter::AppendValue(const ProcessPercent &info) {
JsonWriter writer(m_destination);
writer.Write("user", info.user);
writer.Write("system", info.system);
writer.Finalize();
}
struct ProcessHistory {
u32 num_samples;
u32 current_sample;
ProcessSample *data;
ProcessHistory() : num_samples(0), current_sample(0), data(nullptr) {}
~ProcessHistory() { delete[] data; }
void Resize(u32 _num_samples) {
BASE_ASSERT(_num_samples > 0);
num_samples = _num_samples;
current_sample = 0;
delete[] data;
data = new ProcessSample[num_samples];
}
ProcessSample *GetNextSample() {
BASE_ASSERT(current_sample < num_samples, "sample out of range");
ProcessSample *res = &data[current_sample];
current_sample = (++current_sample) % num_samples;
return res;
}
void LastSampleStats(u32 tick_per_sec, ProcessPercent *out) {
ProcessSample diff;
Diff(data[(current_sample - 1) % num_samples],
data[(current_sample - 2) % num_samples], &diff);
out->Calculate(diff, tick_per_sec);
}
void Diff(const ProcessSample &a, const ProcessSample &b,
ProcessSample *res) {
res->user = a.user - b.user;
res->system = a.system - b.system;
}
};
struct CPUPercent {
float user;
float nice;
float system;
float idle;
float iowait;
float irq;
float softirq;
void InitMax() {
user = 1.f;
nice = 1.f;
system = 1.f;
idle = 1.f;
iowait = 1.f;
irq = 1.f;
softirq = 1.f;
}
void GetMin(const CPUPercent &d) {
if(d.user < user)
user = d.user;
if(d.nice < nice)
nice = d.nice;
if(d.system < system)
system = d.system;
if(d.idle < idle)
idle = d.idle;
if(d.iowait < iowait)
iowait = d.iowait;
if(d.irq < irq)
irq = d.irq;
if(d.softirq < softirq)
softirq = d.softirq;
}
void GetMax(const CPUPercent &d) {
if(d.user > user)
user = d.user;
if(d.nice > nice)
nice = d.nice;
if(d.system > system)
system = d.system;
if(d.idle > idle)
idle = d.idle;
if(d.iowait > iowait)
iowait = d.iowait;
if(d.irq > irq)
irq = d.irq;
if(d.softirq > softirq)
softirq = d.softirq;
}
void Calculate(const CPUSample &delta, u32 hz) {
user = ToPercent(delta.user, delta.timestamp, hz);
nice = ToPercent(delta.nice, delta.timestamp, hz);
system = ToPercent(delta.system, delta.timestamp, hz);
idle = ToPercent(delta.idle, delta.timestamp, hz);
iowait = ToPercent(delta.iowait, delta.timestamp, hz);
irq = ToPercent(delta.irq, delta.timestamp, hz);
softirq = ToPercent(delta.softirq, delta.timestamp, hz);
}
};
template <> inline void JsonWriter::AppendValue(const CPUPercent &info) {
JsonWriter writer(m_destination);
writer.Write("user", info.user);
writer.Write("nice", info.nice);
writer.Write("system", info.system);
writer.Write("idle", info.idle);
writer.Write("iowait", info.iowait);
writer.Write("irq", info.irq);
writer.Write("softirq", info.softirq);
writer.Finalize();
}
struct CPUHistory {
u32 num_samples;
u32 current_sample;
struct CPUSample *data;
struct CPUPercent min, max, avg;
CPUHistory() : num_samples(0), current_sample(0), data(0) {}
~CPUHistory() { delete[] data; }
void Resize(u32 _num_samples) {
BASE_ASSERT(_num_samples > 0);
num_samples = _num_samples;
current_sample = 0;
delete[] data;
data = new CPUSample[num_samples];
}
CPUSample *GetNextSample() {
BASE_ASSERT(current_sample < num_samples, "sample out of range");
CPUSample *res = &data[current_sample];
current_sample = (++current_sample) % num_samples;
return res;
}
void LastSampleStats(u32 tick_per_sec, CPUPercent *out) {
CPUSample diff;
Diff(data[(current_sample - 1) % num_samples],
data[(current_sample - 2) % num_samples], &diff);
out->Calculate(diff, tick_per_sec);
}
void Calculate(u32 tick_per_sec) {
CPUSample sum = {}, diff;
min.InitMax();
for(u32 i = 0; i < num_samples; ++i) {
Diff(data[(i - 1) % num_samples], data[(i - 2) % num_samples], &diff);
sum += diff;
CPUPercent tmp;
tmp.Calculate(diff, tick_per_sec);
min.GetMin(tmp);
max.GetMax(tmp);
}
avg.Calculate(sum, tick_per_sec);
}
void Diff(const CPUSample &a, const CPUSample &b, CPUSample *res) {
res->timestamp = a.timestamp - b.timestamp;
res->user = a.user - b.user;
res->nice = a.nice - b.nice;
res->system = a.system - b.system;
res->idle = a.idle - b.idle;
res->iowait = a.iowait - b.iowait;
res->irq = a.irq - b.irq;
res->softirq = a.softirq - b.softirq;
}
};
template <> inline void JsonWriter::AppendValue(const CPUSample &info) {
JsonWriter writer(m_destination);
writer.Write("timestamp", info.timestamp);
writer.Write("user", info.user);
writer.Write("nice", info.nice);
writer.Write("system", info.system);
writer.Write("idle", info.idle);
writer.Write("iowait", info.iowait);
writer.Write("irq", info.irq);
writer.Write("softirq", info.softirq);
writer.Finalize();
}
char *GoToNextValue(char *cur) {
// skip current value.
while(*cur != ' ' && *cur != '\t') {
++cur;
}
// skip whitespaces.
while(*cur == ' ' || *cur == '\t') {
++cur;
}
return cur;
}
char *GoToNextLine(char *cur) {
while(*cur != '\n' && *cur != 0) {
++cur;
}
if(*cur == '\n') {
++cur;
}
return cur;
}
bool ReadCPUStatus(char *&pointer, struct CPUSample *stats, u32 timestamp) {
// field definition: http://man7.org/linux/man-pages/man5/proc.5.html
if(pointer[0] != 'c' || pointer[1] != 'p' || pointer[2] != 'u') {
return false;
}
stats->timestamp = timestamp;
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->user);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->nice);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->system);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->idle);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->iowait);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->irq);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->softirq);
pointer = GoToNextLine(pointer);
return true;
}
bool ReadCPUStats(struct CPUHistory *total, struct CPUHistory **cpu,
int num_cpu) {
Base::FileHandle file = Base::Open("/proc/stat", Base::OM_Read);
if(file == -1) {
PLUGIN_ERROR("failed opeining proc stat");
return false;
}
char buffer[kProcBufferSize];
size_t nbytes = Base::Read(file, buffer, kProcBufferSize);
if(nbytes == static_cast<size_t>(-1)) {
PLUGIN_ERROR("problem reading proc stat");
return false;
}
u32 timestamp = Base::Time::GetTimeMs();
char *pointer = buffer;
if(!ReadCPUStatus(pointer, total->GetNextSample(), timestamp)) {
PLUGIN_ERROR("problem reading cpu stats");
Base::Close(file);
return false;
}
for(int i = 0; i < num_cpu; ++i) {
if(!pointer ||
!ReadCPUStatus(pointer, cpu[i]->GetNextSample(), timestamp)) {
PLUGIN_ERROR("problem reading %d cpu stats", i);
Base::Close(file);
return false;
}
}
Base::Close(file);
return true;
}
bool ReadProcessStats(struct ProcessHistory *hist) {
Base::FileHandle file = Base::Open("/proc/self/stat", Base::OM_Read);
char buffer[kProcBufferSize];
size_t nbytes = Base::Read(file, buffer, kProcBufferSize);
if(nbytes == static_cast<size_t>(-1)) {
PLUGIN_ERROR("problem reading proc stat");
return false;
}
char *pointer = buffer;
for(int i = 0; i < 13; ++i) {
pointer = GoToNextValue(pointer);
}
ProcessSample *sample = hist->GetNextSample();
Base::String::FromString(pointer, sample->user);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, sample->system);
Base::Close(file);
return true;
}
struct CPUStatsCmd::PIMPL {
u32 m_num_cpu; // number of processors
u32 m_ticks_per_sec; // clock speed.
ProcessHistory m_process; // process stat data.
CPUHistory m_total; // all cpu stat data.
CPUHistory *m_cpu; // stat data per cpu.
u32 m_last_read_time; // last time stats were read.
bool m_error; // true if there was a processing error
PIMPL(u32 sample_count) : m_error(false) {
m_num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
m_ticks_per_sec = sysconf(_SC_CLK_TCK);
m_cpu = new CPUHistory[m_num_cpu];
m_total.Resize(sample_count);
for(u32 i = 0; i < m_num_cpu; ++i) {
m_cpu[i].Resize(sample_count);
}
m_process.Resize(sample_count);
// init stats.
ReadStats();
}
~PIMPL() { delete[] m_cpu; }
void ReadStats() {
ReadCPUStats(&m_total, &m_cpu, m_num_cpu);
ReadProcessStats(&m_process);
m_last_read_time = Base::Time::GetTimeMs();
}
void Recalculate() {
m_total.Calculate(m_ticks_per_sec);
for(u32 i = 0; i < m_num_cpu; ++i) {
m_cpu[i].Calculate(m_ticks_per_sec);
}
}
};
CPUStatsCmd::CPUStatsCmd() {
u32 sample_count = 10;
m_pimpl = new PIMPL(sample_count);
}
CPUStatsCmd::~CPUStatsCmd() { delete m_pimpl; }
void CPUStatsCmd::Sample() {}
bool CPUStatsCmd::OnCommand(const std::string &query_string,
const std::string &post_data,
std::string *response_data) {
u32 prev_read_time = m_pimpl->m_last_read_time;
m_pimpl->ReadStats();
m_pimpl->Recalculate();
CPUPercent total;
m_pimpl->m_total.LastSampleStats(m_pimpl->m_ticks_per_sec, &total);
ProcessPercent process;
m_pimpl->m_process.LastSampleStats(m_pimpl->m_ticks_per_sec, &process);
JsonWriter writer(*response_data);
writer.Write("platform", "linux");
writer.Write("error", m_pimpl->m_error);
writer.Write("cpu_num", m_pimpl->m_num_cpu);
writer.Write("ticks_per_sec", m_pimpl->m_ticks_per_sec);
writer.Write("timestamp", m_pimpl->m_last_read_time);
writer.Write("timeslice", m_pimpl->m_last_read_time - prev_read_time);
writer.Write("total", total);
writer.Write("process", process);
writer.Finalize();
return true;
}
} // namespace Link
| 26.157895 | 77 | 0.638291 | pretty-wise |
3a14d40d59d1c1ddd94b4c01a08c6c40475e01e6 | 150 | cpp | C++ | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "template.hpp"
int main() {
int64_t a, b, k, l;
cin >> a >> b >> k >> l;
cout << min(k % l * a + k / l * b, k / l * b + b) << endl;
}
| 18.75 | 60 | 0.426667 | not522 |
3a15141528e6dda2f9bf0ab28c793d143c7a5f14 | 5,380 | cpp | C++ | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | 1 | 2021-03-09T02:39:45.000Z | 2021-03-09T02:39:45.000Z | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | null | null | null | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | null | null | null | #include "../external_dependencies/cmts/include/cmts.h"
#include "algorithm_thread.h"
#include "graphics/vulkan_state.h"
#include "windows-specific/framework.h"
#include "windows-specific/Resource.h"
#include <atomic>
#include <chrono>
#define MAX_LOADSTRING 100
HINSTANCE hinstance;
HWND hwnd;
static HACCEL accel;
std::atomic<bool> should_continue_global = true;
std::atomic<bool> should_continue_sort;
TCHAR window_title_buffer[4096];
extern LRESULT CALLBACK window_callbacks(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
extern int init_vulkan();
extern void draw_main_array();
namespace cmts_checks
{
const int count = 65536;
alignas(64) std::atomic_int counter_a;
alignas(64) std::atomic_int counter_b;
static void count_test_task_a(void* unused)
{
counter_a.fetch_add(1, std::memory_order_relaxed);
}
static void count_test_task_b(void* unused)
{
counter_b.fetch_add(1, std::memory_order_relaxed);
}
static void count_test()
{
cmts_init_options_t options = {};
options.task_stack_size = cmts_default_task_stack_size();
options.max_tasks = count;
options.thread_count = cmts_processor_count();
auto code = cmts_lib_init(&options);
assert(code == CMTS_OK);
code = cmts_dispatch([](void* unused)
{
cmts_counter_t ca, cb;
cmts_counter_init(&ca, count);
cmts_counter_init(&cb, count);
cmts_dispatch_options_t options = {};
options.flags = CMTS_DISPATCH_FLAGS_FORCE;
options.sync_type = CMTS_SYNC_TYPE_COUNTER;
options.sync_object = &ca;
for (int i = 0; i != count; ++i)
cmts_dispatch(count_test_task_a, &options);
options.sync_object = &cb;
for (int i = 0; i != count; ++i)
cmts_dispatch(count_test_task_b, &options);
cmts_counter_await(&ca);
cmts_counter_await(&cb);
cmts_lib_exit_signal();
}, nullptr);
assert(code == CMTS_OK);
code = cmts_lib_exit_await(nullptr);
assert(code == CMTS_OK);
}
static void run()
{
count_test();
}
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
//cmts_checks::run();
constexpr TCHAR class_name[] = TEXT("AVKClassName");
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = window_callbacks;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ARRAYVK));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = CreateSolidBrush(0);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_MAIN_MENU);
wcex.lpszClassName = class_name;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
constexpr auto base_counter = __COUNTER__;
if (RegisterClassEx(&wcex) == INVALID_ATOM)
return -(__COUNTER__ - base_counter);
hinstance = hInstance;
constexpr TCHAR title[] = TEXT("AVK - Sorting Algorithm Visualizer");
hwnd = CreateWindow(
class_name,
title,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0,
nullptr, nullptr,
hInstance, nullptr);
if (hwnd == nullptr)
return -(__COUNTER__ - base_counter);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
accel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MAIN_MENU));
const int res = init_vulkan();
if (res < 0)
return (1 << 30) | res;
algorithm_thread::launch();
using namespace std::chrono;
auto last = high_resolution_clock::now();
auto delay = std::chrono::milliseconds(1);
main_array::set_compare_delay(delay);
main_array::set_read_delay(delay);
main_array::set_write_delay(delay);
main_array::resize(1 << 8);
constexpr TCHAR title_format[] = TEXT("AVK - Sorting Algorithm Visualizer - [ %u elements ]");
#ifdef UNICODE
wsprintf(window_title_buffer, title_format, main_array::size());
SetWindowText(hwnd, window_title_buffer);
#else
sprintf(window_title_buffer, title_format, main_array::size());
SetWindowTextA(hwnd, window_title_buffer);
#endif
main_array::for_each([&](item& e, uint32_t position)
{
e.value = position;
e.original_position = position;
e.color = item_color::white();
});
constexpr auto framerrate = duration<long double>(1.0 / 60.0);
auto last_draw = high_resolution_clock::now();
MSG msg = {};
while (should_continue_global.load(std::memory_order_acquire))
{
while (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE))
{
if (!TranslateAccelerator(msg.hwnd, accel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
const auto now = high_resolution_clock::now();
if (now - last_draw > framerrate)
{
draw_main_array();
last_draw = now;
}
}
algorithm_thread::terminate();
return (int)msg.message;
} | 28.167539 | 123 | 0.64684 | hanxingyixue-arch |
3a1588c32aae4d242d82280d4d2868edde1df202 | 999 | hpp | C++ | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | 3 | 2019-07-12T23:12:24.000Z | 2019-09-05T07:57:45.000Z | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | #pragma once
#include <PP/declval.hpp>
#include <PP/get_type.hpp>
#include <PP/macros/simple_concept.hpp>
#include <PP/value_t.hpp>
#include <PP/tuple/count.hpp>
#include <PP/tuple/element.hpp>
#include <PP/tuple/get.hpp>
#include <PP/tuple/value_sequence_for.hpp>
namespace PP::detail
{
template <typename T, auto I>
concept tuple_access = requires
{
::PP::declval_impl<T>()[::PP::value<I>];
::PP::tuple::element(::PP::value<I>, ::PP::declval_impl<T>());
};
template <typename T, auto... I>
concept tuple_accesses = (tuple_access<T, I> && ...);
template <auto... I>
constexpr auto is_tuple_helper(concepts::type auto&& t,
value_sequence<I...>) noexcept
{
return tuple_accesses<PP_GT(t), I...>;
}
}
namespace PP::concepts
{
template <typename T>
concept tuple = requires
{
::PP::tuple::count_value_t(::PP::declval_impl<T>());
}
&&PP::detail::is_tuple_helper(PP::type<T>,
tuple::type_value_sequence_for(PP::type<T>));
}
| 24.975 | 75 | 0.648649 | Petkr |
3a163a1d66dc0789e7dda43cf37d991caf425013 | 24,837 | cpp | C++ | src/OrbitVulkanLayer/VulkanLayerProducerImplTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 2 | 2020-07-31T08:18:58.000Z | 2021-12-26T06:43:07.000Z | src/OrbitVulkanLayer/VulkanLayerProducerImplTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | null | null | null | src/OrbitVulkanLayer/VulkanLayerProducerImplTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1 | 2021-03-10T15:21:19.000Z | 2021-03-10T15:21:19.000Z | // Copyright (c) 2020 The Orbit 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 <gmock/gmock.h>
#include <gtest/gtest.h>
#include "FakeProducerSideService/FakeProducerSideService.h"
#include "VulkanLayerProducerImpl.h"
namespace orbit_vulkan_layer {
namespace {
class MockCaptureStatusListener : public VulkanLayerProducer::CaptureStatusListener {
public:
MOCK_METHOD(void, OnCaptureStart, (orbit_grpc_protos::CaptureOptions), (override));
MOCK_METHOD(void, OnCaptureStop, (), (override));
MOCK_METHOD(void, OnCaptureFinished, (), (override));
};
class VulkanLayerProducerImplTest : public ::testing::Test {
protected:
void SetUp() override {
fake_service_.emplace();
grpc::ServerBuilder builder;
builder.RegisterService(&fake_service_.value());
fake_server_ = builder.BuildAndStart();
ASSERT_NE(fake_server_, nullptr);
std::shared_ptr<grpc::Channel> channel =
fake_server_->InProcessChannel(grpc::ChannelArguments{});
producer_.emplace();
producer_->SetCaptureStatusListener(&mock_listener_);
producer_->BringUp(channel);
// Leave some time for the ReceiveCommandsAndSendEvents RPC to actually happen.
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
void TearDown() override {
// Leave some time for all pending communication to finish.
std::this_thread::sleep_for(std::chrono::milliseconds(50));
producer_->TakeDown();
producer_->SetCaptureStatusListener(nullptr);
producer_.reset();
fake_service_->FinishAndDisallowRpc();
fake_server_->Shutdown();
fake_server_->Wait();
fake_service_.reset();
fake_server_.reset();
}
std::optional<orbit_fake_producer_side_service::FakeProducerSideService> fake_service_;
std::unique_ptr<grpc::Server> fake_server_;
std::optional<VulkanLayerProducerImpl> producer_;
MockCaptureStatusListener mock_listener_;
static const std::string kInternedString1;
static const uint64_t kExpectedInternedString1Key;
static const std::string kInternedString2;
static const uint64_t kExpectedInternedString2Key;
static const std::string kInternedString3;
static const uint64_t kExpectedInternedString3Key;
};
const std::string VulkanLayerProducerImplTest::kInternedString1 = "a";
const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString1Key =
std::hash<std::string>{}(kInternedString1);
const std::string VulkanLayerProducerImplTest::kInternedString2 = "b";
const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString2Key =
std::hash<std::string>{}(kInternedString2);
const std::string VulkanLayerProducerImplTest::kInternedString3 = "c";
const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString3Key =
std::hash<std::string>{}(kInternedString3);
constexpr std::chrono::milliseconds kWaitMessagesSentDuration{25};
const orbit_grpc_protos::CaptureOptions kFakeCaptureOptions = [] {
orbit_grpc_protos::CaptureOptions capture_options;
capture_options.set_pid(42);
capture_options.set_samples_per_second(1234.0);
return capture_options;
}();
MATCHER_P(CaptureOptionsEq, that, "") {
const orbit_grpc_protos::CaptureOptions& a = arg;
const orbit_grpc_protos::CaptureOptions& b = that;
return a.SerializeAsString() == b.SerializeAsString();
}
TEST_F(VulkanLayerProducerImplTest, IsCapturingAndListener) {
EXPECT_FALSE(producer_->IsCapturing());
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_TRUE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_TRUE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
}
TEST_F(VulkanLayerProducerImplTest, WorksWithNoListener) {
EXPECT_CALL(mock_listener_, OnCaptureStart).Times(0);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(0);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(0);
producer_->SetCaptureStatusListener(nullptr);
EXPECT_FALSE(producer_->IsCapturing());
fake_service_->SendStartCaptureCommand(orbit_grpc_protos::CaptureOptions{});
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_TRUE(producer_->IsCapturing());
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_FALSE(producer_->IsCapturing());
}
TEST_F(VulkanLayerProducerImplTest, EnqueueCaptureEvent) {
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
int32_t capture_events_received_count = 0;
ON_CALL(*fake_service_, OnCaptureEventsReceived)
.WillByDefault([&capture_events_received_count](
const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
capture_events_received_count += events.size();
});
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(::testing::Between(1, 3));
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
std::this_thread::sleep_for(kWaitMessagesSentDuration);
EXPECT_EQ(capture_events_received_count, 3);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent()));
}
static void ExpectInternedStrings(
const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& actual_events,
const std::vector<std::pair<std::string, uint64_t>>& expected_interns) {
ASSERT_EQ(actual_events.size(), expected_interns.size());
for (size_t i = 0; i < actual_events.size(); ++i) {
ASSERT_EQ(actual_events[i].event_case(),
orbit_grpc_protos::ProducerCaptureEvent::kInternedString);
EXPECT_EQ(actual_events[i].interned_string().intern(), expected_interns[i].first);
EXPECT_EQ(actual_events[i].interned_string().key(), expected_interns[i].second);
}
}
TEST_F(VulkanLayerProducerImplTest, InternStringIfNecessaryAndGetKey) {
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received;
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived)
.Times(::testing::Between(1, 2))
.WillRepeatedly(
[&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
events_received.insert(events_received.end(), events.begin(), events.end());
});
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key},
{kInternedString2, kExpectedInternedString2Key}});
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
// These should not be sent to the service.
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString3);
EXPECT_EQ(actual_key, kExpectedInternedString3Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
// These should not be sent to the service.
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString3);
EXPECT_EQ(actual_key, kExpectedInternedString3Key);
}
TEST_F(VulkanLayerProducerImplTest, DontSendInternTwice) {
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received;
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived)
.Times(1)
.WillRepeatedly(
[&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
events_received.insert(events_received.end(), events.begin(), events.end());
});
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}});
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
}
TEST_F(VulkanLayerProducerImplTest, ReInternInNewCapture) {
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received;
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived)
.Times(::testing::Between(1, 2))
.WillRepeatedly(
[&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
events_received.insert(events_received.end(), events.begin(), events.end());
});
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key},
{kInternedString2, kExpectedInternedString2Key}});
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
events_received.clear();
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived)
.Times(::testing::Between(1, 2))
.WillRepeatedly(
[&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
events_received.insert(events_received.end(), events.begin(), events.end());
});
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key},
{kInternedString2, kExpectedInternedString2Key}});
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
}
TEST_F(VulkanLayerProducerImplTest, InternOnlyWhenCapturing) {
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
// These should not be sent to the service.
uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
// These should not be sent to the service.
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendStartCaptureCommand(kFakeCaptureOptions);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received;
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived)
.Times(::testing::Between(1, 2))
.WillRepeatedly(
[&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) {
events_received.insert(events_received.end(), events.begin(), events.end());
});
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1);
EXPECT_EQ(actual_key, kExpectedInternedString1Key);
actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2);
EXPECT_EQ(actual_key, kExpectedInternedString2Key);
std::this_thread::sleep_for(kWaitMessagesSentDuration);
ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key},
{kInternedString2, kExpectedInternedString2Key}});
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1);
fake_service_->SendStopCaptureCommand();
std::this_thread::sleep_for(kWaitMessagesSentDuration);
::testing::Mock::VerifyAndClearExpectations(&mock_listener_);
::testing::Mock::VerifyAndClearExpectations(&*fake_service_);
EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1);
EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0);
EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0);
fake_service_->SendCaptureFinishedCommand();
}
} // namespace
} // namespace orbit_vulkan_layer
| 47.218631 | 98 | 0.793816 | tufeigunchu |
3a17b43d010b587291241dfa2aec969429e24ef3 | 10,856 | cpp | C++ | RcsPySim/src/cpp/pyEnv/module.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 52 | 2020-05-02T13:55:09.000Z | 2022-03-09T14:49:36.000Z | RcsPySim/src/cpp/pyEnv/module.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 40 | 2020-09-01T15:19:22.000Z | 2021-11-02T14:51:41.000Z | RcsPySim/src/cpp/pyEnv/module.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 13 | 2020-07-03T11:39:21.000Z | 2022-02-20T01:12:42.000Z | /*******************************************************************************
Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
Technical University of Darmstadt.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,
or Technical University of Darmstadt, 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 FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,
OR TECHNICAL UNIVERSITY OF DARMSTADT 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 "RcsSimEnv.h"
#include "config/PropertySourceDict.h"
#include "config/PropertySourceXml.h"
#include "control/ControlPolicy.h"
#include "physics/vortex_log.h"
#include "util/BoxSpace.h"
#include "util/type_casters.h"
#include "util/pybind_dict_utils.h"
#include <pybind11/stl.h>
namespace py = pybind11;
#include <Rcs_resourcePath.h>
#include <Rcs_macros.h>
#include <Rcs_MatNd.h>
#include <Rcs_Vec3d.h>
#include <PhysicsFactory.h>
#include <SegFaultHandler.h>
#include <Rcs_typedef.h>
RCS_INSTALL_ERRORHANDLERS
/* Could be done in the future
void define_gui_classes(py::module& m);
*/
PYBIND11_MODULE(_rcsenv, m)
{
// define exceptions
py::register_exception<Rcs::JointLimitException>(m, "JointLimitException");
// Define BoxSpace as class. It's not providing a constructor here, it's just meant to be passed to python for information
py::class_<Rcs::BoxSpace>(m, "BoxSpace")
.def_property_readonly("min", &Rcs::BoxSpace::getMin, py::return_value_policy::reference_internal)
.def_property_readonly("max", &Rcs::BoxSpace::getMax, py::return_value_policy::reference_internal)
.def_property_readonly("names", [](
const Rcs::BoxSpace& thiz) -> py::object {
auto& names = thiz.getNames();
if (names.empty()) {
return py::none();
}
return py::cast(names);
});
// Define simulator base class
py::class_<Rcs::RcsSimEnv>(m, "RcsSimEnv")
.def(py::init([](py::kwargs kwargs) {
// Get properties from xml or python
Rcs::PropertySource* config;
std::string configFileName;
if (try_get(kwargs, "experimentConfigFile", configFileName)) {
config = new Rcs::PropertySourceXml(configFileName.c_str());
}
else {
config = new Rcs::PropertySourceDict(kwargs);
}
// Create config object, takes ownership of property source
return new Rcs::RcsSimEnv(config);
})
)
.def("step", &Rcs::RcsSimEnv::step, py::arg("action"), py::arg("disturbance") = py::none(),
py::call_guard<py::gil_scoped_release>())
.def("reset", [](Rcs::RcsSimEnv& self, py::object domainParam, const MatNd* initState) {
Rcs::PropertySource* domainParamSource = Rcs::PropertySource::empty();
if (!domainParam.is_none()) {
domainParamSource = new Rcs::PropertySourceDict(domainParam);
}
MatNd* result = self.reset(domainParamSource, initState);
if (!domainParam.is_none()) {
delete domainParamSource;
}
return result;
},
py::arg("domainParam").none(true) = py::none(), py::arg("initState").none(true) = py::none()
)
.def("render", &Rcs::RcsSimEnv::render, py::arg("mode") = "human", py::arg("close") = false)
.def("toggleVideoRecording", &Rcs::RcsSimEnv::toggleVideoRecording)
.def("setTransitionNoiseBuffer", &Rcs::RcsSimEnv::setTransitionNoiseBuffer)
.def("saveConfigXML", [](Rcs::RcsSimEnv& self, const char* fileName) {
self.getConfig()->properties->saveXML(fileName, "Experiment");
})
.def("getBodyPosition",
[](Rcs::RcsSimEnv& self, const char* bodyName, const char* refBodyName, const char* refFrameName) {
const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName);
RCHECK(body);
const RcsBody* refBody = RcsGraph_getBodyByName(self.getConfig()->graph, refBodyName);
const RcsBody* refFrame = RcsGraph_getBodyByName(self.getConfig()->graph, refFrameName);
double I_r[3];
// Effector-fixed reference point in world coordinates
Vec3d_copy(I_r, body->A_BI->org);
// Transform to reference frame: ref_r = A_ref-I * (I_r - I_r_refBdy)
if (refBody != NULL) {
Vec3d_subSelf(I_r, refBody->A_BI->org); // I_r -= I_r_refBdy
// refBody and refFrame, but they differ: refFrame_r = A_refFrame-I*I_r
if ((refFrame != NULL) && (refFrame != refBody)) {
Vec3d_rotateSelf(I_r, refFrame->A_BI->rot);
}
// refBody and refFrame are the same: refFrame_r = A_refBody-I*I_r
else {
Vec3d_rotateSelf(I_r, refBody->A_BI->rot);
}
}
// No refBody, but refFrame: Rotate into refFrame coordinates
else {
// Rotate into refFrame if it exists
if (refFrame != NULL) {
Vec3d_rotateSelf(I_r, refFrame->A_BI->rot);
}
}
MatNd* pos = NULL;
pos = MatNd_create(3, 1);
for (unsigned int i = 0; i < 3; i++) {
MatNd_set(pos, i, 0, I_r[i]);
}
return pos;
},
py::arg("bodyName"), py::arg("refFrameName"), py::arg("refBodyName")
)
.def("getBodyExtents", [](Rcs::RcsSimEnv& self, const char* bodyName, const int shapeIdx) {
const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName);
RCHECK(body);
MatNd* extents = NULL;
extents = MatNd_create(3, 1);
for (unsigned int i = 0; i < 3; i++) {
MatNd_set(extents, i, 0, body->shape[shapeIdx]->extents[i]);
}
return extents;
},
py::arg("bodyName"), py::arg("shapeIdx")
)
// Properties
.def_property_readonly("observationSpace", &Rcs::RcsSimEnv::observationSpace)
.def_property_readonly("actionSpace", &Rcs::RcsSimEnv::actionSpace)
.def_property_readonly("initStateSpace", &Rcs::RcsSimEnv::initStateSpace)
.def_property_readonly("domainParam", [](Rcs::RcsSimEnv& self) {
// Expose the domain parameters to the Python side
py::dict result;
Rcs::PropertySourceDict psink(result);
self.getPhysicsManager()->getValues(&psink);
return result;
})
.def_property_readonly("internalStateDim", &Rcs::RcsSimEnv::getInternalStateDim)
.def_property_readonly("dt", [](Rcs::RcsSimEnv& self) {
return self.getConfig()->dt;
})
.def_property_readonly("lastAction", &Rcs::RcsSimEnv::getCurrentAction, py::return_value_policy::copy)
.def_property_readonly("lastObservation", &Rcs::RcsSimEnv::getCurrentObservation,
py::return_value_policy::copy);
// Define ControlPolicy for tests
py::class_<Rcs::ControlPolicy> controlPolicy(m, "ControlPolicy");
controlPolicy.def(py::init<Rcs::ControlPolicy* (*)(const char*, const char*)>(&Rcs::ControlPolicy::create));
controlPolicy.def("__call__", [](Rcs::ControlPolicy& self, const MatNd* input, unsigned int output_size) {
MatNd* output = MatNd_create(output_size, 1);
self.computeAction(output, input);
return output;
});
controlPolicy.def("reset", &Rcs::ControlPolicy::reset);
controlPolicy.def_property_readonly_static("types", [](py::handle /* self */) {
return Rcs::ControlPolicy::getTypeNames();
});
// Expose the ControlPolicy classes to the Python side
// py::class_<Rcs::ActionModelIKPolicy>(m, "ActionModelIKPolicy", controlPolicy)
// .def(py::init(&Rcs::loadMLPPolicyFromXml));
/* Could be done in the future
#ifdef GUI_AVAILABLE
// Define gui stuff if available
define_gui_classes(m);
#endif
*/
m.def("saveExperimentParams", [](py::dict& config, const char* filename){
std::unique_ptr<Rcs::PropertySource> ps(new Rcs::PropertySourceDict(config));
ps->saveXML(filename, "Experiment");
}, py::arg("config"), py::arg("filename"));
// Sets the rcs log level
m.def("setLogLevel", [](int level) { RcsLogLevel = level; });
// Adds a directory to the resource path
m.def("addResourcePath", [](const char* path) { return Rcs_addResourcePath(path); });
// Check if physics engine is available (can't list, unfortunately)
m.def("supportsPhysicsEngine", &Rcs::PhysicsFactory::hasEngine);
// Control vortex log level, setting it to warnings only by default (this avoids log spam)
Rcs::setVortexLogLevel("warn");
// Allow changing it if desired
m.def("setVortexLogLevel", &Rcs::setVortexLogLevel);
}
| 46.393162 | 126 | 0.605195 | theogruner |
3a1afcbceeae17911fc911949ede0b302f08f7a5 | 1,485 | cpp | C++ | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#define EPSILON 1e-10
bool is_same(double __x, double __y) {
if(std::abs(__x - __y) < EPSILON) {
std::cout << std::fixed << "IN Function __x\t\t" << __x << "\n";
std::cout << std::fixed << "IN Function __y\t\t" << __y << "\n";
std::cout << std::fixed << "std::abs(__x - __y)\t" << std::abs(__x - __y) << "\n";
return true;
} else {
return false;
}
}
double distance(double x1, double y1, double x2, double y2) {
return std::sqrt(std::pow((x2 - x1), 2) + std::pow((y2 - y1), 2));
}
int main() {
std::cout.precision(17); // maximum precision : https://stackoverflow.com/a/554134/7105963
std::cout << std::fixed << "dist (0, 0) ~ (3, 4)\t" << distance(0, 0, 3, 4) << "\n";
std::cout << std::fixed << "EPSILON(small)\t\t" << EPSILON << "\n";
std::cout << std::fixed << "distance + EPSILON\t" << (distance(0, 0, 3, 4) + EPSILON) << "\n";
std::cout << std::fixed << "distance - EPSILON\t" << (distance(0, 0, 3, 4) - EPSILON) << "\n";
// std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + __DBL_EPSILON__)) << "\n";
std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + EPSILON)) << "\n";
std::cout << std::fixed << "5.0 + EPSILON\t\t" << (5.0 + EPSILON) << "\n";
std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n";
std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n";
} | 46.40625 | 101 | 0.517845 | TyeolRik |