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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
87090155798e02849440b7df1a3fa33529136b2a | 269 | hpp | C++ | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | // Copyright 2013, James Mitchell, All rights reserved.
#pragma once
#include "Types.hpp"
namespace util
{
template<bool, typename _Tp = void> struct enable_if { };
template<typename T> struct enable_if<true, T> { DEFINE_TYPE(T) };
}
| 22.416667 | 85 | 0.639405 | jmitchell24 |
870a4efe0b87e9d44cc4fbac19d5f70a924e675a | 1,006 | cpp | C++ | development/C++/src/client/Da/ClientDaGetPropertiesOptions.cpp | Movares/OPC-Classic-SDK | 65e022dd4ccf20bbdacdfc49cac23bd99d773b98 | [
"MIT"
] | 19 | 2021-05-19T11:03:57.000Z | 2022-03-18T06:53:48.000Z | development/C++/src/client/Da/ClientDaGetPropertiesOptions.cpp | Movares/OPC-Classic-SDK | 65e022dd4ccf20bbdacdfc49cac23bd99d773b98 | [
"MIT"
] | 8 | 2021-04-26T10:47:20.000Z | 2022-03-15T11:25:07.000Z | development/C++/src/client/Da/ClientDaGetPropertiesOptions.cpp | Movares/OPC-Classic-SDK | 65e022dd4ccf20bbdacdfc49cac23bd99d773b98 | [
"MIT"
] | 11 | 2021-05-28T06:35:20.000Z | 2022-03-31T14:07:25.000Z | #include "OSCompat.h"
#include "ClientDaGetPropertiesOptions.h"
using namespace SoftingOPCToolboxClient;
DaGetPropertiesOptions::DaGetPropertiesOptions()
{
m_whatPropertyData = (EnumPropertyData)0;
} //end constructor
DaGetPropertiesOptions::~DaGetPropertiesOptions()
{
}//end destructor
EnumPropertyData DaGetPropertiesOptions::getWhatPropertyData()
{
return m_whatPropertyData;
} //end getWhatPropertyData
void DaGetPropertiesOptions::setWhatPropertyData(EnumPropertyData somePropertyData)
{
m_whatPropertyData = somePropertyData;
} //end
std::vector<unsigned long>& DaGetPropertiesOptions::getPropertyIds()
{
return m_pPropertyIds;
} //end
void DaGetPropertiesOptions::setPropertyIds(std::vector<unsigned long>& propertyIds)
{
m_pPropertyIds = propertyIds;
} //end
std::vector<tstring>& DaGetPropertiesOptions::getPropertyNames()
{
return m_pPropertyNames;
} //end
void DaGetPropertiesOptions::setPropertyNames(std::vector<tstring>& propertyNames)
{
m_pPropertyNames = propertyNames;
} //end
| 25.794872 | 84 | 0.813121 | Movares |
8710a8fd5e0fbcff499b7a3a4eb52546c6d56649 | 3,331 | hpp | C++ | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.Enum
#include "System/Enum.hpp"
// Including type: UnityEngine.XR.InputTracking
#include "UnityEngine/XR/InputTracking.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine.XR
namespace UnityEngine::XR {
// Autogenerated type: UnityEngine.XR.InputTracking/TrackingStateEventType
struct InputTracking::TrackingStateEventType : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static constexpr const int NodeAdded = 0;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_NodeAdded();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static void _set_NodeAdded(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static constexpr const int NodeRemoved = 1;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_NodeRemoved();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static void _set_NodeRemoved(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static constexpr const int TrackingAcquired = 2;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_TrackingAcquired();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static void _set_TrackingAcquired(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static constexpr const int TrackingLost = 3;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_TrackingLost();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static void _set_TrackingLost(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// Creating value type constructor for type: TrackingStateEventType
TrackingStateEventType(int value_ = {}) : value{value_} {}
}; // UnityEngine.XR.InputTracking/TrackingStateEventType
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::XR::InputTracking::TrackingStateEventType, "UnityEngine.XR", "InputTracking/TrackingStateEventType");
#pragma pack(pop)
| 62.849057 | 137 | 0.783248 | Futuremappermydud |
87163c9a64bfe7a68cf6b6a346a3343bf9c8d1de | 1,600 | cpp | C++ | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#define SIZE 10001
using namespace std;
typedef struct _Prop
{
int value;
int num;
} prop;
prop arr[SIZE];
int c1[SIZE], c2[SIZE];
const int mod = 10000;
int main()
{
ios::sync_with_stdio(false);
int propNum;
while (cin >> propNum)
{
if (propNum == 0)
break;
int valueSum = 0;
for (int i = 0; i < propNum; i++)
{
cin >> arr[i].value >> arr[i].num;
valueSum += arr[i].value * arr[i].num;
}
if (valueSum % 3 > 0)
{
cout << "sorry" << endl;
}
else
{
int target = valueSum / 3;
memset(c1, 0, sizeof(c1));
c1[0] = 1;
for (int i = 0; i < propNum; i++)
{
memset(c2, 0, sizeof(c2));
for (int j = 0; j <= arr[i].num && j * arr[i].value <= target; j++)
{
for (int k = 0; k + j * arr[i].value <= target; k++)
{
c2[k + j * arr[i].value] += c1[k];
c2[k + j * arr[i].value] %= mod;
}
}
memcpy(c1, c2, sizeof(c2));
}
if (c1[target] > 0)
{
cout << c1[target] % mod << endl;
}
else
{
cout << "sorry" << endl;
}
}
}
return 0;
}
| 21.621622 | 83 | 0.3925 | codgician |
8716e23fdac924e63170d4c0a2c1618179b694c0 | 1,100 | cpp | C++ | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
struct State {
vector<int> v;
State(int n) : v(n) {}
int operator() () {
int ret = 0;
for (auto& i : v) ret = ret * 5 + i;
return ret;
}
bool Check() {
for (auto& i : v) if (i != v[0]) return 0;
return 1;
}
void Flip(const vector<int>& adj, int k) {
for (auto& i : adj) v[i] = (v[i] + k) % 5;
}
};
int main() {
fastio;
int n, k; cin >> n >> k;
State S(n); vector<vector<int>> adj(k);
for (int i = 0; i < n; i++) cin >> S.v[i];
for (int i = 0; i < k; i++) {
int t; cin >> t; adj[i].resize(t);
for (auto& j : adj[i]) cin >> j, --j;
}
auto Sol = [&]() -> int {
int sz = 1;
for (int i = 0; i < n; i++) sz *= 5;
vector<int> dist(sz, -1); queue<State> Q;
Q.push(S); dist[S()] = 0;
while (Q.size()) {
auto cur = Q.front(); Q.pop();
if (cur.Check()) return dist[cur()];
for (int i = 0; i < k; i++) {
auto nxt = cur; nxt.Flip(adj[i], i + 1);
if (!~dist[nxt()]) Q.push(nxt), dist[nxt()] = dist[cur()] + 1;
}
}
return -1;
};
cout << Sol() << '\n';
} | 22.916667 | 66 | 0.490909 | jinhan814 |
871831b48c69ee39c50d0046a02517f1f5fe94b0 | 748 | hpp | C++ | engine/util/WindGenerator.hpp | isonil/survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2017-05-12T10:12:41.000Z | 2017-05-12T10:12:41.000Z | engine/util/WindGenerator.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | null | null | null | engine/util/WindGenerator.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2019-01-09T04:05:36.000Z | 2019-01-09T04:05:36.000Z | #ifndef ENGINE_WIND_GENERATOR_HPP
#define ENGINE_WIND_GENERATOR_HPP
#include "Vec2.hpp"
#include "Vec3.hpp"
namespace engine
{
class WindGenerator
{
public:
WindGenerator(float strength, float regularity);
float getStrength() const;
void setStrength(float strength);
float getRegularity() const;
void setRegularity(float regularity);
FloatVec2 getWind(const FloatVec3 &pos, double time);
private:
float randGenerator(int x) const;
float cosInterpolator(float a, float b, float x) const;
float windSmoother(int x) const;
float noiseInterpolate(float x) const;
float noise(float x) const;
float m_strength;
float m_regularity;
};
} // namespace engine
#endif // ENGINE_WIND_GENERATOR_HPP
| 20.216216 | 59 | 0.735294 | isonil |
8719cf93353ea539a3162d3ff80b5b06f5f6013b | 1,553 | hpp | C++ | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | // Leka - LekaOS
// Copyright 2021 APF France handicap
// SPDX-License-Identifier: Apache-2.0
#ifndef _LEKA_OS_DRIVER_CORE_VIDEO_H_
#define _LEKA_OS_DRIVER_CORE_VIDEO_H_
#include "CoreSTM32HalBase.h"
#include "interface/DMA2D.hpp"
#include "interface/DSI.hpp"
#include "interface/Font.hpp"
#include "interface/Graphics.hpp"
#include "interface/JPEG.hpp"
#include "interface/LCD.hpp"
#include "interface/LTDC.hpp"
#include "interface/SDRAM.hpp"
namespace leka {
class CoreVideo
{
public:
CoreVideo(CoreSTM32HalBase &hal, interface::SDRAM &coresdram, interface::DMA2DBase &coredma2d,
interface::DSIBase &coredsi, interface::LTDCBase &coreltdc, interface::LCD &corelcd,
interface::Graphics &coregraphics, interface::Font &corefont, interface::JPEGBase &corejpeg);
void initialize();
void turnOff();
void turnOn();
void setBrightness(float value);
void clearScreen(CGColor color = CGColor::white);
void displayRectangle(interface::Graphics::FilledRectangle rectangle, CGColor color);
void displayImage(FIL *file);
void displayText(const char *text, uint32_t size, uint32_t starting_line, CGColor foreground = CGColor::black,
CGColor background = CGColor::white);
private:
CoreSTM32HalBase &_hal;
interface::SDRAM &_coresdram;
interface::DMA2DBase &_coredma2d;
interface::DSIBase &_coredsi;
interface::LTDCBase &_coreltdc;
interface::LCD &_corelcd;
interface::Graphics &_coregraphics;
interface::Font &_corefont;
interface::JPEGBase &_corejpeg;
};
} // namespace leka
#endif // _LEKA_OS_DRIVER_CORE_VIDEO_H_
| 28.236364 | 111 | 0.768835 | MMyster |
26bb028f4fa7e6b5a52a3612176d82174ab1587a | 310 | cpp | C++ | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | 1 | 2022-03-01T16:57:32.000Z | 2022-03-01T16:57:32.000Z | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | null | null | null | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | 1 | 2022-03-23T18:35:12.000Z | 2022-03-23T18:35:12.000Z | #include "Teste.h"
#include <string>
using namespace std;
StrAtt::StrAtt(string _str, long long int _linha, long long int _coluna, long long int _posicao) :
Atributo("StrAtt"), str(_str),linha(_linha),coluna(_coluna),posicao(_posicao) {}
NameAtt::NameAtt(string _str) : Atributo("NameAtt"), str(_str) {}
| 28.181818 | 99 | 0.725806 | pedrol3001 |
26bc3aff8d23a92d56377a94beb2252256a9cf07 | 7,290 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2020-01-11T12:53:52.000Z | 2020-01-11T12:53:52.000Z | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | null | null | null | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2021-05-05T12:05:28.000Z | 2021-05-05T12:05:28.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "win32inc.hpp"
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Specialized;
using namespace System::Xml;
using namespace System::Xml::XPath;
#ifndef __PRINTSYSTEMINTEROPINC_HPP__
#include <PrintSystemInteropInc.hpp>
#endif
#ifndef __PRINTSYSTEMINC_HPP__
#include <PrintSystemInc.hpp>
#endif
using namespace System::Printing;
#ifndef __PRINTSYSTEMATTRIBUTEVALUEFACTORY_HPP__
#include <PrintSystemAttributeValueFactory.hpp>
#endif
using namespace System::Printing::Activation;
PrintPropertyFactory::
PrintPropertyFactory(
void
):
valueDelegatesTable(nullptr),
noValueDelegatesTable(nullptr),
valueLinkedDelegatesTable(nullptr),
noValueLinkedDelegatesTable(nullptr)
{
if(!((valueDelegatesTable = gcnew Hashtable) &&
(noValueDelegatesTable = gcnew Hashtable) &&
(valueLinkedDelegatesTable = gcnew Hashtable) &&
(noValueLinkedDelegatesTable = gcnew Hashtable)))
{
}
}
PrintPropertyFactory::
~PrintPropertyFactory(
void
)
{
InternalDispose(true);
}
PrintPropertyFactory::
!PrintPropertyFactory(
void
)
{
InternalDispose(false);
}
void
PrintPropertyFactory::
InternalDispose(
bool disposing
)
{
if(!this->isDisposed)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(!this->isDisposed)
{
if(disposing)
{
isDisposed = true;
valueDelegatesTable = nullptr;
noValueDelegatesTable = nullptr;
valueLinkedDelegatesTable = nullptr;
noValueLinkedDelegatesTable = nullptr;
}
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
}
PrintPropertyFactory^
PrintPropertyFactory::Value::
get(
void
)
{
if(PrintPropertyFactory::value == nullptr)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(PrintPropertyFactory::value == nullptr)
{
PrintPropertyFactory::value = gcnew PrintPropertyFactory();
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
return const_cast<PrintPropertyFactory^>(PrintPropertyFactory::value);
}
Object^
PrintPropertyFactory::SyncRoot::
get(
void
)
{
return const_cast<Object^>(syncRoot);
}
void
PrintPropertyFactory::
RegisterValueCreationDelegate(
Type^ type,
PrintProperty::CreateWithValue^ delegate
)
{
try
{
valueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterNoValueCreationDelegate(
Type^ type,
PrintProperty::CreateWithNoValue^ delegate
)
{
try
{
noValueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterValueLinkedCreationDelegate(
Type^ type,
PrintProperty::CreateWithValueLinked^ delegate
)
{
try
{
valueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterNoValueLinkedCreationDelegate(
Type^ type,
PrintProperty::CreateWithNoValueLinked^ delegate
)
{
try
{
noValueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
UnRegisterValueCreationDelegate(
Type^ type
)
{
valueDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterNoValueCreationDelegate(
Type^ type
)
{
noValueDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterValueLinkedCreationDelegate(
Type^ type
)
{
valueLinkedDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterNoValueLinkedCreationDelegate(
Type^ type
)
{
noValueLinkedDelegatesTable->Remove(type->FullName);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName
)
{
PrintProperty::CreateWithNoValue^ attributeValueDelegate =
(PrintProperty::CreateWithNoValue^)noValueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
Object^ attribValue
)
{
PrintProperty::CreateWithValue^ attributeValueDelegate =
(PrintProperty::CreateWithValue^)valueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,attribValue);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
MulticastDelegate^ delegate
)
{
PrintProperty::CreateWithNoValueLinked^ attributeValueDelegate =
(PrintProperty::CreateWithNoValueLinked^)noValueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,delegate);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
Object^ attribValue,
MulticastDelegate^ delegate
)
{
PrintProperty::CreateWithValueLinked^ attributeValueDelegate =
(PrintProperty::CreateWithValueLinked^)valueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,attribValue,delegate);
}
IEnumerator^
PrintPropertyFactory::
GetEnumerator(
void
)
{
return nullptr;
}
| 22.639752 | 90 | 0.593141 | reyqn |
26be764d9a47683a99f73033ecfaeb1b2023ec1f | 253 | cc | C++ | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | #include "include/jade.hpp"
FUNCTION STRING REMAIN$ (STRING src, STRING match) DO
STRING tmpStr;
INTEGER pos;
pos = src.find(match);
IF (pos >= 0) THEN
tmpStr = src.substr(pos,src.size());
END
RETURN tmpStr;
END
| 15.8125 | 53 | 0.604743 | xet7 |
26c01fac9c00495d500cc22b6a3fe183185c2dc4 | 468 | cpp | C++ | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | #include "gtest/gtest.h"
#include "math/mathfunctions.h"
TEST(MathApprox, HandlesZeroInput) {
const double eps = std::numeric_limits<double>::epsilon();
ASSERT_TRUE(approx(1.0, 1.0, eps));
ASSERT_FALSE(approx(1.0, 1.0 + eps, eps));
const float one = 1.0;
const float epsf = std::numeric_limits<float>::epsilon();
ASSERT_TRUE(approx(one, one, epsf));
ASSERT_FALSE(approx(one, one + epsf, epsf));
ASSERT_TRUE(isEven(2));
ASSERT_FALSE(isEven(1));
}
| 27.529412 | 60 | 0.690171 | SFCMM |
26c07a555e21348d05e8a98da5b7f76539017920 | 1,598 | cpp | C++ | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | #include "RenderingContext.h"
#include "Window.h"
#include <GL\glew.h>
#include <GL\wglew.h>
#include <Log.h>
#include <thread>
using namespace Core;
#define MAX_UNBIND_TRIES 10
RenderingContext::RenderingContext()
{}
RenderingContext::RenderingContext(const Window* window, const RenderingContext* share)
{
this->window = window;
const int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 5,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0
};
// Create a rendering context capable of using OpenGL 3.x or later
handle = wglCreateContextAttribsARB(window->GetDeviceContext(), (share ? share->handle : 0), attributes);
if (!handle)
{
PERROR("ERROR_CREATE_RENDERING_CONTEXT (", GetLastError(), ")");
throw;
}
}
RenderingContext::RenderingContext(RenderingContext&& rendering_context)
{
this->handle = rendering_context.handle;
this->window = rendering_context.window;
rendering_context.handle = 0;
rendering_context.window = 0;
}
RenderingContext& RenderingContext::operator=(RenderingContext&& rendering_context)
{
this->handle = rendering_context.handle;
this->window = rendering_context.window;
rendering_context.handle = 0;
rendering_context.window = 0;
return *this;
}
RenderingContext::~RenderingContext()
{
if (handle)
{
wglMakeCurrent(0, 0);
wglDeleteContext(handle);
}
}
bool RenderingContext::Bind()
{
return wglMakeCurrent(window->GetDeviceContext(), handle) == TRUE;
}
bool RenderingContext::Unbind()
{
return wglMakeCurrent(0, 0) == TRUE;
}
| 20.487179 | 107 | 0.732165 | Morkonena |
26c1007fc53c988c21b4e3c09af06bb56ec394c0 | 781 | cc | C++ | code-examples/absl_flags_demos/flagit/logit.cc | storypku/storydev | 61fbfbf665a5e6e2f1bcfdf80ce6bf21d9e28b95 | [
"Apache-2.0"
] | 6 | 2020-06-11T08:31:48.000Z | 2022-03-29T17:06:42.000Z | code-examples/absl_flags_demos/flagit/logit.cc | storypku/storydev | 61fbfbf665a5e6e2f1bcfdf80ce6bf21d9e28b95 | [
"Apache-2.0"
] | 1 | 2020-06-03T01:45:52.000Z | 2021-07-17T14:49:53.000Z | code-examples/absl_flags_demos/flagit/logit.cc | storypku/storydev | 61fbfbf665a5e6e2f1bcfdf80ce6bf21d9e28b95 | [
"Apache-2.0"
] | 1 | 2022-03-30T15:41:12.000Z | 2022-03-30T15:41:12.000Z | #include <iostream>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "glog/logging.h"
// Conflict with glog
// ABSL_FLAG(bool, logtostderr, false, "Whether log to stderr");
ABSL_FLAG(bool, enable_log, false, "Whether log to stderr");
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
// Overrides the default for FLAGS_logtostderr
absl::SetFlag(&FLAGS_enable_log, true);
// If the command-line contains a value for logtostderr, use that. Otherwise,
// use the default (as set above).
absl::ParseCommandLine(argc, argv);
auto logtostderr = absl::GetFlag(FLAGS_enable_log);
std::cout << (logtostderr ? "Yes, LogIt" : "Silent") << std::endl;
LOG(INFO) << (logtostderr ? "Yes, LogIt" : "Silent") << std::endl;
return 0;
}
| 33.956522 | 79 | 0.696543 | storypku |
26c1518c05ad73b6cd8b78c31bc04883a04377ba | 890 | cpp | C++ | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 1 | 2021-02-12T23:53:55.000Z | 2021-02-12T23:53:55.000Z | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | #define DISH2_LOG_ENABLE
#include <emscripten.h>
#include "conduit/include/uitsl/polyfill/ompi_mpi_comm_world.hpp"
#include "Empirical/include/emp/config/ArgManager.hpp"
#include "Empirical/include/emp/web/UrlParams.hpp"
#include "dish2/config/cfg.hpp"
#include "dish2/config/make_arg_specs.hpp"
#include "dish2/config/setup.hpp"
#include "dish2/spec/Spec.hpp"
#include "dish2/web/WebInterface.hpp"
#include "dish2/world/ProcWorld.hpp"
using Spec = dish2::Spec;
thread_local dish2::WebInterface* interface;
int main() {
dish2::setup( emp::ArgManager{
emp::web::GetUrlParams(), dish2::make_arg_specs()
} );
interface = new dish2::WebInterface;
// set up web interface
interface->Redraw();
emscripten_set_main_loop([](){}, 1, true);
// once we're done setting up, turn off the loading modal
// MAIN_THREAD_EM_ASM({ $('.modal').modal('hide'); });
return 0;
}
| 23.421053 | 65 | 0.723596 | schregardusc |
26c22fb275907e1552ed3e14b095f764b6298159 | 2,341 | hh | C++ | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | 1 | 2021-06-04T13:18:13.000Z | 2021-06-04T13:18:13.000Z | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | null | null | null | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | null | null | null | #ifndef _MEMORY_HH_
#define _MEMORY_HH_
#include <cstdio>
#include <memory>
#include <type_traits>
namespace std {
template <typename T>
constexpr auto is_aligned(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return (x & (a-1)) == 0;
}
template <typename T>
constexpr auto align_up(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return (x + (a-1)) & -a;
}
template <typename T>
constexpr auto align_down(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return x & (-a);
}
inline bool is_aligned(const volatile void* p, size_t a) {
return is_aligned(reinterpret_cast<uintptr_t>(p), a);
}
template <typename T>
inline auto align_up(T p, size_t a)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_up(reinterpret_cast<uintptr_t>(p), a));
}
inline nullptr_t align_up(nullptr_t, size_t) { return nullptr; }
template <typename T>
inline auto align_down(T p, size_t a)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_down(reinterpret_cast<uintptr_t>(p), a));
}
inline nullptr_t align_down(nullptr_t, size_t) { return nullptr; }
template <typename T, typename U>
inline auto align_up_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type))
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_up(p, a));
}
template <typename T>
inline auto align_up_cast(nullptr_t p, size_t a=1)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
(void)a;
nullptr;
}
template <typename T, typename U>
inline auto align_down_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type))
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_down(p, a));
}
template <typename T>
inline auto align_down_cast(nullptr_t p, size_t a=1)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
(void)a;
nullptr;
}
} //namespace std
#endif
| 29.632911 | 96 | 0.668518 | fmatthew5876 |
26c42b996b47698525281a1b721a154d6d7e96b0 | 1,267 | cc | C++ | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | 8 | 2019-08-22T15:17:22.000Z | 2022-02-04T04:24:28.000Z | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | 1 | 2020-05-31T10:29:09.000Z | 2020-06-01T09:57:11.000Z | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | null | null | null | #include "framework/ui.h"
#include <gtk/gtk.h>
struct UI::Impl {
static constexpr unsigned width = 600;
static constexpr unsigned height = 400;
GtkWidget *widget = nullptr;
void create_widget();
};
//==============================================================================
UI::UI(void *parent, LV2_URID_Map *map, LV2_URID_Unmap *unmap,
const char *bundle_path)
: P(new Impl) {
}
UI::~UI() {
}
void UI::option(const LV2_Options_Option &o) {
}
LV2UI_Widget UI::widget() const {
if (!P->widget)
P->create_widget();
return LV2UI_Widget(P->widget);
}
unsigned UI::width() {
return Impl::width;
}
unsigned UI::height() {
return Impl::height;
}
void UI::port_event(
uint32_t port_index, uint32_t buffer_size, uint32_t format, const void *buffer) {
}
bool UI::needs_idle_callback() {
return false;
}
bool UI::idle() {
return false;
}
//==============================================================================
void UI::Impl::create_widget() {
GtkWidget *editor = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_widget_set_size_request(editor, Impl::width, Impl::height);
GtkWidget *label = gtk_label_new("Hello, World!");
gtk_box_pack_start(GTK_BOX(editor), label, true, true, 0);
this->widget = editor;
}
| 22.22807 | 85 | 0.600631 | jpcima |
26c7d4fa3fd4a6eec6125c710a41d0af4af36076 | 334 | hpp | C++ | NCGB/Compile/src/OBSOLETE2009/PrintSet.hpp | mcdeoliveira/NC | 54b2a81ebda9e5260328f88f83f56fe8cf472ac3 | [
"BSD-3-Clause"
] | 103 | 2016-09-21T06:01:23.000Z | 2022-03-27T06:52:10.000Z | NCGB/Compile/src/OBSOLETE2009/PrintSet.hpp | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 11 | 2017-03-27T13:11:42.000Z | 2022-03-08T13:46:14.000Z | NCGB/Compile/src/OBSOLETE2009/PrintSet.hpp | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 21 | 2017-06-23T09:01:21.000Z | 2022-02-18T06:24:00.000Z | // PrintSet.h
#pragma warning(disable:4786)
#include "Choice.hpp"
#ifdef HAS_INCLUDE_NO_DOTS
#include <set>
#else
#include <set.h>
#endif
#include "vcpp.hpp"
class MyOstream;
template<class T,class U> void PrintSet(MyOstream &,const char *,const set<T,U> &);
template<class T,class U> void PrintSet(const char *,const set<T,U> &);
| 22.266667 | 83 | 0.724551 | mcdeoliveira |
26cbf690de01fee725818be049d9fd484ebe3439 | 17,030 | cpp | C++ | emulator/src/mame/drivers/tmc600.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/drivers/tmc600.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/drivers/tmc600.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/*
Telmac TMC-600
PCB Layout
----------
HP14782-1
CN2 CN3
|---------| |------------------------|
|-------|---------|-----|------------------------|------------------------------------------|
| CN1 CN4 SW1 CN5 CN6 P1 SW2 CN7 |
| |-------| 4049 T3 |
| T1 K1 |CDP1852| 4050 4050 4050 40107 T2 C1 C2 8.867238MHz |
| |-------| |-------| 5.6260MHz T4 |
| MC1374 |CDP1852| ROM5 |---------| |
| |-------| | CDP1870 | |
| K2 ROM4 |---------| |
| |-------------| 4050 5114 5114 |
| 4013 | CDP1802 | 4050 5114 5114 ROM3 4030 ROM6 4060|
| 4013 3.57MHz|-------------| 4050 5114 5114 |
| 4081 40106 4051 5114 5114 ROM2 4076 5114 4011|
| 4556 5114 5114 CDP1856 5114 |
| |-------| 5114 5114 ROM1 CDP1856 5114 4076|
| LS1 |CDP1852| CDP1853 CDP1856 5114 5114 |
| |-------| CDP1856 5114 5114 ROM0 |---------| 4011|
| | CDP1869 | |
| 7805 4051 4051 |---------| |
| |
| |--CN8--| |
|-------------------------------------------------------------------------------------------|
Notes:
All IC's shown. TMCP-300 and TMC-700 expansions have been installed.
ROM0-5 - Toshiba TMM2732DI 4Kx8 EPROM
ROM6 - Hitachi HN462732G 4Kx8 EPROM
5114 - RCA MWS5114E1 1024-Word x 4-Bit LSI Static RAM
MC1374 - Motorola MC1374P TV Modulator
CDP1802 - RCA CDP1802BE CMOS 8-Bit Microprocessor running at 3.57MHz
CDP1852 - RCA CDP1852CE Byte-Wide Input/Output Port
CDP1853 - RCA CDP1853CE N-Bit 1 of 8 Decoder
CDP1856 - RCA CDP1856CE 4-Bit Memory Buffer
CDP1869 - RCA CDP1869CE Video Interface System (VIS) Address and Sound Generator
CDP1870 - RCA CDP1870CE Video Interface System (VIS) Color Video (DOT XTAL at 5.6260MHz, CHROM XTAL at 8.867238MHz)
CN1 - RF connector [TMC-700]
CN2 - 10x2 pin printer connector [TMC-700]
CN3 - 32x3 pin EURO connector
CN4 - DIN5D tape connector
1 input (500 mV / 47 Kohm)
2 GND
3 output (580 mV / 47 Kohm)
4 input (500 mV / 47 Kohm)
5 output (580 mV / 47 Kohm)
CN5 - DIN5X video connector
1 GND
2 GND
3 composite video output (75 ohm)
4 GND
5 composite video output (75 ohm)
CN6 - DIN2 power connector
1 input 8..12V DC..400Hz 300mA
2 GND
CN7 - DIN5D audio connector [TMCP-300]
1 N/C
2 GND
3 mono audio output
4 N/C
5 mono audio output
CN8 - 10x2 pin keyboard connector
SW1 - RUN/STOP switch (left=run, right=stop)
SW2 - internal speaker/external audio switch [TMCP-300]
P1 - color phase lock adjustment potentiometer
C1 - dot oscillator adjustment variable capacitor
C2 - chroma oscillator adjustment variable capacitor
T1 - RF signal strength adjustment potentiometer [TMC-700]
T2 - tape recording level adjustment potentiometer (0.57 V p-p)
T3 - video output level adjustment potentiometer (1 V p-p)
T4 - video synchronization pulse adjustment potentiometer
K1 - RF signal quality adjustment variable inductor [TMC-700]
K2 - RF channel adjustment variable inductor (VHF I) [TMC-700]
LS1 - loudspeaker
*/
/*
TODO
- connect expansion bus
*/
#include "emu.h"
#include "includes/tmc600.h"
READ8_MEMBER( tmc600_state::rtc_r )
{
m_rtc_int = m_vismac_reg_latch >> 3;
return 0;
}
WRITE8_MEMBER( tmc600_state::printer_w )
{
m_centronics->write_data0(BIT(data, 0));
m_centronics->write_data1(BIT(data, 1));
m_centronics->write_data2(BIT(data, 2));
m_centronics->write_data3(BIT(data, 3));
m_centronics->write_data4(BIT(data, 4));
m_centronics->write_data5(BIT(data, 5));
m_centronics->write_data6(BIT(data, 6));
m_centronics->write_data7(BIT(data, 7));
m_centronics->write_strobe(0);
m_centronics->write_strobe(1);
}
/* Memory Maps */
void tmc600_state::tmc600_map(address_map &map)
{
map(0x0000, 0x5fff).rom();
map(0x6000, 0x7fff).ram();
map(0xf400, 0xf7ff).m(m_vis, FUNC(cdp1869_device::char_map));
map(0xf800, 0xffff).m(m_vis, FUNC(cdp1869_device::page_map));
}
void tmc600_state::tmc600_io_map(address_map &map)
{
map(0x03, 0x03).w(m_bwio, FUNC(cdp1852_device::write));
map(0x04, 0x04).w(CDP1852_TMC700_TAG, FUNC(cdp1852_device::write));
map(0x05, 0x05).rw(this, FUNC(tmc600_state::rtc_r), FUNC(tmc600_state::vismac_data_w));
// AM_RANGE(0x06, 0x06) AM_WRITE(floppy_w)
map(0x07, 0x07).w(this, FUNC(tmc600_state::vismac_register_w));
}
/* Input Ports */
static INPUT_PORTS_START( tmc600 )
PORT_START("Y0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CODE(KEYCODE_0_PAD) PORT_CHAR('0')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD) PORT_CHAR('2') PORT_CHAR('\"')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CODE(KEYCODE_7_PAD) PORT_CHAR('7') PORT_CHAR('/')
PORT_START("Y1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CODE(KEYCODE_8_PAD) PORT_CHAR('8') PORT_CHAR('(')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CODE(KEYCODE_9_PAD) PORT_CHAR('9') PORT_CHAR(')')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR(':') PORT_CHAR('*')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(';') PORT_CHAR('+')
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('=')
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
PORT_START("Y2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_TILDE) PORT_CHAR('@') PORT_CHAR('\\')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("Y3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("Y4")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("Y5")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("\xC3\x85") PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR(0x00C5)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("\xC3\x84") PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(0x00C4)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("\xC3\x96") PORT_CODE(KEYCODE_COLON) PORT_CHAR(0x00D6)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('^') PORT_CHAR('~')
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("BREAK") PORT_CODE(KEYCODE_END) PORT_CHAR(UCHAR_MAMEKEY(END))
PORT_START("Y6")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("SPACE") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("DEL") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("ESC") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("E2") PORT_CODE(KEYCODE_RALT) PORT_CHAR(UCHAR_MAMEKEY(RALT))
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("CTRL1") PORT_CODE(KEYCODE_LCONTROL) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("CTRL2") PORT_CODE(KEYCODE_RCONTROL) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL))
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("E1") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(LALT))
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("SHIFT") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_START("Y7")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("SHIFT LOCK") PORT_CODE(KEYCODE_CAPSLOCK) PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK))
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("(unknown)") PORT_CODE(KEYCODE_F1) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("LINE FEED") PORT_CODE(KEYCODE_HOME) PORT_CHAR(UCHAR_MAMEKEY(HOME)) PORT_CHAR(10)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_UP) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_RIGHT) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("RETURN") PORT_CODE(KEYCODE_ENTER) PORT_CODE(KEYCODE_ENTER_PAD) PORT_CHAR(13)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_DOWN) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_LEFT) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_START("RUN")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Run/Stop") PORT_CODE(KEYCODE_F3) PORT_CHAR(UCHAR_MAMEKEY(F3)) PORT_TOGGLE PORT_WRITE_LINE_DEVICE_MEMBER(CDP1802_TAG, cosmac_device, clear_w)
INPUT_PORTS_END
/* CDP1802 Interface */
READ_LINE_MEMBER( tmc600_state::ef2_r )
{
return m_cassette->input() < 0;
}
READ_LINE_MEMBER( tmc600_state::ef3_r )
{
uint8_t keylatch = m_bwio->do_r();
return !BIT(m_key_row[(keylatch >> 3) & 0x07]->read(), keylatch & 0x07);
}
WRITE_LINE_MEMBER( tmc600_state::q_w )
{
m_cassette->output(state ? +1.0 : -1.0);
}
WRITE8_MEMBER( tmc600_state::sc_w )
{
if (data == COSMAC_STATE_CODE_S3_INTERRUPT) {
m_maincpu->int_w(CLEAR_LINE);
}
}
/* Machine Drivers */
MACHINE_CONFIG_START(tmc600_state::tmc600)
// CPU
MCFG_CPU_ADD(CDP1802_TAG, CDP1802, XTAL(3'570'000))
MCFG_CPU_PROGRAM_MAP(tmc600_map)
MCFG_CPU_IO_MAP(tmc600_io_map)
MCFG_COSMAC_WAIT_CALLBACK(VCC)
MCFG_COSMAC_EF2_CALLBACK(READLINE(tmc600_state, ef2_r))
MCFG_COSMAC_EF3_CALLBACK(READLINE(tmc600_state, ef3_r))
MCFG_COSMAC_Q_CALLBACK(WRITELINE(tmc600_state, q_w))
MCFG_COSMAC_SC_CALLBACK(WRITE8(tmc600_state, sc_w))
// sound and video hardware
tmc600_video(config);
// keyboard output latch
MCFG_DEVICE_ADD(CDP1852_KB_TAG, CDP1852, XTAL(3'570'000)/8) // clock is CDP1802 TPB
MCFG_CDP1852_MODE_CALLBACK(VCC)
// address bus demux for expansion bus
MCFG_DEVICE_ADD(CDP1852_BUS_TAG, CDP1852, 0) // clock is expansion bus TPA
MCFG_CDP1852_MODE_CALLBACK(GND)
// printer output latch
MCFG_DEVICE_ADD(CDP1852_TMC700_TAG, CDP1852, XTAL(3'570'000)/8) // clock is CDP1802 TPB
MCFG_CDP1852_MODE_CALLBACK(VCC)
MCFG_CDP1852_DO_CALLBACK(WRITE8(tmc600_state, printer_w))
// printer connector
MCFG_CENTRONICS_ADD(CENTRONICS_TAG, centronics_devices, nullptr)
MCFG_CENTRONICS_BUSY_HANDLER(DEVWRITELINE(CDP1802_TAG, cosmac_device, ef4_w)) MCFG_DEVCB_XOR(1)
// cassette
MCFG_CASSETTE_ADD("cassette")
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_MUTED)
// expansion bus connector
MCFG_TMC600_EURO_BUS_SLOT_ADD(TMC600_EURO_BUS_TAG, tmc600_euro_bus_cards, nullptr)
// internal RAM
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("8K")
MACHINE_CONFIG_END
/* ROMs */
#if 0
ROM_START( tmc600s1 )
ROM_REGION( 0x6000, CDP1802_TAG, 0 )
ROM_LOAD( "sb20", 0x0000, 0x1000, NO_DUMP )
ROM_LOAD( "sb21", 0x1000, 0x1000, NO_DUMP )
ROM_LOAD( "sb22", 0x2000, 0x1000, NO_DUMP )
ROM_LOAD( "sb23", 0x3000, 0x1000, NO_DUMP )
ROM_SYSTEM_BIOS( 0, "sb040282", "SB040282" )
ROMX_LOAD( "190482", 0x4000, 0x1000, NO_DUMP, ROM_BIOS(1) )
ROM_SYSTEM_BIOS( 1, "sbdos", "SBDOS" )
ROMX_LOAD( "190482_", 0x4000, 0x1000, NO_DUMP, ROM_BIOS(2) )
ROMX_LOAD( "190482_v", 0x5000, 0x1000, NO_DUMP, ROM_BIOS(2) )
ROM_REGION( 0x1000, "chargen", 0 )
ROM_LOAD( "chargen", 0x0000, 0x1000, CRC(93f92cbf) SHA1(371156fb38fa5319c6fde537ccf14eed94e7adfb) )
ROM_END
#endif
ROM_START( tmc600s2 )
ROM_REGION( 0x6000, CDP1802_TAG, 0 )
ROM_LOAD( "sb30", 0x0000, 0x1000, CRC(95d1292a) SHA1(1fa52d59d3005f8ac74a32c2164fdb22947c2748) )
ROM_LOAD( "sb31", 0x1000, 0x1000, CRC(2c8f3d17) SHA1(f14e8adbcddeaeaa29b1e7f3dfa741f4e230f599) )
ROM_LOAD( "sb32", 0x2000, 0x1000, CRC(dd58a128) SHA1(be9bdb0fc5e0cc3dcc7f2fb7ccab69bf5b043803) )
ROM_LOAD( "sb33", 0x3000, 0x1000, CRC(b7d241fa) SHA1(6f3eadf86c4e3aaf93d123e302a18dc4d9db964b) )
ROM_SYSTEM_BIOS( 0, "sb040282", "SB040282" )
ROMX_LOAD( "151182", 0x4000, 0x1000, CRC(c1a8d9d8) SHA1(4552e1f06d0e338ba7b0f1c3a20b8a51c27dafde), ROM_BIOS(1) )
ROM_SYSTEM_BIOS( 1, "sbdos", "SBDOS" )
ROMX_LOAD( "151182_", 0x4000, 0x1000, NO_DUMP, ROM_BIOS(2) )
ROMX_LOAD( "151182_v", 0x5000, 0x1000, NO_DUMP, ROM_BIOS(2) )
ROM_REGION( 0x1000, "chargen", 0 )
ROM_LOAD( "chargen", 0x0000, 0x1000, CRC(93f92cbf) SHA1(371156fb38fa5319c6fde537ccf14eed94e7adfb) )
ROM_END
/* System Drivers */
// YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS
//COMP( 1982, tmc600s1, 0, 0, tmc600, tmc600, tmc600_state, 0, "Telercas Oy", "Telmac TMC-600 (Sarja I)", MACHINE_NOT_WORKING )
COMP( 1982, tmc600s2, 0, 0, tmc600, tmc600, tmc600_state, 0, "Telercas Oy", "Telmac TMC-600 (Sarja II)", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
| 50.235988 | 199 | 0.669113 | rjw57 |
26cce06b6b5b88197caaa30305218e366defdf88 | 10,894 | cpp | C++ | src/boosted_regression_tree/input_rb.cpp | heyyy/burned-area | f31195d7fc7bec5fba6301e57b4fb76ec7be0075 | [
"NASA-1.3"
] | null | null | null | src/boosted_regression_tree/input_rb.cpp | heyyy/burned-area | f31195d7fc7bec5fba6301e57b4fb76ec7be0075 | [
"NASA-1.3"
] | null | null | null | src/boosted_regression_tree/input_rb.cpp | heyyy/burned-area | f31195d7fc7bec5fba6301e57b4fb76ec7be0075 | [
"NASA-1.3"
] | 1 | 2021-11-07T09:32:59.000Z | 2021-11-07T09:32:59.000Z | /*****************************************************************************
FILE: input_rb.cpp
PURPOSE: Contains functions for opening, reading, closing, and processing
input raw binary products for seasonal summaries and annual maximums.
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
LICENSE TYPE: NASA Open Source Agreement Version 1.3
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
4/9/2014 Gail Schmidt Original Development
NOTES:
*****************************************************************************/
#include "input_rb.h"
/* The following libraries are external C libraries from ESPA */
extern "C" {
FILE *open_raw_binary (char *infile, char *access_type);
void close_raw_binary (FILE *fptr);
int read_raw_binary (FILE *rb_fptr, int nlines, int nsamps, int size,
void *img_array);
int write_raw_binary (FILE *rb_fptr, int nlines, int nsamps, int size,
void *img_array);
}
/******************************************************************************
MODULE: OpenRbInput
PURPOSE: Open the image file (for seasonal summaries and annual maximums) and
read the metadata. Leave the file pointer open in the returned
Input_Rb_t data structure.
RETURN VALUE:
Type = Input_Rb_t *
Value Description
----- -----------
NULL An error occurred during processing
non-NULL Processing was successful
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
8/16/2013 Gail Schmidt Original Development
4/8/2014 Gail Schmidt Updated for raw binary
NOTES:
******************************************************************************/
Input_Rb_t *OpenRbInput
(
char *file_name /* I: input image filename */
)
{
char errmsg[MAX_STR_LEN]; /* error message */
char tmpstr[MAX_STR_LEN]; /* temporary pointer string message */
char input_hdr[MAX_STR_LEN]; /* output header file */
char *cptr = NULL; /* character pointer */
int nlines; /* number of lines in image */
int nsamps; /* number of samples in image */
/* Create the Input data structure */
Input_Rb_t* ds_input = new Input_Rb_t();
if (ds_input == NULL)
RETURN_ERROR ("Error allocating input raw binary data structure",
"OpenRbInput", NULL);
/* Populate the data structure */
ds_input->file_name = DupString(file_name);
if (ds_input->file_name == NULL)
RETURN_ERROR ("Error duplicating input raw binary file name",
"OpenRbInput", NULL);
/* Open the input raw binary file */
ds_input->fp_img = open_raw_binary (file_name, (char *) "rb");
if (ds_input->fp_img == NULL)
{
sprintf (errmsg, "Error opening input raw binary file: %s", file_name);
RETURN_ERROR (errmsg, "OpenRbInput", NULL);
}
/* Read the header file to obtain the nlines and nsamps */
strcpy (input_hdr, file_name);
cptr = strrchr (input_hdr, '.');
if (cptr == NULL)
{
sprintf (errmsg, "Error input filename doesn't match the expected .img "
"file extension (%s)", file_name);
RETURN_ERROR(errmsg, "OpenRbInput", false);
}
strcpy (cptr, ".hdr");
if (!ReadHdr (input_hdr, &nlines, &nsamps)) {
sprintf (errmsg, "reading input header file: %s", tmpstr);
RETURN_ERROR (errmsg, "OpenRbInput", NULL);
}
ds_input->size.l = nlines;
ds_input->size.s = nsamps;
ds_input->open = true;
/* Allocate the input buffer */
ds_input->buf = (int16 *) calloc (ds_input->size.s, sizeof (int16));
if (ds_input->buf == NULL)
{
sprintf (errmsg, "allocating input raw binary buffer");
RETURN_ERROR (errmsg, "OpenRbInput", NULL);
}
return (ds_input);
}
/******************************************************************************
MODULE: CloseRbInput
PURPOSE: Close the raw binary file.
RETURN VALUE:
Type = bool
Value Description
----- -----------
false An error occurred during processing
true Processing was successful
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
8/16/2013 Gail Schmidt Original Development
4/8/2014 Gail Schmidt Updated for raw binary
NOTES:
******************************************************************************/
bool CloseRbInput
(
Input_Rb_t *ds_input /* I: Pointer to the raw binary file data struct */
)
{
char errmsg[MAX_STR_LEN]; /* error message */
/* Make sure file is open and available */
if (!ds_input->open)
{
sprintf (errmsg, "file not open: %s", ds_input->file_name);
RETURN_ERROR (errmsg, "CloseRbInput", false);
}
/* Close the file pointer */
close_raw_binary (ds_input->fp_img);
/* Mark file as closed */
ds_input->open = false;
return true;
}
/******************************************************************************
MODULE: FreeRbInput
PURPOSE: Free the input data structure and memory.
RETURN VALUE:
Type = bool
Value Description
----- -----------
false An error occurred during processing
true Processing was successful
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
4/8/2014 Gail Schmidt Original Development
NOTES:
******************************************************************************/
bool FreeRbInput
(
Input_Rb_t *ds_input /* I: Pointer to the raw binary file data struct */
)
{
if (ds_input != NULL)
{
if (ds_input->open)
RETURN_ERROR ("file still open", "FreeRbInput", false);
/* Free the data buffer */
free (ds_input->buf);
/* Free the filename */
free (ds_input->file_name);
/* Free the structure */
free (ds_input);
}
return true;
}
/******************************************************************************
MODULE: GetRbInputLYSummaryData (class PredictBurnedArea)
PURPOSE: Read one line of the previous years' seasonal summary data for the
specified season and band/index, and copy it to the associated PBA class array.
RETURN VALUE:
Type = bool
Value Description
----- -----------
false An error occurred during processing
true Processing was successful
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
8/16/2013 Gail Schmidt Original Development
4/8/2014 Gail Schmidt Updated for raw binary
NOTES:
******************************************************************************/
bool PredictBurnedArea::GetRbInputLYSummaryData
(
Input_Rb_t *ds_input, /* I: pointer to the raw binary file data struct */
int line, /* I: input line to be read */
BandIndex_t band, /* I: input band/index to be read */
Season_t season /* I: input season to be read */
)
{
char errmsg[MAX_STR_LEN]; /* error message */
int samp; /* current sample to be processed */
/* Validate the line to be read */
if (line < 0 || line >= ds_input->size.l)
RETURN_ERROR("invalid line number", "GetRbInputLYSummaryData", false);
/* Make sure file is open and available */
if (!ds_input->open)
{
sprintf (errmsg, "file not open: %s", ds_input->file_name);
RETURN_ERROR (errmsg, "GetRbInputLYSummaryData", false);
}
/* Read the specified line from the input file */
if (read_raw_binary (ds_input->fp_img, 1, ds_input->size.s,
sizeof (int16), ds_input->buf) != SUCCESS)
{
sprintf (errmsg, "Error reading line %d from the input file %s", line,
ds_input->file_name);
RETURN_ERROR (errmsg, "GetRbInputLYSummaryData", false);
}
/* Store the data as the group of bands/indices per season */
for (samp = 0; samp < ds_input->size.s; samp++)
{
lySummaryMat.at<float>(samp,season*PBA_NBANDS+band) =
ds_input->buf[samp];
}
return true;
}
/******************************************************************************
MODULE: GetRbInputAnnualMaxData (class PredictBurnedArea)
PURPOSE: Read one line of the annual maximum data for the specified index,
and copy it to the associated PBA class array.
RETURN VALUE:
Type = bool
Value Description
----- -----------
false An error occurred during processing
true Processing was successful
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
HISTORY:
Date Programmer Reason
---------- --------------- -------------------------------------
8/16/2013 Gail Schmidt Original Development
4/8/2014 Gail Schmidt Updated for raw binary
NOTES:
******************************************************************************/
bool PredictBurnedArea::GetRbInputAnnualMaxData
(
Input_Rb_t *ds_input, /* I: pointer to the raw binary file data struct */
int line, /* I: input line to be read */
Index_t indx /* I: input index to be read */
)
{
char errmsg[MAX_STR_LEN]; /* error message */
int samp; /* current sample to be processed */
/* Validate the line to be read */
if (line < 0 || line >= ds_input->size.l)
RETURN_ERROR("invalid line number", "GetRbInputAnnualMaxData", false);
/* Make sure file is open and available */
if (!ds_input->open)
{
sprintf (errmsg, "file not open: %s", ds_input->file_name);
RETURN_ERROR (errmsg, "GetRbInputAnnualMaxData", false);
}
/* Read the specified line from the input file */
if (read_raw_binary (ds_input->fp_img, 1, ds_input->size.s,
sizeof (int16), ds_input->buf) != SUCCESS)
{
sprintf (errmsg, "Error reading line %d from the input file %s", line,
ds_input->file_name);
RETURN_ERROR (errmsg, "GetRbInputLYSummaryData", false);
}
/* Store the data as the group of bands/indices per year */
for (samp = 0; samp < ds_input->size.s; samp++)
maxIndxMat.at<float>(samp,indx) = ds_input->buf[samp];
return true;
}
| 32.135693 | 80 | 0.556637 | heyyy |
26d02fc38146af2f48b82f101cfa66584d346a1e | 894 | cpp | C++ | aslam_backend_python/src/L1Regularizer.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 33 | 2017-04-26T13:30:49.000Z | 2022-02-25T01:52:22.000Z | aslam_backend_python/src/L1Regularizer.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 15 | 2017-02-14T16:02:31.000Z | 2020-05-12T06:07:22.000Z | aslam_backend_python/src/L1Regularizer.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 8 | 2017-06-28T04:17:08.000Z | 2021-04-10T04:58:36.000Z | /*
* L1Regularizer.cpp
*
* Created on: 22.09.2015
* Author: Ulrich Schwesinger
*/
#include <numpy_eigen/boost_python_headers.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <aslam/backend/L1Regularizer.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::python;
using namespace aslam::backend;
void exportL1Regularizer()
{
typedef std::vector<Scalar*> ScalarDesignVariables;
class_<ScalarDesignVariables>("ScalarDesignVariableVector")
.def(boost::python::vector_indexing_suite<ScalarDesignVariables>() )
.def("__iter__", boost::python::iterator<ScalarDesignVariables>())
;
class_<L1Regularizer, boost::shared_ptr<L1Regularizer>, bases<ScalarNonSquaredErrorTerm>, boost::noncopyable>("L1Regularizer", no_init)
.def(init<const ScalarDesignVariables&, const double>())
.def("setBeta", &L1Regularizer::setBeta)
;
}
| 27.9375 | 137 | 0.756152 | ethz-asl |
26d168de38dc22e0dc1d78a81e93904099e23ae7 | 1,319 | cpp | C++ | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | 8 | 2018-06-26T05:42:17.000Z | 2021-10-20T23:19:20.000Z | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | null | null | null | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | 5 | 2019-06-01T15:34:07.000Z | 2022-02-12T06:10:16.000Z | #include "algorithms.hpp"
#include "algorithms/cautious.hpp"
#include "algorithms/hungry.hpp"
#include "algorithms/terminator.hpp"
#include "algorithms/dog.hpp"
#include "algorithms/sim.hpp"
#include "algorithms/inyourface.hpp"
#include "algorithms/random.hpp"
#include "algorithms/onedirection.hpp"
Algorithms Algorithms::_instance;
Algorithms::Algorithms()
{
_algorithms["cautious"] = std::make_unique<Cautious>();
_algorithms["hungry"] = std::make_unique<Hungry>();
_algorithms["terminator"] = std::make_unique<Terminator>();
_algorithms["dog"] = std::make_unique<Dog>();
_algorithms["sim"] = std::make_unique<Sim>();
_algorithms["inyourface"] = std::make_unique<InYourFace>();
_algorithms["random"] = std::make_unique<Random>();
_algorithms["onedirection_left"] = std::make_unique<OneDirection>(Direction::Left);
_algorithms["onedirection_right"] = std::make_unique<OneDirection>(Direction::Right);
_algorithms["onedirection_up"] = std::make_unique<OneDirection>(Direction::Up);
_algorithms["onedirection_down"] = std::make_unique<OneDirection>(Direction::Down);
}
Algorithm *Algorithms::get(std::string key)
{
auto it = _instance._algorithms.find(key);
if (it == _instance._algorithms.end())
{
return nullptr;
}
return it->second.get();
}
| 35.648649 | 89 | 0.715694 | graeme-hill |
26d3b8fc08ff61e501e6bb7ce3478f89dcda3e2d | 16,880 | cpp | C++ | moos-ivp/ivp/src/pEchoVar/EchoVar.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/pEchoVar/EchoVar.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/pEchoVar/EchoVar.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | /*****************************************************************/
/* NAME: Michael Benjamin */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: EchoVar.cpp */
/* DATE: July 22 2006 */
/* */
/* This file is part of MOOS-IvP */
/* */
/* MOOS-IvP is free software: you can redistribute it and/or */
/* modify it under the terms of the GNU General Public License */
/* as published by the Free Software Foundation, either version */
/* 3 of the License, or (at your option) any later version. */
/* */
/* MOOS-IvP 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 MOOS-IvP. If not, see */
/* <http://www.gnu.org/licenses/>. */
/*****************************************************************/
#include <cstring>
#include <iterator>
#include "EchoVar.h"
#include "MBUtils.h"
#include "ACTable.h"
using namespace std;
//-----------------------------------------------------------------
// Constructor
EchoVar::EchoVar()
{
// State variables
m_conditions_met = true;
m_no_cycles = false;
// Configuration variables
// If false, all incoming mail relevant to echoing, or flipping,
// is ignored when conditions not met
m_hold_messages_during_pause = true;
// If true only echo the most recently received source posting
m_echo_latest_only = false;
}
//-----------------------------------------------------------------
// Procedure: OnNewMail
bool EchoVar::OnNewMail(MOOSMSG_LIST &NewMail)
{
AppCastingMOOSApp::OnNewMail(NewMail);
if(m_no_cycles == false)
return(false);
// First go through the mail and determine if the current crop
// of mail affects the LogicBuffer.
if(m_logic_buffer.size() > 0) {
MOOSMSG_LIST::iterator p;
for(p=NewMail.begin(); p!=NewMail.end(); p++) {
CMOOSMsg &msg = *p;
string key = msg.GetKey();
string sdata = msg.GetString();
double ddata = msg.GetDouble();
if(msg.IsDouble())
m_logic_buffer.updateInfoBuffer(key, ddata);
else if(msg.IsString())
m_logic_buffer.updateInfoBuffer(key, sdata);
}
}
// If the logic conditions are not satisfied, ignore the rest of
// the mail.
m_conditions_met = m_logic_buffer.checkConditions();
if((!m_conditions_met) && !m_hold_messages_during_pause)
return(true);
MOOSMSG_LIST::iterator p;
for(p=NewMail.begin(); p!=NewMail.end(); p++) {
CMOOSMsg &msg = *p;
holdMessage(msg);
}
return(true);
}
//-----------------------------------------------------------------
// Procedure: OnConnectoToServer()
bool EchoVar::OnConnectToServer()
{
// register for variables here
registerVariables();
return(true);
}
//-----------------------------------------------------------------
// Procedure: Iterate()
// Note: Happens AppTick times per second
bool EchoVar::Iterate()
{
AppCastingMOOSApp::Iterate();
if(m_conditions_met && m_no_cycles)
releaseMessages();
AppCastingMOOSApp::PostReport();
return(true);
}
//-----------------------------------------------------------------
// Procedure: OnStartUp()
// Note: Happens before connection is open
bool EchoVar::OnStartUp()
{
AppCastingMOOSApp::OnStartUp();
CMOOSApp::OnStartUp();
list<string> sParams;
m_MissionReader.EnableVerbatimQuoting(true);
if(m_MissionReader.GetConfiguration(GetAppName(), sParams)) {
list<string>::reverse_iterator p;
for(p=sParams.rbegin(); p!=sParams.rend(); p++) {
string orig = *p;
string line = *p;
string param = tolower(biteStringX(line, '='));
string value = line;
bool handled = false;
if(!strncmp(param.c_str(), "flip", 4))
handled = handleFlipEntry(param, value);
else if(param == "echo") {
bool boolswitch = false;
if(strContains(value, "!->")) {
value = findReplace(value, "!->", ">");
boolswitch = true;
}
value = findReplace(value, "->", ">");
vector<string> svector = parseString(value, '>');
if(svector.size() != 2)
return(false);
string left = stripBlankEnds(svector[0]);
string right = stripBlankEnds(svector[1]);
handled = addMapping(left, right, boolswitch);
}
else if(param == "condition")
handled = m_logic_buffer.addNewCondition(value);
else if(param == "echo_latest_only")
handled = setBooleanOnString(m_echo_latest_only, value);
else if(param == "hold_messages")
handled = setBooleanOnString(m_hold_messages_during_pause, value);
if(!handled)
reportUnhandledConfigWarning(orig);
}
}
m_no_cycles = noCycles();
if(!m_no_cycles) {
reportConfigWarning("An echo cycle was detected.");
reportRunWarning("An echo cycle was detected.");
return(true);
}
unsigned int i, vsize = m_eflippers.size();
for(i=0; i<vsize; i++)
m_eflippers[i].print();
registerVariables();
return(true);
}
//-----------------------------------------------------------------
// Procedure: registerVariables()
void EchoVar::registerVariables()
{
AppCastingMOOSApp::RegisterVariables();
for(unsigned int i=0; i<m_unique_sources.size(); i++)
Register(m_unique_sources[i], 0);
for(unsigned int j=0; j<m_eflippers.size(); j++)
Register(m_eflippers[j].getSourceVar(), 0);
// Register for all variables found in all conditions.
vector<string> all_vars = m_logic_buffer.getAllVars();
for(unsigned int i=0; i<all_vars.size(); i++)
Register(all_vars[i], 0);
}
//-----------------------------------------------------------------
// Procedure: addMapping
bool EchoVar::addMapping(string src, string targ, bool boolswitch)
{
if((src == "") || (targ == ""))
return(false);
bool new_pair = true;
bool new_src = true;
unsigned int i, vsize = m_var_source.size();
for(i=0; i<vsize; i++) {
if(m_var_source[i] == src) {
new_src = false;
if(m_var_target[i] == targ)
new_pair = false;
}
}
if(new_pair) {
m_var_source.push_back(src);
m_var_target.push_back(targ);
m_boolswitch.push_back(boolswitch);
}
if(new_src)
m_unique_sources.push_back(src);
return(true);
}
//-----------------------------------------------------------------
// Procedure: noCycles
bool EchoVar::noCycles()
{
unsigned int i, vsize = m_unique_sources.size();
unsigned int j, map_size = m_var_source.size();;
vector<string> key_vector;
vector<string> new_vector;
for(i=0; i<vsize; i++) {
key_vector.clear();
for(j=0; j<map_size; j++)
if(m_unique_sources[i] == m_var_source[j])
if(!vectorContains(key_vector, m_var_target[j]))
key_vector.push_back(m_var_target[j]);
new_vector = expand(key_vector);
if(vectorContains(new_vector, m_unique_sources[i]))
return(false);
}
return(true);
}
//-----------------------------------------------------------------
// Procedure: expand
vector<string> EchoVar::expand(vector<string> key_vector)
{
unsigned int i, vsize = key_vector.size();
unsigned int j, map_size = m_var_source.size();;
for(i=0; i<vsize; i++) {
string key = key_vector[i];
for(j=0; j<map_size; j++)
if(key == m_var_source[j])
if(!vectorContains(key_vector, m_var_target[j]))
key_vector.push_back(m_var_target[j]);
}
if(key_vector.size() == vsize)
return(key_vector);
else
return(expand(key_vector));
}
//-----------------------------------------------------------------
// Procedure: handleFlipEntry
bool EchoVar::handleFlipEntry(string sKey, string sLine)
{
vector<string> svector = parseString(sKey, ':');
unsigned int vsize = svector.size();
if(vsize != 2)
return(false);
string tag = stripBlankEnds(svector[0]);
string key = stripBlankEnds(svector[1]);
if(tolower(tag) != "flip")
return(false);
// Determine the index of the given flipper reference
int index = -1;
unsigned int i, esize = m_eflippers.size();
for(i=0; i<esize; i++) {
if(key == m_eflippers[i].getKey())
index = i;
}
// If pre-existing EFlipper not found, create a new one
if(index == -1) {
EFlipper new_flipper;
new_flipper.setParam("key", key);
m_eflippers.push_back(new_flipper);
m_eflip_count.push_back(0);
index = esize;
}
if(!strncmp(sLine.c_str(), "source_variable", 15)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("source_variable", right);
return(ok);
}
if(!strncmp(sLine.c_str(), "dest_variable", 13)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("dest_variable", right);
return(ok);
}
if(!strncmp(sLine.c_str(), "source_separator", 16)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("source_separator", right);
return(ok);
}
if(!strncmp(sLine.c_str(), "dest_separator", 14)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("dest_separator", right);
return(ok);
}
if(!strncmp(sLine.c_str(), "filter", 6)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("filter", right);
return(ok);
}
if(strContains(sLine, "==")) {
bool ok = m_eflippers[index].setParam("filter", sLine);
return(ok);
}
if(!strncmp(sLine.c_str(), "component", 9)) {
string left = biteString(sLine, '=');
string right = stripBlankEnds(sLine);
bool ok = m_eflippers[index].setParam("component", right);
return(ok);
}
if(strContains(sLine, "->")) {
bool ok = m_eflippers[index].setParam("component", sLine);
return(ok);
}
return(false);
}
//-----------------------------------------------------------------
// Procedure: holdMessage
// Purpose: Hold a given message in a list ordered by time of
// receipt oldest to newest.
// Prior to adding the new message to the end of the list,
// the list is scanned and if there is an older message
// matching the MOOS variable (key), then that message is
// removed from the list.
// When the list is posted, only the most recent value of
// each variable will be posted.
// This pruning of duplicate messages only applies when the
// logic conditions are not met.
void EchoVar::holdMessage(CMOOSMsg msg)
{
string key = msg.GetKey();
m_map_hits[key]++;
if(!m_conditions_met || m_echo_latest_only) {
list<CMOOSMsg>::iterator p;
for(p=m_held_messages.begin(); p!=m_held_messages.end();) {
CMOOSMsg imsg = *p;
if(imsg.GetKey() == key)
p = m_held_messages.erase(p);
else
++p;
}
}
m_held_messages.push_back(msg);
}
//-----------------------------------------------------------------
// Procedure: releaseMessages
void EchoVar::releaseMessages()
{
list<CMOOSMsg>::iterator p;
for(p=m_held_messages.begin(); p!=m_held_messages.end(); p++) {
CMOOSMsg msg = *p;
string key = msg.GetKey();
string sdata = msg.GetString();
double ddata = msg.GetDouble();
unsigned int i, vsize = m_var_source.size();
for(i=0; i<vsize; i++) {
if(key == m_var_source[i]) {
string new_key = m_var_target[i];
string srctarg = key + ":" + new_key;
m_map_posts[srctarg]++;
if(msg.IsDouble())
Notify(new_key, ddata);
else if(msg.IsString()) {
if(m_boolswitch[i]) {
if(sdata == "true")
sdata = "false";
else if(sdata == "false")
sdata = "true";
else if(sdata == "TRUE")
sdata = "FALSE";
else if(sdata == "FALSE")
sdata = "TRUE";
else if(sdata == "False")
sdata = "True";
else if(sdata == "True")
sdata = "False";
else if(tolower(sdata) == "true")
sdata = "false";
else if(tolower(sdata) == "false")
sdata = "true";
}
Notify(new_key, sdata);
}
}
}
unsigned int j, fsize = m_eflippers.size();
for(j=0; j<fsize; j++) {
if(key == m_eflippers[j].getSourceVar()) {
m_eflip_count[j]++;
string flip_result = m_eflippers[j].flip(sdata);
if(flip_result != "")
Notify(m_eflippers[j].getDestVar(), flip_result);
}
}
}
m_held_messages.clear();
}
//---------------------------------------------------------
// Procedure: buildReport()
// Note: A virtual function of the AppCastingMOOSApp superclass,
// conditionally invoked if either a terminal or appcast
// report is needed.
// Example:
//
// conditions_met: true
// hold_messages: true
// echo_latest_only: true
//
// ==========================================================
// Echoes:
// ==========================================================
//
// Source Dest Hits Posts
// ----------- --- ----- ---- -----
// USM_X --> NAV_X 23 11
// USM_Y --> NAV_Y 23 11
// USM_X --> NAV_XPOS 23 11
// USM_Y --> NAV_YPOS 23 11
// USM_HEADING --> NAV_X 22 9
// USM_SPEED --> NAV_X 24 10
//
// ==========================================================
// Flips:
// ==========================================================
// Src Dest Old New
// Key Hits Source Dest Sep Sep Filter Field Field
// --- ---- ------ ---- --- ---- ------ ----- -----
// 1 17 ALPHA BRAVO , , type=1 xpos x
// ypos y
bool EchoVar::buildReport()
{
unsigned int echo_cnt = m_var_source.size();
m_msgs << "conditions_met: " << boolToString(m_conditions_met) << endl;
m_msgs << "hold_messages: " << boolToString(m_hold_messages_during_pause) << endl;
m_msgs << "echo_latest_only: " << boolToString(m_echo_latest_only) << endl << endl;
m_msgs << "==================================================" << endl;
m_msgs << "Echoes: (" << echo_cnt << ")" << endl;
m_msgs << "==================================================" << endl << endl;
if(echo_cnt > 0) {
ACTable actab(5,2);
actab << "Source | | Dest | Hits | Posts \n";
actab.addHeaderLines();
for(unsigned int i=0; i<echo_cnt; i++) {
string source = m_var_source[i];
string srctarg = source + ":" + m_var_target[i];
string hits = uintToString(m_map_hits[source]);
string posts = uintToString(m_map_posts[srctarg]);
actab << m_var_source[i] << "-->" << m_var_target[i] << hits << posts;;
}
m_msgs << actab.getFormattedString();
}
m_msgs << endl << endl;
unsigned int flip_cnt = m_eflippers.size();
m_msgs << "==================================================" << endl;
m_msgs << "Flips: (" << flip_cnt << ")" << endl;
m_msgs << "==================================================" << endl << endl;
if(flip_cnt > 0) {
ACTable actab(9,2);
actab << " | | | | Src | Dest| | Old | New \n";
actab << "Key | Hits | Source | Dest | Sep | Sep | Filter | Field | Field \n";
actab.addHeaderLines();
for(unsigned int i=0; i<flip_cnt; i++) {
string key = m_eflippers[i].getKey();
string hits = uintToString(m_eflip_count[i]);
string src = m_eflippers[i].getSourceVar();
string dest = m_eflippers[i].getDestVar();
string src_sep = m_eflippers[i].getSourceSep();
string dest_sep = m_eflippers[i].getDestSep();
string filters = m_eflippers[i].getFilters();
string components = m_eflippers[i].getComponents();
vector<string> svector = parseString(components, ',');
for(unsigned int j=0; j<svector.size(); j++) {
string old_fld = biteStringX(svector[j], ':');
string new_fld = svector[j];
actab << key << hits << src << dest << src_sep << dest_sep << filters;
actab << old_fld << new_fld;
}
}
m_msgs << actab.getFormattedString();
}
return(true);
}
| 29.823322 | 87 | 0.544076 | EasternEdgeRobotics |
26d55ffb5234568d62e92cf72fdfe96fb496bc3e | 470 | cpp | C++ | cpp/has-rebind.cpp | lindsayad/misc_programming | 60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e | [
"MIT"
] | null | null | null | cpp/has-rebind.cpp | lindsayad/misc_programming | 60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e | [
"MIT"
] | null | null | null | cpp/has-rebind.cpp | lindsayad/misc_programming | 60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e | [
"MIT"
] | null | null | null | #include <iostream>
template <typename T>
struct hasRebind
{
template <typename C, typename Enable = typename C::value_type>
static constexpr bool test(int)
{
return true;
}
template <typename C>
static constexpr bool test(...)
{
return false;
}
static constexpr bool value = test<T>(int());
};
template <typename T>
struct A
{
static const bool value = !hasRebind<T>::value;
};
int
main()
{
std::cout << A<int>::value << std::endl;
}
| 14.6875 | 65 | 0.648936 | lindsayad |
26d621fbe096a3b23742a5159b6ae15d0bf023a3 | 7,526 | cc | C++ | ftr-js/binding/json.cc | louis-tru/Ngui | c1f25d8b6c42e873d5969fb588af22f428c58d4c | [
"BSD-3-Clause-Clear"
] | 86 | 2017-11-21T01:05:30.000Z | 2020-05-21T12:30:31.000Z | ftr-js/binding/json.cc | louis-tru/Ngui | c1f25d8b6c42e873d5969fb588af22f428c58d4c | [
"BSD-3-Clause-Clear"
] | 14 | 2020-10-16T11:30:57.000Z | 2021-04-16T06:10:06.000Z | ftr-js/binding/json.cc | louis-tru/Ngui | c1f25d8b6c42e873d5969fb588af22f428c58d4c | [
"BSD-3-Clause-Clear"
] | 13 | 2017-11-21T10:18:53.000Z | 2019-10-18T09:15:55.000Z | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2015, xuewen.chu
* 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 xuewen.chu 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 xuewen.chu 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.
*
* ***** END LICENSE BLOCK ***** */
#include "json-1.h"
#include "ftr-js/str.h"
#include "ftr-js/ftr.h"
#include "ftr/view.h"
/**
* @ns ftr::js
*/
JS_BEGIN
static cString Undefined("undefined");
static cString Null("null");
static cString True("true");
static cString False("false");
static cString Circular("[Circular]");
static cString Newline('\n');
static cString Comma(',');
static cString Space(' ');
static cString LBrack('[');
static cString RBrack(']');
static cString LBrace('{');
static cString RBrace('}');
static cString COLON(':');
static cString ELLIPSIS(" ... ");
static cString Quotes('"');
static cString BufferPrefix("<Buffer");
static cString GT(">");
static cString FUNCTION("[Function]");
static cString ARRAY("[Array]");
static cString OBJECT("[Object]");
/**
* @class JSON
*/
class InlJSON {
uint _indent;
StringBuilder* _rv;
Worker* worker;
Persistent<JSSet> _set;
void push_indent() {
for (uint i = 0; i < _indent; i++) {
_rv->push(Space);
}
}
bool stringify_object(Local<JSObject> arg) {
_rv->push(LBrace);
Local<JSArray> names = arg->GetPropertyNames(worker);
if ( names->Length(worker) > 1 ) {
_indent += 2;
for (int i = 0, j = 0; i < names->Length(worker); i++) {
Local<JSValue> key = names->Get(worker, i);
if (j > 0) _rv->push(Comma); // ,
_rv->push(Newline); push_indent();
// _rv->push(Quotes);
_rv->push(key->ToStringValue(worker));
// _rv->push(Quotes);
_rv->push(COLON); _rv->push(Space);
bool rv = stringify( arg->Get(worker, key), false ); // value
if ( ! rv ) return false;
j++;
}
_indent -= 2;
_rv->push(Newline); push_indent();
} else {
_rv->push(Space);
}
_rv->push(RBrace);
return true;
}
bool stringify_array(Local<JSArray> arg) {
_rv->push(LBrack);
if (arg->Length(worker) > 0) {
_indent += 2;
for (int i = 0; i < arg->Length(worker); i++) {
if (i > 0)
_rv->push(Comma);
_rv->push(Newline);
push_indent();
stringify( arg->Get(worker, i), false ); // value
}
_indent -= 2;
_rv->push(Newline);
push_indent();
} else {
_rv->push(Space);
}
_rv->push(RBrack);
return true;
}
bool stringify_buffer(WeakBuffer buf) {
_rv->push(BufferPrefix);
cchar* hex = "0123456789abcdef";
byte* s = (byte*)buf.value();
for (uint i = 0; i < buf.length(); i++) {
byte ch = s[i];
_rv->push(Space);
_rv->push( hex[ch >> 4] );
_rv->push( hex[ch & 15] );
if (i > 50) {
_rv->push(ELLIPSIS); break;
}
}
_rv->push(GT);
return true;
}
bool stringify_view(Local<JSObject> arg) {
_rv->push(LBrace);
Local<JSArray> names = arg->GetPropertyNames(worker);
if ( names->Length(worker) > 0 ) {
_indent += 2;
for (int i = 0, j = 0; i < names->Length(worker); i++) {
Local<JSValue> key = names->Get(worker, i);
if (j > 0) _rv->push(Comma); // ,
_rv->push(Newline); push_indent();
// _rv->push(Quotes);
_rv->push(key->ToStringValue(worker));
// _rv->push(Quotes);
_rv->push(COLON); _rv->push(Space);
bool rv = stringify( arg->Get(worker, key), true ); // value
if ( ! rv ) return false;
j++;
}
_indent -= 2;
_rv->push(Newline); push_indent();
} else {
_rv->push(Space);
}
_rv->push(RBrace);
return true;
}
bool stringify(Local<JSValue> arg, bool leaf) {
if (arg.IsEmpty()) { // error
return false;
}
bool rv = true;
if(arg->IsString(worker)) {
_rv->push(Quotes);
_rv->push( arg->ToStringValue(worker) );
_rv->push(Quotes);
}
else if (arg->IsFunction(worker)) {
_rv->push( FUNCTION );
}
else if (arg->IsObject(worker)) {
Local<JSObject> o = arg.To<JSObject>();
if (arg->IsUint8Array(worker)) {
rv = stringify_buffer(o->AsBuffer(worker));
}
else if (worker->values() && worker->values()->isBase(arg)) {
_rv->push(Quotes);
_rv->push( o->ToStringValue(worker) );
_rv->push(Quotes);
}
else if (leaf) {
if (arg->IsArray(worker)) {
_rv->push(ARRAY);
} else {
_rv->push(OBJECT);
}
}
else if (worker->hasInstance(arg, View::VIEW)) {
rv = stringify_view(o);
}
else if ( arg->IsDate(worker) ) {
_rv->push( arg->ToStringValue(worker) );
}
else {
if ( _set.local()->Has(worker, o).FromMaybe(true) ) {
_rv->push( Circular ); return true;
}
if ( _set.local()->Add(worker, o).IsEmpty() ) return false;
if (arg->IsArray(worker)) {
rv = stringify_array(o.To<JSArray>());
} else {
rv = stringify_object(o);
}
return _set.local()->Delete(worker, o).FromMaybe(false);
}
}
else if(arg->IsInt32(worker)) {
_rv->push( String(arg->ToInt32Value(worker)) );
}
else if(arg->IsNumber(worker)) {
_rv->push( String(arg->ToNumberValue(worker)) );
}
else if(arg->IsBoolean(worker)) {
if (arg->ToBooleanValue(worker)) {
_rv->push(True);
} else {
_rv->push(False);
}
}
else if(arg->IsDate(worker)) {
_rv->push(Quotes);
Local<JSFunction> f =
arg.To<JSObject>()->Get(worker, worker->strs()->toJSON()).To<JSFunction>();
_rv->push( f->Call(worker, 0, NULL, arg)->ToStringValue(worker) );
_rv->push(Quotes);
}
else if(arg->IsNull(worker)) {
_rv->push(Null);
}
else if(arg->IsUndefined(worker)) {
_rv->push(Undefined);
}
return true;
}
public:
InlJSON(Worker* worker) : _indent(0), _rv(NULL), worker(worker) {
_set.Reset(worker, worker->NewSet());
}
~InlJSON() {
_set.Reset();
}
bool stringify_console_styled(Local<JSValue> arg, StringBuilder* out) {
HandleScope scope(worker);
_rv = out;
return stringify(arg, false);
}
};
bool JSON::stringify_console_styled(Worker* worker, Local<JSValue> arg, StringBuilder* out) {
return InlJSON(worker).stringify_console_styled(arg, out);
}
JS_END
| 27.567766 | 93 | 0.623572 | louis-tru |
26d8f5fb3168d29084c4645ed4e692d72ea13e7f | 1,759 | cpp | C++ | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 8 | 2021-01-02T11:41:31.000Z | 2021-04-15T07:05:54.000Z | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 17 | 2021-01-08T06:52:51.000Z | 2021-04-18T20:00:28.000Z | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 1 | 2021-04-16T10:30:23.000Z | 2021-04-16T10:30:23.000Z | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#include "touca/framework/suites.hpp"
#include <algorithm>
#include <fstream>
#include "touca/devkit/platform.hpp"
namespace touca {
namespace framework {
RemoteSuite::RemoteSuite(const Options& options) : Suite(), _options(options) {}
void RemoteSuite::initialize() {
// To obtain list of testcases from the server, we expect
// the following configuration options are set.
const std::vector<std::string> keys = {"api-key", "api-url", "team", "suite",
"revision"};
const auto predicate = [this](const std::string& k) {
return _options.count(k);
};
if (!std::all_of(keys.begin(), keys.end(), predicate)) {
return;
}
// authenticate to the server.
ApiUrl api_url(_options.at("api-url"));
if (!api_url.confirm(_options.at("team"), _options.at("suite"),
_options.at("revision"))) {
throw std::runtime_error(api_url._error);
}
Platform platform(api_url);
if (!platform.auth(_options.at("api-key"))) {
throw std::runtime_error(platform.get_error());
}
// ask the server for the list of elements
for (const auto& element : platform.elements()) {
push(element);
}
}
FileSuite::FileSuite(const std::string& path) : Suite(), _path(path) {}
void FileSuite::initialize() {
std::string line;
std::ifstream ifs(_path);
while (std::getline(ifs, line)) {
// skip empty lines
if (line.empty()) {
continue;
}
// skip comment lines: by default, we define comment lines as
// lines that start with two pound characters
if (line.compare(0, 2, "##") == 0) {
continue;
}
push(line);
}
}
} // namespace framework
} // namespace touca
| 25.492754 | 80 | 0.633314 | getweasel |
26d907f758509cc2a75e820b8e5d8dcbe26968a5 | 13,389 | cpp | C++ | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 691 | 2019-07-10T13:46:05.000Z | 2022-03-31T05:31:56.000Z | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 20 | 2019-07-11T08:16:48.000Z | 2022-02-21T17:59:28.000Z | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 83 | 2019-07-11T09:55:24.000Z | 2022-03-30T03:04:01.000Z | /* vulkan_gl_texture_interop.cpp - Copyright 2019/2020 Utrecht University
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 "core_settings.h"
#ifdef WIN32
static PFN_vkGetMemoryWin32HandleKHR getMemoryWin32HandleKHR = nullptr;
#else
static PFN_vkGetMemoryFdKHR getMemoryFdKHR = nullptr;
#endif
lh2core::VulkanGLTextureInterop::VulkanGLTextureInterop( const VulkanDevice &device, uint32_t width, uint32_t height )
{
m_Device = device;
m_Width = width;
m_Height = height;
if ( glCreateMemoryObjectsEXT == nullptr ||
#if WIN32
glImportMemoryWin32HandleEXT == nullptr ||
#else // LINUX
glImportMemoryFdEXT == nullptr ||
#endif
glTextureStorageMem2DEXT == nullptr )
{
FATALERROR ( "A Vulkan-OpenGL interop requires an OpenGL 4.5 context and the following extensions: GL_EXT_memory_object, GL_EXT_memory_object_fd, GL_EXT_memory_object_win32. At least 1 of these was not found" );
}
m_Width = width;
m_Height = height;
// Create Vulkan image
vk::ImageCreateInfo imageCreateInfo{};
imageCreateInfo.setPNext( nullptr );
imageCreateInfo.setArrayLayers( 1 );
imageCreateInfo.setExtent( {width, height, 1} );
imageCreateInfo.setFlags( vk::ImageCreateFlags() );
imageCreateInfo.setFormat( vk::Format::eR32G32B32A32Sfloat );
imageCreateInfo.setImageType( vk::ImageType::e2D );
imageCreateInfo.setInitialLayout( vk::ImageLayout::eUndefined );
imageCreateInfo.setMipLevels( 1 );
imageCreateInfo.setQueueFamilyIndexCount( 0 );
imageCreateInfo.setPQueueFamilyIndices( nullptr );
imageCreateInfo.setTiling( vk::ImageTiling() );
imageCreateInfo.setUsage( vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst );
m_Image = m_Device->createImage( imageCreateInfo );
assert( m_Image );
// Get memory requirements
auto memoryRequirements = m_Device->getImageMemoryRequirements( m_Image );
// Allocate memory for image
vk::ExportMemoryAllocateInfo exportAllocInfo{};
exportAllocInfo.setHandleTypes( vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
vk::MemoryAllocateInfo memAllocInfo{};
memAllocInfo.pNext = &exportAllocInfo;
m_BufferSize = NEXTMULTIPLEOF( vk::DeviceSize( memoryRequirements.size * 1.3f ), memoryRequirements.alignment );
memAllocInfo.setAllocationSize( m_BufferSize );
memoryRequirements.size = m_BufferSize;
memAllocInfo.setMemoryTypeIndex( m_Device.GetMemoryType( memoryRequirements, vk::MemoryPropertyFlagBits::eDeviceLocal ) );
m_Memory = m_Device->allocateMemory( memAllocInfo );
assert( m_Memory );
// Bind memory to Vulkan image
m_Device->bindImageMemory( m_Image, m_Memory, 0 );
#ifdef WIN32
HANDLE handle = INVALID_HANDLE_VALUE;
#else
int handle = 0;
#endif
#if WIN32 // WINDOWS
// Resolve extension function if needed
if ( getMemoryWin32HandleKHR == nullptr )
getMemoryWin32HandleKHR = reinterpret_cast<PFN_vkGetMemoryWin32HandleKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryWin32HandleKHR" ) );
assert( getMemoryWin32HandleKHR != nullptr );
// Acquire WIN32 handle to Vulkan initialized memory
vk::MemoryGetWin32HandleInfoKHR getMemoryHandleInfo = vk::MemoryGetWin32HandleInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
getMemoryWin32HandleKHR( m_Device.GetVkDevice(), (VkMemoryGetWin32HandleInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != INVALID_HANDLE_VALUE && handle != nullptr );
#else // LINUX
// Resolve extension function if needed
if ( getMemoryFdKHR == nullptr )
getMemoryFdKHR = reinterpret_cast<PFN_vkGetMemoryFdKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryFdKHR" ) );
assert( getMemoryFdKHR != nullptr );
// Acquire Fd handle to Vulkan initialized memory
vk::MemoryGetFdInfoKHR getMemoryHandleInfo = vk::MemoryGetFdInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueFd );
getMemoryFdKHR( m_Device.GetVkDevice(), (VkMemoryGetFdInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != 0 );
#endif
// Create a new texture object in OpenGL
glCreateTextures( GL_TEXTURE_2D, 1, &m_TexID );
// Create external memory object
glCreateMemoryObjectsEXT( 1, &m_GLMemoryObj );
// Import Vulkan memory handle into OpenGL memory object
#if _WIN32
glImportMemoryWin32HandleEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, handle );
#else
glImportMemoryFdEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_FD_EXT, handle );
#endif
CheckGL();
// Point texture object to external OpenGL memory object
m_Width = width;
m_Height = height;
glTextureStorageMem2DEXT( m_TexID, 1, GL_RGBA32F, m_Width, m_Height, m_GLMemoryObj, 0 );
// Check for any errors
CheckGL();
}
lh2core::VulkanGLTextureInterop::~VulkanGLTextureInterop()
{
Cleanup();
}
void lh2core::VulkanGLTextureInterop::RecordTransitionToVulkan( vk::CommandBuffer &cmdBuffer )
{
// Our image has 1 layer
vk::ImageSubresourceRange subresourceRange{};
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
// Transition from color attachment to transfer destination
vk::ImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.oldLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.newLayout = vk::ImageLayout::eTransferDstOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eTransfer;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
}
void lh2core::VulkanGLTextureInterop::RecordTransitionToGL( vk::CommandBuffer &cmdBuffer )
{
// Our image has 1 layer
vk::ImageSubresourceRange subresourceRange;
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
// Transition our image to be used as a color attachment
vk::ImageMemoryBarrier imageMemoryBarrier;
imageMemoryBarrier.oldLayout = vk::ImageLayout::eUndefined;
imageMemoryBarrier.newLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlags();
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eTopOfPipe;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
}
void lh2core::VulkanGLTextureInterop::Cleanup()
{
glFlush();
glFinish();
if ( m_Image )
{
m_Device->destroyImage( m_Image );
m_Image = nullptr;
}
if ( m_Memory )
{
glDeleteMemoryObjectsEXT( 1, &m_GLMemoryObj );
m_GLMemoryObj = 0;
m_Device->freeMemory( m_Memory );
m_Memory = nullptr;
}
}
std::vector<const char *> lh2core::VulkanGLTextureInterop::GetRequiredExtensions()
{
#ifdef WIN32 // WINDOWS
return {
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME};
#else // LINUX
return {
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME};
#endif
}
void lh2core::VulkanGLTextureInterop::Resize( uint32_t width, uint32_t height, bool deleteOldGLTexture )
{
m_Width = width;
m_Height = height;
if ( m_Image ) m_Device->destroyImage( m_Image );
// Create Vulkan image
vk::ImageCreateInfo imageCreateInfo{};
imageCreateInfo.setPNext( nullptr );
imageCreateInfo.setArrayLayers( 1 );
imageCreateInfo.setExtent( {width, height, 1} );
imageCreateInfo.setFlags( vk::ImageCreateFlags() );
imageCreateInfo.setFormat( vk::Format::eR32G32B32A32Sfloat );
imageCreateInfo.setImageType( vk::ImageType::e2D );
imageCreateInfo.setInitialLayout( vk::ImageLayout::eUndefined );
imageCreateInfo.setMipLevels( 1 );
imageCreateInfo.setQueueFamilyIndexCount( 0 );
imageCreateInfo.setPQueueFamilyIndices( nullptr );
imageCreateInfo.setTiling( vk::ImageTiling() );
imageCreateInfo.setUsage( vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst );
m_Image = m_Device->createImage( imageCreateInfo );
assert( m_Image );
// Get memory requirements
auto memoryRequirements = m_Device->getImageMemoryRequirements( m_Image );
if ( memoryRequirements.size > m_BufferSize )
{
m_Device->freeMemory( m_Memory );
m_BufferSize = NEXTMULTIPLEOF( vk::DeviceSize( memoryRequirements.size * 1.3f ), memoryRequirements.alignment );
memoryRequirements.size = m_BufferSize;
// Allocate memory
vk::ExportMemoryAllocateInfo exportAllocInfo{};
exportAllocInfo.setHandleTypes( vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
vk::MemoryAllocateInfo memAllocInfo{};
memAllocInfo.pNext = &exportAllocInfo;
memAllocInfo.setAllocationSize( m_BufferSize );
memAllocInfo.setMemoryTypeIndex( m_Device.GetMemoryType( memoryRequirements, vk::MemoryPropertyFlagBits::eDeviceLocal ) );
m_Memory = m_Device->allocateMemory( memAllocInfo );
}
assert( m_Memory );
m_Device->bindImageMemory( m_Image, m_Memory, 0 );
#ifdef WIN32
HANDLE handle = INVALID_HANDLE_VALUE;
#else
int handle = 0;
#endif
#if _WIN32 // WINDOWS
// Resolve extension function if needed
if ( getMemoryWin32HandleKHR == nullptr )
getMemoryWin32HandleKHR = reinterpret_cast<PFN_vkGetMemoryWin32HandleKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryWin32HandleKHR" ) );
assert( getMemoryWin32HandleKHR != nullptr );
// Acquire WIN32 handle to Vulkan initialized memory
vk::MemoryGetWin32HandleInfoKHR getMemoryHandleInfo = vk::MemoryGetWin32HandleInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
getMemoryWin32HandleKHR( m_Device.GetVkDevice(), (VkMemoryGetWin32HandleInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != INVALID_HANDLE_VALUE && handle != nullptr );
#else // LINUX
// Resolve extension function if needed
if ( getMemoryFdKHR == nullptr )
getMemoryFdKHR = reinterpret_cast<PFN_vkGetMemoryFdKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryFdKHR" ) );
assert( getMemoryFdKHR != nullptr );
// Acquire Fd handle to Vulkan initialized memory
vk::MemoryGetFdInfoKHR getMemoryHandleInfo = vk::MemoryGetFdInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueFd );
getMemoryFdKHR( m_Device.GetVkDevice(), (VkMemoryGetFdInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != 0 );
#endif
// Create a new texture object in OpenGL
if ( deleteOldGLTexture )
glDeleteTextures( 1, &m_TexID );
glDeleteMemoryObjectsEXT( 1, &m_GLMemoryObj );
glCreateTextures( GL_TEXTURE_2D, 1, &m_TexID );
glCreateMemoryObjectsEXT( 1, &m_GLMemoryObj );
assert( m_TexID );
assert( m_GLMemoryObj );
// Bind Vulkan memory handle to OpenGL memory object
#if _WIN32
glImportMemoryWin32HandleEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, handle );
#else
glImportMemoryFdEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_FD_EXT, handle );
#endif
CheckGL();
// Point texture object to external OpenGL memory object
glTextureStorageMem2DEXT( m_TexID, 1, GL_RGBA32F, width, height, m_GLMemoryObj, 0 );
CheckGL();
auto cmdBuffer = m_Device.CreateOneTimeCmdBuffer();
auto queue = m_Device.GetGraphicsQueue();
TransitionImageToInitialState( cmdBuffer, queue );
cmdBuffer.Submit( queue, true );
}
void lh2core::VulkanGLTextureInterop::TransitionImageToInitialState( vk::CommandBuffer &cmdBuffer, vk::Queue &queue )
{
vk::ImageSubresourceRange subresourceRange;
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
vk::ImageMemoryBarrier imageMemoryBarrier;
imageMemoryBarrier.oldLayout = vk::ImageLayout::eUndefined;
imageMemoryBarrier.newLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eTransfer;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
} | 40.696049 | 213 | 0.79528 | vincevannoort |
26d97328bfba1b176f4aa7358df5db6d1a413591 | 755 | cpp | C++ | test/heap_test.cpp | FrezCirno/TinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | 1 | 2021-05-12T13:24:21.000Z | 2021-05-12T13:24:21.000Z | test/heap_test.cpp | FrezCirno/tinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | 1 | 2020-04-29T10:01:18.000Z | 2020-05-01T08:47:27.000Z | test/heap_test.cpp | FrezCirno/tinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | null | null | null | #include "vector.hpp"
#include "heap.hpp"
// #include <queue>
#include <iostream>
using namespace std;
template <typename T>
void print(T &vec)
{
for (auto it = vec.begin(); it < vec.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main(int argc, char const *argv[])
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
tinySTL::vector<int> ivec(a, a + 9);
print(ivec);
tinySTL::make_heap(ivec.begin(), ivec.end());
print(ivec);
ivec.push_back(999);
print(ivec);
tinySTL::push_heap(ivec.begin(), ivec.end());
print(ivec);
tinySTL::pop_heap(ivec.begin(), ivec.end());
print(ivec);
ivec.pop_back();
print(ivec);
return 0;
}
| 17.55814 | 54 | 0.519205 | FrezCirno |
26dc81775866ef94723349774409c2a3709b5db9 | 4,609 | hpp | C++ | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | 1 | 2021-05-15T05:28:02.000Z | 2021-05-15T05:28:02.000Z | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | null | null | null | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | 1 | 2021-07-29T14:21:06.000Z | 2021-07-29T14:21:06.000Z | #ifndef GAME_PLAY_HPP
#define GAME_PLAY_HPP
#include "rsdl.hpp"
#include "game_board.hpp"
#include "doodler.hpp"
#include "platform.hpp"
#include "normal_platform.hpp"
#include "movable_platform.hpp"
#include "breakable_platform.hpp"
#include "spring.hpp"
#include "enemy.hpp"
#include "normal_enemy.hpp"
#include "movable_enemy.hpp"
#include "pistol.hpp"
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
typedef Point sizeVector;
constexpr int DELAY = 15; // in milliseconds
constexpr int BUTTON_PRESS_DELAY = 200; // in milliseconds
constexpr int NAME_LENGTH = 10;
class GamePlay
{
public:
struct Addresses
{
string background;
string normalPlatform;
string MovablePlatform;
vector<string> breakablePlatform;
vector<string> doodler;
vector<string> enemies;
string comicFont;
string scoreBackground;
string gameOver;
vector<string> springs;
vector<string> stars;
string pauseButton;
string pauseMenu;
vector<string> resumeButton;
vector<string> menuButton;
vector<string> playAgainButton;
string mainMenu;
vector<string> playButton;
vector<string> spaceship;
string nameAndScore;
string staticMap;
string dynamicMap;
string pistol;
string jumpEffect;
string springEffect;
string monsterCrashEffect;
string jumpOnMonsterEffect;
string breakPlatformEffect;
string fallEffect;
string nearEnemyEffect;
string pistolShootEffect;
string pistolKilledMonsterEffect;
};
struct Sizes
{
sizeVector background;
sizeVector normalAndMovablePlatforms;
vector<sizeVector> breakablePlatform;
vector<sizeVector> doodler;
vector<sizeVector> enemies;
sizeVector scoreBackground;
vector<sizeVector> springs;
sizeVector stars;
sizeVector pauseButton;
sizeVector resumeButton;
sizeVector menuButton;
sizeVector playAgainButton;
sizeVector nameEdit;
sizeVector playButton;
sizeVector spaceship;
sizeVector pistol;
};
struct Locations
{
Point scoreLocation;
Point stars;
Point pauseButton;
Point resumeButton;
Point menuButton;
Point playAgainButton;
Point gameOverScore;
Point overallHighScore;
Point name;
Point playButton;
Point menuPlatform;
Point spaceship;
};
enum class Actions
{
PlayAgain,
Menu,
Quit
};
GamePlay(const Addresses addresses, const Sizes sizes, Locations location, Window *window, int &highScore, string &name);
~GamePlay();
Actions process();
private:
struct Sequence
{
int start_;
int end_;
int totalHeight_;
vector<string> types_;
vector<int> x_;
vector<int> y_;
Sequence(int start, int end, int totalHeight, vector<string> types, vector<int> x, vector<int> y);
};
vector<Platform *> platforms_;
vector<Spring *> springs_;
vector<Enemy *> enemies_;
vector<Pistol *> pistols_;
Doodler *doodler_;
GameBoard *board_;
Addresses addresses_;
Sizes sizes_;
Locations locations_;
Window *window_;
bool gameOver_;
bool fellAfterGameOver_;
int &highScore_;
string &name_;
vector<Sequence> sequences_;
int sequenceStart_;
int sequenceHeight_;
void printOnScreen() const;
void processPlatformChanges();
void processSpringChanges();
void processEnemyChanges();
void processPistolChanges();
bool checkForInGameEvents();
void moveCamera(int pixel);
void checkForCollision();
bool checkForPlatformCollision();
bool checkForSpringCollision();
bool checkForEnemyCollision();
void printDoodler() const;
void printPlatforms() const;
void printSprings() const;
void printEnemies() const;
void printStars() const;
void printPistols() const;
int getHighScore() const { return doodler_->getScoreInScreen() + board_->getBase(); }
bool fallingHandler();
void moveCameraUp();
Actions gameOverEvent() const;
void printGameOver() const;
static int getAppropriateDelay(unsigned int prevTime);
void processPossibleChanges();
static bool checkForButtonPress(Point topLeftLocation, sizeVector size, const Event &event);
bool pause();
void menuButton() const;
void playAgainButton() const;
int checkForOverallHighScore() const;
void editName() const;
void endEditingName(const ostringstream &nameStream, const string &prevName) const;
bool update();
void readStaticMap();
void readValuesFromStaticMap(ifstream &input);
Point getTopLeftFromMiddleDown(int x, int y, sizeVector size) const;
bool readDynamicMap();
void readValuesFromDynamicMap(ifstream &input);
void addDataFromMap(int x, int y, string type, int base);
void inGameSequenceAdd(int index, int base);
void checkForNewSequence();
void findSuitableSequence();
bool isEnemyNear();
void makePistol();
};
#endif | 24.647059 | 122 | 0.765459 | PashaBarahimi |
26e398b94faf192b549c350f9c711ddd906600f1 | 13,287 | cpp | C++ | src/prod/src/Management/FileStoreService/PartitionContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Management/FileStoreService/PartitionContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Management/FileStoreService/PartitionContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Transport;
using namespace Reliability;
using namespace Api;
using namespace ServiceModel;
using namespace Management::FileStoreService;
StringLiteral const TraceComponent("PartitionContext");
class PartitionContext::RefreshStagingLocationAsyncOperation : public TimedAsyncOperation
{
public:
RefreshStagingLocationAsyncOperation(
PartitionContext & owner,
uint64 const currentSequenceNumber,
TimeSpan timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
: TimedAsyncOperation(timeout, callback, parent)
, owner_(owner)
, currentSequenceNumber_(currentSequenceNumber)
, retryCount_(0)
{
}
~RefreshStagingLocationAsyncOperation()
{
}
EventT<RefreshedStagingLocationEventArgs>::HHandler Add(EventT<RefreshedStagingLocationEventArgs>::EventHandler const & handler)
{
ASSERT_IFNOT(refreshedEvent_, "refreshedEvent_ should be set");
return refreshedEvent_->Add(handler);
}
void Remove(EventT<RefreshedStagingLocationEventArgs>::HHandler const & handleOfHandler)
{
ASSERT_IFNOT(refreshedEvent_, "refreshedEvent_ should be set");
refreshedEvent_->Remove(handleOfHandler);
}
protected:
void OnStart(AsyncOperationSPtr const & thisSPtr)
{
bool alreadyExists = false;
bool alreadyRefreshed = false;
{
AcquireWriteLock lock(owner_.lock_);
if(owner_.refreshAsyncOperation_)
{
// Another thread already started the refresh
alreadyExists = true;
}
else if(currentSequenceNumber_ < owner_.currentShareLocationInfo_.SequenceNumber)
{
// Another thread already refreshed the StagingLocationInfo
alreadyRefreshed = true;
}
else
{
refreshedEvent_ = make_shared<EventT<RefreshedStagingLocationEventArgs>>();
owner_.refreshAsyncOperation_ = this->shared_from_this();
}
}
if(alreadyExists)
{
TryComplete(thisSPtr, ErrorCodeValue::AlreadyExists);
return;
}
if(alreadyRefreshed)
{
TryComplete(thisSPtr, ErrorCodeValue::Success);
return;
}
this->StartRefreshStagingLocation(thisSPtr);
}
void StartRefreshStagingLocation(AsyncOperationSPtr const & thisSPtr)
{
WriteNoise(
TraceComponent,
owner_.Root.TraceId,
"Begin(GetStagingLocation): PartitionId:{0}",
owner_.PartitionId);
auto operation = owner_.fileStoreServiceClient_->BeginGetStagingLocation(
owner_.PartitionId,
FileStoreServiceConfig::GetConfig().GetStagingLocationTimeout,
[this] (AsyncOperationSPtr const & operation) { this->OnGetStagingLocationComplete(operation, false); },
thisSPtr);
this->OnGetStagingLocationComplete(operation, true);
}
void OnGetStagingLocationComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
wstring newStagingLocation;
auto error = owner_.fileStoreServiceClient_->EndGetStagingLocation(operation, newStagingLocation);
WriteTrace(
error.ToLogLevel(),
TraceComponent,
owner_.Root.TraceId,
"End(GetStagingLocation): NewStagingLocation:{0}, Error:{1} retryCount:{2}",
newStagingLocation,
error,
retryCount_);
if(!error.IsSuccess() &&
IsRetryable(error) &&
retryCount_ < FileStoreServiceConfig::GetConfig().MaxGetStagingLocationRetryAttempt &&
this->RemainingTime >= FileStoreServiceConfig::GetConfig().GetStagingLocationTimeout)
{
++retryCount_;
StartRefreshStagingLocation(operation->Parent);
return;
}
this->UpdateStagingLocationAndComplete(operation->Parent, error, newStagingLocation);
}
void UpdateStagingLocationAndComplete(AsyncOperationSPtr const & thisSPtr, ErrorCode const & error, wstring const & newStagingLocation)
{
shared_ptr<EventT<RefreshedStagingLocationEventArgs>> refreshedEvent;
StagingLocationInfo refreshedInfo;
{
AcquireWriteLock lock(owner_.lock_);
if(error.IsSuccess())
{
refreshedInfo = StagingLocationInfo(
newStagingLocation,
owner_.currentShareLocationInfo_.SequenceNumber + 1);
owner_.currentShareLocationInfo_ = refreshedInfo;
}
owner_.refreshAsyncOperation_.reset();
refreshedEvent = move(refreshedEvent_);
}
RefreshedStagingLocationEventArgs eventArg(refreshedInfo, error);
refreshedEvent->Fire(eventArg, true);
TryComplete(thisSPtr, move(error));
}
bool IsRetryable(ErrorCode const & error)
{
switch(error.ReadValue())
{
case ErrorCodeValue::NotPrimary:
case ErrorCodeValue::Timeout:
return true;
default:
return false;
}
}
private:
uint64 const currentSequenceNumber_;
PartitionContext & owner_;
shared_ptr<EventT<RefreshedStagingLocationEventArgs>> refreshedEvent_;
uint32 retryCount_;
};
class PartitionContext::GetStagingLocationAsyncOperation : public TimedAsyncOperation
{
public:
GetStagingLocationAsyncOperation(
PartitionContext & owner,
StagingLocationInfo previousInfo,
TimeSpan timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
: TimedAsyncOperation(timeout, callback, parent)
, owner_(owner)
, previousInfo_(previousInfo)
, newInfo_()
, refreshCount_(0)
, timer_()
, asyncOperationLock_()
{
}
~GetStagingLocationAsyncOperation()
{
}
static ErrorCode End(
AsyncOperationSPtr const & operation,
__out StagingLocationInfo & stagingLocationInfo)
{
auto thisSPtr = AsyncOperation::End<GetStagingLocationAsyncOperation>(operation);
stagingLocationInfo = thisSPtr->newInfo_;
return thisSPtr->Error;
}
protected:
void OnStart(AsyncOperationSPtr const & thisSPtr)
{
ErrorCode error;
bool startRefresh = false;
bool waitForPendingRefresh = false;
uint64 currentSequenceNumber = 0;
{
AcquireReadLock readLock(owner_.lock_);
AcquireExclusiveLock exclusiveLock(this->asyncOperationLock_);
if(owner_.refreshAsyncOperation_)
{
ASSERT_IF(timer_, "Timer should be set only once");
timer_ = Timer::Create(
TimerTagDefault,
[this, thisSPtr] (TimerSPtr const& timer)
{
timer->Cancel();
this->OnTimerExpired(thisSPtr);
},
false);
auto casted = AsyncOperation::Get<RefreshStagingLocationAsyncOperation>(owner_.refreshAsyncOperation_);
eventHandle_ = casted->Add(
[this, thisSPtr] (RefreshedStagingLocationEventArgs const & eventArg) { this->OnStagingLocationRefreshed(thisSPtr, eventArg); });
waitForPendingRefresh = true;
}
else if(previousInfo_.SequenceNumber < owner_.currentShareLocationInfo_.SequenceNumber)
{
newInfo_ = owner_.currentShareLocationInfo_;
}
else
{
// If there are two competing threads to refresh the staging location,
// the currentSequenceNumber check in RefreshStagingLocationAsyncOperation
// guarantees that only one will go through
currentSequenceNumber = owner_.currentShareLocationInfo_.SequenceNumber;
// Try to refresh three times before giving up
if(refreshCount_++ < 3)
{
startRefresh = true;
}
else
{
error = ErrorCodeValue::OperationFailed;
}
}
}
if(startRefresh)
{
this->StartRefresh(thisSPtr, currentSequenceNumber);
}
else if(waitForPendingRefresh)
{
timer_->Change(this->RemainingTime);
}
else
{
TryComplete(thisSPtr, error);
}
}
void StartRefresh(AsyncOperationSPtr const & thisSPtr, uint64 const currentSequenceNumber)
{
owner_.StartRefresh(currentSequenceNumber);
// Post the call on a different thread to avoid callstack from increasing
Threadpool::Post(
[this, thisSPtr] () { this->OnStart(thisSPtr); });
}
void OnStagingLocationRefreshed(AsyncOperationSPtr const & thisSPtr, RefreshedStagingLocationEventArgs const & eventArg)
{
if(TryStartComplete())
{
AcquireExclusiveLock exclusiveLock(this->asyncOperationLock_);
newInfo_ = eventArg.StagingLocation;
timer_->Cancel();
FinishComplete(thisSPtr, eventArg.Error);
}
}
void OnTimerExpired(AsyncOperationSPtr const & thisSPtr)
{
if(TryStartComplete())
{
AcquireReadLock readLock(owner_.lock_);
AcquireExclusiveLock exclusiveLock(this->asyncOperationLock_);
if(owner_.refreshAsyncOperation_)
{
auto casted = AsyncOperation::Get<RefreshStagingLocationAsyncOperation>(owner_.refreshAsyncOperation_);
casted->Remove(eventHandle_);
}
FinishComplete(thisSPtr, ErrorCodeValue::Timeout);
}
}
private:
StagingLocationInfo previousInfo_;
StagingLocationInfo newInfo_;
PartitionContext & owner_;
ExclusiveLock asyncOperationLock_;
// access under lock
uint refreshCount_;
EventT<RefreshedStagingLocationEventArgs>::HHandler eventHandle_;
TimerSPtr timer_;
};
PartitionContext::PartitionContext(
ComponentRoot const & root,
Guid const & partitionId,
IInternalFileStoreServiceClientPtr const & fileStoreServiceClient)
: RootedObject(root)
, partitionId_(partitionId)
, fileStoreServiceClient_(fileStoreServiceClient)
, lock_()
, currentShareLocationInfo_()
, refreshAsyncOperation_()
{
}
PartitionContext::~PartitionContext()
{
}
Common::AsyncOperationSPtr PartitionContext::BeginGetStagingLocation(
StagingLocationInfo previousInfo,
Common::TimeSpan const timeout,
Common::AsyncCallback const &callback,
Common::AsyncOperationSPtr const & parent)
{
return AsyncOperation::CreateAndStart<GetStagingLocationAsyncOperation>(
*this,
previousInfo,
timeout,
callback,
parent);
}
Common::ErrorCode PartitionContext::EndGetStagingLocation(
Common::AsyncOperationSPtr const & operation,
__out StagingLocationInfo & stagingLocationInfo)
{
return GetStagingLocationAsyncOperation::End(operation, stagingLocationInfo);
}
bool PartitionContext::DoesMatchPartition(uint64 const partitionKey) const
{
// Partitioned service not supported yet
UNREFERENCED_PARAMETER(partitionKey);
return true;
}
void PartitionContext::StartRefresh(uint64 const currentSequenceNumber)
{
WriteNoise(
TraceComponent,
Root.TraceId,
"Begin(RefreshStagingLocation): CurrentSequenceNumber:{0}",
currentSequenceNumber);
auto operation = AsyncOperation::CreateAndStart<RefreshStagingLocationAsyncOperation>(
*this,
currentSequenceNumber,
FileStoreServiceConfig::GetConfig().ShortRequestTimeout,
[this] (AsyncOperationSPtr const & operation) { this->OnRefreshCompleted(operation, false); },
Root.CreateAsyncOperationRoot());
this->OnRefreshCompleted(operation, true);
}
void PartitionContext::OnRefreshCompleted(Common::AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
auto error = RefreshStagingLocationAsyncOperation::End(operation);
WriteTrace(
error.ToLogLevel(),
TraceComponent,
Root.TraceId,
"End(RefreshStagingLocation): Error:{0}",
error);
}
| 32.726601 | 165 | 0.631745 | gridgentoo |
26e63fc9dc0714abda70e802c96985b6b8d90175 | 1,424 | cpp | C++ | flume/planner/first_layer_dispatcher.cpp | tushushu/bigflow | ab494e49a02b446bb2f504a2652f866c924c1baf | [
"Apache-2.0"
] | 1,236 | 2017-11-14T11:10:10.000Z | 2022-03-08T11:54:41.000Z | flume/planner/first_layer_dispatcher.cpp | tushushu/bigflow | ab494e49a02b446bb2f504a2652f866c924c1baf | [
"Apache-2.0"
] | 38 | 2017-11-14T16:29:12.000Z | 2020-01-23T08:32:04.000Z | flume/planner/first_layer_dispatcher.cpp | tushushu/bigflow | ab494e49a02b446bb2f504a2652f866c924c1baf | [
"Apache-2.0"
] | 184 | 2017-11-27T07:23:36.000Z | 2022-03-14T02:54:16.000Z | /***************************************************************************
*
* Copyright (c) 2013 Baidu, 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.
*
**************************************************************************/
// Author: Wang Song <bigflow-opensource@baidu.com>
//
#include "flume/planner/first_layer_dispatcher.h"
#include "flume/planner/plan.h"
#include "flume/planner/unit.h"
namespace baidu {
namespace flume {
namespace planner {
FirstLayerDispatcher::~FirstLayerDispatcher() {
}
bool FirstLayerDispatcher::Run(Plan* plan) {
bool changed = false;
Unit* root = plan->Root();
Unit::Children children(root->begin(), root->end());
for (Unit::iterator it = children.begin(); it != children.end(); ++it) {
changed |= Dispatch(plan, *it);
}
return changed;
}
} // namespace planner
} // namespace flume
} // namespace baidu
| 30.297872 | 76 | 0.627809 | tushushu |
26e87f84de5d70c5e017f668a260d085aca36ef5 | 719 | inl | C++ | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #include <Core/Geometry/DCEL/Iterator/Face/FFEIterator.hpp>
#include <Core/Geometry/DCEL/Face.hpp>
#include <Core/Geometry/DCEL/FullEdge.hpp>
#include <Core/Geometry/DCEL/HalfEdge.hpp>
namespace Ra {
namespace Core {
/// CONSTRUCTOR
FFEIterator::FFEIterator( Face_ptr& f ) : FIterator<FullEdge>( f ) {}
/// DESTRUCTOR
FFEIterator::~FFEIterator() {}
/// LIST
inline FullEdgeList FFEIterator::list() const {
FullEdgeList L;
HalfEdge_ptr it = m_f->HE();
do
{
L.push_back( it->FE() );
it = it->Next();
} while ( it != m_f->HE() );
return L;
}
/// OPERATOR
inline FullEdge* FFEIterator::operator->() const {
return m_he->FE().get();
}
} // namespace Core
} // namespace Ra
| 20.542857 | 69 | 0.646732 | sylvaindeker |
26ee413da88a0613a08a7d7190aa25937bf8af91 | 2,835 | hpp | C++ | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | 2 | 2020-11-17T18:40:04.000Z | 2021-02-23T15:18:47.000Z | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | 1 | 2020-09-19T19:24:40.000Z | 2020-09-19T19:24:40.000Z | #pragma once
#include <array>
#include <cstddef>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <iostream>
#include <vector>
#include "t.hpp"
struct ShapeInfo {
std::vector<float> vertices_buffer;
const char* vertex_shader;
const char* pixel_shader;
};
template <class T>
class Shape {
static const ShapeInfo objects_static_info_;
static const std::vector<float> vertices_buffer_;
public:
static auto& ShapeVerticesBuffer2() { return Shape::vertices_buffer_; }
static auto& StaticInfo() { return objects_static_info_; }
};
// Базовый класс физического объекта игрового мира.
class Object {
unsigned int id_;
protected:
static constexpr int num_instances_ = 1;
std::vector<float> coords_;
std::vector<float> angles_;
std::vector<float> params_;
public:
static constexpr int num_coords = 3;
static constexpr int num_angles = 3;
static constexpr int num_params = 4;
Object(glm::vec3 coords = {0, 0, 0}, glm::vec3 angles = {0, 0, 0},
glm::vec4 params = {0, 0, 0, 0});
virtual ~Object() {}
const auto& Coords() { return coords_; }
const auto& Angles() { return angles_; }
const auto& Params() { return params_; }
// Из скольки однотипных фигур составлен объект. Например в стене или в
// снараяде по одной. Человек же состоит из 8: голова, туловище, два плеча,
// два предплечья, два бедра, две голени.
virtual int NumInstances() { return Object::num_instances_; }
// Для обновления параметров для шейдера.
virtual void Step() {}
void Move(tribool backward_forward, tribool left_right, tribool down_up);
unsigned int id() { return id_; }
public:
// TODO OLD
// P orientation_; // В какую сторону смотрит объект.
// P motion_external_; // Запрошенное движение извне (кнопками, Ai).
// P motion_internal_; // Фактическое движение (блокируемое анимацией).
int timer_inertia_; // Таймер отработки анимации.
V v_;
int weight_; // >0 обычный объект, =0 стена, <0 артефактphy
// std::vector<std::array<float, 3>> offsets_old_;
// std::vector<std::array<float, 3>> angles_old_;
// std::vector<std::array<float, 3>> params_old_;
// // Object(V v = V(), float weight = 0, glm::vec3 angles = {0, 0, 0},
// glm::vec3 params = {0, 0, 0});
// P& GetOrientation() { return orientation_; }
// void SetOrientation(P p) { orientation_ = p; }
// void SetMotion(P& p) { motion_external_ = p; }
V& v() { return v_; }
// Возвращает координты вершин базовой формы: параллелепипеда, куба, шара, и
// т.д. в виде: x1,y1,z1,x2,y2,z2,..., где каждая тройка координат
// представляет собой тругольник. Передаётся в рендер.
virtual const std::vector<float>* ShapeVerticesBuffer() = 0;
// virtual const std::vector<std::array<float, 3>>& Offsets() {
// return offsets_old_;
// }
int Weight() { return weight_; }
};
| 32.215909 | 78 | 0.682187 | rokashevich |
26f18562c0d46bd6a5ee111b283e22dab8445d79 | 10,245 | hpp | C++ | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | null | null | null | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | null | null | null | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | 1 | 2021-06-03T09:17:20.000Z | 2021-06-03T09:17:20.000Z | /*
MIT License
Copyright (c) 2019 Berkay Yigit <berkay2578@gmail.com>
Copyright holder detail: Nickname(s) used by the copyright holder: 'berkay2578', 'berkayylmao'.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include "stdafx.h"
#include "Extensions\Extensions.h"
using GameInternals::TimeOfDay;
using GameInternals::TimeOfDayLighting;
using GameInternals::TimeOfDayLightingData;
namespace Extensions {
namespace InGameMenu {
class TimeOfDayEditor : public _BaseInGameMenuItem {
int32_t curLightingIndex = 0;
TimeOfDayLighting* pEditTimeOfDayLighting = nullptr;
std::vector<std::string> vStrLightingHashes;
TimeOfDay* pTimeOfDay = nullptr;
public:
const virtual void loadData() override {
while (!pTimeOfDay) {
pTimeOfDay = TimeOfDayInternals::getTimeOfDay();
Sleep(100);
}
while (!TimeOfDayInternals::loadLightingDefinitions()) {
Sleep(100);
}
int count = TimeOfDayInternals::lightingDefinitions.size();
for (int lightingIndex = 0; lightingIndex < count; lightingIndex++)
{
TimeOfDayInternals::TimeOfDayLightingDefinition* pDefinition = TimeOfDayInternals::lightingDefinitions[lightingIndex];
TimeOfDayLighting* pDefinitionLighting = pDefinition->pTimeOfDayLighting;
std::string lightingHash = pDefinition->getHashAsString();
vStrLightingHashes.push_back(lightingHash);
if (Settings::settingsType.todPresets.size() != 0) {
auto iter = Settings::settingsType.todPresets.find(lightingHash);
if (iter != Settings::settingsType.todPresets.end()) {
auto* pSettingsInstance = &iter->second;
*pDefinitionLighting->pLightingData = pSettingsInstance->LightingDataPreset.getGameInternalsCompliantData();
pDefinitionLighting->FogInLightScatter = pSettingsInstance->FogInLightScatter;
pDefinitionLighting->FogSunFalloff = pSettingsInstance->FogSunFalloff;
}
}
if (pDefinitionLighting == pTimeOfDay->pTimeOfDayLighting)
curLightingIndex = lightingIndex;
}
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
hasLoadedData = true;
}
const virtual void onFrame() override {}
const virtual bool displayMenuItem(const ImVec2& buttonSize) override {
return ImGui::Button("Time of day and lighting editor", buttonSize);
}
const virtual bool displayMenu() override {
static float lineDiff = 0.0f;
lineDiff = ImGui::CalcTextSize("Time of day progression speed multiplier...").x + ImGui::GetStyle().WindowPadding.x;
ImGui::PushItemWidth(lineDiff * 0.625f);
ImGui::Text("Skybox animation speed multiplier"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##SkySpeedMult", &pTimeOfDay->SkyboxSpeedMultiplier, -100.0f, 100.0f);
ImGui::Text("Time of day progression speed multiplier"); ImGui::SameLine(lineDiff);
ImGui::SliderInt("##ToDSpeedMult", &pTimeOfDay->TimeOfDaySpeedMultiplier, -100, 100);
ImGui::Text("Time of day"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##ToDValue", &pTimeOfDay->TimeOfDayValue, 0.05f, 0.95f);
ImGui::Text("Sun default orbit X-Axis (Horizontal)"); ImGui::SameLine(lineDiff);
ImGui::SliderAngle("##SunOrbitXAxis", &pTimeOfDay->SunDefaultOrbitAxisX);
ImGui::Text("Sun default orbit Y-Axis (Vertical)"); ImGui::SameLine(lineDiff);
ImGui::SliderAngle("##SunOrbitYAxis", &pTimeOfDay->SunDefaultOrbitAxisY);
ImGui::PopItemWidth();
ImGui::Separator();
if (pEditTimeOfDayLighting) {
ImGui::Text("Lighting "); ImGui::SameLine();
if (ImGui::Combo("##ActiveLighting", &curLightingIndex, vStrLightingHashes)) {
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
} ImGui::SameLine();
if (ImGui::Button("Set active")) {
pTimeOfDay->pTimeOfDayLighting = pEditTimeOfDayLighting;
pTimeOfDay->pTimeOfDayLightingData = pEditTimeOfDayLighting->pLightingData;
pTimeOfDay->TimeOfDayValue = 0.5f;
}
if (ImGui::Button("Save preset")) {
Settings::TimeOfDayLightingPreset* pSettingsInstance = &Settings::settingsType.todPresets[vStrLightingHashes[curLightingIndex]];
pSettingsInstance->setTo(pEditTimeOfDayLighting);
Settings::saveSettings();
} ImGui::SameLine(); ImGui::VerticalSeparator(); ImGui::SameLine();
if (ImGui::Button("Override all and save")) {
int index = 0;
for (const auto* def : TimeOfDayInternals::lightingDefinitions) {
// save
Settings::TimeOfDayLightingPreset* pSettingsInstance = &Settings::settingsType.todPresets[vStrLightingHashes[index]];
pSettingsInstance->setTo(pEditTimeOfDayLighting);
// apply
def->pTimeOfDayLighting->FogInLightScatter = pEditTimeOfDayLighting->FogInLightScatter;
def->pTimeOfDayLighting->FogSunFalloff = pEditTimeOfDayLighting->FogSunFalloff;
def->pTimeOfDayLighting->pLightingData->setTo(pEditTimeOfDayLighting->pLightingData);
index++;
}
Settings::saveSettings();
}
if (ImGui::Button("Restore all to defaults")) {
TimeOfDayInternals::restoreAll();
Settings::settingsType.todPresets.clear();
Settings::saveSettings();
}
lineDiff = ImGui::CalcTextSize("FixedFunctionSkyColour...").x + ImGui::GetStyle().WindowPadding.x;
ImGui::PushItemWidth(-1.0f);
ImGui::Text("SpecularColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##SpecularColour", pEditTimeOfDayLighting->pLightingData->SpecularColour);
ImGui::Text("DiffuseColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##DiffuseColour", pEditTimeOfDayLighting->pLightingData->DiffuseColour);
ImGui::Text("AmbientColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##AmbientColour", pEditTimeOfDayLighting->pLightingData->AmbientColour);
ImGui::Text("FogHazeColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FogHazeColour", pEditTimeOfDayLighting->pLightingData->FogHazeColour);
ImGui::Text("FixedFunctionSkyColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FixedFunctionSkyColour", pEditTimeOfDayLighting->pLightingData->FixedFunctionSkyColour);
ImGui::Text("FogDistanceScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogDistanceScale", &pEditTimeOfDayLighting->pLightingData->FogDistanceScale, 10.0f, -100.0f, 1000.0f);
ImGui::Text("FogHazeColourScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogHazeColourScale", &pEditTimeOfDayLighting->pLightingData->FogHazeColourScale, 10.0f, 0.0f, 1000.0f);
ImGui::Text("FogSkyColourScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogSkyColourScale", &pEditTimeOfDayLighting->pLightingData->FogSkyColourScale, 10.0f, 0.0f, 1000.0f);
ImGui::Text("EnvSkyBrightness"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##EnvSkyBrightness", &pEditTimeOfDayLighting->pLightingData->EnvSkyBrightness, 0.0f, 10.0f);
ImGui::Text("CarSpecScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##CarSpecScale", &pEditTimeOfDayLighting->pLightingData->CarSpecScale, 0.25f, 0.0f, 100.0f);
ImGui::Text("FogSkyColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FogSkyColour", pEditTimeOfDayLighting->pLightingData->FogSkyColour);
ImGui::Text("FogInLightScatter"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##FogInLightScatter", &pEditTimeOfDayLighting->FogInLightScatter, -100.0f, 100.0f);
ImGui::Text("FogSunFalloff"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##FogSunFalloff", &pEditTimeOfDayLighting->FogSunFalloff, -100.0f, 100.0f);
ImGui::PopItemWidth();
} else {
ImGui::Text("There was an issue setting up the lighting info.");
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
}
return true;
}
};
}
} | 52.809278 | 146 | 0.638555 | berkayylmao |
26f69d3b74c98bffcf7ee6d2d7985a71b8634aa6 | 10,304 | cc | C++ | ast/build_param_dependency_graph.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 10 | 2015-10-28T18:54:41.000Z | 2021-12-29T16:48:31.000Z | ast/build_param_dependency_graph.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 95 | 2020-02-27T22:34:02.000Z | 2022-03-06T19:45:24.000Z | ast/build_param_dependency_graph.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 2 | 2019-02-01T23:16:04.000Z | 2020-02-27T16:06:02.000Z | #include "ast/build_param_dependency_graph.h"
#include "absl/container/node_hash_map.h"
#include "ast/ast.h"
#include "ast/module.h"
#include "ast/visitor.h"
namespace ast {
namespace {
struct ParamDependencyGraphBuilder
: Visitor<void(core::DependencyNode<Declaration const *>)> {
explicit ParamDependencyGraphBuilder(
core::Params<std::unique_ptr<Declaration>> const ¶ms) {
to_process_.reserve(params.size());
for (auto const ¶m : params) {
// Parameters must not be multiple-declarations.
ASSERT(param.value->ids().size() == 1u);
to_process_.push_back(param.value.get());
relevant_decls_.emplace(param.value->ids()[0].name(), param.value.get());
}
}
base::Graph<core::DependencyNode<Declaration>> Visit() && {
for (auto [id, decl] : relevant_decls_) {
graph_.add_edge(core::DependencyNode<Declaration>::ParameterValue(decl),
core::DependencyNode<Declaration>::ParameterType(decl));
graph_.add_edge(core::DependencyNode<Declaration>::ArgumentValue(decl),
core::DependencyNode<Declaration>::ArgumentType(decl));
graph_.add_edge(core::DependencyNode<Declaration>::ParameterType(decl),
core::DependencyNode<Declaration>::ArgumentType(decl));
if (decl->flags() & Declaration::f_IsConst) {
graph_.add_edge(core::DependencyNode<Declaration>::ParameterValue(decl),
core::DependencyNode<Declaration>::ArgumentValue(decl));
}
}
for (auto const *decl : to_process_) {
if (auto const *n = decl->type_expr()) {
Visit(n, core::DependencyNode<Declaration const *>::ParameterType(
&relevant_decls_.at(decl->ids()[0].name())));
} else {
graph_.add_edge(core::DependencyNode<Declaration>::ParameterType(decl),
core::DependencyNode<Declaration>::ArgumentType(decl));
}
if (auto const *n = decl->init_val()) {
Visit(n, core::DependencyNode<Declaration const *>::ParameterValue(
&relevant_decls_.at(decl->ids()[0].name())));
}
}
for (auto [head, tail] : edges_) {
if (*head.node() and *tail.node()) {
graph_.add_edge(
core::DependencyNode<Declaration>(*head.node(), head.kind()),
core::DependencyNode<Declaration>(*tail.node(), tail.kind()));
}
}
return std::move(graph_);
}
void Visit(BindingDeclaration const *node,
core::DependencyNode<Declaration const *> d) {
auto [iter, inserted] =
relevant_decls_.try_emplace(node->ids()[0].name(), node);
edges_.emplace_back(
d, core::DependencyNode<Declaration const *>::ParameterValue(
&iter->second));
edges_.emplace_back(
core::DependencyNode<Declaration const *>::ParameterValue(
&iter->second),
core::DependencyNode<Declaration const *>::ParameterType(
&iter->second));
}
void Visit(Node const *node, core::DependencyNode<Declaration const *> d) {
Visitor<void(core::DependencyNode<Declaration const *>)>::Visit(node, d);
}
void Visit(Access const *node, core::DependencyNode<Declaration const *> d) {
Visit(node->operand(), d);
}
void Visit(ArgumentType const *node,
core::DependencyNode<Declaration const *> d) {
auto [iter, inserted] = relevant_decls_.try_emplace(node->name());
edges_.emplace_back(
d,
core::DependencyNode<Declaration const *>::ArgumentType(&iter->second));
}
void Visit(ArrayLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const *expr : node->elems()) { Visit(expr, d); }
}
void Visit(ArrayType const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const &len : node->lengths()) { Visit(len, d); }
Visit(node->data_type(), d);
}
void Visit(Assignment const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const *l : (node->lhs())) { Visit(l, d); }
for (auto const *r : (node->rhs())) { Visit(r, d); }
}
void Visit(BinaryOperator const *node,
core::DependencyNode<Declaration const *> d) {
Visit(&node->lhs(), d);
Visit(&node->rhs(), d);
}
void Visit(BlockNode const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const &p : node->params()) { Visit(p.value.get(), d); }
for (auto const *stmt : node->stmts()) { Visit(stmt, d); }
}
void Visit(BuiltinFn const *node,
core::DependencyNode<Declaration const *> d) {}
void Visit(Call const *node, core::DependencyNode<Declaration const *> d) {
Visit(node->callee(), d);
for (auto const &arg : node->arguments()) { Visit(&arg.expr(), d); }
}
void Visit(Cast const *node, core::DependencyNode<Declaration const *> d) {
Visit(node->expr(), d);
Visit(node->type(), d);
}
void Visit(ComparisonOperator const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const *expr : node->exprs()) { Visit(expr, d); }
}
void Visit(Declaration const *node,
core::DependencyNode<Declaration const *> d) {
if (node->type_expr()) { Visit(node->type_expr(), d); }
if (node->init_val()) { Visit(node->init_val(), d); }
}
void Visit(DesignatedInitializer const *node,
core::DependencyNode<Declaration const *> d) {
Visit(node->type(), d);
for (auto const *assignment : node->assignments()) { Visit(assignment, d); }
}
void Visit(EnumLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const &[enumerator, value] : node->specified_values()) {
Visit(value.get(), d);
}
}
void Visit(FunctionLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const ¶m : node->params()) { Visit(param.value.get(), d); }
if (auto outputs = node->outputs()) {
for (auto const &out : *outputs) { Visit(out, d); }
}
}
void Visit(FunctionType const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const *param : node->params()) { Visit(param, d); }
for (auto const *out : node->outputs()) { Visit(out, d); }
}
void Visit(ShortFunctionLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const ¶m : node->params()) { Visit(param.value.get(), d); }
}
void Visit(Identifier const *node,
core::DependencyNode<Declaration const *> d) {
auto [iter, inserted] = relevant_decls_.try_emplace(node->name());
edges_.emplace_back(
d, core::DependencyNode<Declaration const *>::ParameterValue(
&iter->second));
}
void Visit(Import const *node, core::DependencyNode<Declaration const *> d) {
Visit(node->operand(), d);
}
void Visit(Index const *node, core::DependencyNode<Declaration const *> d) {
Visit(node->lhs(), d);
Visit(node->rhs(), d);
}
void Visit(InterfaceLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto &[name, expr] : node->entries()) {
Visit(name.get(), d);
Visit(expr.get(), d);
}
}
void Visit(Module const *node, core::DependencyNode<Declaration const *> d) {}
void Visit(Label const *node, core::DependencyNode<Declaration const *> d) {}
void Visit(ReturnStmt const *node,
core::DependencyNode<Declaration const *> d) {
for (auto *expr : node->exprs()) { Visit(expr, d); }
}
void Visit(YieldStmt const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const &arg : node->arguments()) { Visit(&arg.expr(), d); }
}
void Visit(ScopeLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const ¶m : node->params()) { Visit(param.value.get(), d); }
for (auto const *stmt : node->stmts()) { Visit(stmt, d); }
}
void Visit(ScopeNode const *node,
core::DependencyNode<Declaration const *> d) {
Visit(node->name(), d);
for (auto const &arg : node->arguments()) { Visit(&arg.expr(), d); }
for (auto const &block : node->blocks()) { Visit(&block, d); }
}
void Visit(SliceType const *node,
core::DependencyNode<Declaration const *> d) {
Visit(node->data_type(), d);
}
void Visit(StructLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const &f : node->fields()) { Visit(&f, d); }
}
void Visit(PatternMatch const *node,
core::DependencyNode<Declaration const *> d) {
ASSERT(node->is_binary() == false);
Visit(&node->pattern(), d);
}
void Visit(ParameterizedStructLiteral const *node,
core::DependencyNode<Declaration const *> d) {
for (auto const ¶m : node->params()) { Visit(param.value.get(), d); }
for (auto const &f : node->fields()) { Visit(&f, d); }
}
void Visit(Terminal const *node,
core::DependencyNode<Declaration const *> d) {}
void Visit(UnaryOperator const *node,
core::DependencyNode<Declaration const *> d) {
Visit(node->operand(), d);
}
void Visit(IfStmt const *node, core::DependencyNode<Declaration const *> d) {
Visit(&node->condition(), d);
for (auto const *s : node->true_block()) { Visit(s, d); }
if (node->has_false_block()) {
for (auto const *s : node->false_block()) { Visit(s, d); }
}
}
void Visit(WhileStmt const *node,
core::DependencyNode<Declaration const *> d) {
Visit(&node->condition(), d);
for (auto const *s : node->body()) { Visit(s, d); }
}
private:
base::Graph<core::DependencyNode<Declaration>> graph_;
std::vector<Declaration const *> to_process_;
absl::node_hash_map<std::string_view, Declaration const *> relevant_decls_;
std::vector<std::pair<core::DependencyNode<Declaration const *>,
core::DependencyNode<Declaration const *>>>
edges_;
};
} // namespace
base::Graph<core::DependencyNode<Declaration>> BuildParamDependencyGraph(
core::Params<std::unique_ptr<Declaration>> const ¶ms) {
return ParamDependencyGraphBuilder(params).Visit();
}
} // namespace ast
| 35.047619 | 80 | 0.617818 | perimosocordiae |
26f83738d1d5f341deea2f52e36d1fa0f5daff60 | 1,750 | cpp | C++ | src/gui/MainMenuBar.cpp | mbassale/ownpass | a84e0cd3933ec8c3febf0e09647990baf3c2d506 | [
"MIT"
] | null | null | null | src/gui/MainMenuBar.cpp | mbassale/ownpass | a84e0cd3933ec8c3febf0e09647990baf3c2d506 | [
"MIT"
] | null | null | null | src/gui/MainMenuBar.cpp | mbassale/ownpass | a84e0cd3933ec8c3febf0e09647990baf3c2d506 | [
"MIT"
] | null | null | null | //
// Created by Marco Bassaletti on 07-04-21.
//
#include "MainMenuBar.h"
#include "states/StateContext.h"
namespace NSPass::GUI {
using States::StateContext;
using States::StateName;
MainMenuBar::MainMenuBar()
{
// create a menu bar
fileMenu = new wxMenu;
fileMenu->Append(MainFrame_OpenDefault, "Open Default...", "Open default password storage file");
fileMenu->Append(MainFrame_Open, "&Open\tCtrl-O", "Opens a password storage file");
fileMenu->Append(MainFrame_Save, "&Save\tCtrl-S", "Saves current storage file");
fileMenu->Append(MainFrame_Close, "&Close\tCtrl-W", "Closes current storage file");
fileMenu->AppendSeparator();
fileMenu->Append(MainFrame_Quit, "E&xit\tAlt-X", "Quit this program");
// the "About" item should be in the help menu
helpMenu = new wxMenu;
helpMenu->Append(MainFrame_About, "&About\tF1", "Show about dialog");
Append(fileMenu, "&File");
Append(helpMenu, "&Help");
Reset();
wxGetApp().GetStateContext().Subscribe(StateName::Initial, [&] {
Reset();
});
wxGetApp().GetStateContext().Subscribe(StateName::Open, [&] {
OnOpen();
});
wxGetApp().GetStateContext().Subscribe(StateName::Save, [&] {
});
wxGetApp().GetStateContext().Subscribe(StateName::Close, [&] {
OnClose();
});
}
void MainMenuBar::Reset()
{
OnClose();
}
void MainMenuBar::OnOpen()
{
fileMenu->Enable(MainFrame_OpenDefault, false);
fileMenu->Enable(MainFrame_Open, false);
fileMenu->Enable(MainFrame_Save, true);
fileMenu->Enable(MainFrame_Close, true);
}
void MainMenuBar::OnClose()
{
fileMenu->Enable(MainFrame_OpenDefault, true);
fileMenu->Enable(MainFrame_Open, true);
fileMenu->Enable(MainFrame_Save, false);
fileMenu->Enable(MainFrame_Close, false);
}
}
| 26.119403 | 99 | 0.697714 | mbassale |
26fa3a90f5743067b3238a06e3e07f5a5d96047b | 1,107 | cpp | C++ | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | /*
Data una lista di cognomi di studenti e la loro relativa media,
ordinali con ordine non crescente in base alla loro media,
in caso di parità ordinali in ordine alfabetico in base al cognome.
Input:
n (numero di studenti)
[cognome] [media]
...
Output:
[cognome] [media]
...
Esempio di input:
4
Verdi 19
Bianchi 27
Rossi 28
Gialli 27
Esempio di output:
Rossi 28
Gialli 27
Bianchi 27
Verdi 19
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool sortByAscendingIntAndDescendingString(const pair<string,int>& a, const pair<string,int>& b){
if(a.second == b.second) return a.first > b.first;
return a.second > b.second;
}
int main(){
vector<pair<string,int>> v;
int n;
cin >> n;
string name;
int avg;
while(n--){
cin >> name >> avg;
v.push_back({name, avg});
}
sort(v.begin(), v.end(), sortByAscendingIntAndDescendingString);
for(const pair<string,int>& el : v){
cout << el.first << ' ' << el.second << "\n";
}
} | 20.5 | 97 | 0.606143 | NeverMendel |
26ff00b0b16c6de003fb8dba67241c373dc32529 | 29,588 | cc | C++ | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 Google Inc.
//
// 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 "helpers.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include "Linear.h"
#include "MemoryXFile.h"
namespace Torch {
DiskXFile* InitResultsFile(Allocator* allocator,std::string expdir, std::string type)
{
std::stringstream ss;
ss.str("");
ss.clear();
std::string expdirprefix = expdir.substr(0,expdir.length()-1);
ss << expdirprefix << "_" << type << "_results.txt";
DiskXFile *resultsfile = new(allocator) DiskXFile(ss.str().c_str(),"w");
return resultsfile;
}
void AddClassificationMeasurers(Allocator* allocator, std::string expdir,
MeasurerList *measurers, Machine *machine,
DataSet *train, DataSet *valid, DataSet *test,
ClassFormat *class_format, bool disk_results)
{
std::stringstream ss;
XFile* tfile_mentor_train_nll;
XFile* tfile_mentor_train_class;
XFile* tfile_mentor_valid_nll;
XFile* tfile_mentor_valid_class;
XFile* tfile_mentor_test_nll;
XFile* tfile_mentor_test_class;
// train
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_train_nll.txt";
ss << expdir << "train_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_train_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_train_nll = file_mentor_train_nll;
}
else {
MemoryXFile *file_mentor_train_nll = new(allocator) MemoryXFile();
tfile_mentor_train_nll = file_mentor_train_nll;
}
ClassNLLMeasurer *measurer_mentor_train_nll = new(allocator) ClassNLLMeasurer(machine->outputs, train,
class_format, tfile_mentor_train_nll);
measurers->addNode(measurer_mentor_train_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_train_class.txt";
ss << expdir << "train_class.txt";
if (disk_results) {
DiskXFile *file_mentor_train_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_train_class = file_mentor_train_class;
}
else {
MemoryXFile *file_mentor_train_class = new(allocator) MemoryXFile();
tfile_mentor_train_class = file_mentor_train_class;
}
ClassMeasurer *measurer_mentor_train_class = new(allocator) ClassMeasurer(machine->outputs, train,
class_format, tfile_mentor_train_class);
measurers->addNode(measurer_mentor_train_class);
// valid
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_valid_nll.txt";
ss << expdir << "valid_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_valid_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_valid_nll = file_mentor_valid_nll;
}
else {
MemoryXFile *file_mentor_valid_nll = new(allocator) MemoryXFile();
tfile_mentor_valid_nll = file_mentor_valid_nll;
}
ClassNLLMeasurer *measurer_mentor_valid_nll = new(allocator) ClassNLLMeasurer(machine->outputs, valid,
class_format, tfile_mentor_valid_nll);
measurers->addNode(measurer_mentor_valid_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_valid_class.txt";
ss << expdir << "valid_class.txt";
if (disk_results) {
DiskXFile *file_mentor_valid_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_valid_class = file_mentor_valid_class;
}
else {
MemoryXFile *file_mentor_valid_class = new(allocator) MemoryXFile();
tfile_mentor_valid_class = file_mentor_valid_class;
}
ClassMeasurer *measurer_mentor_valid_class = new(allocator) ClassMeasurer(machine->outputs, valid,
class_format, tfile_mentor_valid_class);
measurers->addNode(measurer_mentor_valid_class);
// test
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_test_nll.txt";
ss << expdir << "test_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_test_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_test_nll = file_mentor_test_nll;
}
else {
MemoryXFile *file_mentor_test_nll = new(allocator) MemoryXFile();
tfile_mentor_test_nll = file_mentor_test_nll;
}
ClassNLLMeasurer *measurer_mentor_test_nll = new(allocator) ClassNLLMeasurer(machine->outputs, test,
class_format, tfile_mentor_test_nll);
measurers->addNode(measurer_mentor_test_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_test_class.txt";
ss << expdir << "test_class.txt";
if (disk_results) {
DiskXFile *file_mentor_test_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_test_class = file_mentor_test_class;
}
else {
MemoryXFile *file_mentor_test_class = new(allocator) MemoryXFile();
tfile_mentor_test_class = file_mentor_test_class;
}
ClassMeasurer *measurer_mentor_test_class = new(allocator) ClassMeasurer(machine->outputs, test,
class_format, tfile_mentor_test_class);
measurers->addNode(measurer_mentor_test_class);
}
Criterion* NewUnsupCriterion(Allocator* allocator, std::string recons_cost, int size)
{
if(recons_cost=="xentropy") {
return new(allocator) CrossEntropyCriterion(size);
} else if(recons_cost=="mse") {
return new(allocator) MSECriterion(size);
} else {
error("%s is not a valid reconstruction cost!", recons_cost.c_str());
return NULL;
}
}
Measurer* NewUnsupMeasurer(Allocator* allocator, std::string recons_cost,
Sequence *inputs_, DataSet *data_, XFile *file_)
{
if(recons_cost=="xentropy") {
return new(allocator) CrossEntropyMeasurer(inputs_, data_, file_);
} else if(recons_cost=="mse") {
return new(allocator) MSEMeasurer(inputs_, data_, file_);
} else {
error("%s is not a valid reconstruction measurer!", recons_cost.c_str());
return NULL;
}
}
void BuildSaeUnsupDataSetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
StackedAutoencoder *sae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
bool criterion_avg_frame_size,
DataSet **unsup_datasets,
Criterion **unsup_criterions,
Measurer **unsup_measurers,
bool disk_results)
{
std::stringstream ss;
XFile* thefile;
for(int i=0; i<sae->n_hidden_layers; i++) {
// DataSet
// The first dataset is special, as it can't just monitor a memory
// location. The examples are each at different locations.
if(i==0)
unsup_datasets[0] = new(allocator) InputAsTargetDataSet(supervised_train_data);
else
unsup_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, sae->encoders[i-1]->outputs);
// Criterion
unsup_criterions[i] = NewUnsupCriterion(allocator, recons_cost, sae->decoders[i]->n_outputs);
unsup_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
unsup_criterions[i]->setDataSet(unsup_datasets[i]);
// Measurer
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << sae->name << "_unsup_" << recons_cost << "_layer_" << i << ".txt";
DiskXFile *file = new(allocator) DiskXFile(ss.str().c_str(),"w");
thefile = file;
}
else {
MemoryXFile *file = new(allocator) MemoryXFile();
thefile = file;
}
unsup_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
sae->decoders[i]->outputs,
unsup_datasets[i],
thefile);
}
}
/*
void StackedAutoencoderTrainer::FreeUnsupDataSetsCriteriaMeasurers()
{
for(int i=0; i<sae->n_hidden_layers; i++) {
allocator->free(unsup_datasets[i]);
allocator->free(unsup_criterions[i]);
allocator->free(unsup_measurers[i]->file);
allocator->free(unsup_measurers[i]);
}
allocator->free(unsup_datasets);
allocator->free(unsup_criterions);
allocator->free(unsup_measurers);
}
*/
// We don't know what to agree with yet, so agree with ourself.
// -> the datasets' targets will need to be set!
void BuildSaeComAgreeDatasetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
CommunicatingStackedAutoencoder *csae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
int communication_type,
bool criterion_avg_frame_size,
DataSet **agree_datasets,
Criterion **agree_criterions,
Measurer **agree_measurers,
bool disk_results,
int n_communication_layers)
{
std::stringstream ss;
XFile *file;
for(int i=0; i<n_communication_layers; i++) {
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << csae->name << "_comAgree_" << recons_cost << "_layer_" << i << ".txt";
file = new(allocator) DiskXFile(ss.str().c_str(),"w");
}
else
file = new(allocator) MemoryXFile();
// *** Com0 and Com1 - We try to match the other guy's hidden units...
if( communication_type==0 || communication_type==1 ) {
agree_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->encoders[i]->outputs);
agree_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->encoders[i]->n_outputs);
agree_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
agree_criterions[i]->setDataSet(agree_datasets[i]);
// ... with our own units
if(communication_type==0) {
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->encoders[i]->outputs,
agree_datasets[i], file);
}
// ... with our speech
else {
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->speakers[i]->outputs,
agree_datasets[i], file);
}
}
// *** Com2 - We try to match the other guy's speech with our speech
else {
agree_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->speakers[i]->outputs);
agree_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->speakers[i]->n_outputs);
agree_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
agree_criterions[i]->setDataSet(agree_datasets[i]);
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->speakers[i]->outputs,
agree_datasets[i], file);
}
}
}
void BuildSaeComContentDatasetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
CommunicatingStackedAutoencoder *csae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
bool criterion_avg_frame_size,
DataSet **content_datasets,
Criterion **content_criterions,
Measurer **content_measurers,
bool disk_results,
int n_communication_layers)
{
std::stringstream ss;
XFile *file;
for(int i=0; i<n_communication_layers; i++) {
content_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->encoders[i]->outputs);
content_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->encoders[i]->n_outputs);
content_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
content_criterions[i]->setDataSet(content_datasets[i]);
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << csae->name << "_comContent_" << recons_cost << "_layer_" << i << ".txt";
file = new(allocator) DiskXFile(ss.str().c_str(),"w");
}
else
file = new(allocator) MemoryXFile();
content_measurers[i] = NewUnsupMeasurer(allocator, recons_cost, csae->listeners[i]->outputs,
content_datasets[i], file);
}
}
/*
void CommunicatingSaePairTrainer::FreeComDataSetsCriteriaMeasurers()
{
}
*/
void SaveCoder(std::string expdir, std::string filename, Coder *coder)
{
warning("SaveCoder(...) - implements a partial save only.");
std::string model_filename = expdir + filename;
DiskXFile xfile_model(model_filename.c_str(), "w");
xfile_model.taggedWrite(&coder->n_inputs, sizeof(int), 1, "n_inputs");
xfile_model.taggedWrite(&coder->n_outputs, sizeof(int), 1, "n_outputs");
int nonlinearity_length = coder->nonlinearity.length()+1;
xfile_model.taggedWrite(&nonlinearity_length, sizeof(int), 1, "nonlinearity_length");
xfile_model.taggedWrite((char*)coder->nonlinearity.c_str(), sizeof(char), nonlinearity_length, "nonlinearity");
coder->saveXFile(&xfile_model);
}
Coder* LoadCoder(Allocator* allocator, std::string filename)
{
warning("LoadCoder(...) - implements a partial load only.");
XFile *m = new(allocator) DiskXFile(filename.c_str(), "r");
int n_inputs=0;
m->taggedRead(&n_inputs, sizeof(int), 1, "n_inputs");
int n_outputs=0;
m->taggedRead(&n_outputs, sizeof(int), 1, "n_outputs");
int nonlinearity_length=0;
m->taggedRead(&nonlinearity_length, sizeof(int), 1, "nonlinearity_length");
char *nonlinearity = new char[nonlinearity_length];
m->taggedRead(nonlinearity, sizeof(char), nonlinearity_length, "nonlinearity");
Coder *coder = new(allocator) Coder(n_inputs, n_outputs, false, NULL, false, false, nonlinearity);
coder->loadXFile(m);
delete nonlinearity;
return coder;
}
void SaveCSAE(std::string expdir, std::string type, int n_layers, int n_inputs, int *units_per_hidden_layer, int *units_per_speech_layer,
int n_classes,
bool tied_weights, std::string nonlinearity, std::string recons_cost,
real corrupt_prob, real corrupt_value,
CommunicatingStackedAutoencoder *csae)
{
std::string model_filename = expdir + type + "model.save";
DiskXFile model_(model_filename.c_str(), "w");
// save whar's necessary to rebuilding the architecture
model_.taggedWrite(&n_inputs, sizeof(int), 1, "n_inputs");
model_.taggedWrite(&n_classes, sizeof(int), 1, "n_classes");
model_.taggedWrite(&n_layers, sizeof(int), 1, "n_layers");
model_.taggedWrite(units_per_hidden_layer, sizeof(int), n_layers, "units_per_hidden_layer");
model_.taggedWrite(units_per_speech_layer, sizeof(int), n_layers, "units_per_speech_layer");
model_.taggedWrite(&tied_weights, sizeof(bool), 1, "tied_weights");
model_.taggedWrite(&csae->reparametrize_tied, sizeof(bool), 1, "reparametrize_tied");
model_.taggedWrite(&csae->communication_type, sizeof(int), 1, "communication_type");
model_.taggedWrite(&csae->n_communication_layers, sizeof(int), 1, "n_communication_layers");
int nonlinearity_integer;
if(nonlinearity=="tanh") {
nonlinearity_integer = 0;
} else if(nonlinearity=="sigmoid") {
nonlinearity_integer = 1;
} else if (nonlinearity=="nonlinear") {
nonlinearity_integer = 2;
} else {
nonlinearity_integer = -1;
error("SaveCSAE - Unrecognized nonlinearity!");
}
model_.taggedWrite(&nonlinearity_integer, sizeof(int), 1, "nonlinearity: 0 tanh, 1 sigmoid, 2 nonlinear");
int recons_cost_integer;
if(recons_cost=="xentropy") {
recons_cost_integer = 0;
} else if(recons_cost=="mse") {
recons_cost_integer = 1;
} else {
error("SaveCSAE - %s is not a valid reconstruction cost!", recons_cost.c_str());
}
model_.taggedWrite(&recons_cost_integer, sizeof(int), 1, "recons_cost: 0 xentropy, 1 tanh");
model_.taggedWrite(&corrupt_prob, sizeof(real), 1, "corrupt_prob");
model_.taggedWrite(&corrupt_value, sizeof(real), 1, "corrupt_value");
csae->saveXFile(&model_);
}
CommunicatingStackedAutoencoder* LoadCSAE(Allocator* allocator, std::string filename)
{
int n_layers;
int n_inputs;
int *units_per_hidden_layer;
int *units_per_speech_layer;
int n_classes;
bool tied_weights;
bool reparametrize_tied;
int nonlinearity_integer;
std::string nonlinearity;
int recons_cost_integer;
std::string recons_cost;
real corrupt_prob;
real corrupt_value;
int communication_type;
int n_communication_layers;
CommunicatingStackedAutoencoder *csae;
XFile *m = new(allocator) DiskXFile(filename.c_str(), "r");
m->taggedRead(&n_inputs, sizeof(int), 1, "n_inputs");
m->taggedRead(&n_classes, sizeof(int), 1, "n_classes");
m->taggedRead(&n_layers, sizeof(int), 1, "n_layers");
units_per_hidden_layer = (int*)malloc(sizeof(int)*(n_layers));
m->taggedRead(units_per_hidden_layer, sizeof(int), n_layers, "units_per_hidden_layer");
units_per_speech_layer = (int*)malloc(sizeof(int)*(n_layers));
m->taggedRead(units_per_speech_layer, sizeof(int), n_layers, "units_per_speech_layer");
m->taggedRead(&tied_weights, sizeof(bool), 1, "tied_weights");
warning("Ignoring reparametrize_tied's value");
//m->taggedRead(&reparametrize_tied, sizeof(bool), 1, "reparametrize_tied");
reparametrize_tied = false;
m->taggedRead(&communication_type, sizeof(int), 1, "communication_type");
m->taggedRead(&n_communication_layers, sizeof(int), 1, "n_communication_layers");
m->taggedRead(&nonlinearity_integer, sizeof(int), 1, "nonlinearity: 0 tanh, 1 sigmoid, 2 nonlinear");
if(nonlinearity_integer==0) {
nonlinearity = "tanh";
} else if(nonlinearity_integer==1) {
nonlinearity = "sigmoid";
} else if (nonlinearity_integer==2) {
nonlinearity = "nonlinear";
} else {
nonlinearity = "";
error("LoadCSAE - Unrecognized nonlinearity!");
}
m->taggedRead(&recons_cost_integer, sizeof(int), 1, "recons_cost: 0 xentropy, 1 tanh");
if(recons_cost_integer==0) {
recons_cost = "xentropy";
} else if(recons_cost_integer==1) {
recons_cost = "mse";
} else {
error("LoadCSAE - Unrecognized reconstruction cost!");
}
m->taggedRead(&corrupt_prob, sizeof(real), 1, "corrupt_prob");
m->taggedRead(&corrupt_value, sizeof(real), 1, "corrupt_value");
// ------
/*
cout << "n_layers=" << n_layers << std::endl;
cout << "units_per_hidden_layer";
for(int i=0; i<n_layers; i++) {
cout << " " << units_per_hidden_layer[i];
}
cout << std::endl;
cout << "units_per_speech_layer";
for(int i=0; i<n_layers; i++) {
cout << " " << units_per_speech_layer[i];
}
cout << std::endl;
cout << "tied_weights " << tied_weights << std::endl;
cout << "nonlinearity " << nonlinearity << std::endl;
cout << "recons_cost " << recons_cost << std::endl;
cout << "corrupt_prob " << corrupt_prob << std::endl;
cout << "corrupt_value " << corrupt_value << std::endl;
*/
// ------
warning("should do a lean construction of csae here...");
warning("Ignoring first_layer_smoothed's value");
// Are the autoencoders noisy?
bool is_noisy = false;
if(corrupt_prob>0.0)
is_noisy = true;
csae = new(allocator) CommunicatingStackedAutoencoder("csae", nonlinearity, tied_weights, reparametrize_tied, n_inputs,
n_layers, units_per_hidden_layer, n_classes,
is_noisy, false, units_per_speech_layer, communication_type, n_communication_layers);
csae->loadXFile(m);
return csae;
}
void saveWeightMatrix(std::string filename, Coder* the_coder, bool is_transposed)
{
// find the first linear machine
Linear *linear = the_coder->linear_layer;
int n_inputs = linear->n_inputs;
int n_outputs = linear->n_outputs;
real *weights = linear->weights;
real *bias = linear->bias;
// Open the output file
std::ofstream fd(filename.c_str());
if(!fd.is_open())
error("saveWeightMatrix - can't open %s", filename.c_str());
if(!is_transposed) {
for(int j=0; j<n_outputs; j++) {
for(int k=0; k<n_inputs; k++) {
fd << weights[k] << " ";
}
fd << bias[j] << std::endl;
weights += n_inputs;
}
// these weights are stored transposed
} else {
for(int j=0; j<n_outputs; j++) {
for(int k=0; k<n_inputs; k++) {
fd << weights[k*n_outputs + j] << " ";
}
fd << bias[j] << std::endl;
}
}
fd.close();
}
void saveWeightMatrices(CommunicatingStackedAutoencoder* csae, std::string dir, bool is_transposed)
{
std::stringstream ss;
// save the number of layers in a file
std::string filename_nlayers = dir + "nlayers.txt";
std::ofstream fd_nlayers(filename_nlayers.c_str());
if(!fd_nlayers.is_open()) {
error("saveWeightMatrices - can't open %s", filename_nlayers.c_str());
}
fd_nlayers << csae->n_hidden_layers;
fd_nlayers.close();
// for all hidden layers output the 4 weight matrices (possibly 2 equal)
for(int i=0; i<csae->n_hidden_layers; i++) {
// W
ss.str("");
ss.clear();
ss << dir << "W" << i << ".txt";
saveWeightMatrix(ss.str(), csae->encoders[i], false);
// V
ss.str("");
ss.clear();
ss << dir << "V" << i << ".txt";
saveWeightMatrix(ss.str(), csae->decoders[i], is_transposed);
// F
if (csae->communication_type > 0) {
ss.str("");
ss.clear();
ss << dir << "F" << i << ".txt";
saveWeightMatrix(ss.str(), csae->speakers[i], false);
}
// G
if (csae->communication_type > 1) {
ss.str("");
ss.clear();
ss << dir << "G" << i << ".txt";
saveWeightMatrix(ss.str(), csae->listeners[i], is_transposed);
}
}
// output the output layer
ss.str("");
ss.clear();
ss << dir << "W" << csae->n_hidden_layers << ".txt";
saveWeightMatrix(ss.str(), csae->outputer, false);
}
void saveRepresentation(std::ofstream *fd, real *ptr, int n) {
for(int i=0; i<n; i++) {
*fd << ptr[i] << " ";
}
*fd << std::endl;
}
void openNumberedRepresentationFile(std::ofstream *fd, std::string dir, std::string name, int number)
{
std::stringstream ss;
ss << dir << name << number << ".txt";
fd->open(ss.str().c_str());
if(!fd->is_open()) {
error("openNumberedRepresentationFile - couldn't open %s", ss.str().c_str());
}
}
void saveRepresentations(CommunicatingStackedAutoencoder* csae, std::string dir,
DataSet *data, int n_examples)
{
int nhid = csae->n_hidden_layers;
// open all the necessary files
std::ofstream fd_input;
std::ofstream fd_output;
std::ofstream* fds_hidden = new std::ofstream[nhid];
std::ofstream* fds_speech = new std::ofstream[nhid];
std::ofstream* fds_recons_from_hidden = new std::ofstream[nhid];
std::ofstream* fds_recons_from_speech = new std::ofstream[nhid];
std::string filename;
filename = dir + "input.txt";
fd_input.open(filename.c_str());
filename = dir + "output.txt";
fd_output.open(filename.c_str());
if(!fd_input.is_open() || !fd_output.is_open())
error("saveRepresentations - problem opening a file.");
std::stringstream ss;
for(int i=0; i<nhid; i++) {
openNumberedRepresentationFile(&fds_hidden[i], dir, "hidden_l", i);
openNumberedRepresentationFile(&fds_recons_from_hidden[i], dir, "recons_from_hidden_l", i);
if (csae->communication_type > 0)
openNumberedRepresentationFile(&fds_speech[i], dir, "speech_l", i);
if (csae->communication_type > 1)
openNumberedRepresentationFile(&fds_recons_from_speech[i], dir, "recons_from_speech_l", i);
}
// create a place to exponentiate the outputs (logsoftmax)
real *exp_output = (real*) malloc(sizeof(real)*csae->n_outputs);
// for each example fprop and then print everything
for(int i=0; i<n_examples; i++) {
data->setExample(i);
if (csae->communication_type == 0) {
csae->sup_unsup_comA_machine->forward(data->inputs);
} else if (csae->communication_type == 1) {
csae->sup_unsup_comB_machine->forward(data->inputs);
} else if (csae->communication_type == 2) {
csae->sup_unsup_comC_machine->forward(data->inputs);
} else {
error("saveRepresentations - invalid communication_type.");
}
saveRepresentation(&fd_input, data->inputs->frames[0], data->n_inputs);
for(int j=0; j<csae->n_outputs; j++) {
exp_output[j] = exp(csae->outputs->frames[0][j]);
}
saveRepresentation(&fd_output, exp_output, csae->n_outputs);
for(int l=0; l<nhid; l++) {
saveRepresentation(&fds_hidden[l], csae->encoders[l]->outputs->frames[0], csae->encoders[l]->n_outputs);
saveRepresentation(&fds_recons_from_hidden[l], csae->decoders[l]->outputs->frames[0], csae->decoders[l]->n_outputs);
if (csae->communication_type > 0)
saveRepresentation(&fds_speech[l], csae->speakers[l]->outputs->frames[0], csae->speakers[l]->n_outputs);
if (csae->communication_type > 1)
saveRepresentation(&fds_recons_from_speech[l], csae->listeners[l]->outputs->frames[0], csae->listeners[l]->n_outputs);
}
}
// close all files
fd_input.close();
fd_output.close();
for(int i=0; i<nhid; i++) {
fds_hidden[i].close();
fds_recons_from_hidden[i].close();
if (csae->communication_type > 0)
fds_speech[i].close();
if (csae->communication_type > 1)
fds_recons_from_speech[i].close();
}
}
void saveOutputs(CommunicatingStackedAutoencoder* csae, DataSet *data, int n_outputs,
std::string dir, std::string data_label)
{
csae->setDataSet(data);
std::stringstream ss_outputs;
// Iterate over the data, putting the outputs in a stringstream
for (int i=0; i<data->n_examples; i++) {
data->setExample(i);
csae->forward(data->inputs);
for (int j=0; j<n_outputs; j++)
ss_outputs << csae->outputs->frames[0][j] << " ";
}
// Save the outputs to a file
std::ofstream fd_outputs;
std::stringstream ss_filename;
ss_filename << dir << data_label << n_outputs << "outputs.txt";
fd_outputs.open(ss_filename.str().c_str());
if (!fd_outputs.is_open())
error("saveOutputs(...) - cannot open the file.");
fd_outputs << ss_outputs.str() << std::endl;
fd_outputs.close();
}
void LoadBinners(Allocator* allocator, char* flag_binners_location,
CommunicatingStackedAutoencoder *csae,
Binner **w_binners, Binner **b_binners)
{
std::stringstream filename;
XFile *the_xfile;
for (int i=0; i<csae->n_hidden_layers; i++) {
filename.str("");
filename.clear();
filename << flag_binners_location << "binner_w" << i << ".save";
the_xfile = new(allocator) DiskXFile(filename.str().c_str(), "r");
w_binners[i] = new(allocator) Binner();
w_binners[i]->loadXFile(the_xfile);
allocator->free(the_xfile);
filename.str("");
filename.clear();
filename << flag_binners_location << "binner_b" << i << ".save";
the_xfile = new(allocator) DiskXFile(filename.str().c_str(), "r");
b_binners[i] = new(allocator) Binner();
b_binners[i]->loadXFile(the_xfile);
allocator->free(the_xfile);
}
}
void ReInitCsaeFromBinners(CommunicatingStackedAutoencoder *csae,
Binner **w_binners, Binner **b_binners)
{
for (int i=0; i<csae->n_hidden_layers; i++) {
Linear *linear_layer = csae->encoders[i]->linear_layer;
real *weights_ = linear_layer->weights;
real *bias_ = linear_layer->bias;
for (int j=0; j<linear_layer->n_outputs; j++) {
for (int k=0; k<linear_layer->n_inputs; k++)
weights_[k] = w_binners[i]->draw();
bias_[j] = b_binners[i]->draw();
weights_ += linear_layer->n_inputs;
}
}
}
}
| 37.031289 | 137 | 0.62958 | rbhambriiit |
f8024ae5c224530eb96e8621ece5add32201f971 | 6,686 | cpp | C++ | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | 1 | 2020-06-15T15:58:05.000Z | 2020-06-15T15:58:05.000Z | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | 3 | 2020-06-21T09:08:21.000Z | 2020-06-24T08:14:23.000Z | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | null | null | null | #include "Fill.h"
#include <array>
#include <assert.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Frame/Error.h"
#include "Frame/OpenGL/FrameBuffer.h"
#include "Frame/OpenGL/RenderBuffer.h"
#include "Frame/OpenGL/Renderer.h"
#include "Frame/OpenGL/StaticMesh.h"
namespace frame::opengl {
namespace {
// Get the 6 view for the cube map.
const std::array<glm::mat4, 6> views_cubemap =
{
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(1.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(-1.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, -1.0f),
glm::vec3(0.0f, -1.0f, 0.0f))
};
}
void FillProgramMultiTexture(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface)
{
FillProgramMultiTextureMipmap(
level,
program,
uniform_interface,
0,
[](const int, const std::shared_ptr<ProgramInterface>) {});
}
void FillProgramMultiTextureMipmap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface,
const int mipmap,
const std::function<void(
const int mipmap,
const std::shared_ptr<ProgramInterface> program)> func /*=
[](const int, const std::shared_ptr<sgl::ProgramInterface>) {}*/)
{
auto& error = Error::GetInstance();
assert(program->GetOutputTextureIds().size());
auto texture_out_ids = program->GetOutputTextureIds();
auto texture_ref = level->GetTextureMap().at(*texture_out_ids.cbegin());
auto size = texture_ref->GetSize();
FrameBuffer frame{};
RenderBuffer render{};
ScopedBind scoped_frame(frame);
ScopedBind scoped_render(render);
render.CreateStorage(size);
frame.AttachRender(render);
frame.DrawBuffers(static_cast<std::uint32_t>(texture_out_ids.size()));
int max_mipmap = (mipmap <= 0) ? 1 : mipmap;
if (max_mipmap > 1)
{
for (const auto& texture_id : texture_out_ids)
{
auto texture = level->GetTextureMap().at(texture_id);
texture->Bind();
texture->EnableMipmap();
}
}
glm::mat4 projection = glm::perspective(
glm::radians(90.0f),
1.0f,
0.1f,
10.0f);
std::pair<uint32_t, uint32_t> temporary_size = size;
for (int mipmap_level = 0; mipmap_level < max_mipmap; ++mipmap_level)
{
func(mipmap_level, program);
double fact = std::pow(0.5, mipmap_level);
temporary_size.first =
static_cast<std::uint32_t>(size.first * fact);
temporary_size.second =
static_cast<std::uint32_t>(size.second * fact);
glViewport(0, 0, temporary_size.first, temporary_size.second);
error.Display(__FILE__, __LINE__ - 1);
int i = 0;
for (const auto& texture_id : program->GetOutputTextureIds())
{
frame.AttachTexture(
level->GetTextureMap().at(texture_id)->GetId(),
FrameBuffer::GetFrameColorAttachment(i),
mipmap_level);
i++;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
error.Display(__FILE__, __LINE__ - 1);
Renderer renderer(
level.get(),
uniform_interface.get(),
temporary_size);
renderer.SetProjection(projection);
renderer.RenderMesh(
level->GetStaticMeshMap().at(
level->GetDefaultStaticMeshQuadId()).get());
}
}
void FillProgramMultiTextureCubeMap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface)
{
FillProgramMultiTextureCubeMapMipmap(
level,
program,
uniform_interface,
0,
[](const int, const std::shared_ptr<ProgramInterface>) {});
}
void FillProgramMultiTextureCubeMapMipmap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface,
const int mipmap,
const std::function<void(
const int mipmap,
const std::shared_ptr<ProgramInterface> program)> func /*=
[](const int, const std::shared_ptr<sgl::ProgramInterface>) {}*/)
{
auto& error = Error::GetInstance();
assert(program->GetOutputTextureIds().size());
auto texture_out_ids = program->GetOutputTextureIds();
auto texture_ref = level->GetTextureMap().at(*texture_out_ids.cbegin());
auto size = texture_ref->GetSize();
FrameBuffer frame{};
RenderBuffer render{};
ScopedBind scoped_frame(frame);
ScopedBind scoped_render(render);
frame.AttachRender(render);
frame.DrawBuffers(static_cast<std::uint32_t>(texture_out_ids.size()));
int max_mipmap = (mipmap <= 0) ? 1 : mipmap;
if (max_mipmap > 1)
{
for (const auto& texture_id : texture_out_ids)
{
auto texture = level->GetTextureMap().at(texture_id);
texture->Bind();
texture->EnableMipmap();
}
}
glm::mat4 projection = glm::perspective(
glm::radians(90.0f),
1.0f,
0.1f,
10.0f);
std::pair<std::uint32_t, std::uint32_t> temporary_size = { 0, 0 };
for (int mipmap_level = 0; mipmap_level < max_mipmap; ++mipmap_level)
{
func(mipmap_level, program);
double fact = std::pow(0.5, mipmap_level);
temporary_size.first =
static_cast<std::uint32_t>(size.first * fact);
temporary_size.second =
static_cast<std::uint32_t>(size.second * fact);
render.CreateStorage(temporary_size);
frame.AttachRender(render);
glViewport(0, 0, temporary_size.first, temporary_size.second);
error.Display(__FILE__, __LINE__ - 1);
int cubemap_element = 0;
for (const auto& view : views_cubemap)
{
int i = 0;
for (const auto& texture_id : program->GetOutputTextureIds())
{
frame.AttachTexture(
level->GetTextureMap().at(texture_id)->GetId(),
FrameBuffer::GetFrameColorAttachment(i),
mipmap_level);
}
cubemap_element++;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
error.Display(__FILE__, __LINE__ - 1);
Renderer renderer(
level.get(),
uniform_interface.get(),
temporary_size);
renderer.SetProjection(projection);
renderer.SetView(view);
renderer.RenderMesh(
level->GetStaticMeshMap().at(
level->GetDefaultStaticMeshCubeId()).get());
}
}
}
} // End namespace frame::opengl.
| 30.669725 | 74 | 0.680826 | anirul |
f802aac28738d0e361e44df8f8dc2aad390c8b2a | 2,890 | cpp | C++ | ecal/core/src/ecal_time.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | ecal/core/src/ecal_time.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | ecal/core/src/ecal_time.cpp | jonico/ecal | 244531e4a0f3be8f1ce881f5bbeca354b05d29aa | [
"Apache-2.0"
] | null | null | null | /* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental 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.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief eCAL time interface
**/
#include <ecal/ecal.h>
#include <chrono>
#include <thread>
#include "ecal_timegate.h"
namespace eCAL
{
namespace Time
{
std::string GetName()
{
if (!g_timegate() || !g_timegate()->IsValid()) return("");
return(g_timegate()->GetName());
}
long long GetMicroSeconds()
{
if (!g_timegate() || !g_timegate()->IsValid())
{
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
return(std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
}
return(g_timegate()->GetMicroSeconds());
}
long long GetNanoSeconds()
{
if (!g_timegate() || !g_timegate()->IsValid())
{
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
return(std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count());
}
return(g_timegate()->GetNanoSeconds());
}
bool SetNanoSeconds(long long time_)
{
if (!g_timegate() || !g_timegate()->IsValid()) return(false);
return(g_timegate()->SetNanoSeconds(time_));
}
bool IsSynchronized()
{
if (!g_timegate() || !g_timegate()->IsValid()) return(false);
return(g_timegate()->IsSynchronized());
}
bool IsMaster()
{
if (!g_timegate() || !g_timegate()->IsValid()) return(false);
return(g_timegate()->IsMaster());
}
void SleepForNanoseconds(long long duration_nsecs_)
{
if (!g_timegate() || !g_timegate()->IsValid())
{
std::this_thread::sleep_for(std::chrono::nanoseconds(duration_nsecs_));
}
else
{
g_timegate()->SleepForNanoseconds(duration_nsecs_);
}
}
void GetStatus(int& error_, std::string* const status_message_) {
if (!g_timegate()) {
error_ = -1;
if (status_message_) {
status_message_->assign("Timegate has not been initialized!");
}
}
else {
g_timegate()->GetStatus(error_, status_message_);
}
}
}
}
| 27.788462 | 102 | 0.595156 | jonico |
f803af6cd442c1572b81b3b6598daf2eaff72220 | 2,257 | cpp | C++ | qt/other/wuziqi2/client/chessboard.cpp | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null | qt/other/wuziqi2/client/chessboard.cpp | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null | qt/other/wuziqi2/client/chessboard.cpp | yanrong/book_demo | 20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f | [
"Apache-2.0"
] | null | null | null | //chessboard.cpp
#include "chessboard.h"
#include <iostream>
using namespace std;
ChessBoard::ChessBoard() {
initBoard();
}
void ChessBoard::initBoard()
{
for(int i=0; i<19; i++)
for(int j=0; j<19; j++)
board[i][j] = null;
}
//棋手走一步棋
bool ChessBoard::SetChess(int x, int y, enum Chess c)
{
if(board[x][y] != null) {
return false;
}
else {
board[x][y] = c;
return true;
}
}
//获取坐标为(x,y)的状态(是否已经有棋子)
enum Chess ChessBoard::GetStatus(int x, int y) {
return board[x][y];
}
/*
**判断坐标为(x,y)处的棋子是否获胜
**需要判断四个方向:横向、纵向和两个对角方向
*/
bool ChessBoard::Judge(int x, int y, enum Chess currentchess)
{
int count;
int row, col;
//----------横向----------
count = 1, row = x, col = y;
//判断(x,y)左边
while((--row) >= 0 && board[row][y] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
row = x;
//判断(x,y)右边
while((++row) < 19 && board[row][y] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
//--------纵向----------
count = 1, row = x, col = y;
//判断(x,y)上面
while((--col) >= 0 && board[x][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
col = y;
//判断(x,y)下面
while((++col) < 19 && board[x][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
//-------判断西北到东南方-------
count = 1, row = x, col = y;
//判断(x,y)的左上
while((--row) >= 0 && (--col) >= 0 && board[row][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
row = x, col = y;
//判断(x,y)的右下
while((++row) < 19 && (++col) < 19 && board[row][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
//-------判断东北到西南方-------
count = 1, row = x, col = y;
//判断(x,y)右上方
while((++row) < 19 && (--col) >= 0 && board[row][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
row = x, col = y;
//判断(x,y)的左下方
while((--row) >= 0 && (++col) < 19 && board[row][col] == currentchess)
{
count++;
if(count >= 5) { return true; }
}
return false;
}
| 19.973451 | 74 | 0.454143 | yanrong |
f8040bfe6f3ea5d722d1de0b376a1752b0e55c4d | 304 | cpp | C++ | ion/src/device/n0110/bench/command/vblank.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | ion/src/device/n0110/bench/command/vblank.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | ion/src/device/n0110/bench/command/vblank.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | #include "command.h"
#include <ion/post_and_hardware_tests.h>
namespace Ion {
namespace Device {
namespace Bench {
namespace Command {
void VBlank(const char * input) {
if (input != nullptr) {
reply(sSyntaxError);
return;
}
reply(POSTAndHardwareTests::VBlankOK() ? sOK : sKO);
}
}
}
}
}
| 14.47619 | 54 | 0.677632 | VersiraSec |
f8045d31dce06b3b78588f61714667125d276cbd | 4,875 | cpp | C++ | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
typedef pair<int, int> iPair;
class PuzzleBoard
{
private:
int **graph;
int graphsize;
int cuurentY;
int currentX;
public:
PuzzleBoard(int boardSize, int **fields = nullptr);
bool makeMove(int direction);
bool getResult();
friend ostream &operator<<(ostream &os, PuzzleBoard const &m);
int solve();
~PuzzleBoard();
};
PuzzleBoard::PuzzleBoard(int boardSize, int **fields)
{
currentX = 0;
cuurentY = 0;
graphsize = boardSize * boardSize;
graph = new int *[graphsize];
for (int i = 0; i < graphsize; i++)
{
graph[i] = new int[graphsize];
}
srand(time(0));
if (fields == NULL)
{
fields = new int *[boardSize];
for (int i = 0; i < boardSize; i++)
{
fields[i] = new int[boardSize];
}
}
cout<<"Your Maze looks like this"<<endl;
for (int i = 0; i < boardSize; i++)
{
for (int j = 0; j < boardSize; j++)
{
fields[i][j] = (rand() % boardSize - 1) + 1;
cout<<fields[i][j]<<" ";
}
cout<<endl;
}
for (int i = 0; i < graphsize; i++)
{
for (int j = 0; j < graphsize; j++)
{
graph[i][j] = 0;
}
}
//Creating a type of Adjacency Matrix
for (int i = 0; i < boardSize; i++)
{
for (int j = 0; j < boardSize; j++)
{
int value = fields[i][j];
if (i - value > 0)
{
int x = i * boardSize + j; //Wouldnt require a 2d matrix this way
int y = (i - value) * boardSize + j;
graph[x][y]= 1;
}
if (j - value > 0)
{
int x = i * boardSize + j;
int y = i * boardSize + (j - value);
graph[x][y] = 1;
}
if (i + value < boardSize)
{
int x = i * boardSize + j;
int y = (i + value) * boardSize + j;
graph[x][y] = 1;
}
if (j + value < boardSize)
{
int x = i * boardSize + j;
int y = i * boardSize + (j + value);
graph[x][y] = 1;
}
}
}
}
PuzzleBoard::~PuzzleBoard()
{
for (int i = 0; i < graphsize; i++)
{
delete[] graph[i];
}
delete[] graph;
}
bool PuzzleBoard::getResult()
{
if (solve()==-1)
{
cout<<"Not Solvable"<<endl;
return false;
}
else
{
cout<<"Minimum Number of steps taken to solve the maze is "<<solve()<<endl;
return true;
}
}
ostream &operator<<(ostream &os, PuzzleBoard const &m)
{
for (int i = 0; i < m.graphsize; i++)
{
for (int j = 0; j < m.graphsize; j++)
{
os << m.graph[i][j] << " ";
}
os << endl;
}
return os;
}
int PuzzleBoard::solve()
{
int dist[graphsize];
for (int i = 0; i < graphsize; i++)
{
dist[i] = INF;
}
int start = 0;
dist[start] = 0;
priority_queue<iPair, vector<iPair>, greater<iPair> > pq;
pq.push(make_pair(0, start));
while (!pq.empty())
{
int node = pq.top().second;
pq.pop();
for (int i = 0; i < graphsize; i++)
{
int weight = graph[node][i];
if ((dist[i] > dist[node] + weight) && (weight != 0))
{
dist[i] = dist[node] + weight;
pq.push(make_pair(dist[i], i));
}
}
}
if (dist[graphsize - 1] == INF)
{
return -1;
}
else
{
return dist[graphsize - 1];
}
}
bool PuzzleBoard::makeMove(int direction)
{
int i = currentX;
int j = cuurentY;
int value = graph[i][j];
if (direction == 0)
{
if (i - value > 0)
{
currentX = i - value;
return true;
}
}
else if (direction == 1)
{
if (j + value < graphsize)
{
cuurentY = j + value;
return true;
}
}
else if (direction == 2)
{
if (i + value < graphsize)
{
currentX = i + value;
return true;
}
}
else if (direction == 3)
{
if (j - value > 0)
{
cuurentY = j - value;
return true;
}
}
return false;
}
int main()
{
int **fields = NULL;
int n;
cout << "Welcome to the Puzzle Game" << endl;
cout<<"Enter the size"<<endl;
cin >> n;
PuzzleBoard puzzle(n, fields);
cout<<"A type of Adjacency graph of the maze"<<endl;
cout << puzzle << endl;
puzzle.getResult();
return 0;
} | 20.744681 | 84 | 0.442872 | UrfanAlvany |
f805ea225187bddb821299d8da798e0cfa5c1863 | 137 | cpp | C++ | src/main.cpp | zedrex/algosketch | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 16 | 2021-03-27T06:20:42.000Z | 2022-03-31T16:30:37.000Z | src/main.cpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 1 | 2021-07-13T07:57:41.000Z | 2021-07-13T07:57:41.000Z | src/main.cpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 3 | 2021-04-03T02:58:56.000Z | 2021-06-04T18:23:49.000Z | #include <managers/application.hpp>
using namespace std;
int main()
{
Application algoSketch;
algoSketch.run();
return 0;
} | 13.7 | 35 | 0.686131 | zedrex |
f8064d6b852d0883f3b6fcd1bd3ebb97209f54d7 | 26,781 | cpp | C++ | 01_Develop/libXMFFmpeg/Source/libavcodec/cavsdec.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMFFmpeg/Source/libavcodec/cavsdec.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMFFmpeg/Source/libavcodec/cavsdec.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
* Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
* Copyright (c) 2006 Stefan Gehrer <stefan.gehrer@gmx.de>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Chinese AVS video (AVS1-P2, JiZhun profile) decoder
* @author Stefan Gehrer <stefan.gehrer@gmx.de>
*/
#include "internal.h"
#include "get_bits.h"
#include "golomb.h"
#include "cavs.h"
static const uint8_t mv_scan[4] = {
MV_FWD_X0,MV_FWD_X1,
MV_FWD_X2,MV_FWD_X3
};
static const uint8_t cbp_tab[64][2] = {
{63, 0},{15,15},{31,63},{47,31},{ 0,16},{14,32},{13,47},{11,13},
{ 7,14},{ 5,11},{10,12},{ 8, 5},{12,10},{61, 7},{ 4,48},{55, 3},
{ 1, 2},{ 2, 8},{59, 4},{ 3, 1},{62,61},{ 9,55},{ 6,59},{29,62},
{45,29},{51,27},{23,23},{39,19},{27,30},{46,28},{53, 9},{30, 6},
{43,60},{37,21},{60,44},{16,26},{21,51},{28,35},{19,18},{35,20},
{42,24},{26,53},{44,17},{32,37},{58,39},{24,45},{20,58},{17,43},
{18,42},{48,46},{22,36},{33,33},{25,34},{49,40},{40,52},{36,49},
{34,50},{50,56},{52,25},{54,22},{41,54},{56,57},{38,41},{57,38}
};
/*****************************************************************************
*
* motion vector prediction
*
****************************************************************************/
static inline void store_mvs(AVSContext *h) {
h->col_mv[h->mbidx*4 + 0] = h->mv[MV_FWD_X0];
h->col_mv[h->mbidx*4 + 1] = h->mv[MV_FWD_X1];
h->col_mv[h->mbidx*4 + 2] = h->mv[MV_FWD_X2];
h->col_mv[h->mbidx*4 + 3] = h->mv[MV_FWD_X3];
}
static inline void mv_pred_direct(AVSContext *h, cavs_vector *pmv_fw,
cavs_vector *col_mv) {
cavs_vector *pmv_bw = pmv_fw + MV_BWD_OFFS;
int den = h->direct_den[col_mv->ref];
int m = col_mv->x >> 31;
pmv_fw->dist = h->dist[1];
pmv_bw->dist = h->dist[0];
pmv_fw->ref = 1;
pmv_bw->ref = 0;
/* scale the co-located motion vector according to its temporal span */
pmv_fw->x = (((den+(den*col_mv->x*pmv_fw->dist^m)-m-1)>>14)^m)-m;
pmv_bw->x = m-(((den+(den*col_mv->x*pmv_bw->dist^m)-m-1)>>14)^m);
m = col_mv->y >> 31;
pmv_fw->y = (((den+(den*col_mv->y*pmv_fw->dist^m)-m-1)>>14)^m)-m;
pmv_bw->y = m-(((den+(den*col_mv->y*pmv_bw->dist^m)-m-1)>>14)^m);
}
static inline void mv_pred_sym(AVSContext *h, cavs_vector *src, enum cavs_block size) {
cavs_vector *dst = src + MV_BWD_OFFS;
/* backward mv is the scaled and negated forward mv */
dst->x = -((src->x * h->sym_factor + 256) >> 9);
dst->y = -((src->y * h->sym_factor + 256) >> 9);
dst->ref = 0;
dst->dist = h->dist[0];
set_mvs(dst, size);
}
/*****************************************************************************
*
* residual data decoding
*
****************************************************************************/
/** kth-order exponential golomb code */
static inline int get_ue_code(GetBitContext *gb, int order) {
if(order) {
int ret = get_ue_golomb(gb) << order;
return ret + get_bits(gb,order);
}
return get_ue_golomb(gb);
}
/**
* decode coefficients from one 8x8 block, dequantize, inverse transform
* and add them to sample block
* @param r pointer to 2D VLC table
* @param esc_golomb_order escape codes are k-golomb with this order k
* @param qp quantizer
* @param dst location of sample block
* @param stride line stride in frame buffer
*/
static int decode_residual_block(AVSContext *h, GetBitContext *gb,
const struct dec_2dvlc *r, int esc_golomb_order,
int qp, uint8_t *dst, int stride) {
int i, esc_code, level, mask;
unsigned int level_code, run;
DCTELEM level_buf[65];
uint8_t run_buf[65];
DCTELEM *block = h->block;
for(i=0;i<65;i++) {
level_code = get_ue_code(gb,r->golomb_order);
if(level_code >= ESCAPE_CODE) {
run = ((level_code - ESCAPE_CODE) >> 1) + 1;
if(run > 64)
return -1;
esc_code = get_ue_code(gb,esc_golomb_order);
level = esc_code + (run > r->max_run ? 1 : r->level_add[run]);
while(level > r->inc_limit)
r++;
mask = -(level_code & 1);
level = (level^mask) - mask;
} else {
level = r->rltab[level_code][0];
if(!level) //end of block signal
break;
run = r->rltab[level_code][1];
r += r->rltab[level_code][2];
}
level_buf[i] = level;
run_buf[i] = run;
}
if(dequant(h,level_buf, run_buf, block, ff_cavs_dequant_mul[qp],
ff_cavs_dequant_shift[qp], i))
return -1;
h->cdsp.cavs_idct8_add(dst,block,stride);
h->s.dsp.clear_block(block);
return 0;
}
static inline void decode_residual_chroma(AVSContext *h) {
if(h->cbp & (1<<4))
decode_residual_block(h,&h->s.gb,ff_cavs_chroma_dec,0,
ff_cavs_chroma_qp[h->qp],h->cu,h->c_stride);
if(h->cbp & (1<<5))
decode_residual_block(h,&h->s.gb,ff_cavs_chroma_dec,0,
ff_cavs_chroma_qp[h->qp],h->cv,h->c_stride);
}
static inline int decode_residual_inter(AVSContext *h) {
int block;
/* get coded block pattern */
int cbp= get_ue_golomb(&h->s.gb);
if(cbp > 63U){
av_log(h->s.avctx, AV_LOG_ERROR, "illegal inter cbp\n");
return -1;
}
h->cbp = cbp_tab[cbp][1];
/* get quantizer */
if(h->cbp && !h->qp_fixed)
h->qp = (h->qp + get_se_golomb(&h->s.gb)) & 63;
for(block=0;block<4;block++)
if(h->cbp & (1<<block))
decode_residual_block(h,&h->s.gb,ff_cavs_inter_dec,0,h->qp,
h->cy + h->luma_scan[block], h->l_stride);
decode_residual_chroma(h);
return 0;
}
/*****************************************************************************
*
* macroblock level
*
****************************************************************************/
static int decode_mb_i(AVSContext *h, int cbp_code) {
GetBitContext *gb = &h->s.gb;
unsigned pred_mode_uv;
int block;
uint8_t top[18];
uint8_t *left = NULL;
uint8_t *d;
ff_cavs_init_mb(h);
/* get intra prediction modes from stream */
for(block=0;block<4;block++) {
int nA,nB,predpred;
int pos = ff_cavs_scan3x3[block];
nA = h->pred_mode_Y[pos-1];
nB = h->pred_mode_Y[pos-3];
predpred = FFMIN(nA,nB);
if(predpred == NOT_AVAIL) // if either is not available
predpred = INTRA_L_LP;
if(!get_bits1(gb)){
int rem_mode= get_bits(gb, 2);
predpred = rem_mode + (rem_mode >= predpred);
}
h->pred_mode_Y[pos] = predpred;
}
pred_mode_uv = get_ue_golomb(gb);
if(pred_mode_uv > 6) {
av_log(h->s.avctx, AV_LOG_ERROR, "illegal intra chroma pred mode\n");
return -1;
}
ff_cavs_modify_mb_i(h, (int *)&pred_mode_uv);
/* get coded block pattern */
if(h->pic_type == AV_PICTURE_TYPE_I)
cbp_code = get_ue_golomb(gb);
if(cbp_code > 63U){
av_log(h->s.avctx, AV_LOG_ERROR, "illegal intra cbp\n");
return -1;
}
h->cbp = cbp_tab[cbp_code][0];
if(h->cbp && !h->qp_fixed)
h->qp = (h->qp + get_se_golomb(gb)) & 63; //qp_delta
/* luma intra prediction interleaved with residual decode/transform/add */
for(block=0;block<4;block++) {
d = h->cy + h->luma_scan[block];
ff_cavs_load_intra_pred_luma(h, top, &left, block);
h->intra_pred_l[h->pred_mode_Y[ff_cavs_scan3x3[block]]]
(d, top, left, h->l_stride);
if(h->cbp & (1<<block))
decode_residual_block(h,gb,ff_cavs_intra_dec,1,h->qp,d,h->l_stride);
}
/* chroma intra prediction */
ff_cavs_load_intra_pred_chroma(h);
h->intra_pred_c[pred_mode_uv](h->cu, &h->top_border_u[h->mbx*10],
h->left_border_u, h->c_stride);
h->intra_pred_c[pred_mode_uv](h->cv, &h->top_border_v[h->mbx*10],
h->left_border_v, h->c_stride);
decode_residual_chroma(h);
ff_cavs_filter(h,I_8X8);
set_mv_intra(h);
return 0;
}
static void decode_mb_p(AVSContext *h, enum cavs_mb mb_type) {
GetBitContext *gb = &h->s.gb;
int ref[4];
ff_cavs_init_mb(h);
switch(mb_type) {
case P_SKIP:
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_PSKIP, BLK_16X16, 0);
break;
case P_16X16:
ref[0] = h->ref_flag ? 0 : get_bits1(gb);
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16,ref[0]);
break;
case P_16X8:
ref[0] = h->ref_flag ? 0 : get_bits1(gb);
ref[2] = h->ref_flag ? 0 : get_bits1(gb);
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP, BLK_16X8, ref[0]);
ff_cavs_mv(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT, BLK_16X8, ref[2]);
break;
case P_8X16:
ref[0] = h->ref_flag ? 0 : get_bits1(gb);
ref[1] = h->ref_flag ? 0 : get_bits1(gb);
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT, BLK_8X16, ref[0]);
ff_cavs_mv(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_TOPRIGHT,BLK_8X16, ref[1]);
break;
case P_8X8:
ref[0] = h->ref_flag ? 0 : get_bits1(gb);
ref[1] = h->ref_flag ? 0 : get_bits1(gb);
ref[2] = h->ref_flag ? 0 : get_bits1(gb);
ref[3] = h->ref_flag ? 0 : get_bits1(gb);
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_MEDIAN, BLK_8X8, ref[0]);
ff_cavs_mv(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_MEDIAN, BLK_8X8, ref[1]);
ff_cavs_mv(h, MV_FWD_X2, MV_FWD_X1, MV_PRED_MEDIAN, BLK_8X8, ref[2]);
ff_cavs_mv(h, MV_FWD_X3, MV_FWD_X0, MV_PRED_MEDIAN, BLK_8X8, ref[3]);
}
ff_cavs_inter(h, mb_type);
set_intra_mode_default(h);
store_mvs(h);
if(mb_type != P_SKIP)
decode_residual_inter(h);
ff_cavs_filter(h,mb_type);
h->col_type_base[h->mbidx] = mb_type;
}
static void decode_mb_b(AVSContext *h, enum cavs_mb mb_type) {
int block;
enum cavs_sub_mb sub_type[4];
int flags;
ff_cavs_init_mb(h);
/* reset all MVs */
h->mv[MV_FWD_X0] = ff_cavs_dir_mv;
set_mvs(&h->mv[MV_FWD_X0], BLK_16X16);
h->mv[MV_BWD_X0] = ff_cavs_dir_mv;
set_mvs(&h->mv[MV_BWD_X0], BLK_16X16);
switch(mb_type) {
case B_SKIP:
case B_DIRECT:
if(!h->col_type_base[h->mbidx]) {
/* intra MB at co-location, do in-plane prediction */
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_BSKIP, BLK_16X16, 1);
ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_BSKIP, BLK_16X16, 0);
} else
/* direct prediction from co-located P MB, block-wise */
for(block=0;block<4;block++)
mv_pred_direct(h,&h->mv[mv_scan[block]],
&h->col_mv[h->mbidx*4 + block]);
break;
case B_FWD_16X16:
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);
break;
case B_SYM_16X16:
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);
mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X16);
break;
case B_BWD_16X16:
ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_MEDIAN, BLK_16X16, 0);
break;
case B_8X8:
for(block=0;block<4;block++)
sub_type[block] = (cavs_sub_mb)get_bits(&h->s.gb,2);
for(block=0;block<4;block++) {
switch(sub_type[block]) {
case B_SUB_DIRECT:
if(!h->col_type_base[h->mbidx]) {
/* intra MB at co-location, do in-plane prediction */
ff_cavs_mv(h, (cavs_mv_loc)mv_scan[block], (cavs_mv_loc)(mv_scan[block]-3),
MV_PRED_BSKIP, BLK_8X8, 1);
ff_cavs_mv(h, (cavs_mv_loc)(mv_scan[block]+MV_BWD_OFFS),
(cavs_mv_loc)(mv_scan[block]-3+MV_BWD_OFFS),
MV_PRED_BSKIP, BLK_8X8, 0);
} else
mv_pred_direct(h,&h->mv[mv_scan[block]],
&h->col_mv[h->mbidx*4 + block]);
break;
case B_SUB_FWD:
ff_cavs_mv(h, (cavs_mv_loc)mv_scan[block], (cavs_mv_loc)(mv_scan[block]-3),
MV_PRED_MEDIAN, BLK_8X8, 1);
break;
case B_SUB_SYM:
ff_cavs_mv(h, (cavs_mv_loc)mv_scan[block], (cavs_mv_loc)(mv_scan[block]-3),
MV_PRED_MEDIAN, BLK_8X8, 1);
mv_pred_sym(h, &h->mv[mv_scan[block]], BLK_8X8);
break;
}
}
for(block=0;block<4;block++) {
if(sub_type[block] == B_SUB_BWD)
ff_cavs_mv(h, (cavs_mv_loc)(mv_scan[block]+MV_BWD_OFFS),
(cavs_mv_loc)(mv_scan[block]+MV_BWD_OFFS-3),
MV_PRED_MEDIAN, BLK_8X8, 0);
}
break;
default:
assert((mb_type > B_SYM_16X16) && (mb_type < B_8X8));
flags = ff_cavs_partition_flags[mb_type];
if(mb_type & 1) { /* 16x8 macroblock types */
if(flags & FWD0)
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP, BLK_16X8, 1);
if(flags & SYM0)
mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X8);
if(flags & FWD1)
ff_cavs_mv(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT, BLK_16X8, 1);
if(flags & SYM1)
mv_pred_sym(h, &h->mv[MV_FWD_X2], BLK_16X8);
if(flags & BWD0)
ff_cavs_mv(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_TOP, BLK_16X8, 0);
if(flags & BWD1)
ff_cavs_mv(h, MV_BWD_X2, MV_BWD_A1, MV_PRED_LEFT, BLK_16X8, 0);
} else { /* 8x16 macroblock types */
if(flags & FWD0)
ff_cavs_mv(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT, BLK_8X16, 1);
if(flags & SYM0)
mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_8X16);
if(flags & FWD1)
ff_cavs_mv(h,MV_FWD_X1,MV_FWD_C2,MV_PRED_TOPRIGHT,BLK_8X16,1);
if(flags & SYM1)
mv_pred_sym(h, &h->mv[MV_FWD_X1], BLK_8X16);
if(flags & BWD0)
ff_cavs_mv(h, MV_BWD_X0, MV_BWD_B3, MV_PRED_LEFT, BLK_8X16, 0);
if(flags & BWD1)
ff_cavs_mv(h,MV_BWD_X1,MV_BWD_C2,MV_PRED_TOPRIGHT,BLK_8X16,0);
}
}
ff_cavs_inter(h, mb_type);
set_intra_mode_default(h);
if(mb_type != B_SKIP)
decode_residual_inter(h);
ff_cavs_filter(h,mb_type);
}
/*****************************************************************************
*
* slice level
*
****************************************************************************/
static inline int decode_slice_header(AVSContext *h, GetBitContext *gb) {
if(h->stc > 0xAF)
av_log(h->s.avctx, AV_LOG_ERROR, "unexpected start code 0x%02x\n", h->stc);
h->mby = h->stc;
h->mbidx = h->mby*h->mb_width;
/* mark top macroblocks as unavailable */
h->flags &= ~(B_AVAIL|C_AVAIL);
if((h->mby == 0) && (!h->qp_fixed)){
h->qp_fixed = get_bits1(gb);
h->qp = get_bits(gb,6);
}
/* inter frame or second slice can have weighting params */
if((h->pic_type != AV_PICTURE_TYPE_I) || (!h->pic_structure && h->mby >= h->mb_width/2))
if(get_bits1(gb)) { //slice_weighting_flag
av_log(h->s.avctx, AV_LOG_ERROR,
"weighted prediction not yet supported\n");
}
return 0;
}
static inline int check_for_slice(AVSContext *h) {
GetBitContext *gb = &h->s.gb;
int align;
if(h->mbx)
return 0;
align = (-get_bits_count(gb)) & 7;
/* check for stuffing byte */
if(!align && (show_bits(gb,8) == 0x80))
align = 8;
if((show_bits_long(gb,24+align) & 0xFFFFFF) == 0x000001) {
skip_bits_long(gb,24+align);
h->stc = get_bits(gb,8);
if (h->stc >= h->mb_height)
return 0;
decode_slice_header(h,gb);
return 1;
}
return 0;
}
/*****************************************************************************
*
* frame level
*
****************************************************************************/
static int decode_pic(AVSContext *h) {
MpegEncContext *s = &h->s;
int skip_count = -1;
enum cavs_mb mb_type;
if (!s->context_initialized) {
s->avctx->idct_algo = FF_IDCT_CAVS;
if (MPV_common_init(s) < 0)
return -1;
ff_init_scantable(s->dsp.idct_permutation,&h->scantable,ff_zigzag_direct);
}
skip_bits(&s->gb,16);//bbv_dwlay
if(h->stc == PIC_PB_START_CODE) {
h->pic_type = get_bits(&s->gb,2) + AV_PICTURE_TYPE_I;
if(h->pic_type > AV_PICTURE_TYPE_B) {
av_log(s->avctx, AV_LOG_ERROR, "illegal picture type\n");
return -1;
}
/* make sure we have the reference frames we need */
if(!h->DPB[0].f.data[0] ||
(!h->DPB[1].f.data[0] && h->pic_type == AV_PICTURE_TYPE_B))
return -1;
} else {
h->pic_type = AV_PICTURE_TYPE_I;
if(get_bits1(&s->gb))
skip_bits(&s->gb,24);//time_code
/* old sample clips were all progressive and no low_delay,
bump stream revision if detected otherwise */
if (s->low_delay || !(show_bits(&s->gb,9) & 1))
h->stream_revision = 1;
/* similarly test top_field_first and repeat_first_field */
else if(show_bits(&s->gb,11) & 3)
h->stream_revision = 1;
if(h->stream_revision > 0)
skip_bits(&s->gb,1); //marker_bit
}
/* release last B frame */
if(h->picture.f.data[0])
s->avctx->release_buffer(s->avctx, (AVFrame *)&h->picture);
s->avctx->get_buffer(s->avctx, (AVFrame *)&h->picture);
ff_cavs_init_pic(h);
h->picture.poc = get_bits(&s->gb,8)*2;
/* get temporal distances and MV scaling factors */
if(h->pic_type != AV_PICTURE_TYPE_B) {
h->dist[0] = (h->picture.poc - h->DPB[0].poc + 512) % 512;
} else {
h->dist[0] = (h->DPB[0].poc - h->picture.poc + 512) % 512;
}
h->dist[1] = (h->picture.poc - h->DPB[1].poc + 512) % 512;
h->scale_den[0] = h->dist[0] ? 512/h->dist[0] : 0;
h->scale_den[1] = h->dist[1] ? 512/h->dist[1] : 0;
if(h->pic_type == AV_PICTURE_TYPE_B) {
h->sym_factor = h->dist[0]*h->scale_den[1];
} else {
h->direct_den[0] = h->dist[0] ? 16384/h->dist[0] : 0;
h->direct_den[1] = h->dist[1] ? 16384/h->dist[1] : 0;
}
if(s->low_delay)
get_ue_golomb(&s->gb); //bbv_check_times
h->progressive = get_bits1(&s->gb);
h->pic_structure = 1;
if(!h->progressive)
h->pic_structure = get_bits1(&s->gb);
if(!h->pic_structure && h->stc == PIC_PB_START_CODE)
skip_bits1(&s->gb); //advanced_pred_mode_disable
skip_bits1(&s->gb); //top_field_first
skip_bits1(&s->gb); //repeat_first_field
h->qp_fixed = get_bits1(&s->gb);
h->qp = get_bits(&s->gb,6);
if(h->pic_type == AV_PICTURE_TYPE_I) {
if(!h->progressive && !h->pic_structure)
skip_bits1(&s->gb);//what is this?
skip_bits(&s->gb,4); //reserved bits
} else {
if(!(h->pic_type == AV_PICTURE_TYPE_B && h->pic_structure == 1))
h->ref_flag = get_bits1(&s->gb);
skip_bits(&s->gb,4); //reserved bits
h->skip_mode_flag = get_bits1(&s->gb);
}
h->loop_filter_disable = get_bits1(&s->gb);
if(!h->loop_filter_disable && get_bits1(&s->gb)) {
h->alpha_offset = get_se_golomb(&s->gb);
h->beta_offset = get_se_golomb(&s->gb);
} else {
h->alpha_offset = h->beta_offset = 0;
}
if(h->pic_type == AV_PICTURE_TYPE_I) {
do {
check_for_slice(h);
decode_mb_i(h, 0);
} while(ff_cavs_next_mb(h));
} else if(h->pic_type == AV_PICTURE_TYPE_P) {
do {
if(check_for_slice(h))
skip_count = -1;
if(h->skip_mode_flag && (skip_count < 0))
skip_count = get_ue_golomb(&s->gb);
if(h->skip_mode_flag && skip_count--) {
decode_mb_p(h,P_SKIP);
} else {
mb_type = (cavs_mb)(get_ue_golomb(&s->gb) + P_SKIP + h->skip_mode_flag);
if(mb_type > P_8X8)
decode_mb_i(h, mb_type - P_8X8 - 1);
else
decode_mb_p(h,mb_type);
}
} while(ff_cavs_next_mb(h));
} else { /* AV_PICTURE_TYPE_B */
do {
if(check_for_slice(h))
skip_count = -1;
if(h->skip_mode_flag && (skip_count < 0))
skip_count = get_ue_golomb(&s->gb);
if(h->skip_mode_flag && skip_count--) {
decode_mb_b(h,B_SKIP);
} else {
mb_type = (cavs_mb)(get_ue_golomb(&s->gb) + B_SKIP + h->skip_mode_flag);
if(mb_type > B_8X8)
decode_mb_i(h, mb_type - B_8X8 - 1);
else
decode_mb_b(h,mb_type);
}
} while(ff_cavs_next_mb(h));
}
if(h->pic_type != AV_PICTURE_TYPE_B) {
if(h->DPB[1].f.data[0])
s->avctx->release_buffer(s->avctx, (AVFrame *)&h->DPB[1]);
h->DPB[1] = h->DPB[0];
h->DPB[0] = h->picture;
memset(&h->picture,0,sizeof(Picture));
}
return 0;
}
/*****************************************************************************
*
* headers and interface
*
****************************************************************************/
static int decode_seq_header(AVSContext *h) {
MpegEncContext *s = &h->s;
int frame_rate_code;
h->profile = get_bits(&s->gb,8);
h->level = get_bits(&s->gb,8);
skip_bits1(&s->gb); //progressive sequence
s->width = get_bits(&s->gb,14);
s->height = get_bits(&s->gb,14);
skip_bits(&s->gb,2); //chroma format
skip_bits(&s->gb,3); //sample_precision
h->aspect_ratio = get_bits(&s->gb,4);
frame_rate_code = get_bits(&s->gb,4);
skip_bits(&s->gb,18);//bit_rate_lower
skip_bits1(&s->gb); //marker_bit
skip_bits(&s->gb,12);//bit_rate_upper
s->low_delay = get_bits1(&s->gb);
h->mb_width = (s->width + 15) >> 4;
h->mb_height = (s->height + 15) >> 4;
h->s.avctx->time_base.den = avpriv_frame_rate_tab[frame_rate_code].num;
h->s.avctx->time_base.num = avpriv_frame_rate_tab[frame_rate_code].den;
h->s.avctx->width = s->width;
h->s.avctx->height = s->height;
if(!h->top_qp)
ff_cavs_init_top_lines(h);
return 0;
}
static void cavs_flush(AVCodecContext * avctx) {
AVSContext *h = (AVSContext *)avctx->priv_data;
h->got_keyframe = 0;
}
static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,
AVPacket *avpkt) {
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
AVSContext *h = (AVSContext *)avctx->priv_data;
MpegEncContext *s = &h->s;
int input_size;
const uint8_t *buf_end;
const uint8_t *buf_ptr;
AVFrame *picture = (AVFrame *)data;
uint32_t stc = -1;
s->avctx = avctx;
if (buf_size == 0) {
if (!s->low_delay && h->DPB[0].f.data[0]) {
*data_size = sizeof(AVPicture);
*picture = h->DPB[0].f;
memset(&h->DPB[0], 0, sizeof(h->DPB[0]));
}
return 0;
}
buf_ptr = buf;
buf_end = buf + buf_size;
for(;;) {
buf_ptr = avpriv_mpv_find_start_code(buf_ptr,buf_end, &stc);
if((stc & 0xFFFFFE00) || buf_ptr == buf_end)
return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);
input_size = (buf_end - buf_ptr)*8;
switch(stc) {
case CAVS_START_CODE:
init_get_bits(&s->gb, buf_ptr, input_size);
decode_seq_header(h);
break;
case PIC_I_START_CODE:
if(!h->got_keyframe) {
if(h->DPB[0].f.data[0])
avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]);
if(h->DPB[1].f.data[0])
avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]);
h->got_keyframe = 1;
}
case PIC_PB_START_CODE:
*data_size = 0;
if(!h->got_keyframe)
break;
init_get_bits(&s->gb, buf_ptr, input_size);
h->stc = stc;
if(decode_pic(h))
break;
*data_size = sizeof(AVPicture);
if(h->pic_type != AV_PICTURE_TYPE_B) {
if(h->DPB[1].f.data[0]) {
*picture = *(AVFrame *) &h->DPB[1];
} else {
*data_size = 0;
}
} else
*picture = *(AVFrame *) &h->picture;
break;
case EXT_START_CODE:
//mpeg_decode_extension(avctx,buf_ptr, input_size);
break;
case USER_START_CODE:
//mpeg_decode_user_data(avctx,buf_ptr, input_size);
break;
default:
if (stc <= SLICE_MAX_START_CODE) {
init_get_bits(&s->gb, buf_ptr, input_size);
decode_slice_header(h, &s->gb);
}
break;
}
}
}
AVCodec ff_cavs_decoder = {
/*.name = */ "cavs",
/*.type = */ AVMEDIA_TYPE_VIDEO,
/*.id = */ CODEC_ID_CAVS,
/*.priv_data_size = */ sizeof(AVSContext),
/*.init = */ ff_cavs_init,
/*.encode = */ 0,
/*.close = */ ff_cavs_end,
/*.decode = */ cavs_decode_frame,
/*.capabilities = */ CODEC_CAP_DR1 | CODEC_CAP_DELAY,
/*.next = */ 0,
/*.flush = */ cavs_flush,
/*.supported_framerates = */ 0,
/*.pix_fmts = */ 0,
/*.long_name = */ NULL_IF_CONFIG_SMALL("Chinese AVS video (AVS1-P2, JiZhun profile)"),
};
| 36.436735 | 95 | 0.534633 | mcodegeeks |
f8065874dd9df276f5ece038c3f0b65c3f8c1425 | 46 | hpp | C++ | src/app/include/example.hpp | rockonedege/SCPI-CPP | f295f684ffbd4b03e65b439bf0d771fb673fd700 | [
"MIT"
] | null | null | null | src/app/include/example.hpp | rockonedege/SCPI-CPP | f295f684ffbd4b03e65b439bf0d771fb673fd700 | [
"MIT"
] | null | null | null | src/app/include/example.hpp | rockonedege/SCPI-CPP | f295f684ffbd4b03e65b439bf0d771fb673fd700 | [
"MIT"
] | null | null | null | #pragma once
void example(const char* port); | 11.5 | 31 | 0.73913 | rockonedege |
f808b7ca2fa22ee382ec1025148e25f60324239f | 2,279 | hpp | C++ | vendor/bit7z/include/bit7z/include/fileextractcallback.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 16 | 2021-07-15T04:00:38.000Z | 2022-02-27T02:37:23.000Z | vendor/bit7z/include/bit7z/include/fileextractcallback.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 15 | 2018-10-02T22:14:17.000Z | 2018-10-12T08:01:36.000Z | vendor/bit7z/include/bit7z/include/fileextractcallback.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 16 | 2021-07-18T02:40:12.000Z | 2022-02-09T05:25:07.000Z | /*
* bit7z - A C++ static library to interface with the 7-zip DLLs.
* Copyright (c) 2014-2019 Riccardo Ostani - All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* Bit7z 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 bit7z; if not, see https://www.gnu.org/licenses/.
*/
#ifndef FILEEXTRACTCALLBACK_HPP
#define FILEEXTRACTCALLBACK_HPP
#include <string>
#include "7zip/Common/FileStreams.h"
#include "../include/bitguids.hpp"
#include "../include/extractcallback.hpp"
namespace bit7z {
using std::wstring;
class FileExtractCallback : public ExtractCallback {
public:
FileExtractCallback( const BitArchiveHandler& handler,
const BitInputArchive& inputArchive,
const wstring& inFilePath,
const wstring& directoryPath );
virtual ~FileExtractCallback() override;
// IArchiveExtractCallback
STDMETHOD( GetStream )( UInt32 index, ISequentialOutStream** outStream, Int32 askExtractMode );
STDMETHOD( SetOperationResult )( Int32 resultEOperationResult );
private:
wstring mInFilePath; // Input file path
wstring mDirectoryPath; // Output directory
wstring mFilePath; // name inside archive
wstring mDiskFilePath; // full path to file on disk
struct CProcessedFileInfo {
FILETIME MTime;
UInt32 Attrib;
bool isDir;
bool AttribDefined;
bool MTimeDefined;
} mProcessedFileInfo;
COutFileStream* mOutFileStreamSpec;
CMyComPtr< ISequentialOutStream > mOutFileStream;
};
}
#endif // FILEEXTRACTCALLBACK_HPP
| 35.609375 | 107 | 0.649846 | moonantonio |
f80a6b9eb32daca9e2594a462c011ec4273909b8 | 2,995 | hpp | C++ | AudioKit/Common/Nodes/Mixing/Panner/AKPannerDSP.hpp | MattTolleson/AudioKit | 796c974e5f6ea00fdacca062f20f01bfb4689de8 | [
"MIT"
] | 1,699 | 2017-05-06T02:22:00.000Z | 2022-03-30T07:51:03.000Z | Pods/AudioKit/macOS/AudioKit.framework/Versions/A/Headers/AKPannerDSP.hpp | guruantree/MacAssistant | 21c4537fbedaab1a3be28daef578ad8d91cf8604 | [
"MIT"
] | 85 | 2017-05-08T18:48:44.000Z | 2022-03-07T05:30:01.000Z | Pods/AudioKit/macOS/AudioKit.framework/Versions/A/Headers/AKPannerDSP.hpp | guruantree/MacAssistant | 21c4537fbedaab1a3be28daef578ad8d91cf8604 | [
"MIT"
] | 180 | 2017-05-18T22:28:37.000Z | 2022-03-28T12:28:04.000Z | //
// AKPannerDSP.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
#import <AVFoundation/AVFoundation.h>
typedef NS_ENUM(AUParameterAddress, AKPannerParameter) {
AKPannerParameterPan,
AKPannerParameterRampDuration
};
#import "AKLinearParameterRamp.hpp" // have to put this here to get it included in umbrella header
#ifndef __cplusplus
AKDSPRef createPannerDSP(int channelCount, double sampleRate);
#else
#import "AKSoundpipeDSPBase.hpp"
class AKPannerDSP : public AKSoundpipeDSPBase {
sp_panst *panst;
private:
AKLinearParameterRamp panRamp;
public:
AKPannerDSP() {
panRamp.setTarget(0, true);
panRamp.setDurationInSamples(10000);
}
/** Uses the ParameterAddress as a key */
void setParameter(AUParameterAddress address, float value, bool immediate) override {
switch (address) {
case AKPannerParameterPan:
panRamp.setTarget(value, immediate);
break;
case AKPannerParameterRampDuration:
panRamp.setRampDuration(value, sampleRate);
break;
}
}
/** Uses the ParameterAddress as a key */
float getParameter(AUParameterAddress address) override {
switch (address) {
case AKPannerParameterPan:
return panRamp.getTarget();
case AKPannerParameterRampDuration:
return panRamp.getRampDuration(sampleRate);
}
return 0;
}
void init(int channelCount, double sampleRate) override {
AKSoundpipeDSPBase::init(channelCount, sampleRate);
sp_panst_create(&panst);
sp_panst_init(sp, panst);
panst->pan = 0;
}
void deinit() override {
sp_panst_destroy(&panst);
}
void process(uint32_t frameCount, uint32_t bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
// do ramping every 8 samples
if ((frameOffset & 0x7) == 0) {
panRamp.advanceTo(now + frameOffset);
}
panst->pan = panRamp.getValue();
float *tmpin[2];
float *tmpout[2];
for (int channel = 0; channel < channelCount; ++channel) {
float *in = (float *)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (channel < 2) {
tmpin[channel] = in;
tmpout[channel] = out;
}
if (!isStarted) {
*out = *in;
}
}
if (isStarted) {
sp_panst_compute(sp, panst, tmpin[0], tmpin[1], tmpout[0], tmpout[1]);
}
}
}
};
#endif
| 27.477064 | 99 | 0.589649 | MattTolleson |
f80d1c980f1270a4f36835c7818e42763e39dab0 | 12,902 | cc | C++ | components/safe_browsing/content/browser/browser_url_loader_throttle.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/safe_browsing/content/browser/browser_url_loader_throttle.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/safe_browsing/content/browser/browser_url_loader_throttle.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/safe_browsing/content/browser/browser_url_loader_throttle.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/trace_event/trace_event.h"
#include "components/safe_browsing/core/browser/safe_browsing_url_checker_impl.h"
#include "components/safe_browsing/core/browser/url_checker_delegate.h"
#include "components/safe_browsing/core/common/safebrowsing_constants.h"
#include "components/safe_browsing/core/common/utils.h"
#include "components/safe_browsing/core/realtime/policy_engine.h"
#include "components/safe_browsing/core/realtime/url_lookup_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/web_contents.h"
#include "net/log/net_log_event_type.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
namespace safe_browsing {
// TODO(http://crbug.com/824843): Remove this if safe browsing is moved to the
// UI thread.
class BrowserURLLoaderThrottle::CheckerOnIO
: public base::SupportsWeakPtr<BrowserURLLoaderThrottle::CheckerOnIO> {
public:
CheckerOnIO(
GetDelegateCallback delegate_getter,
int frame_tree_node_id,
base::RepeatingCallback<content::WebContents*()> web_contents_getter,
base::WeakPtr<BrowserURLLoaderThrottle> throttle,
bool real_time_lookup_enabled,
bool enhanced_protection_enabled,
base::WeakPtr<RealTimeUrlLookupService> url_lookup_service)
: delegate_getter_(std::move(delegate_getter)),
frame_tree_node_id_(frame_tree_node_id),
web_contents_getter_(web_contents_getter),
throttle_(std::move(throttle)),
real_time_lookup_enabled_(real_time_lookup_enabled),
enhanced_protection_enabled_(enhanced_protection_enabled),
url_lookup_service_(url_lookup_service) {}
// Starts the initial safe browsing check. This check and future checks may be
// skipped after checking with the UrlCheckerDelegate.
void Start(const net::HttpRequestHeaders& headers,
int load_flags,
blink::mojom::ResourceType resource_type,
bool has_user_gesture,
bool originated_from_service_worker,
const GURL& url,
const std::string& method) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
scoped_refptr<UrlCheckerDelegate> url_checker_delegate =
std::move(delegate_getter_).Run();
skip_checks_ =
!url_checker_delegate ||
!url_checker_delegate->GetDatabaseManager()->IsSupported() ||
url_checker_delegate->ShouldSkipRequestCheck(
url, frame_tree_node_id_, -1 /* render_process_id */,
-1 /* render_frame_id */, originated_from_service_worker);
if (skip_checks_) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&BrowserURLLoaderThrottle::SkipChecks, throttle_));
return;
}
url_checker_ = std::make_unique<SafeBrowsingUrlCheckerImpl>(
headers, load_flags, resource_type, has_user_gesture,
url_checker_delegate, web_contents_getter_, real_time_lookup_enabled_,
enhanced_protection_enabled_, url_lookup_service_);
CheckUrl(url, method);
}
// Checks the specified |url| using |url_checker_|.
void CheckUrl(const GURL& url, const std::string& method) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (skip_checks_) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&BrowserURLLoaderThrottle::SkipChecks, throttle_));
return;
}
DCHECK(url_checker_);
url_checker_->CheckUrl(
url, method,
base::BindOnce(&BrowserURLLoaderThrottle::CheckerOnIO::OnCheckUrlResult,
base::Unretained(this)));
}
private:
// If |slow_check_notifier| is non-null, it indicates that a "slow check" is
// ongoing, i.e., the URL may be unsafe and a more time-consuming process is
// required to get the final result. In that case, the rest of the callback
// arguments should be ignored. This method sets the |slow_check_notifier|
// output parameter to a callback to receive the final result.
void OnCheckUrlResult(NativeUrlCheckNotifier* slow_check_notifier,
bool proceed,
bool showed_interstitial) {
if (!slow_check_notifier) {
OnCompleteCheck(false /* slow_check */, proceed, showed_interstitial);
return;
}
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&BrowserURLLoaderThrottle::NotifySlowCheck, throttle_));
// In this case |proceed| and |showed_interstitial| should be ignored. The
// result will be returned by calling |*slow_check_notifier| callback.
*slow_check_notifier =
base::BindOnce(&BrowserURLLoaderThrottle::CheckerOnIO::OnCompleteCheck,
base::Unretained(this), true /* slow_check */);
}
// |slow_check| indicates whether it reports the result of a slow check.
// (Please see comments of OnCheckUrlResult() for what slow check means).
void OnCompleteCheck(bool slow_check,
bool proceed,
bool showed_interstitial) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&BrowserURLLoaderThrottle::OnCompleteCheck, throttle_,
slow_check, proceed, showed_interstitial));
}
// The following member stays valid until |url_checker_| is created.
GetDelegateCallback delegate_getter_;
std::unique_ptr<SafeBrowsingUrlCheckerImpl> url_checker_;
int frame_tree_node_id_;
base::RepeatingCallback<content::WebContents*()> web_contents_getter_;
bool skip_checks_ = false;
base::WeakPtr<BrowserURLLoaderThrottle> throttle_;
bool real_time_lookup_enabled_ = false;
bool enhanced_protection_enabled_ = false;
base::WeakPtr<RealTimeUrlLookupService> url_lookup_service_;
};
// static
std::unique_ptr<BrowserURLLoaderThrottle> BrowserURLLoaderThrottle::Create(
GetDelegateCallback delegate_getter,
const base::RepeatingCallback<content::WebContents*()>& web_contents_getter,
int frame_tree_node_id,
base::WeakPtr<RealTimeUrlLookupService> url_lookup_service) {
return base::WrapUnique<BrowserURLLoaderThrottle>(
new BrowserURLLoaderThrottle(std::move(delegate_getter),
web_contents_getter, frame_tree_node_id,
url_lookup_service));
}
BrowserURLLoaderThrottle::BrowserURLLoaderThrottle(
GetDelegateCallback delegate_getter,
const base::RepeatingCallback<content::WebContents*()>& web_contents_getter,
int frame_tree_node_id,
base::WeakPtr<RealTimeUrlLookupService> url_lookup_service) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Decide whether to do real time URL lookups or not.
bool real_time_lookup_enabled =
url_lookup_service ? url_lookup_service->CanPerformFullURLLookup()
: false;
bool enhanced_protection_enabled =
url_lookup_service && url_lookup_service->IsUserEpOptedIn();
io_checker_ = std::make_unique<CheckerOnIO>(
std::move(delegate_getter), frame_tree_node_id, web_contents_getter,
weak_factory_.GetWeakPtr(), real_time_lookup_enabled,
enhanced_protection_enabled, url_lookup_service);
}
BrowserURLLoaderThrottle::~BrowserURLLoaderThrottle() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (deferred_)
TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this);
DeleteCheckerOnIO();
}
void BrowserURLLoaderThrottle::WillStartRequest(
network::ResourceRequest* request,
bool* defer) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_EQ(0u, pending_checks_);
DCHECK(!blocked_);
original_url_ = request->url;
pending_checks_++;
base::PostTask(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(
&BrowserURLLoaderThrottle::CheckerOnIO::Start,
io_checker_->AsWeakPtr(), request->headers, request->load_flags,
static_cast<blink::mojom::ResourceType>(request->resource_type),
request->has_user_gesture, request->originated_from_service_worker,
request->url, request->method));
}
void BrowserURLLoaderThrottle::WillRedirectRequest(
net::RedirectInfo* redirect_info,
const network::mojom::URLResponseHead& /* response_head */,
bool* defer,
std::vector<std::string>* /* to_be_removed_headers */,
net::HttpRequestHeaders* /* modified_headers */) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (blocked_) {
// OnCheckUrlResult() has set |blocked_| to true and called
// |delegate_->CancelWithError|, but this method is called before the
// request is actually cancelled. In that case, simply defer the request.
*defer = true;
return;
}
if (skip_checks_)
return;
pending_checks_++;
base::PostTask(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&BrowserURLLoaderThrottle::CheckerOnIO::CheckUrl,
io_checker_->AsWeakPtr(), redirect_info->new_url,
redirect_info->new_method));
}
void BrowserURLLoaderThrottle::WillProcessResponse(
const GURL& response_url,
network::mojom::URLResponseHead* response_head,
bool* defer) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (blocked_) {
// OnCheckUrlResult() has set |blocked_| to true and called
// |delegate_->CancelWithError|, but this method is called before the
// request is actually cancelled. In that case, simply defer the request.
*defer = true;
return;
}
if (pending_checks_ == 0)
return;
DCHECK(!deferred_);
deferred_ = true;
defer_start_time_ = base::TimeTicks::Now();
*defer = true;
TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "Deferred", this, "original_url",
original_url_.spec());
}
void BrowserURLLoaderThrottle::OnCompleteCheck(bool slow_check,
bool proceed,
bool showed_interstitial) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(!blocked_);
DCHECK_LT(0u, pending_checks_);
pending_checks_--;
if (slow_check) {
DCHECK_LT(0u, pending_slow_checks_);
pending_slow_checks_--;
}
user_action_involved_ = user_action_involved_ || showed_interstitial;
// If the resource load is currently deferred and is going to exit that state
// (either being cancelled or resumed), record the total delay.
if (deferred_ && (!proceed || pending_checks_ == 0))
total_delay_ = base::TimeTicks::Now() - defer_start_time_;
if (proceed) {
if (pending_slow_checks_ == 0 && slow_check)
delegate_->ResumeReadingBodyFromNet();
if (pending_checks_ == 0 && deferred_) {
deferred_ = false;
TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this);
delegate_->Resume();
}
} else {
blocked_ = true;
DeleteCheckerOnIO();
pending_checks_ = 0;
pending_slow_checks_ = 0;
// If we didn't show an interstitial, we cancel with ERR_ABORTED to not show
// an error page either.
delegate_->CancelWithError(showed_interstitial
? GetNetErrorCodeForSafeBrowsing()
: net::ERR_ABORTED,
kCustomCancelReasonForURLLoader);
}
}
void BrowserURLLoaderThrottle::SkipChecks() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Future checks for redirects will be skipped.
skip_checks_ = true;
pending_checks_--;
if (pending_checks_ == 0 && deferred_)
delegate_->Resume();
}
void BrowserURLLoaderThrottle::NotifySlowCheck() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
pending_slow_checks_++;
// Pending slow checks indicate that the resource may be unsafe. In that case,
// pause reading response body from network to minimize the chance of
// processing unsafe contents (e.g., writing unsafe contents into cache),
// until we get the results. According to the results, we may resume reading
// or cancel the resource load.
// For real time Safe Browsing checks, we continue reading the response body
// but, similar to hash-based checks, do not process it until we know it is
// SAFE.
if (pending_slow_checks_ == 1)
delegate_->PauseReadingBodyFromNet();
}
void BrowserURLLoaderThrottle::DeleteCheckerOnIO() {
base::DeleteSoon(FROM_HERE, {content::BrowserThread::IO},
std::move(io_checker_));
}
} // namespace safe_browsing
| 38.861446 | 81 | 0.708185 | sarang-apps |
f80ddc18169a57b6eb52ab5e40b3d31efed68896 | 1,972 | cpp | C++ | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | // https://codeforces.com/contest/59/problem/E
#include <iostream>
#include <vector>
#include <map>
#include <tuple>
#include <queue>
#include <algorithm>
using namespace std;
int N;
vector<vector<int>> adj;
map<tuple<int,int,int>,bool> prohibit;
vector<int> solve() {
tuple<int,int,int> last;
map<pair<int,int>,int> prev;
map<pair<int,int>,bool> used;
queue<tuple<int,int,int>> Q;
Q.push({0, 0, 0});
while (!Q.empty()) {
auto now = Q.front(); Q.pop();
int a = get<0>(now), b = get<1>(now), c = get<2>(now);
if (c == N-1) {
last = now;
break;
}
for (auto u : adj[c]) {
if (used[{c,u}]) continue;
if (prohibit[{b,c,u}]) continue;
used[{c,u}] = true;
prev[{b,c}] = a;
Q.push({b,c,u});
}
}
// No path
if (get<2>(last) != N-1) {
return vector<int>();
}
vector<int> ans;
while (true) {
int a = get<0>(last), b = get<1>(last), c = get<2>(last);
ans.push_back(c);
if (c == 0) {
break;
}
last = {prev[{a,b}],a,b};
}
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int M, K;
cin >> N >> M >> K;
adj.assign(N, vector<int>());
for (int i = 0; i < M; ++i) {
int a, b;
cin >> a >> b;
--a, --b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 0; i < K; ++i) {
int a, b, c;
cin >> a >> b >> c;
--a, --b, --c;
prohibit[{a,b,c}] = true;
}
auto ans = solve();
if (ans.size() == 0) {
cout << -1 << endl;
} else {
cout << ans.size() - 1 << endl;
for (int i = 0; i < ans.size(); ++i) {
if (i > 0) cout << " ";
cout << ans[i] + 1;
}
cout << endl;
}
return 0;
} | 21.911111 | 65 | 0.43002 | xirc |
f8136c19f7063125f0532ef70d598dc3146fe837 | 2,249 | cpp | C++ | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | #ifndef ES_ACTION_H
#include <ESAction.h>
#endif
#ifndef ES_ENTITY_TEST_H
#include "ESEntityTest.h"
#endif
#include <gtest/gtest.h>
#define UUID "0f42a1d1-cb6e-4a7b-be44-35fe34c6d5e1"
using namespace ES;
class ActionTest : public EntityTest {
public:
ActionTest() {}
virtual ~ActionTest() {}
virtual void SetUp() { ASSERT_EQ(ESB_SUCCESS, ESB::UniqueId::Parse(UUID, _uuid)); }
protected:
ESB::UniqueId _uuid;
ESB_DISABLE_AUTO_COPY(ActionTest);
};
TEST_F(ActionTest, ParseTransition) {
const char *conf =
" {"
" \"type\": \"TRANSITION\","
" \"destination\": \"" UUID
"\""
" }";
ESB::AST::Tree tree;
ASSERT_EQ(ESB_SUCCESS, parseString(conf, tree));
ASSERT_TRUE(tree.root());
ASSERT_EQ(tree.root()->type(), ESB::AST::Element::MAP);
ESB::AST::Map &map = *(ESB::AST::Map *)tree.root();
Action *action = NULL;
ASSERT_EQ(ESB_SUCCESS, Action::Build(map, ESB::SystemAllocator::Instance(), &action));
ASSERT_TRUE(action);
ASSERT_TRUE(action->cleanupHandler());
ASSERT_EQ(Action::TRANSITION, action->type());
TransitionAction *transition = (TransitionAction *)action;
ASSERT_EQ(_uuid, transition->destination());
action->cleanupHandler()->destroy(action);
}
TEST_F(ActionTest, ParseSendResponse) {
const char *conf =
" {"
" \"type\": \"SEND_RESPONSE\","
" \"status_code\": 404,"
" \"reason_phrase\": \"Not Found\""
" }";
ESB::AST::Tree tree;
ASSERT_EQ(ESB_SUCCESS, parseString(conf, tree));
ASSERT_TRUE(tree.root());
ASSERT_EQ(tree.root()->type(), ESB::AST::Element::MAP);
ESB::AST::Map &map = *(ESB::AST::Map *)tree.root();
Action *action = NULL;
ASSERT_EQ(ESB_SUCCESS, Action::Build(map, ESB::SystemAllocator::Instance(), &action));
ASSERT_TRUE(action);
ASSERT_TRUE(action->cleanupHandler());
ASSERT_EQ(Action::SEND_RESPONSE, action->type());
SendResponseAction *sendResponse = (SendResponseAction *)action;
ASSERT_EQ(404, sendResponse->statusCode());
const char *reasonPhrase = sendResponse->reasonPhrase();
ASSERT_EQ(0, strcmp("Not Found", reasonPhrase));
action->cleanupHandler()->destroy(action);
} | 28.833333 | 88 | 0.640285 | duderino |
f81b9243dee9c450c31d3a4a10bf7af796d89a30 | 562 | hpp | C++ | library/ATF/CNetTimer.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CNetTimer.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CNetTimer.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
#pragma pack(push, 4)
struct CNetTimer
{
int m_nTickTerm;
unsigned int m_dwTickOld;
bool m_bOper;
public:
void BeginTimer(unsigned int dwTerm);
CNetTimer();
void ctor_CNetTimer();
bool CountingTimer();
};
#pragma pack(pop)
static_assert(ATF::checkSize<CNetTimer, 12>(), "CNetTimer");
END_ATF_NAMESPACE
| 24.434783 | 108 | 0.653025 | lemkova |
f81ca2d3a28a56ad94fc4e7bc20523a4ef0a0365 | 555 | hpp | C++ | src/cuda/n_body.hpp | savcardamone/tyche- | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | null | null | null | src/cuda/n_body.hpp | savcardamone/tyche- | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | 1 | 2018-12-28T13:30:16.000Z | 2018-12-29T10:30:33.000Z | src/cuda/n_body.hpp | savcardamone/tyche | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | null | null | null | /**
* @file n_body.hpp
* @author Salvatore Cardamone
* @brief Basic N-Body implementation using CUDA.
*/
#ifndef N_BODY_CUDA_HPP__
#define N_BODY_CUDA_HPP__
// See https://stackoverflow.com/a/6978720
#ifdef __CUDACC__
#define CUDA_MEMBER __host__ __device__
#else
#define CUDA_MEMBER
#endif /* #ifdef __CUDACC__ */
class NBody {
public:
private:
unsigned int nParticles_;
std::vector<float4> particle_, acc_;
CUDA_MEMBER void PairwiseInteraction( const unsigned int& i, const unsigned int& j );
};
#endif /* #ifndef N_BODY_CUDA_HPP__ */
| 18.5 | 87 | 0.744144 | savcardamone |
f81e00fd1c7e53cdf2a97abdb19467afff9085bc | 1,164 | cpp | C++ | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
int n, lang;
string textos[] = {"De: (ej. jpg/png/etc) ", "Cantidad de archivos: ", "Nombre de archivo: "};
string texts[] = {"From: (e.g. jpg/png/etc) ","File quantity: ", "filename: "};
string actual[] = {""};
vector<string> files;
cout<<"Idioma/Language\n Spanish: 0 \n English: 1 \n"; cin>>lang;
if(lang == 0){
for (int i = 0; i < sizeof(textos)/sizeof(textos[0]); i++){
actual[i] = textos[i];
}
}else{
for (int i = 0; i < sizeof(texts)/sizeof(texts[0]); i++){
actual[i] = texts[i];
}
}
string type, from, to, res;
cout<<actual[0];
cin>>type;
cout<<actual[1];
cin>>n;
for (int i = 0; i < n; i++){
cout<<actual[2]<<" ";
string file;
cin>>file;
files.push_back(file);
}
system("mkdir output");
for(int i = 0; i < n; i++){
from = files[i] + "." + type;
to = files[i] + ".webp";
res = "cwebp " + from + " -o output/" + to;
system(res.c_str());
}
system("start output");
} | 29.1 | 99 | 0.49055 | TomasDmArg |
f81e85c2db0556c68b7556aa87c71f1899ad4e71 | 6,954 | cpp | C++ | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | /*******************************
Copyright (c) 2016-2022 Grégoire Angerand
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 <editor/Widget.h>
#include <editor/EditorWorld.h>
#include <editor/utils/memory.h>
#include <yave/scene/SceneView.h>
#include <yave/systems/OctreeSystem.h>
#include <yave/graphics/device/MeshAllocator.h>
#include <editor/utils/ui.h>
#include <external/imgui/yave_imgui.h>
namespace editor {
class CameraDebug : public Widget {
editor_widget(CameraDebug, "View", "Debug")
public:
CameraDebug() : Widget(ICON_FA_VIDEO " Camera debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const Camera& camera = scene_view().camera();
const math::Vec3 pos = camera.position();
const math::Vec3 fwd = camera.forward();
const math::Vec3 rht = camera.right();
const math::Vec3 up = fwd.cross(rht);
const math::Quaternion<> rot = math::Quaternion<>::from_base(fwd, rht, up);
ImGui::Text("FoV: %.1f", camera.field_of_view());
ImGui::Text("Aspect ratio: %.2f", camera.aspect_ratio());
ImGui::Separator();
ImGui::Text("position: %.1f, %.1f, %.1f", pos.x(), pos.y(), pos.z());
ImGui::Text("forward : %.1f, %.1f, %.1f", fwd.x(), fwd.y(), fwd.z());
ImGui::Text("right : %.1f, %.1f, %.1f", rht.x(), rht.y(), rht.z());
ImGui::Text("up : %.1f, %.1f, %.1f", up.x(), up.y(), up.z());
ImGui::Text("rotation: %.1f, %.1f, %.1f, %.1f", rot.x(), rot.y(), rot.z(), rot.w());
if(ImGui::CollapsingHeader("Rotation")) {
const math::Vec3 x = rot({1.0f, 0.0f, 0.0f});
const math::Vec3 y = rot({0.0f, 1.0f, 0.0f});
const math::Vec3 z = rot({0.0f, 0.0f, 1.0f});
ImGui::Text("X axis: %.1f, %.1f, %.1f", x.x(), x.y(), x.z());
ImGui::Text("Y axis: %.1f, %.1f, %.1f", y.x(), y.y(), y.z());
ImGui::Text("Z axis: %.1f, %.1f, %.1f", z.x(), z.y(), z.z());
ImGui::Separator();
auto euler = rot.to_euler();
ImGui::Text("pitch: %.1f°", math::to_deg(euler[math::Quaternion<>::PitchIndex]));
ImGui::Text("yaw : %.1f°", math::to_deg(euler[math::Quaternion<>::YawIndex]));
ImGui::Text("roll : %.1f°", math::to_deg(euler[math::Quaternion<>::RollIndex]));
}
}
};
class CullingDebug : public Widget {
editor_widget(CullingDebug, "View", "Debug")
public:
CullingDebug() : Widget("Culling debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const EditorWorld& world = current_world();
const Camera& camera = scene_view().camera();
core::Vector<ecs::EntityId> visible;
const OctreeSystem* octree_system = world.find_system<OctreeSystem>();
if(octree_system) {
visible = octree_system->octree().find_entities(camera.frustum());
}
const usize in_frustum = visible.size();
const usize total = world.component_ids<TransformableComponent>().size();
ImGui::Text("%u entities in octree", u32(total));
ImGui::Text("%u entities in frustum", u32(in_frustum));
ImGui::Text("%u%% culled", u32(float(total - in_frustum) / float(total) * 100.0f));
}
};
class MemoryDebug : public Widget {
editor_widget(MemoryDebug, "View", "Debug")
public:
MemoryDebug() : Widget("Memory debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const u64 total_allocs = memory::total_allocations();
ImGui::TextUnformatted(fmt_c_str("% live allocations", memory::live_allocations()));
ImGui::TextUnformatted(fmt_c_str("% allocations per frame", total_allocs - _last_total));
_last_total = total_allocs;
}
private:
u64 _last_total = 0;
};
class EcsDebug : public Widget {
editor_widget(EcsDebug, "View", "Debug")
public:
EcsDebug() : Widget("ECS Debug") {
}
protected:
void on_gui() override {
const EditorWorld& world = current_world();
if(ImGui::CollapsingHeader("Systems")) {
ImGui::BeginChild("##systems", ImVec2(0, 0), true);
imgui::alternating_rows_background();
for(const auto& system : world.systems()) {
ImGui::Selectable(system->name().data());
}
ImGui::EndChild();
}
}
};
class MeshAllocatorDebug : public Widget {
editor_widget(MeshAllocatorDebug, "View", "Debug")
public:
MeshAllocatorDebug() : Widget("Mesh allocator debug") {
}
protected:
void on_gui() override {
auto [vert, tris] = mesh_allocator().allocated();
{
ImGui::TextUnformatted("Vertex buffer:");
ImGui::SameLine();
ImGui::ProgressBar(float(vert) / MeshAllocator::default_vertex_count, ImVec2(-1.0f, 0.0f),
fmt_c_str("%k / %k", vert / 1000, MeshAllocator::default_vertex_count / 1000)
);
}
{
ImGui::TextUnformatted("Triangle buffer:");
ImGui::SameLine();
ImGui::ProgressBar(float(tris) / MeshAllocator::default_triangle_count, ImVec2(-1.0f, 0.0f),
fmt_c_str("%k / %k", tris / 1000, MeshAllocator::default_triangle_count / 1000)
);
}
}
};
}
| 36.793651 | 109 | 0.563129 | gan74 |
f81f92fe645075b68e828b219b6060e97187c699 | 518 | cpp | C++ | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define LSB(i) ((i)&-(i))
const int SIZE = 5;
int A[SIZE];
int sum(int i)
{
int sum = 0;
while(i > 0){
sum += A[i], i -= LSB(i);
}
return sum;
}
void add(int i, int p)
{
while(i < SIZE){
A[i] += p, i += LSB(i);
}
}
int main()
{
for(int i = 1; i < SIZE; i++)
add(i, i);
for(int i = 1; i < SIZE; i++)
cout<<sum(i)<<endl;
return 0;
}
| 15.69697 | 41 | 0.388031 | freedomDR |
f824bf9d8353425e66d331f7f8224a1305789731 | 17,897 | cpp | C++ | ardupilot/ArduPlane/Log.cpp | quadrotor-IITKgp/emulate_GPS | 3c888d5b27b81fb17e74d995370f64bdb110fb65 | [
"MIT"
] | 1 | 2021-07-17T11:37:16.000Z | 2021-07-17T11:37:16.000Z | ardupilot/ArduPlane/Log.cpp | arl-kgp/emulate_GPS | 3c888d5b27b81fb17e74d995370f64bdb110fb65 | [
"MIT"
] | null | null | null | ardupilot/ArduPlane/Log.cpp | arl-kgp/emulate_GPS | 3c888d5b27b81fb17e74d995370f64bdb110fb65 | [
"MIT"
] | null | null | null | // -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#include "Plane.h"
#if LOGGING_ENABLED == ENABLED
#if CLI_ENABLED == ENABLED
// Code to Write and Read packets from DataFlash.log memory
// Code to interact with the user to dump or erase logs
// Creates a constant array of structs representing menu options
// and stores them in Flash memory, not RAM.
// User enters the string in the console to call the functions on the right.
// See class Menu in AP_Coommon for implementation details
static const struct Menu::command log_menu_commands[] PROGMEM = {
{"dump", MENU_FUNC(dump_log)},
{"erase", MENU_FUNC(erase_logs)},
{"enable", MENU_FUNC(select_logs)},
{"disable", MENU_FUNC(select_logs)}
};
// A Macro to create the Menu
MENU2(log_menu, "Log", log_menu_commands, FUNCTOR_BIND(&plane, &Plane::print_log_menu, bool));
bool Plane::print_log_menu(void)
{
cliSerial->println_P(PSTR("logs enabled: "));
if (0 == g.log_bitmask) {
cliSerial->println_P(PSTR("none"));
}else{
// Macro to make the following code a bit easier on the eye.
// Pass it the capitalised name of the log option, as defined
// in defines.h but without the LOG_ prefix. It will check for
// the bit being set and print the name of the log option to suit.
#define PLOG(_s) if (g.log_bitmask & MASK_LOG_ ## _s) cliSerial->printf_P(PSTR(" %S"), PSTR(# _s))
PLOG(ATTITUDE_FAST);
PLOG(ATTITUDE_MED);
PLOG(GPS);
PLOG(PM);
PLOG(CTUN);
PLOG(NTUN);
PLOG(MODE);
PLOG(IMU);
PLOG(CMD);
PLOG(CURRENT);
PLOG(COMPASS);
PLOG(TECS);
PLOG(CAMERA);
PLOG(RC);
PLOG(SONAR);
#undef PLOG
}
cliSerial->println();
DataFlash.ListAvailableLogs(cliSerial);
return(true);
}
int8_t Plane::dump_log(uint8_t argc, const Menu::arg *argv)
{
int16_t dump_log_num;
uint16_t dump_log_start;
uint16_t dump_log_end;
// check that the requested log number can be read
dump_log_num = argv[1].i;
if (dump_log_num == -2) {
DataFlash.DumpPageInfo(cliSerial);
return(-1);
} else if (dump_log_num <= 0) {
cliSerial->printf_P(PSTR("dumping all\n"));
Log_Read(0, 1, 0);
return(-1);
} else if ((argc != 2) || ((uint16_t)dump_log_num > DataFlash.get_num_logs())) {
cliSerial->printf_P(PSTR("bad log number\n"));
return(-1);
}
DataFlash.get_log_boundaries(dump_log_num, dump_log_start, dump_log_end);
Log_Read((uint16_t)dump_log_num, dump_log_start, dump_log_end);
return 0;
}
int8_t Plane::erase_logs(uint8_t argc, const Menu::arg *argv)
{
in_mavlink_delay = true;
do_erase_logs();
in_mavlink_delay = false;
return 0;
}
int8_t Plane::select_logs(uint8_t argc, const Menu::arg *argv)
{
uint32_t bits;
if (argc != 2) {
cliSerial->printf_P(PSTR("missing log type\n"));
return(-1);
}
bits = 0;
// Macro to make the following code a bit easier on the eye.
// Pass it the capitalised name of the log option, as defined
// in defines.h but without the LOG_ prefix. It will check for
// that name as the argument to the command, and set the bit in
// bits accordingly.
//
if (!strcasecmp_P(argv[1].str, PSTR("all"))) {
bits = 0xFFFFFFFFUL;
} else {
#define TARG(_s) if (!strcasecmp_P(argv[1].str, PSTR(# _s))) bits |= MASK_LOG_ ## _s
TARG(ATTITUDE_FAST);
TARG(ATTITUDE_MED);
TARG(GPS);
TARG(PM);
TARG(CTUN);
TARG(NTUN);
TARG(MODE);
TARG(IMU);
TARG(CMD);
TARG(CURRENT);
TARG(COMPASS);
TARG(TECS);
TARG(CAMERA);
TARG(RC);
TARG(SONAR);
#undef TARG
}
if (!strcasecmp_P(argv[0].str, PSTR("enable"))) {
g.log_bitmask.set_and_save(g.log_bitmask | bits);
}else{
g.log_bitmask.set_and_save(g.log_bitmask & ~bits);
}
return(0);
}
int8_t Plane::process_logs(uint8_t argc, const Menu::arg *argv)
{
log_menu.run();
return 0;
}
#endif // CLI_ENABLED == ENABLED
void Plane::do_erase_logs(void)
{
gcs_send_text_P(MAV_SEVERITY_WARNING, PSTR("Erasing logs"));
DataFlash.EraseAll();
gcs_send_text_P(MAV_SEVERITY_WARNING, PSTR("Log erase complete"));
}
// Write an attitude packet
void Plane::Log_Write_Attitude(void)
{
Vector3f targets; // Package up the targets into a vector for commonality with Copter usage of Log_Wrote_Attitude
targets.x = nav_roll_cd;
targets.y = nav_pitch_cd;
targets.z = 0; //Plane does not have the concept of navyaw. This is a placeholder.
DataFlash.Log_Write_Attitude(ahrs, targets);
#if HAL_CPU_CLASS > HAL_CPU_CLASS_16
DataFlash.Log_Write_PID(LOG_PIDR_MSG, rollController.get_pid_info());
DataFlash.Log_Write_PID(LOG_PIDP_MSG, pitchController.get_pid_info());
DataFlash.Log_Write_PID(LOG_PIDY_MSG, yawController.get_pid_info());
DataFlash.Log_Write_PID(LOG_PIDS_MSG, steerController.get_pid_info());
#endif
#if AP_AHRS_NAVEKF_AVAILABLE
#if OPTFLOW == ENABLED
DataFlash.Log_Write_EKF(ahrs,optflow.enabled());
#else
DataFlash.Log_Write_EKF(ahrs,false);
#endif
DataFlash.Log_Write_AHRS2(ahrs);
#endif
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
sitl.Log_Write_SIMSTATE(DataFlash);
#endif
DataFlash.Log_Write_POS(ahrs);
}
struct PACKED log_Performance {
LOG_PACKET_HEADER;
uint64_t time_us;
uint32_t loop_time;
uint16_t main_loop_count;
uint32_t g_dt_max;
int16_t gyro_drift_x;
int16_t gyro_drift_y;
int16_t gyro_drift_z;
uint8_t i2c_lockup_count;
uint16_t ins_error_count;
};
// Write a performance monitoring packet. Total length : 19 bytes
void Plane::Log_Write_Performance()
{
struct log_Performance pkt = {
LOG_PACKET_HEADER_INIT(LOG_PERFORMANCE_MSG),
time_us : hal.scheduler->micros64(),
loop_time : millis() - perf_mon_timer,
main_loop_count : mainLoop_count,
g_dt_max : G_Dt_max,
gyro_drift_x : (int16_t)(ahrs.get_gyro_drift().x * 1000),
gyro_drift_y : (int16_t)(ahrs.get_gyro_drift().y * 1000),
gyro_drift_z : (int16_t)(ahrs.get_gyro_drift().z * 1000),
i2c_lockup_count: hal.i2c->lockup_count(),
ins_error_count : ins.error_count()
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
struct PACKED log_Startup {
LOG_PACKET_HEADER;
uint64_t time_us;
uint8_t startup_type;
uint16_t command_total;
};
// do not add any extra log writes to this function; see LogStartup.cpp
bool Plane::Log_Write_Startup(uint8_t type)
{
struct log_Startup pkt = {
LOG_PACKET_HEADER_INIT(LOG_STARTUP_MSG),
time_us : hal.scheduler->micros64(),
startup_type : type,
command_total : mission.num_commands()
};
return DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
struct PACKED log_Control_Tuning {
LOG_PACKET_HEADER;
uint64_t time_us;
int16_t nav_roll_cd;
int16_t roll;
int16_t nav_pitch_cd;
int16_t pitch;
int16_t throttle_out;
int16_t rudder_out;
float accel_y;
};
// Write a control tuning packet. Total length : 22 bytes
void Plane::Log_Write_Control_Tuning()
{
Vector3f accel = ins.get_accel();
struct log_Control_Tuning pkt = {
LOG_PACKET_HEADER_INIT(LOG_CTUN_MSG),
time_us : hal.scheduler->micros64(),
nav_roll_cd : (int16_t)nav_roll_cd,
roll : (int16_t)ahrs.roll_sensor,
nav_pitch_cd : (int16_t)nav_pitch_cd,
pitch : (int16_t)ahrs.pitch_sensor,
throttle_out : (int16_t)channel_throttle->servo_out,
rudder_out : (int16_t)channel_rudder->servo_out,
accel_y : accel.y
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
// Write a TECS tuning packet
void Plane::Log_Write_TECS_Tuning(void)
{
SpdHgt_Controller->log_data(DataFlash, LOG_TECS_MSG);
}
struct PACKED log_Nav_Tuning {
LOG_PACKET_HEADER;
uint64_t time_us;
uint16_t yaw;
float wp_distance;
int16_t target_bearing_cd;
int16_t nav_bearing_cd;
int16_t altitude_error_cm;
int16_t airspeed_cm;
float altitude;
uint32_t groundspeed_cm;
};
// Write a navigation tuning packe
void Plane::Log_Write_Nav_Tuning()
{
struct log_Nav_Tuning pkt = {
LOG_PACKET_HEADER_INIT(LOG_NTUN_MSG),
time_us : hal.scheduler->micros64(),
yaw : (uint16_t)ahrs.yaw_sensor,
wp_distance : auto_state.wp_distance,
target_bearing_cd : (int16_t)nav_controller->target_bearing_cd(),
nav_bearing_cd : (int16_t)nav_controller->nav_bearing_cd(),
altitude_error_cm : (int16_t)altitude_error_cm,
airspeed_cm : (int16_t)airspeed.get_airspeed_cm(),
altitude : barometer.get_altitude(),
groundspeed_cm : (uint32_t)(gps.ground_speed()*100)
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
struct PACKED log_Status {
LOG_PACKET_HEADER;
uint64_t time_us;
uint8_t is_flying;
float is_flying_probability;
uint8_t armed;
uint8_t safety;
bool is_crashed;
bool is_still;
uint8_t stage;
};
void Plane::Log_Write_Status()
{
struct log_Status pkt = {
LOG_PACKET_HEADER_INIT(LOG_STATUS_MSG)
,time_us : hal.scheduler->micros64()
,is_flying : is_flying()
,is_flying_probability : isFlyingProbability
,armed : hal.util->get_soft_armed()
,safety : hal.util->safety_switch_state()
,is_crashed : crash_state.is_crashed
,is_still : plane.ins.is_still()
,stage : flight_stage
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
struct PACKED log_Sonar {
LOG_PACKET_HEADER;
uint64_t time_us;
uint16_t distance;
float voltage;
float baro_alt;
float groundspeed;
uint8_t throttle;
uint8_t count;
float correction;
};
// Write a sonar packet
void Plane::Log_Write_Sonar()
{
#if RANGEFINDER_ENABLED == ENABLED
uint16_t distance = 0;
if (rangefinder.status() == RangeFinder::RangeFinder_Good) {
distance = rangefinder.distance_cm();
}
struct log_Sonar pkt = {
LOG_PACKET_HEADER_INIT(LOG_SONAR_MSG),
time_us : hal.scheduler->micros64(),
distance : distance,
voltage : rangefinder.voltage_mv()*0.001f,
baro_alt : barometer.get_altitude(),
groundspeed : gps.ground_speed(),
throttle : (uint8_t)(100 * channel_throttle->norm_output()),
count : rangefinder_state.in_range_count,
correction : rangefinder_state.correction
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
DataFlash.Log_Write_RFND(rangefinder);
#endif
}
struct PACKED log_Optflow {
LOG_PACKET_HEADER;
uint64_t time_us;
uint8_t surface_quality;
float flow_x;
float flow_y;
float body_x;
float body_y;
};
#if OPTFLOW == ENABLED
// Write an optical flow packet
void Plane::Log_Write_Optflow()
{
// exit immediately if not enabled
if (!optflow.enabled()) {
return;
}
const Vector2f &flowRate = optflow.flowRate();
const Vector2f &bodyRate = optflow.bodyRate();
struct log_Optflow pkt = {
LOG_PACKET_HEADER_INIT(LOG_OPTFLOW_MSG),
time_us : hal.scheduler->micros64(),
surface_quality : optflow.quality(),
flow_x : flowRate.x,
flow_y : flowRate.y,
body_x : bodyRate.x,
body_y : bodyRate.y
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
#endif
struct PACKED log_Arm_Disarm {
LOG_PACKET_HEADER;
uint64_t time_us;
uint8_t arm_state;
uint16_t arm_checks;
};
void Plane::Log_Write_Current()
{
DataFlash.Log_Write_Current(battery, channel_throttle->control_in);
// also write power status
DataFlash.Log_Write_Power();
}
void Plane::Log_Arm_Disarm() {
struct log_Arm_Disarm pkt = {
LOG_PACKET_HEADER_INIT(LOG_ARM_DISARM_MSG),
time_us : hal.scheduler->micros64(),
arm_state : arming.is_armed(),
arm_checks : arming.get_enabled_checks()
};
DataFlash.WriteBlock(&pkt, sizeof(pkt));
}
void Plane::Log_Write_GPS(uint8_t instance)
{
DataFlash.Log_Write_GPS(gps, instance, current_loc.alt - ahrs.get_home().alt);
}
void Plane::Log_Write_IMU()
{
DataFlash.Log_Write_IMU(ins);
}
void Plane::Log_Write_RC(void)
{
DataFlash.Log_Write_RCIN();
DataFlash.Log_Write_RCOUT();
if (rssi.enabled()) {
DataFlash.Log_Write_RSSI(rssi);
}
}
void Plane::Log_Write_Baro(void)
{
DataFlash.Log_Write_Baro(barometer);
}
// Write a AIRSPEED packet
void Plane::Log_Write_Airspeed(void)
{
DataFlash.Log_Write_Airspeed(airspeed);
}
// log ahrs home and EKF origin to dataflash
void Plane::Log_Write_Home_And_Origin()
{
#if AP_AHRS_NAVEKF_AVAILABLE
// log ekf origin if set
Location ekf_orig;
if (ahrs.get_NavEKF_const().getOriginLLH(ekf_orig)) {
DataFlash.Log_Write_Origin(LogOriginType::ekf_origin, ekf_orig);
}
#endif
// log ahrs home if set
if (home_is_set != HOME_UNSET) {
DataFlash.Log_Write_Origin(LogOriginType::ahrs_home, ahrs.get_home());
}
}
static const struct LogStructure log_structure[] PROGMEM = {
LOG_COMMON_STRUCTURES,
{ LOG_PERFORMANCE_MSG, sizeof(log_Performance),
"PM", "QIHIhhhBH", "TimeUS,LTime,MLC,gDt,GDx,GDy,GDz,I2CErr,INSErr" },
{ LOG_STARTUP_MSG, sizeof(log_Startup),
"STRT", "QBH", "TimeUS,SType,CTot" },
{ LOG_CTUN_MSG, sizeof(log_Control_Tuning),
"CTUN", "Qcccchhf", "TimeUS,NavRoll,Roll,NavPitch,Pitch,ThrOut,RdrOut,AccY" },
{ LOG_NTUN_MSG, sizeof(log_Nav_Tuning),
"NTUN", "QCfccccfI", "TimeUS,Yaw,WpDist,TargBrg,NavBrg,AltErr,Arspd,Alt,GSpdCM" },
{ LOG_SONAR_MSG, sizeof(log_Sonar),
"SONR", "QHfffBBf", "TimeUS,DistCM,Volt,BaroAlt,GSpd,Thr,Cnt,Corr" },
{ LOG_ARM_DISARM_MSG, sizeof(log_Arm_Disarm),
"ARM", "QBH", "TimeUS,ArmState,ArmChecks" },
{ LOG_ATRP_MSG, sizeof(AP_AutoTune::log_ATRP),
"ATRP", "QBBcfff", "TimeUS,Type,State,Servo,Demanded,Achieved,P" },
{ LOG_STATUS_MSG, sizeof(log_Status),
"STAT", "QBfBBBBB", "TimeUS,isFlying,isFlyProb,Armed,Safety,Crash,Still,Stage" },
#if OPTFLOW == ENABLED
{ LOG_OPTFLOW_MSG, sizeof(log_Optflow),
"OF", "QBffff", "TimeUS,Qual,flowX,flowY,bodyX,bodyY" },
#endif
TECS_LOG_FORMAT(LOG_TECS_MSG)
};
#if CLI_ENABLED == ENABLED
// Read the DataFlash.log memory : Packet Parser
void Plane::Log_Read(uint16_t list_entry, int16_t start_page, int16_t end_page)
{
cliSerial->printf_P(PSTR("\n" FIRMWARE_STRING
"\nFree RAM: %u\n"),
(unsigned)hal.util->available_memory());
cliSerial->println_P(PSTR(HAL_BOARD_NAME));
DataFlash.LogReadProcess(list_entry, start_page, end_page,
FUNCTOR_BIND_MEMBER(&Plane::print_flight_mode, void, AP_HAL::BetterStream *, uint8_t),
cliSerial);
}
#endif // CLI_ENABLED
void Plane::Log_Write_Vehicle_Startup_Messages()
{
// only 200(?) bytes are guaranteed by DataFlash
Log_Write_Startup(TYPE_GROUNDSTART_MSG);
DataFlash.Log_Write_Mode(control_mode);
}
// start a new log
void Plane::start_logging()
{
DataFlash.set_mission(&mission);
DataFlash.setVehicle_Startup_Log_Writer(
FUNCTOR_BIND(&plane, &Plane::Log_Write_Vehicle_Startup_Messages, void)
);
DataFlash.StartNewLog();
}
/*
initialise logging subsystem
*/
void Plane::log_init(void)
{
DataFlash.Init(log_structure, ARRAY_SIZE(log_structure));
if (!DataFlash.CardInserted()) {
gcs_send_text_P(MAV_SEVERITY_WARNING, PSTR("No dataflash card inserted"));
g.log_bitmask.set(0);
} else if (DataFlash.NeedPrep()) {
gcs_send_text_P(MAV_SEVERITY_WARNING, PSTR("Preparing log system"));
DataFlash.Prep();
gcs_send_text_P(MAV_SEVERITY_WARNING, PSTR("Prepared log system"));
for (uint8_t i=0; i<num_gcs; i++) {
gcs[i].reset_cli_timeout();
}
}
arming.set_logging_available(DataFlash.CardInserted());
}
#else // LOGGING_ENABLED
#if CLI_ENABLED == ENABLED
bool Plane::print_log_menu(void) { return true; }
int8_t Plane::dump_log(uint8_t argc, const Menu::arg *argv) { return 0; }
int8_t Plane::erase_logs(uint8_t argc, const Menu::arg *argv) { return 0; }
int8_t Plane::select_logs(uint8_t argc, const Menu::arg *argv) { return 0; }
int8_t Plane::process_logs(uint8_t argc, const Menu::arg *argv) { return 0; }
#endif // CLI_ENABLED == ENABLED
void Plane::do_erase_logs(void) {}
void Plane::Log_Write_Attitude(void) {}
void Plane::Log_Write_Performance() {}
void Plane::Log_Write_Startup(uint8_t type) {}
void Plane::Log_Write_Control_Tuning() {}
void Plane::Log_Write_TECS_Tuning(void) {}
void Plane::Log_Write_Nav_Tuning() {}
void Plane::Log_Write_Status() {}
void Plane::Log_Write_Sonar() {}
#if OPTFLOW == ENABLED
void Plane::Log_Write_Optflow() {}
#endif
void Plane::Log_Write_Current() {}
void Plane::Log_Arm_Disarm() {}
void Plane::Log_Write_GPS(uint8_t instance) {}
void Plane::Log_Write_IMU() {}
void Plane::Log_Write_RC(void) {}
void Plane::Log_Write_Baro(void) {}
void Plane::Log_Write_Airspeed(void) {}
void Plane::Log_Write_Home_And_Origin() {}
#if CLI_ENABLED == ENABLED
void Plane::Log_Read(uint16_t log_num, int16_t start_page, int16_t end_page) {}
#endif // CLI_ENABLED
void Plane::start_logging() {}
void Plane::log_init(void) {}
#endif // LOGGING_ENABLED
| 29.87813 | 123 | 0.661228 | quadrotor-IITKgp |
f8264539778f2687084a99144e72cea6aaaee963 | 25,196 | cpp | C++ | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | 1 | 2022-03-30T15:53:09.000Z | 2022-03-30T15:53:09.000Z | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | //-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT
This file is part of NBlood.
NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h" // Must come before everything else!
#include "build.h"
#include "blood.h"
BEGIN_BLD_NS
static void cultThinkSearch(DBloodActor*);
static void cultThinkGoto(DBloodActor*);
static void cultThinkChase(DBloodActor*);
AISTATE cultistIdle = { kAiStateIdle, 0, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistProneIdle = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE fanaticProneIdle = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistProneIdle3 = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistChase = { kAiStateChase, 9, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE fanaticChase = { kAiStateChase, 0, -1, 0, NULL, aiMoveTurn, cultThinkChase, NULL };
AISTATE cultistDodge = { kAiStateMove, 9, -1, 90, NULL, aiMoveDodge, NULL, &cultistChase };
AISTATE cultistGoto = { kAiStateMove, 9, -1, 600, NULL, aiMoveForward, cultThinkGoto, &cultistIdle };
AISTATE cultistProneChase = { kAiStateChase, 14, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE cultistProneDodge = { kAiStateMove, 14, -1, 90, NULL, aiMoveDodge, NULL, &cultistProneChase };
AISTATE cultistTThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistTFire };
AISTATE cultistSThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistSFire };
AISTATE cultistTsThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistTsFire };
AISTATE cultistDThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistChase };
AISTATE cultist139A78 = { kAiStateChase, 7, n68170Client, 120, NULL, NULL, NULL, &cultistChase };
AISTATE cultist139A94 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, NULL, &cultistIdle };
AISTATE cultist139AB0 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139A94 };
AISTATE cultist139ACC = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139AB0 };
AISTATE cultist139AE8 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139AE8 };
AISTATE cultistSearch = { kAiStateSearch, 9, -1, 1800, NULL, aiMoveForward, cultThinkSearch, &cultistIdle };
AISTATE cultistSFire = { kAiStateChase, 6, nShotClient, 60, NULL, NULL, NULL, &cultistChase };
AISTATE cultistTFire = { kAiStateChase, 6, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTFire };
AISTATE cultistTsFire = { kAiStateChase, 6, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistChase };
AISTATE cultistSProneFire = { kAiStateChase, 8, nShotClient, 60, NULL, NULL, NULL, &cultistProneChase };
AISTATE cultistTProneFire = { kAiStateChase, 8, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTProneFire };
AISTATE cultistTsProneFire = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, NULL, &cultistTsProneFire }; // vanilla, broken
AISTATE cultistTsProneFireFixed = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTsProneFireFixed };
AISTATE cultistRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistDodge };
AISTATE cultistProneRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistProneDodge };
AISTATE cultistTeslaRecoil = { kAiStateRecoil, 4, -1, 0, NULL, NULL, NULL, &cultistDodge };
AISTATE cultistSwimIdle = { kAiStateIdle, 13, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistSwimChase = { kAiStateChase, 13, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE cultistSwimDodge = { kAiStateMove, 13, -1, 90, NULL, aiMoveDodge, NULL, &cultistSwimChase };
AISTATE cultistSwimGoto = { kAiStateMove, 13, -1, 600, NULL, aiMoveForward, cultThinkGoto, &cultistSwimIdle };
AISTATE cultistSwimSearch = { kAiStateSearch, 13, -1, 1800, NULL, aiMoveForward, cultThinkSearch, &cultistSwimIdle };
AISTATE cultistSSwimFire = { kAiStateChase, 8, nShotClient, 60, NULL, NULL, NULL, &cultistSwimChase };
AISTATE cultistTSwimFire = { kAiStateChase, 8, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTSwimFire };
AISTATE cultistTsSwimFire = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTsSwimFire };
AISTATE cultistSwimRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistSwimDodge };
void TommySeqCallback(int, DBloodActor* actor)
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random3((5 - gGameOptions.nDifficulty) * 1000);
dy += Random3((5 - gGameOptions.nDifficulty) * 1000);
dz += Random3((5 - gGameOptions.nDifficulty) * 500);
actFireVector(actor, 0, 0, dx, dy, dz, kVectorBullet);
sfxPlay3DSound(actor, 4001, -1, 0);
}
void TeslaSeqCallback(int, DBloodActor* actor)
{
if (Chance(dword_138BB0[gGameOptions.nDifficulty]))
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random3((5 - gGameOptions.nDifficulty) * 1000);
dy += Random3((5 - gGameOptions.nDifficulty) * 1000);
dz += Random3((5 - gGameOptions.nDifficulty) * 500);
actFireMissile(actor, 0, 0, dx, dy, dz, kMissileTeslaRegular);
sfxPlay3DSound(actor, 470, -1, 0);
}
}
void ShotSeqCallback(int, DBloodActor* actor)
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random2((5 - gGameOptions.nDifficulty) * 1000 - 500);
dy += Random2((5 - gGameOptions.nDifficulty) * 1000 - 500);
dz += Random2((5 - gGameOptions.nDifficulty) * 500);
for (int i = 0; i < 8; i++)
{
int r1 = Random3(500);
int r2 = Random3(1000);
int r3 = Random3(1000);
actFireVector(actor, 0, 0, dx + r3, dy + r2, dz + r1, kVectorShell);
}
if (Chance(0x8000))
sfxPlay3DSound(actor, 1001, -1, 0);
else
sfxPlay3DSound(actor, 1002, -1, 0);
}
void cultThrowSeqCallback(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
uint8_t v4 = Chance(0x6000);
sfxPlay3DSound(actor, 455, -1, 0);
if (!actor->ValidateTarget(__FUNCTION__)) return;
auto target = actor->GetTarget();
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
int dz = target->spr.pos.Z - actor->spr.pos.Z;
int nDist = approxDist(dx, dy);
int nDist2 = nDist / 540;
if (nDist > 0x1e00)
v4 = 0;
auto* pMissile = actFireThing(actor, 0, 0, dz / 128 - 14500, nMissile, (nDist2 << 23) / 120);
if (v4)
pMissile->xspr.Impact = 1;
else
evPostActor(pMissile, 120 * (1 + Random(2)), kCmdOn);
}
void sub_68170(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
sfxPlay3DSound(actor, 455, -1, 0);
auto pMissile = actFireThing(actor, 0, 0, actor->dudeSlope - 9460, nMissile, 0x133333);
evPostActor(pMissile, 120 * (2 + Random(2)), kCmdOn);
}
void sub_68230(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
sfxPlay3DSound(actor, 455, -1, 0);
if (!actor->ValidateTarget(__FUNCTION__)) return;
auto target = actor->GetTarget();
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
int dz = target->spr.pos.Z - actor->spr.pos.Z;
int nDist = approxDist(dx, dy);
int nDist2 = nDist / 540;
auto pMissile = actFireThing(actor, 0, 0, dz / 128 - 14500, nMissile, (nDist2 << 17) / 120);
pMissile->xspr.Impact = 1;
}
static bool TargetNearExplosion(sectortype* sector)
{
BloodSectIterator it(sector);
while (auto actor = it.Next())
{
if (actor->spr.type == kThingArmedTNTStick || actor->spr.statnum == kStatExplosion)
return true;
}
return false;
}
static void cultThinkSearch(DBloodActor* actor)
{
aiChooseDirection(actor, actor->xspr.goalAng);
aiLookForTarget(actor);
}
static void cultThinkGoto(DBloodActor* actor)
{
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
DUDEINFO* pDudeInfo = getDudeInfo(actor->spr.type);
int dx = actor->xspr.TargetPos.X - actor->spr.pos.X;
int dy = actor->xspr.TargetPos.Y - actor->spr.pos.Y;
int nAngle = getangle(dx, dy);
int nDist = approxDist(dx, dy);
aiChooseDirection(actor, nAngle);
if (nDist < 5120 && abs(actor->spr.ang - nAngle) < pDudeInfo->periphery)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
}
aiThinkTarget(actor);
}
static void cultThinkChase(DBloodActor* actor)
{
if (actor->GetTarget() == nullptr)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistGoto);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimGoto);
break;
}
return;
}
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
DUDEINFO* pDudeInfo = getDudeInfo(actor->spr.type);
auto target = actor->GetTarget();
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
aiChooseDirection(actor, getangle(dx, dy));
if (target->xspr.health == 0)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
if (actor->spr.type == kDudeCultistTommy)
aiPlay3DSound(actor, 4021 + Random(4), AI_SFX_PRIORITY_1, -1);
else
aiPlay3DSound(actor, 1021 + Random(4), AI_SFX_PRIORITY_1, -1);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
return;
}
if (target->IsPlayerActor() && powerupCheck(&gPlayer[target->spr.type - kDudePlayer1], kPwUpShadowCloak) > 0)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
return;
}
int nDist = approxDist(dx, dy);
if (nDist > 0 && nDist <= pDudeInfo->seeDist)
{
int nDeltaAngle = ((getangle(dx, dy) + 1024 - actor->spr.ang) & 2047) - 1024;
int height = (pDudeInfo->eyeHeight * actor->spr.yrepeat) << 2;
if (cansee(target->spr.pos.X, target->spr.pos.Y, target->spr.pos.Z, target->sector(), actor->spr.pos.X, actor->spr.pos.Y, actor->spr.pos.Z - height, actor->sector()))
{
if (nDist < pDudeInfo->seeDist && abs(nDeltaAngle) <= pDudeInfo->periphery)
{
aiSetTarget(actor, actor->GetTarget());
actor->dudeSlope = nDist == 0 ? 0 : DivScale(target->spr.pos.Z - actor->spr.pos.Z, nDist, 10);
switch (actor->spr.type) {
case kDudeCultistTommy:
if (nDist < 0x1e00 && nDist > 0xe00 && abs(nDeltaAngle) < 85 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTThrow);
break;
default:
aiNewState(actor, &cultistTThrow);
break;
}
}
else if (nDist < 0x4600 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (dudeIsPlayingSeq(actor, 13) && (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo))
aiNewState(actor, &cultistTSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTSwimFire);
break;
}
}
break;
case kDudeCultistShotgun:
if (nDist < 0x2c00 && nDist > 0x1400 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty >= 2 && target->IsPlayerActor() && !gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
default:
aiNewState(actor, &cultistSThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
}
}
break;
case kDudeCultistTesla:
if (nDist < 0x1e00 && nDist > 0xe00 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTsThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTsThrow);
break;
default:
aiNewState(actor, &cultistTsThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
AISTATE *pCultistTsProneFire = !cl_bloodvanillaenemies && !VanillaMode() ? &cultistTsProneFireFixed : &cultistTsProneFire;
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
break;
}
}
break;
case kDudeCultistTNT:
if (nDist < 0x2c00 && nDist > 0x1400 && abs(nDeltaAngle) < 85
&& (target->spr.flags & 2) && target->IsPlayerActor())
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistDThrow);
break;
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistDThrow);
break;
default:
aiNewState(actor, &cultistDThrow);
break;
}
}
else if (nDist < 0x1400 && abs(nDeltaAngle) < 85
&& (target->spr.flags & 2) && target->IsPlayerActor())
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != 1 && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultist139A78);
break;
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultist139A78);
break;
default:
aiNewState(actor, &cultist139A78);
break;
}
}
break;
case kDudeCultistBeast:
if (nDist < 0x1e00 && nDist > 0xe00 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
default:
aiNewState(actor, &cultistSThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
}
}
break;
}
return;
}
}
}
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistGoto);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimGoto);
break;
}
actor->SetTarget(nullptr);
}
END_BLD_NS
| 40.573269 | 184 | 0.65173 | Quake-Backup |
f828ccf5f29d887122b5f31c780777d3c04d5d21 | 1,143 | cpp | C++ | src/bitshow.cpp | kindlychung/bitshow | b94ab1e7b6cdb32ad5ce8a22d5696eb52168e2e4 | [
"MIT"
] | null | null | null | src/bitshow.cpp | kindlychung/bitshow | b94ab1e7b6cdb32ad5ce8a22d5696eb52168e2e4 | [
"MIT"
] | null | null | null | src/bitshow.cpp | kindlychung/bitshow | b94ab1e7b6cdb32ad5ce8a22d5696eb52168e2e4 | [
"MIT"
] | null | null | null | #include "bitshow.h"
#include "details.h"
#include "masks.h"
#include "types.h"
namespace bitshow {
floating_formats::format<double> anatomy(double x) {
auto x_bits = bits(x);
std::bitset<1> sign_bit(
((x_bits & masks::double_sign_mask) >> 63).to_ullong());
std::bitset<11> exponent_bits(
((x_bits & masks::double_exponent_mask) >> 52).to_ullong());
std::bitset<52> mantissa_bits(
(x_bits & masks::double_mantissa_mask).to_ullong());
floating_formats::format<double> result{sign_bit, exponent_bits,
mantissa_bits};
return result;
}
floating_formats::format<float> anatomy(float x) {
auto x_bits = bits(x);
std::bitset<1> sign_bit(
((x_bits & masks::float_sign_mask) >> 63).to_ullong());
std::bitset<8> exponent_bits(
((x_bits & masks::float_exponent_mask) >> 52).to_ullong());
std::bitset<23> mantissa_bits(
(x_bits & masks::float_mantissa_mask).to_ullong());
floating_formats::format<float> result{sign_bit, exponent_bits,
mantissa_bits};
return result;
}
} | 35.71875 | 68 | 0.622047 | kindlychung |
f82cae8e8b8d25cdcefc2cffde99716d5148896e | 1,528 | hpp | C++ | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | 2 | 2019-02-28T00:28:08.000Z | 2019-10-20T14:39:48.000Z | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | null | null | null | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | null | null | null | // ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <ztn@zurreal.com> wrote this file. As long as you retain this notice you
// can do whatever you want with this stuff. If we meet some day, and you think
// this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman
// ----------------------------------------------------------------------------
#ifndef HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
#define HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
//
// popup-stage-system-error.hpp
//
#include "popup/popup-stage-base.hpp"
namespace heroespath
{
namespace popup
{
// Responsible for implementing the System Error Popup Stage.
class PopupStageSystemError : public PopupStageBase
{
public:
PopupStageSystemError(const PopupStageSystemError &) = delete;
PopupStageSystemError(PopupStageSystemError &&) = delete;
PopupStageSystemError & operator=(const PopupStageSystemError &) = delete;
PopupStageSystemError & operator=(PopupStageSystemError &&) = delete;
explicit PopupStageSystemError(const PopupInfo &);
virtual ~PopupStageSystemError();
void Setup() override;
void draw(sf::RenderTarget &, sf::RenderStates) const override;
private:
gui::CachedTexture bgCachedTexture_;
sf::Sprite bgSprite_;
};
} // namespace popup
} // namespace heroespath
#endif // HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
| 36.380952 | 82 | 0.656414 | tilnewman |
f82d257f89575fff02afb18bb59610c72de43037 | 11,545 | cpp | C++ | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | 2 | 2015-11-07T18:32:10.000Z | 2017-11-20T21:13:22.000Z | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | null | null | null | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | null | null | null | /*
This source is part of libobdref
Copyright (C) 2012,2013 Preet Desai (preet.desai@gmail.com)
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 "obdreftest.h"
bool test_legacy(obdref::Parser & parser,
bool const randomizeHeader=false);
bool test_iso14230(obdref::Parser & parser,
bool const randomizeHeader=false,
int const headerLength=3,
bool const checkHeaderFormatByte=true);
bool test_iso15765(obdref::Parser & parser,
bool const randomizeHeader=false,
bool const extendedId=false);
int main(int argc, char* argv[])
{
// we expect a single argument that specifies
// the path to the test definitions file
bool opOk = false;
QString filePath(argv[1]);
if(filePath.isEmpty()) {
qDebug() << "Pass the test definitions file in as an argument:";
qDebug() << "./test_basic /path/to/test.xml";
return -1;
}
// read in xml definitions file
obdref::Parser parser(filePath,opOk);
if(!opOk) { return -1; }
g_debug_output = false;
bool randHeaders=true;
g_test_desc = "test legacy (sae j1850, iso 9141)";
if(!test_legacy(parser,randHeaders)) {
return -1;
}
g_test_desc = "test iso 14230 (1 byte header)";
if(!test_iso14230(parser,randHeaders,1,false)) {
return -1;
}
g_test_desc = "test iso 14230 (2 byte header)";
if(!test_iso14230(parser,randHeaders,2,false)) {
return -1;
}
g_test_desc = "test iso 14230 (3 byte header)";
if(!test_iso14230(parser,randHeaders,3,true)) {
return -1;
}
g_test_desc = "test iso 14230 (4 byte header)";
if(!test_iso14230(parser,randHeaders,4,true)) {
return -1;
}
g_test_desc = "test iso 15765 (standard ids)";
if(!test_iso15765(parser,randHeaders,false)) {
return -1;
}
g_test_desc = "test iso 15765 (extended ids)";
if(!test_iso15765(parser,randHeaders,true)) {
return -1;
}
return 0;
}
// ========================================================================== //
// ========================================================================== //
bool test_legacy(obdref::Parser & parser,
bool const randomizeHeader)
{
QStringList listParams =
parser.GetParameterNames("TEST","ISO 9141-2","Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = "ISO 9141-2";
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_legacy(param,2,randomizeHeader);
sim_vehicle_message_legacy(param,2,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,2,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
// ========================================================================== //
// ========================================================================== //
bool test_iso14230(obdref::Parser & parser,
bool const randomizeHeader,
int const headerLength,
bool const checkHeaderFormatByte)
{
QStringList listParams =
parser.GetParameterNames("TEST","ISO 14230","Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = "ISO 14230";
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if(checkHeaderFormatByte==false) {
// just makes testing multiple header lengths
// at once a bit easier
for(int j=0; j < param.listMessageData.size(); j++) {
param.listMessageData[j].expHeaderMask[0] = 0x00;
}
}
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,2,randomizeHeader);
sim_vehicle_message_iso14230(param,2,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,2,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
// ========================================================================== //
// ========================================================================== //
bool test_iso15765(obdref::Parser & parser,
bool const randomizeHeader,
bool const extendedId)
{
QString protocol = (extendedId) ?
"ISO 15765 Extended Id" : "ISO 15765 Standard Id";
QStringList listParams =
parser.GetParameterNames("TEST",protocol,"Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = protocol;
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,3,randomizeHeader);
sim_vehicle_message_iso15765(param,4,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,2,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
| 37.36246 | 80 | 0.532438 | preet |
f82df592f8a01ac47de7f3c28dd253350fcb3d04 | 240 | cpp | C++ | cpp/abl_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/abl_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/abl_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
long long A, B, C, D;
cin >> A >> B >> C >> D;
if(!((B < C) || (D < A))) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
| 14.117647 | 31 | 0.4 | kokosabu |
f830375d6113627933b3c59105412991899b795a | 2,590 | hpp | C++ | Sources/Post/IPostFilter.hpp | 0xflotus/Acid | cf680a13c3894822920737dcf1b7d17aef74a474 | [
"MIT"
] | 3 | 2018-10-19T23:33:37.000Z | 2019-04-07T11:46:44.000Z | Sources/Post/IPostFilter.hpp | sum01/Acid | d921472e062fc26b87c0163918aab553ac20739a | [
"MIT"
] | null | null | null | Sources/Post/IPostFilter.hpp | sum01/Acid | d921472e062fc26b87c0163918aab553ac20739a | [
"MIT"
] | null | null | null | #pragma once
#include "Models/Model.hpp"
#include "Renderer/IRenderer.hpp"
#include "Renderer/Renderer.hpp"
#include "Renderer/Handlers/DescriptorsHandler.hpp"
#include "Renderer/Pipelines/Pipeline.hpp"
namespace acid
{
/// <summary>
/// Represents a post effect shader and on application saves the result into a FBO.
/// </summary>
class ACID_EXPORT IPostFilter :
public IRenderer
{
protected:
static uint32_t GLOBAL_SWITCHING;
DescriptorsHandler m_descriptorSet;
Pipeline m_pipeline;
std::shared_ptr<Model> m_model;
std::map<std::string, IDescriptor *> m_attachments;
public:
/// <summary>
/// Creates a new post effect filter.
/// </summary>
/// <param name="graphicsStage"> The pipelines graphics stage. </param>
/// <param name="shaderStages"> The pipelines shader stages. </param>
/// <param name="defines"> A list of names that will be added as a #define. </param>
IPostFilter(const GraphicsStage &graphicsStage, const std::vector<std::string> &shaderStages, const std::vector<PipelineDefine> &defines = {});
virtual void Render(const CommandBuffer &commandBuffer, const Vector4 &clipPlane, const ICamera &camera) override = 0;
const DescriptorsHandler &GetDescriptorSet() const { return m_descriptorSet; }
const Pipeline &GetPipeline() const { return m_pipeline; }
std::shared_ptr<Model> GetModel() const { return m_model; }
IDescriptor *GetAttachment(const std::string &descriptorName, IDescriptor *descriptor) const;
IDescriptor *GetAttachment(const std::string &descriptorName, const std::string &rendererAttachment) const;
void SetAttachment(const std::string &descriptorName, IDescriptor *descriptor);
bool RemoveAttachment(const std::string &name);
protected:
/// <summary>
/// Used instead of `m_descriptorSet.Push()` in instances where a writeColour is the same as samplerColour in a shader.
/// By switching between what will be the input and output of each filter previous changes are available to the shader.
/// </summary>
/// <param name="descriptorName1"> The first descriptor in the shader. </param>
/// <param name="descriptorName2"> The second descriptor in the shader. </param>
/// <param name="rendererAttachment1"> The name of the renderers attachment that will be first option. </param>
/// <param name="rendererAttachment2"> The name of the renderers attachment that will be second option. </param>
void PushConditional(const std::string &descriptorName1, const std::string &descriptorName2, const std::string &rendererAttachment1, const std::string &rendererAttachment2);
};
}
| 41.774194 | 175 | 0.745946 | 0xflotus |
f830701d4dd232a2392ad1c173ac9dd1cb5d1655 | 1,029 | cpp | C++ | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | 2 | 2020-05-31T19:54:19.000Z | 2021-09-14T12:00:12.000Z | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | #include "Image.hpp"
#include <cassert>
#include <stdexcept>
namespace cdm
{
Image::Image(const VulkanDevice& device_, VkFormat format)
: AbstractImage(device_, format)
{
}
Image::~Image() { device().destroy(m_image.get()); }
VkImage Image::image()
{
if (outdated())
recreate();
return m_image.get();
}
bool Image::outdated() const
{
assert(false && "not implemented yet");
return true;
}
void Image::recreate()
{
assert(false && "not implemented yet");
setCreationTime();
}
SwapchainImage::SwapchainImage(const VulkanDevice& device_, VkImage image_,
VkFormat format)
: Image(device_, format),
m_image(image_)
{
setCreationTime();
}
SwapchainImage::~SwapchainImage()
{
// The parent class can not destroy the image if there's no image
m_image = nullptr;
}
void SwapchainImage::setImage(VkImage image_)
{
m_image = image_;
setCreationTime();
}
void SwapchainImage::setFormat(VkFormat format_)
{
m_format = format_;
setCreationTime();
}
} // namespace cdm
| 16.078125 | 75 | 0.683188 | WubiCookie |
f830aa215f418e783a4e7a32c67d379d189fbae3 | 19,991 | cpp | C++ | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 10 | 2017-07-06T18:47:02.000Z | 2019-03-22T04:49:41.000Z | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | null | null | null | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 6 | 2017-09-05T14:40:19.000Z | 2018-11-01T08:00:53.000Z | #include "ScoutManager.h"
#include "Bases.h"
#include "GameCommander.h"
#include "MapGrid.h"
#include "MapTools.h"
#include "Micro.h"
#include "OpponentModel.h"
#include "ProductionManager.h"
#include "The.h"
// This class is responsible for early game scouting.
// It controls any scouting worker and scouting overlord that it is given.
using namespace UAlbertaBot;
ScoutManager::ScoutManager()
: _overlordScout(nullptr)
, _workerScout(nullptr)
, _scoutStatus("None")
, _gasStealStatus("None")
, _scoutCommand(MacroCommandType::None)
, _overlordAtEnemyBase(false)
, _overlordAtBaseTarget(BWAPI::Positions::Invalid)
, _scoutUnderAttack(false)
, _tryGasSteal(false)
, _enemyGeyser(nullptr)
, _startedGasSteal(false)
, _queuedGasSteal(false)
, _gasStealOver(false)
, _previousScoutHP(0)
, _nextDestination(BWAPI::Positions::Invalid)
{
setScoutTargets();
}
ScoutManager & ScoutManager::Instance()
{
static ScoutManager instance;
return instance;
}
// Target locations are set while we are still looking for the enemy base.
// After the enemy base is found, we unset the targets and go to or ignore the enemy base as appropriate.
// If we have both an overlord and a worker, send them to search different places.
// Guarantee: We only set a target if the scout for the target is set.
void ScoutManager::setScoutTargets()
{
Base * enemyBase = the.bases.enemyStart();
if (enemyBase)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
_workerScoutTarget = BWAPI::TilePositions::Invalid;
return;
}
if (!_overlordScout)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
}
if (!_workerScout)
{
_workerScoutTarget = BWAPI::TilePositions::Invalid;
}
// Unset any targets that we have searched.
for (BWAPI::TilePosition pos : BWAPI::Broodwar->getStartLocations())
{
if (BWAPI::Broodwar->isExplored(pos))
{
// We've seen it. No need to look there any more.
if (_overlordScoutTarget == pos)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
}
if (_workerScoutTarget == pos)
{
_workerScoutTarget = BWAPI::TilePositions::Invalid;
}
}
}
// Set any target that we need to search.
for (BWAPI::TilePosition pos : BWAPI::Broodwar->getStartLocations())
{
if (!BWAPI::Broodwar->isExplored(pos))
{
if (_overlordScout && !_overlordScoutTarget.isValid() && _workerScoutTarget != pos)
{
_overlordScoutTarget = pos;
}
else if (_workerScout && !_workerScoutTarget.isValid() && _overlordScoutTarget != pos)
{
_workerScoutTarget = pos;
}
}
}
// NOTE There cannot be only one target. We found the base, or there are >= 2 possibilities.
// If there is one place left to search, then the enemy base is there and we know it,
// because InformationManager infers the enemy base position by elimination.
}
// Should we send out a worker scout now?
bool ScoutManager::shouldScout()
{
// If we're stealing gas, it doesn't matter what the scout command is: We need to send a worker.
if (wantGasSteal())
{
return true;
}
if (_scoutCommand == MacroCommandType::None)
{
return false;
}
// If we only want to find the enemy base location and we already know it, don't send a worker.
if (_scoutCommand == MacroCommandType::ScoutIfNeeded || _scoutCommand == MacroCommandType::ScoutLocation)
{
return !the.bases.enemyStart();
}
return true;
}
void ScoutManager::update()
{
// If we're not scouting now, minimum effort.
if (!_workerScout && !_overlordScout)
{
return;
}
// If a scout is gone, admit it.
if (_workerScout &&
(!_workerScout->exists() || _workerScout->getHitPoints() <= 0 || // it died (or became a zerg extractor)
_workerScout->getPlayer() != the.self())) // it got mind controlled!
{
_workerScout = nullptr;
}
if (_overlordScout &&
(!_overlordScout->exists() || _overlordScout->getHitPoints() <= 0 || // it died
_overlordScout->getPlayer() != the.self())) // it got mind controlled!
{
_overlordScout = nullptr;
}
// Release the overlord scout if the enemy has mobile or static anti-air.
if (_overlordScout && (InformationManager::Instance().enemyHasAntiAir() || overlordBlockedByAirDefense()))
{
releaseOverlordScout();
}
// If we only want to locate the enemy base and we have, release the scout worker.
if (_scoutCommand == MacroCommandType::ScoutLocation &&
the.bases.enemyStart() &&
!wantGasSteal())
{
releaseWorkerScout();
}
// If we're done with a gas steal and we don't want to keep scouting, release the worker.
// If we're zerg, the worker may have turned into an extractor. That is handled elsewhere.
if (_scoutCommand == MacroCommandType::None && _gasStealOver)
{
releaseWorkerScout();
}
// Release the worker if it can no longer help: Enemy has combat units to chase it,
// we have combat units to keep watch.
if (_workerScout &&
the.bases.enemyStart() &&
_workerScout->getDistance(the.bases.enemyStart()->getCenter()) < 40 * 32 &&
the.info.enemyHasCombatUnits() &&
friendlyUnitNear(_workerScout))
{
releaseWorkerScout();
}
// Do the actual scouting. Also steal gas if called for.
setScoutTargets();
if (_workerScout)
{
bool moveScout = true;
if (wantGasSteal()) // implies !_gasStealOver
{
if (gasSteal())
{
moveScout = false;
}
else if (_queuedGasSteal) // gas steal queued but not finished
{
// We're in the midst of stealing gas. Let BuildingManager control the worker.
moveScout = false;
_gasStealStatus = "Stealing gas";
}
}
else
{
if (_gasStealOver)
{
_gasStealStatus = "Finished or failed";
}
else
{
_gasStealStatus = "Not planned";
}
}
if (moveScout)
{
moveGroundScout();
}
}
else if (_gasStealOver)
{
// We get here if we're stealing gas as zerg when the worker turns into an extractor.
_gasStealStatus = "Finished or failed";
}
if (_overlordScout)
{
moveAirScout();
}
drawScoutInformation(200, 320);
}
// If zerg, our first overlord is used to scout immediately at the start of the game.
void ScoutManager::setOverlordScout(BWAPI::Unit unit)
{
_overlordScout = unit;
}
// The worker scout is assigned only when it is time to go scout.
void ScoutManager::setWorkerScout(BWAPI::Unit unit)
{
releaseWorkerScout();
_workerScout = unit;
WorkerManager::Instance().setScoutWorker(_workerScout);
}
// Send the worker scout home.
void ScoutManager::releaseWorkerScout()
{
if (_workerScout)
{
WorkerManager::Instance().finishedWithWorker(_workerScout);
_gasStealOver = true;
_workerScout = nullptr;
}
}
// The scouting overlord is near enemy static air defense.
bool ScoutManager::overlordBlockedByAirDefense() const
{
if (the.now() % 3 != 0) // check once each 3 frames
{
return false;
}
// Notice a turret, cannon, spore starting nearby.
BWAPI::Unit enemy = BWAPI::Broodwar->getClosestUnit(
_overlordScout->getPosition(),
BWAPI::Filter::IsEnemy && BWAPI::Filter::AirWeapon != BWAPI::WeaponTypes::None,
8 * 32
);
return enemy != nullptr;
}
// Send the overlord scout home.
void ScoutManager::releaseOverlordScout()
{
if (_overlordScout)
{
GameCommander::Instance().releaseOverlord(_overlordScout);
_overlordScout = nullptr;
}
}
void ScoutManager::setScoutCommand(MacroCommandType cmd)
{
UAB_ASSERT(
cmd == MacroCommandType::Scout ||
cmd == MacroCommandType::ScoutIfNeeded ||
cmd == MacroCommandType::ScoutLocation ||
cmd == MacroCommandType::ScoutOnceOnly,
"bad scout command");
_scoutCommand = cmd;
}
void ScoutManager::drawScoutInformation(int x, int y)
{
if (!Config::Debug::DrawScoutInfo)
{
return;
}
BWAPI::Broodwar->drawTextScreen(x, y, "Scout info: %s", _scoutStatus.c_str());
BWAPI::Broodwar->drawTextScreen(x, y+10, "Gas steal: %s", _gasStealStatus.c_str());
std::string more = "not yet";
if (_scoutCommand == MacroCommandType::Scout)
{
more = "and stay";
}
else if (_scoutCommand == MacroCommandType::ScoutLocation)
{
more = "location";
}
else if (_scoutCommand == MacroCommandType::ScoutOnceOnly)
{
more = "once around";
}
else if (_scoutCommand == MacroCommandType::ScoutWhileSafe)
{
more = "while safe";
}
else if (wantGasSteal())
{
more = "to steal gas";
}
// NOTE "go scout if needed" doesn't need to be represented here.
BWAPI::Broodwar->drawTextScreen(x, y + 20, "Go scout: %s", more.c_str());
if (_workerScout && _nextDestination.isValid())
{
BWAPI::Broodwar->drawLineMap(_workerScout->getPosition(), _nextDestination, BWAPI::Colors::Green);
}
}
// Move the worker scout.
void ScoutManager::moveGroundScout()
{
const int scoutDistanceThreshold = 30; // in tiles
if (_workerScoutTarget.isValid())
{
// The target is valid exactly when we are still looking for the enemy base.
_scoutStatus = "Seeking enemy base";
the.micro.MoveSafely(_workerScout, BWAPI::Position(_workerScoutTarget));
}
else
{
const Base * enemyBase = the.bases.enemyStart();
UAB_ASSERT(enemyBase, "no enemy base");
int scoutDistanceToEnemy = the.map.getGroundTileDistance(_workerScout->getPosition(), enemyBase->getCenter());
bool scoutInRangeOfenemy = scoutDistanceToEnemy <= scoutDistanceThreshold;
int scoutHP = _workerScout->getHitPoints() + _workerScout->getShields();
if (scoutHP < _previousScoutHP)
{
_scoutUnderAttack = true;
}
_previousScoutHP = scoutHP;
if (!_workerScout->isUnderAttack() && !enemyWorkerInRadius())
{
_scoutUnderAttack = false;
}
if (scoutInRangeOfenemy)
{
if (_scoutUnderAttack)
{
_scoutStatus = "Under attack, fleeing";
followGroundPath();
}
else
{
BWAPI::Unit closestWorker = enemyWorkerToHarass();
// If configured and reasonable, harass an enemy worker.
if (Config::Skills::ScoutHarassEnemy && closestWorker &&
!wantGasSteal() &&
_workerScout->getHitPoints() + _workerScout->getShields() > 20)
{
_scoutStatus = "Harass enemy worker";
the.micro.CatchAndAttackUnit(_workerScout, closestWorker);
}
// otherwise keep circling the enemy region
else
{
_scoutStatus = "Following perimeter";
followGroundPath();
}
}
}
// if the scout is not in the enemy region
else if (_scoutUnderAttack)
{
_scoutStatus = "Under attack, fleeing";
followGroundPath();
}
else
{
_scoutStatus = "Enemy located, going there";
followGroundPath();
}
}
}
// Explore inside the enemy base. Or, if not there yet, move toward it.
// NOTE This may release the worker scout if scouting is complete!
void ScoutManager::followGroundPath()
{
// Called only after the enemy base is found.
Base * enemyBase = the.bases.enemyStart();
if (the.zone.at(enemyBase->getTilePosition()) != the.zone.at(_workerScout->getTilePosition()))
{
// We're not there yet. Go there.
the.micro.MoveSafely(_workerScout, enemyBase->getCenter());
return;
}
// NOTE Sight range of a worker is 224, except a probe which has 256.
if (_nextDestination.isValid() && _workerScout->getDistance(_nextDestination) > 96)
{
// We're still a fair distance from the next waypoint. Stay the course.
if (Config::Debug::DrawScoutInfo)
{
BWAPI::Broodwar->drawCircleMap(_nextDestination, 3, BWAPI::Colors::Yellow, true);
BWAPI::Broodwar->drawLineMap(_workerScout->getPosition(), _nextDestination, BWAPI::Colors::Yellow);
}
the.micro.MoveSafely(_workerScout, _nextDestination);
return;
}
// We're at the enemy base and need another waypoint.
BWAPI::Position destination = the.grid.getLeastExploredNear(enemyBase->getPosition(), true);
if (destination.isValid())
{
_nextDestination = destination;
if (_scoutCommand == MacroCommandType::ScoutOnceOnly && !wantGasSteal())
{
if (BWAPI::Broodwar->isExplored(BWAPI::TilePosition(_nextDestination)))
{
releaseWorkerScout();
return;
}
}
}
else
{
_nextDestination = enemyBase->getCenter();
}
the.micro.MoveSafely(_workerScout, _nextDestination);
}
// Move the overlord scout.
void ScoutManager::moveAirScout()
{
const Base * enemyBase = the.bases.enemyStart();
if (enemyBase)
{
// We know where the enemy base is.
_overlordScoutTarget = BWAPI::TilePositions::Invalid; // it's only set while we are seeking the enemy base
if (!_overlordAtEnemyBase)
{
if (!_workerScout)
{
_scoutStatus = "Overlord to enemy base";
}
the.micro.MoveSafely(_overlordScout, enemyBase->getCenter());
if (_overlordScout->getDistance(enemyBase->getCenter()) < 8)
{
_overlordAtEnemyBase = true;
}
}
if (_overlordAtEnemyBase)
{
if (!_workerScout)
{
_scoutStatus = "Overlord at enemy base";
}
moveAirScoutAroundEnemyBase();
}
}
else
{
// We haven't found the enemy base yet.
if (!_workerScout) // give the worker priority in reporting status
{
_scoutStatus = "Overlord scouting";
}
if (_overlordScoutTarget.isValid())
{
the.micro.MoveSafely(_overlordScout, BWAPI::Position(_overlordScoutTarget));
}
}
}
// Called after the overlord has reached the enemy resource depot,
// or has been turned away from it by static defense.
void ScoutManager::moveAirScoutAroundEnemyBase()
{
const Base * enemyBase = the.bases.enemyStart();
//UAB_ASSERT(enemyBase, "no enemy base");
//UAB_ASSERT(_overlordAtEnemyBase, "not at enemy base");
if (!_overlordAtBaseTarget.isValid())
{
// Choose a new destination in or near the enemy base.
if (_overlordScout->getDistance(enemyBase->getCenter()) < 8)
{
// We're at the enemy resource depot. Choose somewhere else.
if (enemyBase->getNatural() && !enemyBase->getNatural()->isExplored())
{
enemyBase->getNatural()->getCenter();
}
else
{
_overlordAtBaseTarget = the.grid.getLeastExploredNear(enemyBase->getPosition(), false);
}
}
else
{
// We're somewhere else. Go back to the enemy resource depot.
_overlordAtBaseTarget = enemyBase->getCenter();
}
}
if (_overlordAtBaseTarget.isValid())
{
the.micro.MoveSafely(_overlordScout, _overlordAtBaseTarget);
// If we arrived, choose somewhere else next time.
if (_overlordScout->getDistance(_overlordAtBaseTarget) < 8)
{
_overlordAtBaseTarget = BWAPI::Positions::Invalid;
}
}
else
{
// We apparently can't go anywhere. Let the overlord run free.
releaseOverlordScout();
}
}
// Called only when a gas steal is requested.
// Return true to say that gas stealing controls the worker, and
// false if the caller gets control.
bool ScoutManager::gasSteal()
{
Base * enemyBase = the.bases.enemyStart();
if (!enemyBase)
{
_gasStealStatus = "Enemy base not found";
return false;
}
_enemyGeyser = getTheEnemyGeyser();
if (!_enemyGeyser || !_enemyGeyser->getInitialTilePosition().isValid())
{
// No need to set status. It will change on the next frame.
_gasStealOver = true;
return false;
}
// The conditions are met. Do it!
_startedGasSteal = true;
if (_enemyGeyser->isVisible() && _enemyGeyser->getType() != BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
// We can see the geyser and it has become something else.
// That should mean that the geyser has been taken since we first saw it.
_gasStealOver = true; // give up
// No need to set status. It will change on the next frame.
return false;
}
else if (_enemyGeyser->isVisible() && _workerScout->getDistance(_enemyGeyser) < 300)
{
// We see the geyser. Queue the refinery, if it's not already done.
// We can't rely on _queuedGasSteal to know, because the queue may be cleared
// if a surprise occurs.
// Therefore _queuedGasSteal affects mainly the debug display for the UI.
if (!ProductionManager::Instance().isGasStealInQueue())
{
// NOTE Queueing the gas steal orders the building constructed.
// Control of the worker passes to the BuildingManager until it releases the
// worker with a call to setGasStealOver().
ProductionManager::Instance().queueGasSteal();
_queuedGasSteal = true;
// Regardless, make sure we are moving toward the geyser.
// It makes life easier on the building manager.
the.micro.Move(_workerScout, _enemyGeyser->getInitialPosition());
}
_gasStealStatus = "Stealing gas";
}
else
{
// We don't see the geyser yet. Move toward it.
the.micro.MoveSafely(_workerScout, _enemyGeyser->getInitialPosition());
_gasStealStatus = "Moving to steal gas";
}
return true;
}
// Choose an enemy worker to harass, or none.
BWAPI::Unit ScoutManager::enemyWorkerToHarass() const
{
// First look for any enemy worker that is building.
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker() && unit->isConstructing())
{
return unit;
}
}
BWAPI::Unit enemyWorker = nullptr;
int maxDist = 500; // ignore any beyond this range
// Failing that, find the enemy worker closest to the gas.
BWAPI::Unit geyser = getAnyEnemyGeyser();
if (geyser)
{
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker())
{
int dist = unit->getDistance(geyser->getInitialPosition());
if (dist < maxDist)
{
maxDist = dist;
enemyWorker = unit;
}
}
}
}
return enemyWorker;
}
// Used in choosing an enemy worker to harass.
// Find an enemy geyser and return it, if there is one.
BWAPI::Unit ScoutManager::getAnyEnemyGeyser() const
{
Base * enemyBase = the.bases.enemyStart();
BWAPI::Unitset geysers = enemyBase->getGeysers();
if (geysers.size() > 0)
{
return *(geysers.begin());
}
return nullptr;
}
// Used in stealing gas. Only called after the enemy base is found.
// If there is exactly 1 geyser in the enemy base and it may be untaken, return it.
// If 0 we can't steal it, and if >1 then it's no use to steal one.
BWAPI::Unit ScoutManager::getTheEnemyGeyser() const
{
Base * enemyBase = the.bases.enemyStart();
BWAPI::Unitset geysers = enemyBase->getGeysers();
if (geysers.size() == 1)
{
BWAPI::Unit geyser = *(geysers.begin());
// If the geyser is visible, we may be able to reject it as already taken.
// TODO get the last known status from the.info.isGeyserTaken()
if (!geyser->isVisible() || geyser->getType() == BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
// We see it is untaken, or we don't see the geyser. Assume the best.
return geyser;
}
}
return nullptr;
}
// Is a friendly combat unit nearby?
bool ScoutManager::friendlyUnitNear(BWAPI::Unit unit) const
{
return
BWAPI::Broodwar->getClosestUnit(
unit->getPosition(),
BWAPI::Filter::CanAttack && BWAPI::Filter::GetPlayer == the.self() && !BWAPI::Filter::IsWorker,
6 * 32
) != nullptr;
}
bool ScoutManager::enemyWorkerInRadius()
{
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker() && unit->getDistance(_workerScout) < 300)
{
return true;
}
}
return false;
}
| 28.4367 | 113 | 0.656045 | kant2002 |
f834d86cd5a85b91413774337c3d1cabe45fd571 | 15,315 | cpp | C++ | blades/xbmc/xbmc/network/linux/ZeroconfBrowserAvahi.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/network/linux/ZeroconfBrowserAvahi.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/network/linux/ZeroconfBrowserAvahi.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "ZeroconfBrowserAvahi.h"
#ifdef HAS_AVAHI
#include <utils/log.h>
#include "guilib/GUIWindowManager.h"
#include "guilib/GUIMessage.h"
#include "GUIUserMessages.h"
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>
namespace
{
///helper RAII-struct to block event loop for modifications
struct ScopedEventLoopBlock
{
ScopedEventLoopBlock ( AvahiThreadedPoll* fp_poll ) : mp_poll ( fp_poll )
{
avahi_threaded_poll_lock ( mp_poll );
}
~ScopedEventLoopBlock()
{
avahi_threaded_poll_unlock ( mp_poll );
}
private:
AvahiThreadedPoll* mp_poll;
};
}
CZeroconfBrowserAvahi::CZeroconfBrowserAvahi() : mp_client ( 0 ), mp_poll ( 0 ), m_shutdown(false), m_thread_id(0)
{
if ( ! ( mp_poll = avahi_threaded_poll_new() ) )
{
CLog::Log ( LOGERROR, "CZeroconfAvahi::CZeroconfAvahi(): Could not create threaded poll object" );
//TODO: throw exception? can this even happen?
return;
}
if ( !createClient() )
{
CLog::Log ( LOGERROR, "CZeroconfAvahi::CZeroconfAvahi(): Could not create client" );
//yeah, what if not? but should always succeed (as client_no_fail or something is passed)
}
//start event loop thread
if ( avahi_threaded_poll_start ( mp_poll ) < 0 )
{
CLog::Log ( LOGERROR, "CZeroconfAvahi::CZeroconfAvahi(): Failed to start avahi client thread" );
}
}
CZeroconfBrowserAvahi::~CZeroconfBrowserAvahi()
{
CLog::Log ( LOGDEBUG, "CZeroconfAvahi::~CZeroconfAvahi() Going down! cleaning up..." );
if ( mp_poll )
{
//normally we would stop the avahi thread here and do our work, but
//it looks like this does not work -> www.avahi.org/ticket/251
//so instead of calling
//avahi_threaded_poll_stop(mp_poll);
//we set m_shutdown=true, post an event and wait for it to stop itself
struct timeval tv = { 0, 0 }; //TODO: does tv survive the thread?
AvahiTimeout* lp_timeout;
{
ScopedEventLoopBlock l_block(mp_poll);
const AvahiPoll* cp_apoll = avahi_threaded_poll_get(mp_poll);
m_shutdown = true;
lp_timeout = cp_apoll->timeout_new(cp_apoll,
&tv,
shutdownCallback,
this);
}
//now wait for the thread to stop
assert(m_thread_id);
pthread_join(m_thread_id, NULL);
avahi_threaded_poll_get(mp_poll)->timeout_free(lp_timeout);
}
//free the client (frees all browsers, groups, ...)
if ( mp_client )
avahi_client_free ( mp_client );
if ( mp_poll )
avahi_threaded_poll_free ( mp_poll );
}
bool CZeroconfBrowserAvahi::doAddServiceType ( const std::string& fcr_service_type )
{
ScopedEventLoopBlock lock ( mp_poll );
tBrowserMap::iterator it = m_browsers.find ( fcr_service_type );
if ( it != m_browsers.end() )
return false;
else
it = m_browsers.insert ( std::make_pair ( fcr_service_type, ( AvahiServiceBrowser* ) 0 ) ).first;
//if the client is running, we directly create a browser for the service here
if ( mp_client && avahi_client_get_state ( mp_client ) == AVAHI_CLIENT_S_RUNNING )
{
AvahiServiceBrowser* browser = createServiceBrowser ( fcr_service_type, mp_client, this);
if ( !browser )
{
m_browsers.erase ( it );
return false;
}
else
{
it->second = browser;
return true;
}
}
else
{
CLog::Log ( LOGINFO, "CZeroconfBrowserAvahi::doAddServiceType client not available. service browsing queued" );
return true;
}
}
bool CZeroconfBrowserAvahi::doRemoveServiceType ( const std::string& fcr_service_type )
{
ScopedEventLoopBlock lock ( mp_poll );
tBrowserMap::iterator it = m_browsers.find ( fcr_service_type );
if ( it == m_browsers.end() )
return false;
else
{
if ( it->second )
{
avahi_service_browser_free ( it->second );
m_all_for_now_browsers.erase ( it->second );
}
m_browsers.erase ( it );
//remove this serviceType from the list of discovered services
for ( tDiscoveredServices::iterator it = m_discovered_services.begin(); it != m_discovered_services.end(); ++it )
if ( it->first.GetType() == fcr_service_type )
m_discovered_services.erase ( it++ );
}
return true;
}
std::vector<CZeroconfBrowser::ZeroconfService> CZeroconfBrowserAvahi::doGetFoundServices()
{
std::vector<CZeroconfBrowser::ZeroconfService> ret;
ScopedEventLoopBlock lock ( mp_poll );
ret.reserve ( m_discovered_services.size() );
for ( tDiscoveredServices::iterator it = m_discovered_services.begin(); it != m_discovered_services.end(); ++it )
ret.push_back ( it->first );
return ret;
}
bool CZeroconfBrowserAvahi::doResolveService ( CZeroconfBrowser::ZeroconfService& fr_service, double f_timeout )
{
{
//wait for lock on event-loop to schedule resolving
ScopedEventLoopBlock lock ( mp_poll );
//avahi can only resolve already discovered services, as it needs info from there
tDiscoveredServices::const_iterator it = m_discovered_services.find( fr_service );
if ( it == m_discovered_services.end() )
{
CLog::Log ( LOGERROR, "CZeroconfBrowserAvahi::doResolveService called with undiscovered service, resolving is NOT possible" );
return false;
}
//start resolving
m_resolving_service = fr_service;
m_resolved_event.Reset();
if ( !avahi_service_resolver_new ( mp_client, it->second.interface, it->second.protocol,
it->first.GetName().c_str(), it->first.GetType().c_str(), it->first.GetDomain().c_str(),
AVAHI_PROTO_UNSPEC, AvahiLookupFlags ( 0 ), resolveCallback, this ) )
{
CLog::Log ( LOGERROR, "CZeroconfBrowserAvahi::doResolveService Failed to resolve service '%s': %s\n", it->first.GetName().c_str(),
avahi_strerror ( avahi_client_errno ( mp_client ) ) );
return false;
}
} // end of this block releases lock of eventloop
//wait for resolve to return or timeout
m_resolved_event.WaitMSec(f_timeout*1000);
{
ScopedEventLoopBlock lock ( mp_poll );
fr_service = m_resolving_service;
return (!fr_service.GetIP().empty());
}
}
void CZeroconfBrowserAvahi::clientCallback ( AvahiClient* fp_client, AvahiClientState f_state, void* fp_data )
{
CZeroconfBrowserAvahi* p_instance = static_cast<CZeroconfBrowserAvahi*> ( fp_data );
//store our thread ID and check for shutdown -> check details in destructor
p_instance->m_thread_id = pthread_self();
if (p_instance->m_shutdown)
{
avahi_threaded_poll_quit(p_instance->mp_poll);
return;
}
switch ( f_state )
{
case AVAHI_CLIENT_S_RUNNING:
{
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::clientCallback: client is up and running" );
for ( tBrowserMap::iterator it = p_instance->m_browsers.begin(); it != p_instance->m_browsers.end(); ++it )
{
assert ( !it->second );
it->second = createServiceBrowser ( it->first, fp_client, fp_data );
}
break;
}
case AVAHI_CLIENT_FAILURE:
{
CLog::Log ( LOGINFO, "CZeroconfBrowserAvahi::clientCallback: client failure. avahi-daemon stopped? Recreating client..." );
//We were forced to disconnect from server. now free and recreate the client object
avahi_client_free ( fp_client );
p_instance->mp_client = 0;
//freeing the client also frees all groups and browsers, pointers are undefined afterwards, so fix that now
for ( tBrowserMap::iterator it = p_instance->m_browsers.begin(); it != p_instance->m_browsers.end(); ++it )
it->second = ( AvahiServiceBrowser* ) 0;
//clean the list of discovered services and update gui (if someone is interested)
p_instance->m_discovered_services.clear();
CGUIMessage message ( GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_PATH );
message.SetStringParam ( "zeroconf://" );
g_windowManager.SendThreadMessage ( message );
p_instance->createClient();
break;
}
case AVAHI_CLIENT_S_COLLISION:
case AVAHI_CLIENT_S_REGISTERING:
//HERE WE SHOULD REMOVE ALL OF OUR SERVICES AND "RESCHEDULE" them for later addition
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::clientCallback: This should not happen" );
break;
case AVAHI_CLIENT_CONNECTING:
CLog::Log ( LOGINFO, "CZeroconfBrowserAvahi::clientCallback: avahi server not available. But may become later..." );
break;
}
}
void CZeroconfBrowserAvahi::browseCallback (
AvahiServiceBrowser *browser, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event,
const char *name, const char *type, const char *domain,
AvahiLookupResultFlags flags, void* fp_data )
{
CZeroconfBrowserAvahi* p_instance = static_cast<CZeroconfBrowserAvahi*> ( fp_data );
assert ( browser );
bool update_gui = false;
/* Called whenever a new services becomes available on the LAN or is removed from the LAN */
switch ( event )
{
case AVAHI_BROWSER_FAILURE:
CLog::Log ( LOGERROR, "CZeroconfBrowserAvahi::browseCallback error: %s\n", avahi_strerror ( avahi_client_errno ( avahi_service_browser_get_client ( browser ) ) ) );
//TODO
return;
case AVAHI_BROWSER_NEW:
{
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::browseCallback NEW: service '%s' of type '%s' in domain '%s'\n", name, type, domain );
//store the service
ZeroconfService service(name, type, domain);
AvahiSpecificInfos info;
info.interface = interface;
info.protocol = protocol;
p_instance->m_discovered_services.insert ( std::make_pair ( service, info ) );
//if this browser already sent the all for now message, we need to update the gui now
if( p_instance->m_all_for_now_browsers.find(browser) != p_instance->m_all_for_now_browsers.end() )
update_gui = true;
break;
}
case AVAHI_BROWSER_REMOVE:
{
//remove the service
ZeroconfService service(name, type, domain);
p_instance->m_discovered_services.erase ( service );
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::browseCallback REMOVE: service '%s' of type '%s' in domain '%s'\n", name, type, domain );
//if this browser already sent the all for now message, we need to update the gui now
if( p_instance->m_all_for_now_browsers.find(browser) != p_instance->m_all_for_now_browsers.end() )
update_gui = true;
break;
}
case AVAHI_BROWSER_CACHE_EXHAUSTED:
//do we need that?
break;
case AVAHI_BROWSER_ALL_FOR_NOW:
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::browseCallback all for now (service = %s)", type);
//if this browser already sent the all for now message, we need to update the gui now
bool success = p_instance->m_all_for_now_browsers.insert(browser).second;
if(!success)
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::browseCallback AVAHI_BROWSER_ALL_FOR_NOW sent twice?!");
update_gui = true;
break;
}
if ( update_gui )
{
CGUIMessage message ( GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_PATH );
message.SetStringParam ( "zeroconf://" );
g_windowManager.SendThreadMessage ( message );
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::browseCallback sent gui update for path zeroconf://" );
}
}
CZeroconfBrowser::ZeroconfService::tTxtRecordMap GetTxtRecords(AvahiStringList *txt)
{
AvahiStringList *i = NULL;
CZeroconfBrowser::ZeroconfService::tTxtRecordMap recordMap;
for( i = txt; i; i = i->next )
{
char *key, *value;
if( avahi_string_list_get_pair( i, &key, &value, NULL ) < 0 )
continue;
recordMap.insert(
std::make_pair(
std::string(key),
std::string(value)
)
);
if( key )
avahi_free(key);
if( value )
avahi_free(value);
}
return recordMap;
}
void CZeroconfBrowserAvahi::resolveCallback(
AvahiServiceResolver *r, AvahiIfIndex interface, AvahiProtocol protocol, AvahiResolverEvent event,
const char *name, const char *type, const char *domain, const char *host_name,
const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void* userdata )
{
assert ( r );
assert ( userdata );
CZeroconfBrowserAvahi* p_instance = static_cast<CZeroconfBrowserAvahi*> ( userdata );
switch ( event )
{
case AVAHI_RESOLVER_FAILURE:
CLog::Log ( LOGERROR, "CZeroconfBrowserAvahi::resolveCallback Failed to resolve service '%s' of type '%s' in domain '%s': %s\n", name, type, domain, avahi_strerror ( avahi_client_errno ( avahi_service_resolver_get_client ( r ) ) ) );
break;
case AVAHI_RESOLVER_FOUND:
{
char a[AVAHI_ADDRESS_STR_MAX];
CLog::Log ( LOGDEBUG, "CZeroconfBrowserAvahi::resolveCallback resolved service '%s' of type '%s' in domain '%s':\n", name, type, domain );
avahi_address_snprint ( a, sizeof ( a ), address );
p_instance->m_resolving_service.SetIP(a);
p_instance->m_resolving_service.SetPort(port);
//get txt-record list
p_instance->m_resolving_service.SetTxtRecords(GetTxtRecords(txt));
break;
}
}
avahi_service_resolver_free ( r );
p_instance->m_resolved_event.Set();
}
bool CZeroconfBrowserAvahi::createClient()
{
assert ( mp_poll );
if ( mp_client )
{
avahi_client_free ( mp_client );
}
mp_client = avahi_client_new ( avahi_threaded_poll_get ( mp_poll ),
AVAHI_CLIENT_NO_FAIL, &clientCallback, this, 0 );
if ( !mp_client )
{
mp_client = 0;
return false;
}
return true;
}
AvahiServiceBrowser* CZeroconfBrowserAvahi::createServiceBrowser ( const std::string& fcr_service_type, AvahiClient* fp_client, void* fp_userdata)
{
assert(fp_client);
AvahiServiceBrowser* ret = avahi_service_browser_new ( fp_client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, fcr_service_type.c_str(),
NULL, ( AvahiLookupFlags ) 0, browseCallback, fp_userdata );
if ( !ret )
{
CLog::Log ( LOGERROR, "CZeroconfBrowserAvahi::createServiceBrowser Failed to create service (%s) browser: %s",
avahi_strerror ( avahi_client_errno ( fp_client ) ), fcr_service_type.c_str() );
}
return ret;
}
void CZeroconfBrowserAvahi::shutdownCallback(AvahiTimeout *fp_e, void *fp_data)
{
CZeroconfBrowserAvahi* p_instance = static_cast<CZeroconfBrowserAvahi*>(fp_data);
//should only be called on shutdown
if (p_instance->m_shutdown)
{
avahi_threaded_poll_quit(p_instance->mp_poll);
}
}
#endif //HAS_AVAHI
| 36.903614 | 239 | 0.685472 | krattai |
f83956db74d79cb7106e8f6c9cfb6716adfaaea0 | 987 | hpp | C++ | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 15 | 2020-07-13T03:51:10.000Z | 2022-03-16T13:56:28.000Z | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 2 | 2021-01-07T20:31:29.000Z | 2021-12-15T21:20:34.000Z | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 4 | 2020-08-15T01:52:31.000Z | 2022-03-16T13:56:30.000Z | #ifndef PlaylistsPage_HPP_
#define PlaylistsPage_HPP_
#include "src/utils/BasePage.hpp"
#include "src/parser/models/StorageData.hpp"
#include "src/parser/models/VideoMetadata.hpp"
#include "src/models/PlaylistVideoModel.hpp"
#include "src/models/PlaylistListItemModel.hpp"
#include <bb/cascades/Page>
#include <bb/cascades/ListView>
#include <bb/cascades/NavigationPane>
#include <QVariantList>
class PlaylistsPage: public BasePage
{
Q_OBJECT
private slots:
void onPlaylistsListItemClick(QVariantList indexPath);
void onPlaylistVideoAdded(PlaylistVideoModel* video);
void onPlaylistVideoDeleted(QString videoId, PlaylistListItemModel::Type playlistType);
void onPlaylistVideoDeletedAll(PlaylistListItemModel::Type playlistType);
private:
bb::cascades::ListView *playlistsList;
public:
PlaylistsPage(bb::cascades::NavigationPane *navigationPane);
virtual ~PlaylistsPage()
{
}
void playVideo(QString videoId);
};
#endif /* PlaylistsPage_HPP_ */
| 29.029412 | 91 | 0.787234 | AlexeyGurevsky |
f83b0fd5ac67bf7a21b3d1fdc11ea2010feecdf9 | 3,010 | cpp | C++ | src/world/Scene.cpp | jensmcatanho/iris | 0334bc0ec34be4a6702462480b6452fcc2d1172c | [
"MIT"
] | 2 | 2019-10-23T01:03:39.000Z | 2020-03-31T18:59:16.000Z | src/world/Scene.cpp | jensmcatanho/iris | 0334bc0ec34be4a6702462480b6452fcc2d1172c | [
"MIT"
] | 2 | 2016-11-02T10:41:02.000Z | 2017-07-19T01:41:33.000Z | src/world/Scene.cpp | jensmcatanho/iris | 0334bc0ec34be4a6702462480b6452fcc2d1172c | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2016-2017 Jean Michel Catanho
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 "Scene.h"
#include "Ambient.h"
#include "Object.h"
#include "Ray.h"
#include "Sampler.h"
#include "Surface.h"
#include "Tracer.h"
Scene::Scene() :
m_BackgroundColor(RGBColor::Black),
m_AmbientPtr(new Ambient),
m_CameraPtr(nullptr),
m_TracerPtr(nullptr) {
m_Pixels = new RGBColor[m_ProjectionPlane.m_Width * m_ProjectionPlane.m_Height];
}
void Scene::DisplayPixel(const int row, const int column, const RGBColor &raw_color) const {
RGBColor mapped_color;
if (m_ProjectionPlane.m_ClampOutOfGamut)
mapped_color = RGBColor::ClampToColor(raw_color, m_ProjectionPlane.m_ClampColor);
else
mapped_color = RGBColor::MaxToOne(raw_color);
if (m_ProjectionPlane.m_Gamma != 1.0)
mapped_color = RGBColor(glm::pow(mapped_color.r, m_ProjectionPlane.m_InvGamma),
glm::pow(mapped_color.g, m_ProjectionPlane.m_InvGamma),
glm::pow(mapped_color.b, m_ProjectionPlane.m_InvGamma));
m_Pixels[row * m_ProjectionPlane.m_Width + column].r = mapped_color.r;
m_Pixels[row * m_ProjectionPlane.m_Width + column].g = mapped_color.g;
m_Pixels[row * m_ProjectionPlane.m_Width + column].b = mapped_color.b;
}
Surface Scene::HitObjects(const Ray &ray) {
Surface sr(*this);
double t;
double tmin = kHugeValue;
glm::vec3 normal;
glm::vec3 local_hit_point;
int num_objects = m_Objects.size();
for (int i = 0; i < num_objects; i++)
if (m_Objects[i]->Hit(ray, t, sr) && (t < tmin)) {
sr.m_Hit = true;
tmin = t;
sr.m_MaterialPtr = m_Objects[i]->GetMaterial();
sr.m_HitPoint = ray.m_Origin + static_cast<float>(t) * ray.m_Direction;
normal = sr.m_Normal;
local_hit_point = sr.m_LocalHitPoint;
}
if (sr.m_Hit) {
sr.m_T = tmin;
sr.m_Normal = normal;
sr.m_LocalHitPoint = local_hit_point;
}
return sr;
}
| 33.820225 | 92 | 0.711296 | jensmcatanho |
f840bced7bf2ee6717187698f544317555047880 | 55,779 | cpp | C++ | @VyperLogixProjects/@workspace_fb46/as3gullinburstilibs/raw/wxChecksums-1.2.0/src/lvwSums.cpp | raychorn/svn_Flash_Builder_4 | 17069d420d5d9b9635738d4ce40395d85213e785 | [
"CC0-1.0"
] | null | null | null | @VyperLogixProjects/@workspace_fb46/as3gullinburstilibs/raw/wxChecksums-1.2.0/src/lvwSums.cpp | raychorn/svn_Flash_Builder_4 | 17069d420d5d9b9635738d4ce40395d85213e785 | [
"CC0-1.0"
] | null | null | null | @VyperLogixProjects/@workspace_fb46/as3gullinburstilibs/raw/wxChecksums-1.2.0/src/lvwSums.cpp | raychorn/svn_Flash_Builder_4 | 17069d420d5d9b9635738d4ce40395d85213e785 | [
"CC0-1.0"
] | null | null | null | /*
* wxChecksums
* Copyright (C) 2003-2004 Julien Couot
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* \file lvwSums.cpp
* A personalized listview to display information about checksums.
*/
//---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
// Include your minimal set of headers here, or wx.h
#include <wx/wx.h>
#endif
#if wxUSE_DRAG_AND_DROP
#include <wx/dnd.h>
#endif // wxUSE_DRAG_AND_DROP
#include <wx/datetime.h>
#include <wx/imaglist.h>
#include "lvwSums.hpp"
#include "dlgAddMatchFiles.hpp"
#include "dlgInvalidFiles.hpp"
#include "dlgProgress.hpp"
#include "appprefs.hpp"
#include "bytedisp.hpp"
#include "checksumutil.hpp"
#include "comdefs.hpp"
#include "fileutil.hpp"
#include "fdftlmk.hpp"
#include "osdep.hpp"
#include "sumfile.hpp"
#include "utils.hpp"
#include "bitmaps/lvw_sums_notverified.xpm"
#include "bitmaps/lvw_sums_verified.xpm"
#include "bitmaps/lvw_sums_invalid.xpm"
#include "bitmaps/lvw_sums_notfound.xpm"
#include "bitmaps/hi16_action_fileadd.xpm"
#include "bitmaps/hi16_action_directoryadd.xpm"
#include "bitmaps/hi16_action_addmatchingfiles.xpm"
#include "bitmaps/hi16_action_fileremove.xpm"
#include "compat.hpp"
//---------------------------------------------------------------------------
/// The C++ standard namespace.
using namespace std;
/*
* Defines a custom event for files dropping from the explorer or a file
* manager.
*
* On Windows the Explorer waits that DndCheckSumListView::OnDropFiles()
* return a value that could be long if the checksums are proceeded.
* So DndCheckSumListView::OnDropFiles() post a EVT_DNDFILES_COMMAND
* event and the checksums list adds itself the files.
*/
BEGIN_DECLARE_EVENT_TYPES()
DECLARE_EVENT_TYPE(EVENT_DNDFILES_COMMAND, 10001)
END_DECLARE_EVENT_TYPES()
DEFINE_EVENT_TYPE(EVENT_DNDFILES_COMMAND)
/*
* Defines a custom event for updating the dialog title.
* Use this event when a child want the dialog title to be updated.
*/
DEFINE_LOCAL_EVENT_TYPE(EVENT_UPDATE_SUMS_FRAME_TITLE_COMMAND)
/*
* Defines a custom event for updating the status bar.
* Use this event when a child want the dialog status bar to be updated.
*/
DEFINE_LOCAL_EVENT_TYPE(EVENT_UPDATE_SUMS_FRAME_STATUSBAR_COMMAND)
/*
* Defines a custom event for adding a file in the open recently file list.
*/
DEFINE_LOCAL_EVENT_TYPE(EVENT_OPEN_RECENT_ADD_FILE)
//###########################################################################
// A custom drop target which accepts files
//###########################################################################
#if wxUSE_DRAG_AND_DROP
/**
* Drop target which accepts files for the checksums list.
*/
class DndCheckSumListView : public wxFileDropTarget
{
public:
// Constructor.
DndCheckSumListView(ChecksumsListView *pOwner);
// Event handler for dropped file of the list.
virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames);
private:
ChecksumsListView* owner; ///< Owner list of this object.
};
//---------------------------------------------------------------------------
/**
* Constructor.
*
* @param pOwner Adress of the list which owns this drop target.
*/
DndCheckSumListView::DndCheckSumListView(ChecksumsListView *pOwner)
{
owner = pOwner;
}
//---------------------------------------------------------------------------
/**
* Event handler for dropped file of the list.
*
* Posts an EVENT_DNDFILES_COMMAND event. The owner MUST register the
* EVENT_DNDFILES_COMMAND event and delete the array pointed by the client data
* member.
*
* @param x The x coordinate of the mouse.
* @param y The y coordinate of the mouse.
* @param filenames An array of filenames.
*/
bool DndCheckSumListView::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames)
{
if (owner != NULL)
{
// owner->addFiles(filenames); // old method. Freeze explorer on Windows.
wxArrayString* f = new wxArrayString(filenames);
wxCommandEvent event(EVENT_DNDFILES_COMMAND);
event.SetClientData(f);
owner->AddPendingEvent(event);
}
return true;
}
//---------------------------------------------------------------------------
#endif // wxUSE_DRAG_AND_DROP
//###########################################################################
// A progression updater for the ChecksumFileCalculator class
//###########################################################################
/**
* Displays the progression of the process of computing of a checksum.
*/
class ChecksumsListView::ChecksumProgress : public ::ChecksumProgress
{
protected:
wxString fileName; ///< Name of the current file.
wxString msg; ///< Message to display.
BytesDisplayer current; ///< numbers of preceeded bytes.
double dTotal; ///< Total of bytes to process.
wxString sTotal; ///< Total of bytes to process.
int p; ///< Progress in %.
wxTimeSpan timeSpan; ///< Time between to updates of the progress dialog.
wxDateTime lt; ///< Last saved time.
wxDateTime ct; ///< Current time.
dlgProgress* progress; ///< Progress dialog.
int maxProgress; ///< Maximal value of the progress dialog.
int maxProgressM1; ///< Maximal value of the progress dialog - 1.
double maxProgressD; ///< Maximal value of the progress dialog (double).
/// Default constructor. Don't call it.
ChecksumProgress() { init(); };
// Initializes the instance.
void init();
public:
// Constructor.
ChecksumProgress(const wxString& message, const wxString& title, wxWindow* parent, const BytesDisplayer& total);
// Destructor.
virtual ~ChecksumProgress();
// Updates the progression of the computing of a checksum.
virtual void update(size_t read, bool& canceled);
// Indicates that the process is finished (hides the progress dialog).
void finished();
// Gets the current file that is processed.
wxString getFileName() const;
// Sets the current file that is processed.
void setFileName(const wxString& curFileName);
};
//---------------------------------------------------------------------------
/**
* Initializes the instance.
*/
void ChecksumsListView::ChecksumProgress::init()
{
progress = NULL;
}
//---------------------------------------------------------------------------
/**
* Constructor.
*
* @param message Message that will be displayed in the progress dialog.
* It should have the following from :
* "Proceeding %s, %s on %s read."
* @param title Title of the progress dialog.
* @param parent Parent of the progress dialog.
* @param total Total of bytes to process.
*/
ChecksumsListView::ChecksumProgress::ChecksumProgress(const wxString& message, const wxString& title, wxWindow* parent, const BytesDisplayer& total)
{
init();
msg = message;
dTotal = total.toDouble(BytesDisplayer::byte);
sTotal = total.toString();
maxProgress = SHRT_MAX;
maxProgressM1 = maxProgress - 1;
maxProgressD = static_cast<double>(maxProgress);
timeSpan = wxTimeSpan(0, 0, 0, UPDATE_PROGRESS_DLG);
lt = wxDateTime::UNow() - timeSpan;
progress = new dlgProgress(title, _("Beginning..."), maxProgress, parent,
wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);
}
//---------------------------------------------------------------------------
/**
* Destructor.
*/
ChecksumsListView::ChecksumProgress::~ChecksumProgress()
{
if (progress != NULL)
{
delete progress;
progress = NULL;
}
}
//---------------------------------------------------------------------------
/**
* Updates the progression of the computing of a checksum.
*
* @param read Number of bytes read.
* @param canceled Set it to <CODE>true</CODE> if the user want to cancel
* the calculation. The caller should call it with its value
* set to <CODE>false</CODE>.
*/
void ChecksumsListView::ChecksumProgress::update(size_t read, bool& canceled)
{
current += static_cast<unsigned long>(read);
p = (dTotal != 0.0) ? static_cast<int>(current.toDouble(BytesDisplayer::byte) * maxProgressD / dTotal) : maxProgress;
if (p >= maxProgress)
p = maxProgressM1;
ct = wxDateTime::UNow();
if (ct.IsLaterThan(lt))
{
canceled = !progress->Update(p, wxString::Format(msg, fileName.c_str(), current.toString().c_str(), sTotal.c_str()));
::wxYield();
lt = ct + timeSpan;
}
// Pause ?
while (progress->isPaused())
::wxYield();
}
//---------------------------------------------------------------------------
/**
* Indicates that the process is finished (hides the progress dialog).
*/
void ChecksumsListView::ChecksumProgress::finished()
{
progress->Update(maxProgress, _("Finished"));
}
//---------------------------------------------------------------------------
/**
* Gets the current file that is processed.
*
* @return The current file that is processed.
*/
wxString ChecksumsListView::ChecksumProgress::getFileName() const
{
return fileName;
}
//---------------------------------------------------------------------------
/**
* Sets the current file that is processed.
*
* @param curFileName New name of the current file which is processed.
*/
void ChecksumsListView::ChecksumProgress::setFileName(const wxString& curFileName)
{
fileName = curFileName;
}
//---------------------------------------------------------------------------
//###########################################################################
// ChecksumsListView methods
//###########################################################################
IMPLEMENT_DYNAMIC_CLASS(ChecksumsListView, wxListView)
/**
* Default constructor.
*/
ChecksumsListView::ChecksumsListView() : wxListView()
{
init();
sumFile = NULL;
}
//---------------------------------------------------------------------------
/**
* Constructor, creating and showing a list control.
*
* @param parent Parent window. Must not be <CODE>NULL</CODE>.
* @param id Window identifier. A value of <CODE>-1</CODE> indicates a
* default value.
* @param checksumFile The checksum file linked with this listview.
* @param pos Window position.
* @param size Window size. If the default size <CODE>(-1, -1)</CODE> is
* specified then the window is sized appropriately.
* @param style Window style. See <I>wxListCtrl</I>.
* @param validator Window validator.
* @param name Window name.
*/
ChecksumsListView::ChecksumsListView(wxWindow* parent, wxWindowID id,
SumFile* checksumFile, const wxPoint& pos,
const wxSize& size, long style,
const wxValidator& validator,
const wxString& name) :
wxListView(parent, id, pos, size, style, validator, name)
{
init();
sumFile = checksumFile;
}
//---------------------------------------------------------------------------
/**
* Destructor.
*/
ChecksumsListView::~ChecksumsListView()
{
if (sumFile != NULL)
{
delete sumFile;
sumFile = NULL;
}
}
//---------------------------------------------------------------------------
/**
* Initializes the list parameters.
*/
void ChecksumsListView::init()
{
// Creates an image list for this listview.
// Order and index should corresponds to ChecksumData::State
wxImageList* imlStateIcons = new wxImageList(16, 16);
imlStateIcons->Add(wxIcon(lvw_sums_notverified_xpm));
imlStateIcons->Add(wxIcon(lvw_sums_verified_xpm));
imlStateIcons->Add(wxIcon(lvw_sums_invalid_xpm));
imlStateIcons->Add(wxIcon(lvw_sums_notfound_xpm));
setColumnToSort(0, NONE);
AssignImageList(imlStateIcons, wxIMAGE_LIST_SMALL);
#if wxUSE_DRAG_AND_DROP
SetDropTarget(new DndCheckSumListView(this));
#endif // wxUSE_DRAG_AND_DROP
columns[0] = FILE_NAME;
columns[1] = DIRECTORY;
columns[2] = CHECKSUM_VALUE;
columns[3] = STATE;
InsertColumn(0, getColumnName(columns[0]), wxLIST_FORMAT_LEFT);
InsertColumn(1, getColumnName(columns[1]), wxLIST_FORMAT_LEFT);
InsertColumn(2, getColumnName(columns[2]), wxLIST_FORMAT_LEFT);
InsertColumn(3, getColumnName(columns[3]), wxLIST_FORMAT_LEFT);
}
//---------------------------------------------------------------------------
/**
* Gets to sort order.
*
* @return The sort order.
*/
ChecksumsListView::SortOrder ChecksumsListView::getSortOrder() const
{
return sortOrder;
}
//---------------------------------------------------------------------------
/**
* Sets the sort order.
*
* @param newSortOrder New sort order. Must be <CODE>ASCENDING</CODE> or
* <CODE>DESCENDING</CODE>. If other value is given,
* <CODE>ASCENDING</CODE> is assumed by default.
*/
void ChecksumsListView::setSortOrder(const SortOrder newSortOrder)
{
switch (newSortOrder)
{
case NONE :
case ASCENDING :
case DESCENDING :
sortOrder = newSortOrder;
break;
default :
sortOrder = NONE;
}
}
//---------------------------------------------------------------------------
/**
* Gets the column to be sorted
*
* @return The column to be sorted.
*/
int ChecksumsListView::getColumnToSort() const
{
return colToSort;
}
//---------------------------------------------------------------------------
/**
* Sets the column to be sorted.
*
* @param col The column with witch the sort will be done. If the given
* column is invalid, the first column of the list will be taken.
*/
void ChecksumsListView::setColumnToSort(const int col)
{
if (col >= 0 && col < GetColumnCount())
colToSort = col;
else
colToSort = 0;
}
//---------------------------------------------------------------------------
/**
* Sets the column to be sorted.
*
* @param col The column with witch the sort will be done.
* @param newSortOrder New sort order.
* @see getSortOrder(), setColumnToSort(int)
*/
void ChecksumsListView::setColumnToSort(const int col, const SortOrder newSortOrder)
{
setColumnToSort(col);
setSortOrder(newSortOrder);
}
//---------------------------------------------------------------------------
/**
* List compare function.
*
* <B>Warning :</B> this is a quick&dirty fonction, where a pointer
* on a ChecksumsListView class is passed in a parameter with the long type.
*
* @param item1 data on the first item.
* @param item2 data on the second item.
* @param sortData adress of the wallpaper list (yerk !)
*/
static int wxCALLBACK SumListCompareFnct(long item1, long item2, long sortData)
{
ChecksumsListView* pList = reinterpret_cast<ChecksumsListView*>(sortData);
// Gets the checksum data of the items
ChecksumData cd1 = pList->getSumFile()->getChecksumData(item1);
ChecksumData cd2 = pList->getSumFile()->getChecksumData(item2);
// Gets the sort parameters
int colToSort = pList->getColumnToSort();
ChecksumsListView::SortOrder sortOrder = pList->getSortOrder();
// Compare the items.
if (sortOrder == ChecksumsListView::NONE)
// Compare the keys
return item1 - item2;
int res;
ChecksumsListView::Columns cols[LVW_SUMS_NBCOLS];
pList->getColumns(cols);
switch (cols[colToSort])
{
case ChecksumsListView::FILE_NAME :
res = ::compareFileName(cd1.getFileName().GetFullName(), cd2.getFileName().GetFullName());
break;
case ChecksumsListView::DIRECTORY : {
wxFileName fn1 = cd1.getFileName();
wxFileName fn2 = cd2.getFileName();
wxFileName sumFileName = pList->getSumFile()->getFileName();
if (AppPrefs::get()->readBool(prGUI_MAIN_SUMS_DIRSINABSOLUTEPATH))
{
if (fn1.IsRelative())
fn1.MakeAbsolute(sumFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
if (fn2.IsRelative())
fn2.MakeAbsolute(sumFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
}
else
{
if (fn1.IsAbsolute())
fn1.MakeRelativeTo(sumFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
if (fn2.IsAbsolute())
fn2.MakeRelativeTo(sumFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
}
res = ::compareFileName(fn1.GetPath(wxPATH_GET_VOLUME), fn2.GetPath(wxPATH_GET_VOLUME)); }
break;
case ChecksumsListView::CHECKSUM_VALUE :
res = cd1.getChecksum().Cmp(cd2.getChecksum());
break;
case ChecksumsListView::STATE :
res = static_cast<int>(cd1.getState()) - static_cast<int>(cd2.getState());
break;
}
if (sortOrder == ChecksumsListView::DESCENDING)
res = -res;
return res;
}
//---------------------------------------------------------------------------
/**
* Sort the list.
*/
void ChecksumsListView::sort()
{
if (this->getSumFile() != NULL)
{
wxBusyCursor wait;
this->Freeze();
this->SortItems(SumListCompareFnct, reinterpret_cast<long>(this));
this->Thaw();
}
}
//---------------------------------------------------------------------------
/**
* Gets a pointer on the checksum file.
*
* @return A pointer on the checksum file.
*/
SumFile* ChecksumsListView::getSumFile() const
{
return sumFile;
}
//---------------------------------------------------------------------------
/**
* Sets the checksum file.
*
* - Deletes the old checksums' file instance in memory.
* - Deletes all the items.
* - Creates new item from the given checksums file if not <CODE>NULL</CODE>.
*
* @param pSumFile A pointer on the new checksums file.
* @remarks The given <CODE>SumFile*</CODE> instance will be deleted by this
* class.
*/
void ChecksumsListView::setSumFile(SumFile* pSumFile)
{
// If sums file is the same do nothing.
if (sumFile == pSumFile)
return;
if (sumFile != NULL)
delete sumFile;
this->DeleteAllItems();
sumFile = pSumFile;
if (sumFile != NULL)
{
MChecksumDataKeys keys;
sumFile->getChecksumDataKeys(keys);
size_t i, l = keys.GetCount();
for (i = 0; i < l; i++)
addChecksum(keys[i], _("Not verified"));
}
// Sort the list.
sort();
}
//---------------------------------------------------------------------------
/**
* Selects all the items.
*/
void ChecksumsListView::selectAll()
{
int state;
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
while (item != -1)
{
state = this->GetItemState(item, wxLIST_STATE_SELECTED);
if (!(state & wxLIST_STATE_SELECTED))
this->SetItemState(item, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
item = this->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
}
}
//---------------------------------------------------------------------------
/**
* Inverts the selection.
*/
void ChecksumsListView::invertSelection()
{
int state;
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
while (item != -1)
{
state = this->GetItemState(item, wxLIST_STATE_SELECTED);
state = ~state;
this->SetItemState(item, state, wxLIST_STATE_SELECTED);
item = this->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
}
}
//---------------------------------------------------------------------------
/**
* Open a dialog to select the files to add to the list.
*/
void ChecksumsListView::selectFilesToAdd()
{
if (this->getSumFile() != NULL)
{
// Show the open dialog
wxFileDialogFilterMaker fltMaker;
fltMaker.AddFilter(_("All the files"), wxT("*"));
wxFileDialog dlgOpen(this, _("Select the files to be added"),
wxEmptyString, wxEmptyString, fltMaker.GetFilters(),
wxOPEN | wxHIDE_READONLY | wxMULTIPLE | wxFILE_MUST_EXIST, wxDefaultPosition);
wxFileName direct(wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
if (direct.DirExists())
dlgOpen.SetDirectory(direct.GetFullPath());
if (dlgOpen.ShowModal() == wxID_OK)
{
wxArrayString files;
dlgOpen.GetPaths(files);
this->addFiles(files);
}
}
}
//---------------------------------------------------------------------------
/**
* Open a dialog to select the directories to add to the list.
*/
void ChecksumsListView::selectDirectoriesToAdd()
{
if (this->getSumFile() != NULL)
{
// Show the open dialog
wxDirDialog dlgDir(this, _("Select the directory"));
wxFileName direct(wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
if (direct.DirExists())
dlgDir.SetPath(direct.GetFullPath());
if (dlgDir.ShowModal() == wxID_OK)
{
wxArrayString files;
files.Add(dlgDir.GetPath());
this->addFiles(files);
}
}
}
//---------------------------------------------------------------------------
/**
* Open a dialog to select files to add from matching patterns.
*/
void ChecksumsListView::selectMatchingFilesToAdd()
{
if (this->getSumFile() != NULL)
{
dlgAddMatchFiles dlg(this, this->getSumFile()->getFileName());
if (dlg.ShowModal() == wxID_OK)
{
// Gets the patterns
size_t i;
dlgAddMatchFiles::ArrayMatchPattern patterns;
dlg.getMatchPatterns(patterns);
if (patterns.getCount() > 0)
{
wxFileName checksum(getSumFile()->getFileName());
dlgAddMatchFiles::ArrayMatchPattern pats;
for (i = 0; i < patterns.getCount(); i++)
{
// Get a beautiful directory name and remove some possible multiple
// same patterns.
wxFileName fn(patterns[i].getDirectory() + wxFileName::GetPathSeparator());
if (fn.IsRelative())
// Make it absolute
{
fn.MakeAbsolute(checksum.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
pats.add(dlgAddMatchFiles::MatchPattern(fn.GetPath(wxPATH_GET_VOLUME), patterns[i].getPattern(), patterns[i].getDepth()));
}
else
{
fn.MakeRelativeTo(checksum.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
fn.MakeAbsolute(checksum.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
pats.add(dlgAddMatchFiles::MatchPattern(fn.GetPath(wxPATH_GET_VOLUME), patterns[i].getPattern(), patterns[i].getDepth()));
}
}
wxArrayString files;
BytesDisplayer bs;
bool cont = true;
i = 0;
while (cont && i < pats.getCount())
{
wxArrayString lFiles;
lFiles.Add(pats[i].getDirectory());
cont = ::getFilesInSubdirectories(lFiles, files, bs,
pats[i].getPattern(),
pats[i].getDepth());
i++;
}
if (cont)
addFiles(files);
}
}
}
}
//---------------------------------------------------------------------------
/**
* Adds files to the list of checksums.
*
* This function will search recursively files in subdirectories.
* All the files and all the directories that are provided in the array
* must be in absolute path.
*
* @param files A list of files and directories to add.
*/
void ChecksumsListView::addFiles(const wxArrayString& files)
{
if (this->getSumFile() == NULL || files.IsEmpty())
return;
// No log
wxLogNull logNo;
// Search the files in the subdirectories.
wxArrayString allFiles;
BytesDisplayer total;
if (!::getFilesInSubdirectories(files, allFiles, total))
return;
if (allFiles.IsEmpty())
// No files to add, exiting
return;
this->Freeze();
// Adds the checksums
InvalidFilesContainer invalidFiles; // all the invalid files.
wxString sumFilePath = wxFileName(getSumFile()->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
Checksum* c = sumFile->getChecksumCalculator(); // checksum calculator
wxFileName fn; // name of the current file
ChecksumFileCalculator::State retState; // state returned by the checksum' calculator.
wxString calcSumValue; // Calculated checksum's value
bool cont = true; // continue ?
// Removes the files that are already in the list.
// wxArrayString in;
cont = removeFilesInList(allFiles/*, &in*/);
/* if (in.GetCount() > 0) // For debug only
{
for (size_t i = 0; i < in.GetCount(); i++)
invalidFiles[in[i]] = _("Already in the list");
}*/
// Show the progress dialog
ChecksumProgress progressUpdater(_("Computing the checkum of %s\n%s on %s read."), _("Computing the checksums"), this, total);
ChecksumFileCalculator cfc(c, &progressUpdater);
size_t i = 0;
size_t l = allFiles.GetCount();
while (i < l && cont)
{
wxString& curFile = allFiles[i];
fn = curFile;
// Compute the checksum.
progressUpdater.setFileName(fn.GetFullName());
retState = cfc.calculate(curFile, calcSumValue);
switch (retState)
{
case ChecksumFileCalculator::Ok : // Checksum has been calculated (and corresponds for the check method).
{
fn.MakeRelativeTo(sumFilePath);
ChecksumData d(fn, calcSumValue, ChecksumData::Verified);
long k = this->getSumFile()->addChecksumData(d);
this->addChecksum(k, _("OK"));
}
break;
case ChecksumFileCalculator::ReadError : // Error while reading the stream.
invalidFiles[curFile] = _("Error while reading the file");
break;
case ChecksumFileCalculator::FileNotFound : // The file has been not found.
invalidFiles[curFile] = _("File not found");
break;
case ChecksumFileCalculator::CantOpenFile : // Can't open the stream.
invalidFiles[curFile] = _("File cannot be open");
break;
case ChecksumFileCalculator::CanceledByUser : // User has canceled the calculation.
cont = false;
break;
}
i++;
}
delete c;
progressUpdater.finished();
this->Thaw();
// Sort the list
sort();
if (!invalidFiles.empty())
{
dlgInvalidFiles dlg(this, _("Invalid files"),
_("The following files were not added to the list of the checksums:"), invalidFiles);
dlg.ShowModal();
}
}
//---------------------------------------------------------------------------
/**
* Compare function for <CODE>removeFilesInList</CODE>.
*
* For internal use only.
* For more information, see <CODE>wxArrayString::Sort</CODE> in the wxWidgets
* documentation.
*/
static int removeFilesInListCompare(const wxString& first, const wxString& second)
{
return ::compareFileName(first, second);
}
//---------------------------------------------------------------------------
/**
* Removes the files that are already in the listview.
*
* @param files List of files to be checked. The files already present in
* the listview will be removed list of <CODE>files</CODE>.
* @param in Pointer on an array string where the files already present in
* the listview will be stored. Could be <CODE>NULL</CODE>.
* @return <CODE>true</CODE> if the user hasn't canceled.
*/
bool ChecksumsListView::removeFilesInList(wxArrayString& files, wxArrayString* in)
{
if (sumFile->getChecksumDataCount() == 0 && files.IsEmpty())
return true;
wxArrayString lFiles; // Files in the listview
wxFileName fn;
bool cont = true;
wxString sumFilePath = wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
MChecksumData::const_iterator it = sumFile->getChecksumDataBegin();
MChecksumData::const_iterator end = sumFile->getChecksumDataEnd();
// Get the files in the list
lFiles.Alloc(sumFile->getChecksumDataCount() + files.GetCount());
while (it != end)
{
fn = it->second.getFileName();
if (!fn.IsAbsolute())
fn.MakeAbsolute(sumFilePath);
lFiles.Add(fn.GetFullPath());
it++;
}
dlgProgress dlgProgress(_("Checking for duplicate files"), _("Beginning..."), 100, this,
wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);
lFiles.Sort(removeFilesInListCompare);
wxTimeSpan timeSpan(0, 0, 0, UPDATE_PROGRESS_DLG);
wxDateTime lt = wxDateTime::UNow() - timeSpan; // last saved time
wxDateTime ct; // current time
// Search for the present files
size_t i = 0;
int r, a, b;
while (cont && i < files.GetCount())
{
fn = files[i];
fn.Normalize(wxPATH_NORM_ALL, sumFilePath);
wxString s = fn.GetFullPath();
int c = -1;
a = 0;
b = lFiles.GetCount() - 1;
r = (a + b) / 2;
while ((a < b) && (r >= 0) && (r < lFiles.GetCount()) && ((c = ::compareFileName(s, lFiles[r])) != 0))
{
if (c < 0)
b = r - 1;
else
a = r + 1;
r = (a + b) / 2;
}
if ((r >= 0) && (r < lFiles.GetCount()) && ::compareFileName(s, lFiles[r]) == 0)
{
if (in != NULL)
in->Add(s);
files.Remove(i);
}
else
{
// To avoid to add files likes /dir1/dir2/file1 and /dir1/dir2/../dir2/file1
if (r < 0) r = 0;
if (!lFiles.IsEmpty() && r >= lFiles.GetCount()) r = lFiles.GetCount() - 1;
while (r > 0 && ::compareFileName(s, lFiles[r]) < 0)
r--;
while (r < lFiles.GetCount() && ::compareFileName(s, lFiles[r]) >= 0)
r++;
lFiles.Insert(s, r);
/* Reference for debugging
lFiles.Add(s);
lFiles.Sort(removeFilesInListCompare); */
i++;
}
// Upadate the progress dialog
ct = wxDateTime::UNow();
if (ct.IsLaterThan(lt))
{
int p; // progress value (0-100)
lt = ct + timeSpan;
size_t fc = files.GetCount();
if (fc > 0)
p = static_cast<int>((static_cast<double>(i) / static_cast<double>(fc)) * 100.0);
else
p = 100;
if (p >= 100) p = 99;
cont = dlgProgress.Update(p, wxString::Format(_("Checking %s"), s.c_str()));
::wxYield();
}
// Pause ?
while (dlgProgress.isPaused())
::wxYield();
}
files.Shrink();
dlgProgress.Update(100, wxString::Format(_("Finished."), files[i].c_str()));
return cont;
}
//---------------------------------------------------------------------------
/**
* Indicates if the specified file is present in the list.
*
* The given file name must be an absolute path.
*
* @param fileName File name to test the presence in the list.
* @return <CODE>true</CODE> if the file is present in the list,
* <CODE>false</CODE> otherwise.
*/
bool ChecksumsListView::isInList(const wxString& fileName)
{
bool found = false;
wxFileName fn;
wxString sumFilePath = wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
MChecksumData::const_iterator it = sumFile->getChecksumDataBegin();
MChecksumData::const_iterator end = sumFile->getChecksumDataEnd();
while (!found && it != end)
{
fn = it->second.getFileName();
fn.MakeAbsolute(sumFilePath);
if (::compareFileName(fn.GetFullPath(), fileName) == 0)
found = true;
else
it++;
}
return found;
}
//---------------------------------------------------------------------------
/**
* Adds a checksum in the list.
*
* @param key Key of the item in the file of checksums.
* @param stateMsg Information about the state.
* @return The index of the new item.
*/
long ChecksumsListView::addChecksum(const long key, const wxString& stateMsg)
{
int p = this->GetItemCount();
// Create the item and set its data as the key of corresponding ChecksumData
InsertItem(p, wxT(""), 0);
SetItemData(p, key);
// Sets the item text and picture
setChecksum(p, stateMsg);
ChecksumData cd = sumFile->getChecksumData(key);
setChecksumState(p, cd.getState(), stateMsg);
return p;
}
//---------------------------------------------------------------------------
/**
* Sets an item.
*
* This function doesn't set the item picture and the data associated with
* the item.
*
* @param item Item to set.
* @param stateMsg Information about the state.
*/
void ChecksumsListView::setChecksum(long item, const wxString& stateMsg)
{
wxFileName fn;
ChecksumData cd = sumFile->getChecksumData(this->GetItemData(item));
for (int i = 0; i < LVW_SUMS_NBCOLS; i++)
switch (columns[i])
{
case FILE_NAME :
SetItem(item, i, cd.getFileName().GetFullName());
break;
case DIRECTORY :
fn = cd.getFileName();
if (AppPrefs::get()->readBool(prGUI_MAIN_SUMS_DIRSINABSOLUTEPATH))
{
if (fn.IsRelative())
fn.MakeAbsolute(wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
}
else
{
if (fn.IsAbsolute())
fn.MakeRelativeTo(wxFileName(sumFile->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
}
SetItem(item, i, fn.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
break;
case CHECKSUM_VALUE :
if (AppPrefs::get()->readBool(prGUI_MAIN_SUMS_UPPERCASE))
SetItem(item, i, cd.getChecksum().Upper());
else
SetItem(item, i, cd.getChecksum().Lower());
break;
case STATE :
SetItem(item, i, stateMsg);
break;
}
}
//---------------------------------------------------------------------------
/**
* Sets the state of a checksum
*
* @param item Item which to state should be modified.
* @param state New state of the checksum corresponding to the item.
* @param msg Information about the state.
*/
void ChecksumsListView::setChecksumState(long item, const ChecksumData::State state, const wxString& msg)
{
long key = GetItemData(item);
ChecksumData d = sumFile->getChecksumData(key);
sumFile->setChecksumState(key, state);
// Find the column of the state
int stateCol = -1;
for (int i = 0; (i < LVW_SUMS_NBCOLS) && (stateCol == -1); i++)
if (columns[i] == STATE)
stateCol = i;
SetItem(item, stateCol, msg);
SetItem(item, 0, GetItemText(item), state);
}
//---------------------------------------------------------------------------
/**
* Removes the selected checksums from the list.
*/
void ChecksumsListView::removeSelectedChecksums()
{
if (this->getSumFile() != NULL)
{
long item;
item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
while (item != -1)
{
sumFile->removeChecksumData(this->GetItemData(item));
this->DeleteItem(item);
item = this->GetNextItem(item - 1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
}
}
}
//---------------------------------------------------------------------------
/**
* Gets the total of each state in the list of checksums.
*
* @param onlySelected If <CODE>true</CODE> gets the state of the selected
* checksums/files. If <CODE>false</CODE> gets the state
* of all the files.
* @return An array that contains the total of each state in the list of
* checksums or an empty array if there is no checksum file opened.
*/
wxArrayInt ChecksumsListView::getStates(const bool onlySelected) const
{
wxArrayInt states;
if (this->getSumFile() != NULL)
{
ChecksumData d;
const int state = onlySelected ? wxLIST_STATE_SELECTED : wxLIST_STATE_DONTCARE;
states.Add(0, CD_STATE_COUNT);
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, state);
while (item != -1)
{
d = this->getSumFile()->getChecksumData(this->GetItemData(item));
states[static_cast<size_t>(d.getState())]++;
item = this->GetNextItem(item, wxLIST_NEXT_ALL, state);
}
}
return states;
}
//---------------------------------------------------------------------------
/**
* Sums up the total of each state in the list of checksums.
*
* @param onlySelected If <CODE>true</CODE> gets the state of the selected
* checksums/files. If <CODE>false</CODE> gets the state
* of all the files.
* @return A string which contains a sum up of the total of each state in the
* list of checksums or an empty string if there is no checksum file
* opened.
*/
wxString ChecksumsListView::sumUpStates(const bool onlySelected) const
{
wxString res;
if (this->getSumFile() != NULL)
{
wxArrayInt states = getStates(onlySelected);
int itemsCount = onlySelected ? this->GetSelectedItemCount() : this->GetItemCount();
if (itemsCount == 1)
res = _("1 file was checked. ");
else
res.Printf(_("%d files were checked. "), itemsCount);
if (states[ChecksumData::Verified] == itemsCount)
res += _("All are ok.");
else if (states[ChecksumData::Invalid] == itemsCount)
res += _("All are invalid.");
else if (states[ChecksumData::NotFound] == itemsCount)
res += _("All cannot be opened.");
else
{
if (states[ChecksumData::Verified] == 0)
res += _("None is ok");
else if (states[ChecksumData::Verified] == 1)
res += _("1 is ok");
else
res += wxString::Format(_("%d are ok"), states[ChecksumData::Verified]);
if (states[ChecksumData::Invalid] == 1)
res += _(", 1 is invalid");
else if (states[ChecksumData::Invalid] > 1)
res += wxString::Format(_(", %d are invalid"), states[ChecksumData::Invalid]);
if (states[ChecksumData::NotFound] == 1)
res += _(", 1 can't be opened");
else if (states[ChecksumData::NotFound] > 1)
res += wxString::Format(_(", %d can't be opened"), states[ChecksumData::NotFound]);
res += wxT('.');
}
}
return res;
}
//---------------------------------------------------------------------------
/**
* Open a checksum file.
*
* @param fileName Name of the file to open.
* @return <CODE>true</CODE> if the has has been opened successfully,
* <CODE>false</CODE> otherwise.
*/
bool ChecksumsListView::openChecksumFile(const wxFileName& fileName)
{
SumFile* sf = ::openChecksumFile(fileName);
if (sf != NULL)
{
// Assign the read file to this list
this->setSumFile(sf);
// Update the main dialog title
wxCommandEvent event(EVENT_UPDATE_SUMS_FRAME_TITLE_COMMAND);
this->GetParent()->ProcessEvent(event);
// Auto check ?
if (AppPrefs::get()->readBool(prGUI_AUTO_CHECK_ON_OPEN))
this->check();
// Adds the file in the recently open files history
wxCommandEvent event2(EVENT_OPEN_RECENT_ADD_FILE);
event2.SetString(fileName.GetFullPath());
this->GetParent()->ProcessEvent(event2);
return true;
}
else
{
::wxMessageBox(wxString::Format(_("'%s' cannot be read."), fileName.GetFullPath().c_str()), _("Open a checksums' file"), wxOK | wxICON_EXCLAMATION);
return false;
}
}
//---------------------------------------------------------------------------
/**
* Checks the files.
*/
void ChecksumsListView::check()
{
if (this->getSumFile() == NULL)
return; // no file is open
wxLogNull logNo; // No log
ChecksumData d; // a checksum data
wxFileName fn; // name of the current file
wxCOff_t fs; // rest of the file size to read
BytesDisplayer total; // total of bytes to process
const int state = (this->GetSelectedItemCount() > 0) ? wxLIST_STATE_SELECTED : wxLIST_STATE_DONTCARE;
// Get the number of bytes to read.
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, state);
while (item != -1)
{
d = this->getSumFile()->getChecksumData(this->GetItemData(item));
fn = d.getFileName();
if (!fn.IsAbsolute())
fn.MakeAbsolute(wxFileName(this->getSumFile()->getFileName()).GetPath(wxPATH_GET_VOLUME));
if ((fs = wxCGetFileLength(fn.GetFullPath())) != static_cast<wxCOff_t>(wxInvalidOffset))
total += static_cast<double>(fs);
item = this->GetNextItem(item, wxLIST_NEXT_ALL, state);
}
// Check the checksums
Checksum* c = sumFile->getChecksumCalculator(); // checksum calculator
ChecksumFileCalculator::State retState; // state returned by the checksum' calculator.
bool cont = true; // continue ?
// Show the progress dialog
ChecksumProgress progressUpdater(_("Checking %s\n%s on %s read."), _("Checking the files"), this, total);
ChecksumFileCalculator cfc(c, &progressUpdater);
item = this->GetNextItem(-1, wxLIST_NEXT_ALL, state);
while (item != -1 && cont)
{
// Get the name of the next file to check.
d = this->getSumFile()->getChecksumData(this->GetItemData(item));
fn = d.getFileName();
if (!fn.IsAbsolute())
fn.MakeAbsolute(wxFileName(this->getSumFile()->getFileName()).GetPath(wxPATH_GET_VOLUME));
// Check the file.
progressUpdater.setFileName(fn.GetFullName());
retState = cfc.check(fn.GetFullPath(), d.getChecksum());
switch (retState)
{
case ChecksumFileCalculator::Ok : // Checksum has been calculated (and corresponds for the check method).
this->setChecksumState(item, ChecksumData::Verified, _("OK"));
break;
case ChecksumFileCalculator::Invalid : // Checksum has been verified and not corresponds.
this->setChecksumState(item, ChecksumData::Invalid, _("Checksums differ"));
break;
case ChecksumFileCalculator::ReadError : // Error while reading the stream.
this->setChecksumState(item, ChecksumData::NotFound, _("Error while reading the file"));
break;
case ChecksumFileCalculator::FileNotFound : // The file has been not found.
this->setChecksumState(item, ChecksumData::NotFound, _("File not found"));
break;
case ChecksumFileCalculator::CantOpenFile : // Can't open the stream.
this->setChecksumState(item, ChecksumData::NotFound, _("File cannot be open"));
break;
case ChecksumFileCalculator::CanceledByUser : // User has canceled the calculation.
cont = false;
break;
}
item = this->GetNextItem(item, wxLIST_NEXT_ALL, state);
}
delete c;
progressUpdater.finished();
// Sort the list
sort();
// Display the result
if (cont && AppPrefs::get()->readBool(prGUI_DLG_SUMUP_CHECK))
::wxMessageBox(this->sumUpStates(), _("Checking checksums"), wxOK | wxICON_INFORMATION);
// Update the main dialog status bar
wxCommandEvent event(EVENT_UPDATE_SUMS_FRAME_STATUSBAR_COMMAND);
event.SetString(this->sumUpStates(this->GetSelectedItemCount() != 0));
event.SetInt(0);
this->GetParent()->ProcessEvent(event);
}
//---------------------------------------------------------------------------
/**
* Recomputes the checksums.
*/
void ChecksumsListView::recompute()
{
if (this->getSumFile() == NULL || this->GetSelectedItemCount() == 0)
return; // no file is open or no file is selected
wxLogNull logNo; // No log
ChecksumData d; // a checksum data
wxFileName fn; // name of the current file
wxCOff_t fs; // rest of the file size to read
BytesDisplayer total; // total of bytes to process
// Get the number of bytes to read.
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
while (item != -1)
{
d = this->getSumFile()->getChecksumData(this->GetItemData(item));
fn = d.getFileName();
if (!fn.IsAbsolute())
fn.MakeAbsolute(wxFileName(this->getSumFile()->getFileName()).GetPath(wxPATH_GET_VOLUME));
if ((fs = wxCGetFileLength(fn.GetFullPath())) != static_cast<wxCOff_t>(wxInvalidOffset))
total += static_cast<double>(fs);
item = this->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
}
// Recompute the checksums
Checksum* c = sumFile->getChecksumCalculator(); // checksum calculator
ChecksumFileCalculator::State retState; // state returned by the checksum' calculator.
wxString calcSumValue; // Calculated checksum's value.
bool cont = true; // continue ?
// Show the progress dialog
ChecksumProgress progressUpdater(_("Recomputing the checkum of %s\n%s on %s read."), _("Recomputing the checksums"), this, total);
ChecksumFileCalculator cfc(c, &progressUpdater);
item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
while (item != -1 && cont)
{
d = this->getSumFile()->getChecksumData(this->GetItemData(item));
fn = d.getFileName();
if (!fn.IsAbsolute())
fn.MakeAbsolute(wxFileName(this->getSumFile()->getFileName()).GetPath(wxPATH_GET_VOLUME));
// Recompute the checksum.
progressUpdater.setFileName(fn.GetFullName());
retState = cfc.calculate(fn.GetFullPath(), calcSumValue);
switch (retState)
{
case ChecksumFileCalculator::Ok : // Checksum has been calculated (and corresponds for the check method).
this->setChecksumState(item, ChecksumData::Verified, _("OK"));
if (calcSumValue.CmpNoCase(d.getChecksum()) != 0)
// changes the checksum value
{
ChecksumData cd = this->getSumFile()->getChecksumData(this->GetItemData(item));
cd.setChecksum(calcSumValue);
this->getSumFile()->setChecksumData(this->GetItemData(item), cd);
this->setChecksum(item, _("OK"));
}
break;
case ChecksumFileCalculator::ReadError : // Error while reading the stream.
this->setChecksumState(item, ChecksumData::NotFound, _("Error while reading the file"));
break;
case ChecksumFileCalculator::FileNotFound : // The file has been not found.
this->setChecksumState(item, ChecksumData::NotFound, _("File not found"));
break;
case ChecksumFileCalculator::CantOpenFile : // Can't open the stream.
this->setChecksumState(item, ChecksumData::NotFound, _("File cannot be open"));
break;
case ChecksumFileCalculator::CanceledByUser : // User has canceled the calculation.
cont = false;
break;
}
item = this->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
}
delete c;
progressUpdater.finished();
// Sort the list
sort();
}
//---------------------------------------------------------------------------
/**
* Reformats the list.
*/
void ChecksumsListView::reformat()
{
reformat(NULL);
}
//---------------------------------------------------------------------------
#if defined(__WXMSW__)
/**
* Event handler for the context menu demand.
*
* @param event event parameters.
*/
void ChecksumsListView::OnContextMenu(wxContextMenuEvent& event)
{
ShowContextMenu(ScreenToClient(event.GetPosition()));
}
//---------------------------------------------------------------------------
#else
/**
* Event handler for the context menu demand.
*
* @param event event parameters.
*/
void ChecksumsListView::OnRightUp(wxMouseEvent& event)
{
ShowContextMenu(event.GetPosition());
}
//---------------------------------------------------------------------------
#endif // defined(__WXMSW__)
/**
* Shows the context menu.
*
* @param p Position of the context menu.
*/
void ChecksumsListView::ShowContextMenu(const wxPoint& p)
{
if (sumFile != NULL)
{
// Initializes the popup-menu
wxMenu pmnFonds;
wxMenuItem* itpFilesAdd = new wxMenuItem(&pmnFonds, ITP_FILESADD, wxString(_("&Add files...")));
itpFilesAdd->SetBitmap(wxBitmap(hi16_action_fileadd_xpm));
wxMenuItem* itpDirectoriesAdd = new wxMenuItem(&pmnFonds, ITP_DIRECTORIESADD, wxString(_("A&dd directories...")));
itpDirectoriesAdd->SetBitmap(wxBitmap(hi16_action_directoryadd_xpm));
wxMenuItem* itpAddMatchingFiles = new wxMenuItem(&pmnFonds, ITP_ADDMATCHINGFILES, wxString(_("Add &matching files...")));
itpAddMatchingFiles->SetBitmap(wxBitmap(hi16_action_addmatchingfiles_xpm));
wxMenuItem* itpRemove = new wxMenuItem(&pmnFonds, ITP_REMOVE, wxString(_("&Remove")));
itpRemove->SetBitmap(wxBitmap(hi16_action_fileremove_xpm));
pmnFonds.Append(itpFilesAdd);
pmnFonds.Append(itpDirectoriesAdd);
pmnFonds.Append(itpAddMatchingFiles);
pmnFonds.Append(itpRemove);
// Check for the remove menu
if (this->GetSelectedItemCount() == 0)
itpRemove->Enable(false);
PopupMenu(&pmnFonds, p);
}
}
//---------------------------------------------------------------------------
/**
* Event handler a pop-up menu click on 'Add files...'.
*
* @param event event parameters.
*/
void ChecksumsListView::itpAddFilesClick(wxCommandEvent& event)
{
this->selectFilesToAdd();
}
//---------------------------------------------------------------------------
/**
* Event handler a pop-up menu click on 'Add directories...'.
*
* @param event event parameters.
*/
void ChecksumsListView::itpAddDirectoriesClick(wxCommandEvent& event)
{
this->selectDirectoriesToAdd();
}
//---------------------------------------------------------------------------
/**
* Event handler a pop-up menu click on 'Add matching files...'.
*
* @param event event parameters.
*/
void ChecksumsListView::itpAddMatchingFilesClick(wxCommandEvent& event)
{
this->selectMatchingFilesToAdd();
}
//---------------------------------------------------------------------------
/**
* Event handler a pop-up menu click on 'Remove'.
*
* @param event event parameters.
*/
void ChecksumsListView::itpRemoveClick(wxCommandEvent& event)
{
this->removeSelectedChecksums();
}
//---------------------------------------------------------------------------
/**
* Processes a drop of files on the list.
*
* @param event event parameters.
*/
void ChecksumsListView::DnDFiles(wxCommandEvent& event)
{
// Get the files list
wxArrayString* f = reinterpret_cast<wxArrayString*>(event.GetClientData());
// Add the files in the list or open a file
if (f != NULL)
{
if (this->getSumFile() == NULL)
{
size_t i = 0;
while (i < f->GetCount() && !(this->openChecksumFile((*f)[i])))
i++;
}
else // add the files in the list
{
this->addFiles(*f);
// Update the main dialog title
wxCommandEvent event(EVENT_UPDATE_SUMS_FRAME_TITLE_COMMAND);
this->GetParent()->ProcessEvent(event);
}
}
// Delete the array created by DndCheckSumListView::OnDropFiles()
if (f != NULL)
delete f;
}
//---------------------------------------------------------------------------
/**
* Gets the columns.
*
* @param cols Array that will contain the columns.
*/
void ChecksumsListView::getColumns(Columns cols[LVW_SUMS_NBCOLS])
{
for (int i = 0; i < LVW_SUMS_NBCOLS; i++)
cols[i] = columns[i];
}
//---------------------------------------------------------------------------
/**
* Sets the columns.
*
* @param newColumns The new columns order.
* @return <CODE>true</CODE> if the order of the columns has been changed,
* <CODE>false</CODE> otherwise.
*/
bool ChecksumsListView::setColumns(Columns newColumns[LVW_SUMS_NBCOLS])
{
int i = 0;
int j;
bool OK = true;
bool hasChanged = false;
Columns oldColumns[LVW_SUMS_NBCOLS];
// Checks values of the given array.
while (OK && i < LVW_SUMS_NBCOLS)
{
if (newColumns[i] != FILE_NAME && newColumns[i] != DIRECTORY &&
newColumns[i] != CHECKSUM_VALUE && newColumns[i] != STATE)
OK = false;
i++;
}
// Checks that all the values are unique
i = 0;
while (OK && i < LVW_SUMS_NBCOLS)
{
j = i + 1;
while (j < LVW_SUMS_NBCOLS)
{
if (newColumns[i] == newColumns[j])
OK = false;
j++;
}
i++;
}
// Copy the array
if (OK)
for (i = 0; i < LVW_SUMS_NBCOLS; i++)
{
oldColumns[i] = columns[i];
if (columns[i] != newColumns[i])
{
hasChanged = true;
columns[i] = newColumns[i];
}
}
// Reformat the list
if (OK && hasChanged)
{
reformat(oldColumns);
return true;
}
return false;
}
//---------------------------------------------------------------------------
/**
* Reformats the list.
*
* @param oldColumns Old order of the columns. <CODE>NULL</CODE> if the order
* has not changed.
*/
void ChecksumsListView::reformat(Columns oldColumns[LVW_SUMS_NBCOLS])
{
wxBusyCursor wait;
this->Freeze();
// Sets the text of the headers of the columns
if (oldColumns != NULL)
{
wxListItem colitem;
colitem.SetMask(wxLIST_MASK_TEXT);
for (int i = 0; i < LVW_SUMS_NBCOLS; i++)
{
this->GetColumn(i, colitem);
colitem.SetText(getColumnName(columns[i]));
this->SetColumn(i, colitem);
}
}
wxString state;
int i;
wxListItem li;
Columns* refTab = (oldColumns == NULL) ? columns : oldColumns;
// Find the column of the state
int stateCol = -1;
for (i = 0; (i < LVW_SUMS_NBCOLS) && (stateCol == -1); i++)
if (refTab[i] == STATE)
stateCol = i;
li.SetMask(wxLIST_MASK_TEXT);
long item = this->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
while (item != -1)
{
// Get necessary data.
li.SetId(item);
li.SetColumn(stateCol);
this->GetItem(li);
state = li.GetText();
// Sets the item data
setChecksum(item, state);
item = this->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
}
this->Thaw();
// Sort the list
sort();
}
//---------------------------------------------------------------------------
/**
* Gets the name of a column.
*
* @param col The column which the name will be returned.
* @return The name of a column.
*/
wxString ChecksumsListView::getColumnName(const Columns col)
{
wxString res;
switch (col)
{
case FILE_NAME :
res = _("File name");
break;
case DIRECTORY :
res = _("Directory");
break;
case CHECKSUM_VALUE :
res = _("Checksum value");
break;
case STATE :
res = _("State");
break;
default :
res = wxT("");
}
return res;
}
//---------------------------------------------------------------------------
BEGIN_EVENT_TABLE(ChecksumsListView, wxListView)
EVT_MENU(ITP_FILESADD, ChecksumsListView::itpAddFilesClick)
EVT_MENU(ITP_DIRECTORIESADD, ChecksumsListView::itpAddDirectoriesClick)
EVT_MENU(ITP_ADDMATCHINGFILES, ChecksumsListView::itpAddMatchingFilesClick)
EVT_MENU(ITP_REMOVE, ChecksumsListView::itpRemoveClick)
EVT_CUSTOM(EVENT_DNDFILES_COMMAND, -1, ChecksumsListView::DnDFiles)
#if defined(__WXMSW__)
EVT_CONTEXT_MENU(ChecksumsListView::OnContextMenu)
#else
EVT_RIGHT_UP(ChecksumsListView::OnRightUp)
#endif // defined(__WXMSW__)
END_EVENT_TABLE()
//---------------------------------------------------------------------------
| 30.150811 | 152 | 0.599347 | raychorn |
f840fae09ce816f07c74e06fb22a7184a8f82b6d | 438 | cpp | C++ | POO/Exercitii_examen/Exercitii/063.cpp | andrei-micuda/teme-fmi | d31c032c45e0e910d75fc05faab3681d421aac7c | [
"MIT"
] | 1 | 2020-06-07T09:45:17.000Z | 2020-06-07T09:45:17.000Z | POO/Exercitii_examen/Exercitii/063.cpp | micu01/teme-fmi | d31c032c45e0e910d75fc05faab3681d421aac7c | [
"MIT"
] | null | null | null | POO/Exercitii_examen/Exercitii/063.cpp | micu01/teme-fmi | d31c032c45e0e910d75fc05faab3681d421aac7c | [
"MIT"
] | 2 | 2020-04-09T19:27:36.000Z | 2020-06-28T17:45:14.000Z | #include<iostream>
using namespace std;
class cls {
public:
int x;
cls() { x = 3; }
void f(cls& c) { cout << c.x; }
};
/*void f(const cls& c) { cout << c.x; }*/ // REZ: cls& c => const cls& c si scoatem functia in afara clasei
void main()
{
const cls d;
f(d); // f este metoda nestatica a clasei => trebuie apelata cu un obiect implicit + transmitem un obiect const prin referinta catre o functie al carui parametru nu este const
} | 27.375 | 176 | 0.659817 | andrei-micuda |
f8414574671acb0dd73638b76e08400db7c9e0da | 2,224 | cpp | C++ | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | 1 | 2016-05-15T21:17:26.000Z | 2016-05-15T21:17:26.000Z | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | 1 | 2016-05-19T12:39:58.000Z | 2016-09-19T07:37:50.000Z | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | null | null | null | #include "Tokens.h"
namespace element
{
const char* TokenAsString(Token token)
{
switch(token)
{
case T_EOF: return "EOF";
case T_NewLine: return "\\n";
case T_Identifier: return "identifier";
case T_Integer: return "integer";
case T_Float: return "float";
case T_String: return "string";
case T_Bool: return "bool";
case T_If: return "if";
case T_Else: return "else";
case T_Elif: return "elif";
case T_For: return "for";
case T_In: return "in";
case T_While: return "while";
case T_This: return "this";
case T_Nil: return "nil";
case T_Return: return "return";
case T_Break: return "break";
case T_Continue: return "continue";
case T_Yield: return "yield ";
case T_And: return "and";
case T_Or: return "or";
case T_Xor: return "xor";
case T_Not: return "not";
case T_SizeOf: return "#";
case T_Underscore: return "_";
case T_LeftParent: return "(";
case T_RightParent: return ")";
case T_LeftBrace: return "{";
case T_RightBrace: return "}";
case T_LeftBracket: return "[";
case T_RightBracket: return "]";
case T_Column: return ":";
case T_Semicolumn: return ";";
case T_Comma: return ",";
case T_Dot: return ".";
case T_Add: return "+";
case T_Subtract: return "-";
case T_Divide: return "/";
case T_Multiply: return "*";
case T_Power: return "^";
case T_Modulo: return "%%";
case T_Concatenate: return "~";
case T_AssignAdd: return "+=";
case T_AssignSubtract: return "-=";
case T_AssignDivide: return "/=";
case T_AssignMultiply: return "*=";
case T_AssignPower: return "^=";
case T_AssignModulo: return "%%=";
case T_AssignConcatenate: return "~=";
case T_Assignment: return "=";
case T_Equal: return "==";
case T_NotEqual: return "!=";
case T_Less: return "<";
case T_Greater: return ">";
case T_LessEqual: return "<=";
case T_GreaterEqual: return ">=";
case T_Argument: return "$N";
case T_ArgumentList: return "$$";
case T_Arrow: return "->";
case T_ArrayPushBack: return "<<";
case T_ArrayPopBack: return ">>";
default:
case T_InvalidToken: return "InvalidToken";
}
}
}
| 23.659574 | 45 | 0.627698 | KaloyanKaludov |
f842fddbfae1336624a484543253acc3faa68c12 | 3,655 | cpp | C++ | third_party_builtin/tuvok/tuvok/Basics/DynamicDX.cpp | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | third_party_builtin/tuvok/tuvok/Basics/DynamicDX.cpp | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | third_party_builtin/tuvok/tuvok/Basics/DynamicDX.cpp | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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 DynamicDX.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date January 2009
*/
#if defined(_WIN32) && defined(USE_DIRECTX)
#include "DynamicDX.h"
#include <string>
#include <sstream>
using namespace std;
DynamicDX::LPCREATEDXGIFACTORY DynamicDX::CreateDXGIFactory = NULL;
DynamicDX::LPD3D10CREATEDEVICE DynamicDX::D3D10CreateDevice = NULL;
DynamicDX::LPD3DX10CREATEEFFECTFROMFILEW DynamicDX::D3DX10CreateEffectFromFileW = NULL;
DynamicDX::LPD3DX10CREATEEFFECTFROMFILEA DynamicDX::D3DX10CreateEffectFromFileA = NULL;
int DynamicDX::m_iD3DX10Version = 0;
bool DynamicDX::m_bDynamicDXIsInitialized = false;
HINSTANCE DynamicDX::m_hD3D10 = NULL;
HINSTANCE DynamicDX::m_hDXGI = NULL;
HINSTANCE DynamicDX::m_hD3DX10 = NULL;
bool DynamicDX::InitializeDX() {
if (m_bDynamicDXIsInitialized) return true;
m_hD3D10 = LoadLibrary( L"d3d10.dll" );
m_hDXGI = LoadLibrary( L"dxgi.dll" );
#ifdef _DEBUG
wstring wstrD3DX10DLL_prefix = L"d3dx10d_";
#else
wstring wstrD3DX10DLL_prefix = L"d3dx10_";
#endif
// try a few different D3DX10 DLLs
for (int i = 42; i>=33; i--) {
wstringstream wstrD3DX10DLL;
wstrD3DX10DLL << wstrD3DX10DLL_prefix << i << ".dll";
m_iD3DX10Version = i;
m_hD3DX10 = LoadLibrary( wstrD3DX10DLL.str().c_str() );
if (m_hD3DX10) break;
}
if( !m_hD3D10 || !m_hDXGI || !m_hD3DX10 ) return false;
// DXGI calls
CreateDXGIFactory = ( LPCREATEDXGIFACTORY )GetProcAddress( m_hDXGI, "CreateDXGIFactory" );
if (!CreateDXGIFactory) return false;
// D3D10 calls
D3D10CreateDevice = ( LPD3D10CREATEDEVICE )GetProcAddress( m_hD3D10, "D3D10CreateDevice" );
if (!D3D10CreateDevice) return false;
// D3DX10 calls
D3DX10CreateEffectFromFileW = ( LPD3DX10CREATEEFFECTFROMFILEW )GetProcAddress( m_hD3DX10, "D3DX10CreateEffectFromFileW" );
if (!D3DX10CreateEffectFromFileW) return false;
D3DX10CreateEffectFromFileA = ( LPD3DX10CREATEEFFECTFROMFILEA )GetProcAddress( m_hD3DX10, "D3DX10CreateEffectFromFileA" );
if (!D3DX10CreateEffectFromFileA) return false;
m_bDynamicDXIsInitialized = true;
return true;
}
void DynamicDX::CleanupDX( ) {
if (m_bDynamicDXIsInitialized) return;
FreeLibrary( m_hD3D10 );
FreeLibrary( m_hDXGI );
FreeLibrary( m_hD3DX10 );
}
#endif // _WIN32 && USE_DIRECTX | 34.809524 | 124 | 0.734337 | ahota |
f84381986bc199b3e2b8f142d7b97c934dfd94b2 | 1,951 | cc | C++ | set_modulation_curve/main.cc | tsubasatamba/cipher_analysis | 395aa270810c12515d64cacd74cb70388ce55ada | [
"Unlicense"
] | null | null | null | set_modulation_curve/main.cc | tsubasatamba/cipher_analysis | 395aa270810c12515d64cacd74cb70388ce55ada | [
"Unlicense"
] | null | null | null | set_modulation_curve/main.cc | tsubasatamba/cipher_analysis | 395aa270810c12515d64cacd74cb70388ce55ada | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <TStyle.h>
#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TH1.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TGraphErrors.h>
#include "FitModulationCurve.hh"
#include "GetAngle.hh"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
const std::string json_filename = "/Users/tamba/work/cipher/SPring8_analysis_2021/modulation_factor/modulation_factors.json";
json js;
std::ifstream fin(json_filename);
fin >> js;
json js_out;
for (auto e1: js.items()) {
const std::string experiment_name = e1.key();
int n = 0;
for (json e2: e1.value().items()) {
n++;
}
TGraphErrors* gr = new TGraphErrors(n);
int index = 0;
for (auto e2: e1.value().items()) {
const std::string degree = e2.key();
const double x = getAngle(degree);
const double xerror = 0.0;
const double y = e2.value()["modulation_factor"];
const double yerror = e2.value()["error"];
gr->SetPoint(index, x, y);
gr->SetPointError(index, xerror, yerror);
index++;
}
TF1* f = fitModulationCurve(gr);
std::vector<std::string> parameters = {"offset", "amplitude", "phase"};
json js_now;
for (int i=0; i<3; i++) {
const double value = f->GetParameter(i);
const double error = f->GetParError(i);
json js_tmp;
js_tmp.push_back(json::object_t::value_type("value", value));
js_tmp.push_back(json::object_t::value_type("error", error));
js_now.push_back(json::object_t::value_type(parameters[i], js_tmp));
}
js_out.push_back(json::object_t::value_type(experiment_name, js_now));
}
const std::string output_json_filename = "/Users/tamba/work/cipher/SPring8_analysis_2021/analysis/modulation_curve/modulation_curves.json";
std::ofstream fout(output_json_filename);
fout << std::setw(2) << js_out;
return 0;
}
| 30.484375 | 141 | 0.660174 | tsubasatamba |
f84749945c2c591a8e604fee572a3bbf27da23ba | 801 | cpp | C++ | tests/test-library.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | 1 | 2020-03-08T14:25:24.000Z | 2020-03-08T14:25:24.000Z | tests/test-library.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | null | null | null | tests/test-library.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | null | null | null | #include <liboslayer/TestSuite.hpp>
#include <liboslayer/Library.hpp>
using namespace std;
using namespace osl;
class LoadLibraryTestCase : public TestCase {
public:
LoadLibraryTestCase() : TestCase("LoadLibraryTestCase") { /**/ }
virtual ~LoadLibraryTestCase() { /**/ }
virtual void setUp(TestEnvironment & env) {
}
virtual void tearDown() {
}
virtual void test() {
try {
Library lib(DATA_PATH"/.libs", "hello");
lib.load();
((void (*)(void))*lib.symbol("hello"))();
} catch (Exception e) {
cerr << e.toString() << endl;
}
}
};
int main(int argc, char *args[]) {
TestSuite ts;
ts.addTestCase(AutoRef<TestCase>(new LoadLibraryTestCase));
TestReport report(ts.testAll());
ASSERT(report.failed(), ==, 0);
return 0;
}
| 21.648649 | 68 | 0.62422 | bjtj |
f847c59fe4a13875127a3bd23613ae7892e3733b | 8,264 | cpp | C++ | Engine/Plugins/Runtime/GameplayAbilities/Source/GameplayAbilities/Private/GameplayCueInterface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Runtime/GameplayAbilities/Source/GameplayAbilities/Private/GameplayCueInterface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Runtime/GameplayAbilities/Source/GameplayAbilities/Private/GameplayCueInterface.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GameplayCueInterface.h"
#include "AbilitySystemStats.h"
#include "GameplayTagsModule.h"
#include "AbilitySystemComponent.h"
#include "GameplayCueSet.h"
namespace GameplayCueInterfacePrivate
{
struct FCueNameAndUFunction
{
FGameplayTag Tag;
UFunction* Func;
};
typedef TMap<FGameplayTag, TArray<FCueNameAndUFunction> > FGameplayCueTagFunctionList;
static TMap<FObjectKey, FGameplayCueTagFunctionList > PerClassGameplayTagToFunctionMap;
}
UGameplayCueInterface::UGameplayCueInterface(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
void IGameplayCueInterface::DispatchBlueprintCustomHandler(AActor* Actor, UFunction* Func, EGameplayCueEvent::Type EventType, FGameplayCueParameters Parameters)
{
GameplayCueInterface_eventBlueprintCustomHandler_Parms Parms;
Parms.EventType = EventType;
Parms.Parameters = Parameters;
Actor->ProcessEvent(Func, &Parms);
}
void IGameplayCueInterface::ClearTagToFunctionMap()
{
GameplayCueInterfacePrivate::PerClassGameplayTagToFunctionMap.Empty();
}
void IGameplayCueInterface::HandleGameplayCues(AActor *Self, const FGameplayTagContainer& GameplayCueTags, EGameplayCueEvent::Type EventType, FGameplayCueParameters Parameters)
{
for (auto TagIt = GameplayCueTags.CreateConstIterator(); TagIt; ++TagIt)
{
HandleGameplayCue(Self, *TagIt, EventType, Parameters);
}
}
bool IGameplayCueInterface::ShouldAcceptGameplayCue(AActor *Self, FGameplayTag GameplayCueTag, EGameplayCueEvent::Type EventType, FGameplayCueParameters Parameters)
{
return true;
}
void IGameplayCueInterface::HandleGameplayCue(AActor *Self, FGameplayTag GameplayCueTag, EGameplayCueEvent::Type EventType, FGameplayCueParameters Parameters)
{
SCOPE_CYCLE_COUNTER(STAT_GameplayCueInterface_HandleGameplayCue);
// Look up a custom function for this gameplay tag.
UClass* Class = Self->GetClass();
FGameplayTagContainer TagAndParentsContainer = GameplayCueTag.GetGameplayTagParents();
Parameters.OriginalTag = GameplayCueTag;
//Find entry for the class
FObjectKey ClassObjectKey(Class);
GameplayCueInterfacePrivate::FGameplayCueTagFunctionList& GameplayTagFunctionList = GameplayCueInterfacePrivate::PerClassGameplayTagToFunctionMap.FindOrAdd(ClassObjectKey);
TArray<GameplayCueInterfacePrivate::FCueNameAndUFunction>* FunctionList = GameplayTagFunctionList.Find(GameplayCueTag);
if (FunctionList == NULL)
{
//generate new function list
FunctionList = &GameplayTagFunctionList.Add(GameplayCueTag);
for (auto InnerTagIt = TagAndParentsContainer.CreateConstIterator(); InnerTagIt; ++InnerTagIt)
{
UFunction* Func = NULL;
FName CueName = InnerTagIt->GetTagName();
Func = Class->FindFunctionByName(CueName, EIncludeSuperFlag::IncludeSuper);
// If the handler calls ForwardGameplayCueToParent, keep calling functions until one consumes the cue and doesn't forward it
while (Func)
{
GameplayCueInterfacePrivate::FCueNameAndUFunction NewCueFunctionPair;
NewCueFunctionPair.Tag = *InnerTagIt;
NewCueFunctionPair.Func = Func;
FunctionList->Add(NewCueFunctionPair);
Func = Func->GetSuperFunction();
}
// Native functions cant be named with ".", so look for them with _.
FName NativeCueFuncName = *CueName.ToString().Replace(TEXT("."), TEXT("_"));
Func = Class->FindFunctionByName(NativeCueFuncName, EIncludeSuperFlag::IncludeSuper);
while (Func)
{
GameplayCueInterfacePrivate::FCueNameAndUFunction NewCueFunctionPair;
NewCueFunctionPair.Tag = *InnerTagIt;
NewCueFunctionPair.Func = Func;
FunctionList->Add(NewCueFunctionPair);
Func = Func->GetSuperFunction();
}
}
}
//Iterate through all functions in the list until we should no longer continue
check(FunctionList);
bool bShouldContinue = true;
for (int32 FunctionIndex = 0; bShouldContinue && (FunctionIndex < FunctionList->Num()); ++FunctionIndex)
{
GameplayCueInterfacePrivate::FCueNameAndUFunction& CueFunctionPair = FunctionList->GetData()[FunctionIndex];
UFunction* Func = CueFunctionPair.Func;
Parameters.MatchedTagName = CueFunctionPair.Tag;
// Reset the forward parameter now, so we can check it after function
bForwardToParent = false;
IGameplayCueInterface::DispatchBlueprintCustomHandler(Self, Func, EventType, Parameters);
bShouldContinue = bForwardToParent;
}
if (bShouldContinue)
{
TArray<UGameplayCueSet*> Sets;
GetGameplayCueSets(Sets);
for (UGameplayCueSet* Set : Sets)
{
bShouldContinue = Set->HandleGameplayCue(Self, GameplayCueTag, EventType, Parameters);
if (!bShouldContinue)
{
break;
}
}
}
if (bShouldContinue)
{
Parameters.MatchedTagName = GameplayCueTag;
GameplayCueDefaultHandler(EventType, Parameters);
}
}
void IGameplayCueInterface::GameplayCueDefaultHandler(EGameplayCueEvent::Type EventType, FGameplayCueParameters Parameters)
{
// No default handler, subclasses can implement
}
void IGameplayCueInterface::ForwardGameplayCueToParent()
{
// Consumed by HandleGameplayCue
bForwardToParent = true;
}
void FActiveGameplayCue::PreReplicatedRemove(const struct FActiveGameplayCueContainer &InArray)
{
// We don't check the PredictionKey here like we do in PostReplicatedAdd. PredictionKey tells us
// if we were predictely created, but this doesn't mean we will predictively remove ourselves.
if (bPredictivelyRemoved == false)
{
// If predicted ignore the add/remove
InArray.Owner->UpdateTagMap(GameplayCueTag, -1);
InArray.Owner->InvokeGameplayCueEvent(GameplayCueTag, EGameplayCueEvent::Removed, Parameters);
}
}
void FActiveGameplayCue::PostReplicatedAdd(const struct FActiveGameplayCueContainer &InArray)
{
InArray.Owner->UpdateTagMap(GameplayCueTag, 1);
if (PredictionKey.IsLocalClientKey() == false)
{
// If predicted ignore the add/remove
InArray.Owner->InvokeGameplayCueEvent(GameplayCueTag, EGameplayCueEvent::WhileActive, Parameters);
}
}
FString FActiveGameplayCue::GetDebugString()
{
return FString::Printf(TEXT("(%s / %s"), *GameplayCueTag.ToString(), *PredictionKey.ToString());
}
void FActiveGameplayCueContainer::AddCue(const FGameplayTag& Tag, const FPredictionKey& PredictionKey, const FGameplayCueParameters& Parameters)
{
UWorld* World = Owner->GetWorld();
// Store the prediction key so the client can investigate it
FActiveGameplayCue& NewCue = GameplayCues[GameplayCues.AddDefaulted()];
NewCue.GameplayCueTag = Tag;
NewCue.PredictionKey = PredictionKey;
NewCue.Parameters = Parameters;
MarkItemDirty(NewCue);
Owner->UpdateTagMap(Tag, 1);
}
void FActiveGameplayCueContainer::RemoveCue(const FGameplayTag& Tag)
{
for (int32 idx=0; idx < GameplayCues.Num(); ++idx)
{
FActiveGameplayCue& Cue = GameplayCues[idx];
if (Cue.GameplayCueTag == Tag)
{
GameplayCues.RemoveAt(idx);
MarkArrayDirty();
Owner->UpdateTagMap(Tag, -1);
return;
}
}
}
void FActiveGameplayCueContainer::PredictiveRemove(const FGameplayTag& Tag)
{
for (int32 idx=0; idx < GameplayCues.Num(); ++idx)
{
FActiveGameplayCue& Cue = GameplayCues[idx];
if (Cue.GameplayCueTag == Tag)
{
// Predictive remove: mark the cue as predictive remove, invoke remove event, update tag map.
// DONT remove from the replicated array.
Cue.bPredictivelyRemoved = true;
Owner->UpdateTagMap(Tag, -1);
Owner->InvokeGameplayCueEvent(Tag, EGameplayCueEvent::Removed, Cue.Parameters);
return;
}
}
}
void FActiveGameplayCueContainer::PredictiveAdd(const FGameplayTag& Tag, FPredictionKey& PredictionKey)
{
Owner->UpdateTagMap(Tag, 1);
PredictionKey.NewRejectOrCaughtUpDelegate(FPredictionKeyEvent::CreateUObject(Owner, &UAbilitySystemComponent::OnPredictiveGameplayCueCatchup, Tag));
}
bool FActiveGameplayCueContainer::HasCue(const FGameplayTag& Tag) const
{
for (int32 idx=0; idx < GameplayCues.Num(); ++idx)
{
const FActiveGameplayCue& Cue = GameplayCues[idx];
if (Cue.GameplayCueTag == Tag)
{
return true;
}
}
return false;
}
bool FActiveGameplayCueContainer::NetDeltaSerialize(FNetDeltaSerializeInfo & DeltaParms)
{
if (bMinimalReplication && (Owner && Owner->ReplicationMode == EReplicationMode::Full))
{
return false;
}
return FastArrayDeltaSerialize<FActiveGameplayCue>(GameplayCues, DeltaParms, *this);
}
| 31.907336 | 176 | 0.779768 | windystrife |
f848c06c62dadad4f9e00b4264a6df74cd2010b3 | 5,983 | cpp | C++ | CPUT/source/opengl/CPUTGPUTimerOGL.cpp | GameTechDev/ChatHeads | f83c43f7fd3537badd74c31545ce2a45340474ee | [
"Apache-2.0"
] | 13 | 2016-03-11T16:39:13.000Z | 2021-09-16T09:05:50.000Z | CPUT/source/opengl/CPUTGPUTimerOGL.cpp | GameTechDev/ChatHeads | f83c43f7fd3537badd74c31545ce2a45340474ee | [
"Apache-2.0"
] | 1 | 2016-09-14T01:57:00.000Z | 2016-09-18T19:29:06.000Z | CPUT/source/opengl/CPUTGPUTimerOGL.cpp | GameTechDev/ChatHeads | f83c43f7fd3537badd74c31545ce2a45340474ee | [
"Apache-2.0"
] | 10 | 2016-04-27T02:09:52.000Z | 2019-12-08T12:35:40.000Z |
/////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 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 imlied.
// See the License for the specific language governing permissions and
// limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////
#include "CPUTGPUTimerOGL.h"
#include "CPUT_OGL.h"
#include <algorithm>
std::vector<CPUTGPUTimerOGL*> CPUTGPUTimerOGL::s_instances;
unsigned int CPUTGPUTimerOGL::s_lastFrameID = 0;
bool CPUTGPUTimerOGL::s_frameActive = false;
std::vector<GLuint> CPUTGPUTimerOGL::s_timerQueries;
#ifdef CPUT_OS_WINDOWS
#define OSSleep Sleep
#else
#include <unistd.h>
#define OSSleep sleep
#endif
CPUTGPUTimerOGL::CPUTGPUTimerOGL()
{
s_instances.push_back( this );
memset( m_history, 0, sizeof(m_history) );
for( int i = 0; i < (int)c_historyLength; i++ )
{
m_history[i].TimingResult = -1.0;
m_history[i].StartData = 0;
m_history[i].StopData = 0;
}
m_historyLastIndex = 0;
m_active = false;
m_lastTime = 0.0f;
m_avgTime = 0.0f;
}
CPUTGPUTimerOGL::~CPUTGPUTimerOGL()
{
std::vector<CPUTGPUTimerOGL*>::iterator it = std::find(s_instances.begin(), s_instances.end(), this);
if( it != s_instances.end() )
{
s_instances.erase( it );
}
else
{
// this instance not found in the global list?
assert( false );
}
}
void CPUTGPUTimerOGL::OnDeviceAndContextCreated()
{
s_lastFrameID = 0;
s_frameActive = false;
}
void CPUTGPUTimerOGL::OnDeviceAboutToBeDestroyed()
{
FrameFinishQueries( true );
s_timerQueries.clear();
}
void CPUTGPUTimerOGL::FrameFinishQueries(bool forceAll)
{
assert( !s_frameActive );
for( int i = 0; i < (int)s_instances.size(); i++ )
s_instances[i]->FinishQueries( forceAll );
}
GLuint CPUTGPUTimerOGL::GetTimerQuery2()
{
GLuint queryID;
if( s_timerQueries.size() == 0 )
{
GL_CHECK(glGenQueries(1,&queryID));
}
else
{
queryID = s_timerQueries.back();
s_timerQueries.pop_back();
}
return queryID;
}
void CPUTGPUTimerOGL::OnFrameStart()
{
FrameFinishQueries( false );
assert( !s_frameActive );
s_frameActive = true;
s_lastFrameID++;
}
void CPUTGPUTimerOGL::OnFrameEnd()
{
assert( s_frameActive );
s_frameActive = false;
}
static bool GetQueryDataHelper( bool loopUntilDone, GLuint query, GLuint64* startTime )
{
if( query == 0 )
return false;
int attempts = 0;
do
{
// wait until the results are available
GLint stopTimerAvailable = 0;
glGetQueryObjectiv(query,GL_QUERY_RESULT_AVAILABLE, &stopTimerAvailable);
if (stopTimerAvailable == 0)
{
// results not available yet - should try again later
}
else
{
glGetQueryObjectui64v(query, GL_QUERY_RESULT, startTime);
return true;
}
attempts++;
if( attempts > 1000 )
OSSleep(0);
if( attempts > 100000 )
{
ASSERT( false, "CPUTGPUTimerOGL.cpp - Infinite loop while doing s_immediateContext->GetData()\n");
return false;
}
} while ( loopUntilDone);
return false;
}
void CPUTGPUTimerOGL::FinishQueries(bool forceAll)
{
assert( !m_active );
int dataGathered = 0;
m_avgTime = 0.0;
m_NewRetires = 0;
// get data from previous frames queries if available
for( int i = 0; i < (int)c_historyLength; i++ )
{
int safeIndex = (i % c_historyLength);
GPUTimerInfo & item = m_history[safeIndex];
bool tryGather = true;
if( item.QueryActive )
{
bool loopUntilDone = ((s_lastFrameID - item.FrameID) >= c_dataQueryMaxLag) || forceAll;
GLuint64 startTime = 0, stopTime = 0;
GetQueryDataHelper( loopUntilDone, item.StartQuery2, &startTime );
GetQueryDataHelper( loopUntilDone, item.StopQuery2, &stopTime );
if(startTime && stopTime )
{
item.TimingResult = (double)(stopTime-startTime)/1000000000.0f;
item.QueryActive = false;
m_NewRetires++;
if(item.FrameID>m_lastFrameID)
{
m_lastFrameID = item.FrameID;
m_lastTime = item.TimingResult;
}
}
}
if( (!item.QueryActive) && (item.TimingResult != -1.0) )
{
dataGathered++;
m_avgTime += item.TimingResult;
if(item.StartQuery2 && item.StopQuery2)
{
s_timerQueries.push_back(item.StartQuery2);
s_timerQueries.push_back(item.StopQuery2);
item.StartQuery2 = 0;
item.StopQuery2 = 0;
}
}
}
if( dataGathered == 0 )
m_avgTime = 0.0f;
else
m_avgTime /= (double)dataGathered;
}
void CPUTGPUTimerOGL::Start()
{
assert( s_frameActive );
assert( !m_active );
m_historyLastIndex = (m_historyLastIndex+1)%c_historyLength;
assert( !m_history[m_historyLastIndex].QueryActive );
m_history[m_historyLastIndex].StartQuery2 = GetTimerQuery2();
glQueryCounter(m_history[m_historyLastIndex].StartQuery2, GL_TIMESTAMP);
m_history[m_historyLastIndex].QueryActive = true;
m_history[m_historyLastIndex].FrameID = s_lastFrameID;
m_active = true;
m_history[m_historyLastIndex].TimingResult = -1.0;
}
void CPUTGPUTimerOGL::Stop()
{
assert( s_frameActive );
assert( m_active );
assert( m_history[m_historyLastIndex].QueryActive );
m_history[m_historyLastIndex].StopQuery2 = GetTimerQuery2();
glQueryCounter(m_history[m_historyLastIndex].StopQuery2, GL_TIMESTAMP);
m_active = false;
}
| 23.011538 | 111 | 0.644994 | GameTechDev |
f84d951333fd041c064a8d421406648cdf837983 | 2,015 | cpp | C++ | src/lib/AST/PType.cpp | LittleLaGi/p2llvm | 549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3 | [
"MIT"
] | null | null | null | src/lib/AST/PType.cpp | LittleLaGi/p2llvm | 549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3 | [
"MIT"
] | null | null | null | src/lib/AST/PType.cpp | LittleLaGi/p2llvm | 549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3 | [
"MIT"
] | null | null | null | #include "AST/PType.hpp"
#include <cassert>
const char *kTypeString[] = {"void", "integer", "real", "boolean", "string"};
// logical constness
const char *PType::getPTypeCString() const {
if (!m_type_string_is_valid) {
m_type_string += kTypeString[static_cast<size_t>(m_type)];
if (m_dimensions.size() != 0) {
m_type_string += " ";
for (const auto &dim : m_dimensions) {
m_type_string += "[" + std::to_string(dim) + "]";
}
}
m_type_string_is_valid = true;
}
return m_type_string.c_str();
}
PType *PType::getStructElementType(const std::size_t nth) const {
if (nth > m_dimensions.size()) {
return nullptr;
}
auto *type_ptr = new PType(m_type);
std::vector<uint64_t> dims;
for (std::size_t i = nth; i < m_dimensions.size(); ++i) {
dims.emplace_back(m_dimensions[i]);
}
type_ptr->setDimensions(dims);
return type_ptr;
}
bool PType::compare(const PType *p_type) const {
// primitive type comparison
switch(m_type) {
case PrimitiveTypeEnum::kIntegerType:
case PrimitiveTypeEnum::kRealType:
if (!p_type->isPrimitiveInteger() && !p_type->isPrimitiveReal()) {
return false;
}
break;
case PrimitiveTypeEnum::kBoolType:
if (!p_type->isPrimitiveBool()) {
return false;
}
break;
case PrimitiveTypeEnum::kStringType:
if (!p_type->isPrimitiveString()) {
return false;
}
break;
default:
assert(false && "comparing unknown primitive type or void type");
return false;
}
// dimensions comparison
auto &dimensions = p_type->getDimensions();
if (m_dimensions.size() != dimensions.size()) {
return false;
}
for (decltype(m_dimensions)::size_type i = 0; i < m_dimensions.size(); ++i) {
if (m_dimensions[i] != dimensions[i]) {
return false;
}
}
return true;
}
| 25.833333 | 81 | 0.583623 | LittleLaGi |
f84ed5a21909008dd393c61e05f5a189c81629e6 | 627 | cpp | C++ | .emacs.d/cedet/semantic/tests/testfriends.cpp | littletwolee/emacs-configure | 6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3 | [
"MIT"
] | 6 | 2019-01-06T05:55:47.000Z | 2021-05-28T09:29:58.000Z | .emacs.d/cedet/semantic/tests/testfriends.cpp | littletwolee/emacs-configure | 6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3 | [
"MIT"
] | null | null | null | .emacs.d/cedet/semantic/tests/testfriends.cpp | littletwolee/emacs-configure | 6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3 | [
"MIT"
] | 2 | 2015-12-09T19:06:16.000Z | 2021-12-02T14:41:31.000Z | // Test parsing of friends and how they are used in completion.
/*
>> Thanks Damien Profeta for the nice example.
>
> I paste a small example.
> It would be great if friend can be well parsed and even greater if
> class B can access to all the members of A.
*/
class Af // %2% ( ( "testfriends.cpp" ) ( "Af" "B::testB" ) )
{
public:
int pubVar;
private:
int privateVar;
friend class B;
};
class B
{
public:
int testB();
int testAB();
};
int B::testB() {
Af classA;
classA.//-1-
; //#1# ( "privateVar" "pubVar" )
}
int B::testAB() { // %1% ( ( "testfriends.cpp" ) ( "B" "B::testAB" ) )
}
| 16.5 | 71 | 0.590112 | littletwolee |
f8514663a9a5964d0ca85313a06ce10e16016bc9 | 1,951 | cc | C++ | src/rns/main.cc | emer/pdpp | ccce243ae356dc5908cdd667419a7afd74cf22ad | [
"BSD-3-Clause"
] | null | null | null | src/rns/main.cc | emer/pdpp | ccce243ae356dc5908cdd667419a7afd74cf22ad | [
"BSD-3-Clause"
] | null | null | null | src/rns/main.cc | emer/pdpp | ccce243ae356dc5908cdd667419a7afd74cf22ad | [
"BSD-3-Clause"
] | null | null | null | /* -*- C++ -*- */
/*=============================================================================
// //
// This file is part of the PDP++ software package. //
// //
// Copyright (c) 1994 Carnegie Mellon University (CMU), James L. McClelland, //
// Chadley K. Dawson, and Randall C. O'Reilly //
// //
// Permission to use, copy, modify, distribute, and sell this software and //
// its documentation for any purpose is hereby granted without fee, provided //
// that (i) the above copyright notices and this permission notice appear in //
// all copies of the software and related documentation, and (ii) the name of //
// Carnegie Mellon University may not be used in any advertising or //
// publicity relating to the software without the specific, prior written //
// permission of Carnegie Mellon University. //
// //
// THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, //
// EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY //
// WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. //
// //
// IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR //
// ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, //
// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, //
// WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF //
// LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE //
// OF THIS SOFTWARE. //
// //
==============================================================================*/
// this is the main that is included to make pdplib executable
//
#include <pdp/base.h>
#include "rns_TA_type.h"
int main(int argc, char* argv[]) {
pdpMisc::Init_Hook = ta_Init_rns;
return pdpMisc::Main(argc, argv);
}
| 48.775 | 80 | 0.578678 | emer |
f8515cb5e9bbf5ef7a813577bf3884c9c6c7ef4b | 6,122 | hpp | C++ | src/pyinterp/core/include/pyinterp/detail/math.hpp | apatlpo/pangeo-pyinterp | b5242c6869d7e601a5695b304c81992deb63367d | [
"BSD-3-Clause"
] | null | null | null | src/pyinterp/core/include/pyinterp/detail/math.hpp | apatlpo/pangeo-pyinterp | b5242c6869d7e601a5695b304c81992deb63367d | [
"BSD-3-Clause"
] | null | null | null | src/pyinterp/core/include/pyinterp/detail/math.hpp | apatlpo/pangeo-pyinterp | b5242c6869d7e601a5695b304c81992deb63367d | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019 CNES
//
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#pragma once
#include <cmath>
#include <tuple>
namespace pyinterp {
namespace detail {
namespace math {
/// π
template <typename T>
inline constexpr T pi() noexcept {
return std::atan2(T(0), T(-1));
}
/// π/2
template <typename T>
inline constexpr T pi_2() noexcept {
return 0.5 * pi<T>();
}
/// 2π
template <typename T>
inline constexpr T two_pi() noexcept {
return T(2) * pi<T>();
}
/// Convert angle x from radians to degrees.
template <typename T>
inline constexpr T radians(const T& x) noexcept {
return x * pi<T>() / T(180);
}
/// Convert angle x from degrees to radians.
template <typename T>
inline constexpr T degrees(const T& x) noexcept {
return x * T(180) / pi<T>();
}
/// Normalize an angle.
///
/// @param x The angle in degrees.
/// @param min Minimum circle value
/// @param circle Circle value
/// @return the angle reduced to the range [min, circle + min[
template <typename T>
inline constexpr T normalize_angle(const T& x, const T& min = T(-180),
const T& circle = T(360)) noexcept {
T result = std::remainder(x - min, circle);
if (result < T(0)) {
result += circle;
}
result += min;
return result;
}
/// Computes the remainder of the operation x/y
///
/// @return a result with the same sign as its second operand
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
inline constexpr T remainder(const T& x, const T& y) noexcept {
auto result = x % y;
return result != 0 && (result ^ y) < 0 ? result + y : result;
}
/// Evaluate the sine function with the argument in degrees
///
/// In order to minimize round-off errors, this function exactly reduces the
/// argument to the range [-45, 45] before converting it to radians.
///
/// @param x x in degrees.
/// @return sin(x).
template <typename T>
inline constexpr T sind(const T& x) noexcept {
int quotient{};
T result = radians(std::remquo(x, T(90), "ient));
// now |result| <= π/4
auto quadrant = static_cast<unsigned int>(quotient);
result = (quadrant & 1U) ? std::cos(result) : std::sin(result);
if (quadrant & 2U) {
result = -result;
}
return result;
}
/// Evaluate the cosine function with the argument in degrees
///
/// @param x in degrees.
/// @return cos(x).
template <typename T>
inline constexpr T cosd(const T& x) noexcept {
int quotient{};
T result = radians(std::remquo(x, T(90), "ient));
// now |result| <= π/4
auto quadrant = static_cast<unsigned int>(quotient + 1);
result = (quadrant & 1U) ? std::cos(result) : std::sin(result);
if (quadrant & 2U) {
result = -result;
}
return result;
}
/// Evaluate the sine and cosine function with the argument in degrees
///
/// @param x in degrees.
/// @return a tuple that contains sin(x) and cos(x)
template <typename T>
inline constexpr std::tuple<T, T> sincosd(const T& x) noexcept {
int quotient{};
T angle = radians(std::remquo(x, T(90), "ient));
// now |angle| <= π/4
switch (static_cast<unsigned int>(quotient) & 3U) {
case 0U:
return std::make_tuple(std::sin(angle), std::cos(angle));
case 1U:
return std::make_tuple(std::cos(angle), -std::sin(angle));
case 2U:
return std::make_tuple(-std::sin(angle), -std::cos(angle));
// case 3U
default:
return std::make_tuple(-std::cos(angle), std::sin(angle));
}
}
/// Evaluate the tangent function with the argument in degrees
///
/// @param x in degrees.
/// @return tan(x).
template <typename T>
inline constexpr T tand(const T& x) noexcept {
T sinx{}, cosx{};
std::tie(sinx, cosx) = sincosd(x);
return cosx != 0 ? sinx / cosx : (sinx < 0 ? -HUGE_VAL : HUGE_VAL);
}
/// Evaluate the atan2 function with the result in degrees
///
/// @param y
/// @param x
/// @return atan2(y, x) in degrees.
template <typename T>
inline constexpr T atan2d(T y, T x) noexcept {
// In order to minimize round-off errors, this function rearranges the
// arguments so that result of atan2 is in the range [-π/4, π/4] before
// converting it to degrees and mapping the result to the correct
// quadrant.
int quadrant = 0;
if (std::abs(y) > std::abs(x)) {
std::swap(x, y);
quadrant = 2;
}
if (x < 0) {
x = -x;
++quadrant;
}
// here x >= 0 and x >= abs(y), so angle is in [-π/4, π/4]
T angle = degrees(std::atan2(y, x));
switch (quadrant) {
case 1:
angle = (y >= 0 ? 180 : -180) - angle;
break;
case 2:
angle = 90 - angle;
break;
case 3:
angle = -90 + angle;
break;
default:
break;
}
return angle;
}
/// Evaluate the atan function with the result in degrees
///
/// @param x
/// @return atan(x) in degrees.
template <typename T>
inline constexpr T atand(const T& x) noexcept {
return atan2d(x, T(1));
}
/// Square a number.
///
/// @return \f$x^2\f$
template <typename T>
inline constexpr T sqr(const T& x) noexcept {
return x * x;
}
/// True if a and b are two values identical to an epsilon.
template <typename T>
inline constexpr bool is_same(const T& a, const T& b,
const T& epsilon) noexcept {
return std::fabs(a - b) <= epsilon;
}
/// Represents a filling value
template <typename T, class Enable = void>
struct Fill;
/// Represents a filling value for floating point number
template <class T>
struct Fill<T, std::enable_if_t<std::is_floating_point<T>::value>> {
static inline constexpr T value() noexcept {
return std::numeric_limits<T>::quiet_NaN();
}
static inline constexpr T is_not(const T& x) noexcept {
return !std::isnan(x);
}
};
/// Represents a filling value for integer number
template <class T>
struct Fill<T, std::enable_if_t<std::is_integral<T>::value>> {
static inline constexpr T value() noexcept {
return std::numeric_limits<T>::max();
}
static inline constexpr T is_not(const T& x) noexcept {
return Fill::value() != x;
}
};
} // namespace math
} // namespace detail
} // namespace pyinterp
| 26.617391 | 78 | 0.639824 | apatlpo |
f8517aaf27e3823e0bab69f02e0c7766c43c9a3f | 1,144 | cpp | C++ | niceday-1.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 264 | 2015-01-08T10:07:01.000Z | 2022-03-26T04:11:51.000Z | niceday-1.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 17 | 2016-04-15T03:38:07.000Z | 2020-10-30T00:33:57.000Z | niceday-1.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 127 | 2015-01-08T04:56:44.000Z | 2022-02-25T18:40:37.000Z | // 2008-09-01
// niceday-1.cpp uses misof's "staircase" data structure.
// See niceday-2.cpp for another approach.
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
#define MAX(a,b) ((a)>(b)?(a):(b))
#ifdef _MSC_VER
#define GC getchar
#else
#define GC getchar_unlocked
#endif
#define SIZE 100000
int input()
{
int x=0;
char c;
for(;;)
{
c=GC();
if (c==' '||c=='\n')
return x;
x=10*x+c-'0';
}
}
static pair<int,pair<int,int> > C[SIZE];
int main()
{
int i,t,N,j,excellent;
t=input();
for (i=0; i<t; i++)
{
N=input();
map<int,int> M;
for (j=0; j<N; j++)
{
C[j].first=input();
C[j].second.first=input();
C[j].second.second=input();
}
excellent=1;
sort(C,C+N);
map<int,int>::iterator I1,I2;
M.insert(C[0].second);
int x,y;
for (j=1; j<N; j++)
{
x=C[j].second.first;
y=C[j].second.second;
I1=M.lower_bound(x);
if (I1!=M.begin())
{
I1--;
if (I1->second<y)
continue;
I1++;
}
I2=I1;
while (I2!=M.end()&&I2->second>y)
I2++;
M.erase(I1,I2);
M.insert(C[j].second);
excellent++;
}
printf("%d\n",excellent);
}
return 0;
}
| 16.342857 | 57 | 0.557692 | ohmyjons |
f8520985b3e1a675d9f327e1ea6af307d93a8e42 | 7,723 | cpp | C++ | src/tsppd/solver/oneil/oneil_atsppd_solver.cpp | ryanjoneil/tsppd | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 4 | 2018-03-30T20:58:57.000Z | 2018-04-25T01:48:09.000Z | src/tsppd/solver/oneil/oneil_atsppd_solver.cpp | ryanjoneil/tsppd | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 7 | 2019-04-21T13:42:09.000Z | 2019-05-09T15:49:56.000Z | src/tsppd/solver/oneil/oneil_atsppd_solver.cpp | ryanjoneil/tsppd-hybrid | f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4 | [
"AFL-1.1"
] | 1 | 2020-03-01T16:19:18.000Z | 2020-03-01T16:19:18.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the tsppd program and library for solving */
/* Traveling Salesman Problems with Pickup and Delivery. tsppd requires */
/* other commercial and open source software to build. tsppd is decribed */
/* in the paper "Exact Methods for Solving Traveling Salesman Problems */
/* with Pickup and Delivery in Real Time". */
/* */
/* Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu> */
/* */
/* tsppd is distributed under the terms of the ZIB Academic License. */
/* You should have received a copy of the ZIB Academic License along with */
/* tsppd. See the file LICENSE. If not, email roneil1@gmu.edu. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <cstdio>
#include <iomanip>
#include <vector>
#include <tsppd/data/tsppd_search_statistics.h>
#include <tsppd/solver/ap/ap_atsppd_callback.h>
#include <tsppd/solver/oneil/oneil_atsppd_solver.h>
#include <tsppd/util/exception.h>
using namespace TSPPD::Data;
using namespace TSPPD::IO;
using namespace TSPPD::Solver;
using namespace TSPPD::Util;
using namespace std;
ONeilATSPPDSolver::ONeilATSPPDSolver(
const TSPPDProblem& problem,
const map<string, string> options,
TSPSolutionWriter& writer) :
APATSPPDSolver(problem, options, writer),
w() {
initialize_oneil_options();
initialize_oneil_variables();
initialize_oneil_constraints();
}
TSPPDSolution ONeilATSPPDSolver::solve() {
configure_solver();
APATSPPDCallback callback(problem, x, sec, writer);
model.setCallback(&callback);
model.optimize();
return solution();
}
void ONeilATSPPDSolver::initialize_oneil_options() {
if (options["relax"] == "" || options["relax"] == "off")
relaxed = false;
else if (options["relax"] == "on")
relaxed = true;
else
throw TSPPDException("relax can be either on or off");
if (options["sec"] == "" || options["sec"] == "subtour")
sec = ATSP_SEC_SUBTOUR;
else if (options["sec"] == "cutset")
sec = ATSP_SEC_CUTSET;
else
throw TSPPDException("sec can be either subtour or cutset");
}
void ONeilATSPPDSolver::initialize_oneil_variables() {
auto pickups = problem.pickup_indices();
for (unsigned int i = 0; i < pickups.size(); ++i) {
auto pi = pickups[i];
for (unsigned int j = i + 1; j < pickups.size(); ++j) {
auto pj = pickups[j];
auto w_ij1 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +i +j -i -j -> w_ij1
auto w_ij2 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +i +j -j -i -> w_ij2
auto w_ij3 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +i -i +j -j -> w_ij3
auto w_ji1 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +j +i -j -i -> w_ji1
auto w_ji2 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +j +i -i -j -> w_ji2
auto w_ji3 = model.addVar(0, 1, 0, GRB_CONTINUOUS); // +j -j +i -i -> w_ji3
w[{pi, pj}] = {w_ij1, w_ij2, w_ij3};
w[{pj, pi}] = {w_ji1, w_ji2, w_ji3};
model.addConstr(w_ij1 + w_ij2 + w_ij3 + w_ji1 + w_ji2 + w_ji3 == 1);
}
}
}
void ONeilATSPPDSolver::initialize_oneil_constraints() {
// Link x and w variables
for (unsigned int i = 0; i < x.size(); ++i) {
if (i == start_index || i == end_index)
continue;
for (unsigned int j = 0; j < x.size(); ++j) {
if (j == start_index || j == end_index || j == i)
continue;
auto x_ij = x[i][j];
if (problem.has_successor(i) && problem.has_successor(j)) {
// x(+i,+j) <= w_ij1 + w_ij2
auto pi = i;
auto pj = j;
model.addConstr(x_ij <= w[{pi,pj}][0] + w[{pi,pj}][1]);
// x(+i,-i) <= w_ij3 + w_ji2 + w_ji3
auto x_ii = x[pi][problem.successor_index(i)];
model.addConstr(x_ii <= w[{pi,pj}][2] + w[{pj,pi}][1] + w[{pj,pi}][2]);
} else if (problem.has_successor(i) && problem.has_predecessor(j)) {
// x(+i,-j) <= w_ji1
auto pi = i;
auto pj = problem.predecessor_index(j);
if (pi != pj)
model.addConstr(x_ij <= w[{pj,pi}][0]);
} else if (problem.has_predecessor(i) && problem.has_successor(j)) {
// x(-i,+j) <= w_ij3
auto pi = problem.predecessor_index(i);
auto pj = j;
if (pi != pj)
model.addConstr(x_ij <= w[{pi,pj}][2]);
} else if (problem.has_predecessor(i) && problem.has_predecessor(j)) {
// x(-i,-j) <= w_ij1 + w_ji2
auto pi = problem.predecessor_index(i);
auto pj = problem.predecessor_index(j);
model.addConstr(x_ij <= w[{pi,pj}][0] + w[{pj,pi}][1]);
}
}
}
// Subtour elimination and precedence constraints
if (!relaxed) {
for (auto pi : problem.pickup_indices()) {
auto di = problem.successor_index(pi);
for (auto pj : problem.pickup_indices()) {
if (pi == pj)
continue;
auto dj = problem.successor_index(pj);
for (auto pk : problem.pickup_indices()) {
if (pk == pi || pk == pj)
continue;
auto dk = problem.successor_index(pk);
model.addConstr(s(pi,pj) + s(pj,pk) + s(pk,pi) <= 2); // +i +j +k +i
model.addConstr(s(pi,pj) + s(pj,dk) + s(dk,pi) <= 2); // +i +j -k +i
model.addConstr(s(pi,dj) + s(dj,pk) + s(pk,pi) <= 2); // +i -j +k +i
model.addConstr(s(pi,dj) + s(dj,dk) + s(dk,pi) <= 2); // +i -j -k +i
model.addConstr(s(di,pj) + s(pj,pk) + s(pk,di) <= 2); // -i +j +k -i
model.addConstr(s(di,pj) + s(pj,dk) + s(dk,di) <= 2); // -i +j -k -i
model.addConstr(s(di,dj) + s(dj,pk) + s(pk,di) <= 2); // -i -j +k -i
model.addConstr(s(di,dj) + s(dj,dk) + s(dk,di) <= 2); // -i -j -k -i
}
}
}
}
}
GRBLinExpr ONeilATSPPDSolver::s(unsigned int i, unsigned int j) {
GRBLinExpr expr = 0;
if (problem.has_successor(i) && problem.has_successor(j)) {
auto pi = i;
auto pj = j;
expr = w[{pi,pj}][0] + w[{pi,pj}][1] + w[{pi,pj}][2];
} else if (problem.has_successor(i) && problem.has_predecessor(j)) {
auto pi = i;
auto pj = problem.predecessor_index(j);
if (pi != pj)
expr = w[{pi,pj}][0] + w[{pi,pj}][1] + w[{pi,pj}][2] + w[{pj,pi}][0] + w[{pj,pi}][1];
} else if (problem.has_predecessor(i) && problem.has_successor(j)) {
auto pi = problem.predecessor_index(i);
auto pj = j;
if (pi != pj)
expr = w[{pi,pj}][2];
} else if (problem.has_predecessor(i) && problem.has_predecessor(j)) {
auto pi = problem.predecessor_index(i);
auto pj = problem.predecessor_index(j);
if (pi != pj)
expr = w[{pi,pj}][0] + w[{pi,pj}][2] + w[{pj,pi}][1];
}
return expr;
}
| 38.809045 | 101 | 0.491389 | ryanjoneil |
f858ec4fad057dd63562ccfd42a5c660c2675b38 | 8,755 | cpp | C++ | external/Coin3D/src/lists/SbList.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 7 | 2018-03-07T06:51:41.000Z | 2020-05-22T08:32:54.000Z | external/Coin3D/src/lists/SbList.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 1 | 2019-03-06T08:59:24.000Z | 2019-03-06T08:59:24.000Z | external/Coin3D/src/lists/SbList.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 8 | 2018-05-02T20:16:07.000Z | 2021-06-10T03:06:04.000Z | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder 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.
\**************************************************************************/
/*!
\class SbList SbList.h Inventor/lists/SbList.h
\brief The SbList class is a template container class for lists.
\ingroup base
SbList is an extension of the Coin library versus the original Open
Inventor API. Open Inventor handles most list classes by inheriting
the SbPList class, which contains an array of generic \c void*
pointers. By using this template-based class instead, we can share
more code and make the list handling code more typesafe.
Care has been taken to make sure the list classes which are part of
the Open Inventor API to still be compatible with their original
interfaces, as derived from the SbPList base class. But if you still
bump into any problems when porting your Open Inventor applications,
let us know and we'll do our best to sort them out.
A feature with this class is that the list object arrays grow
dynamically as you append() more items to the list. The actual
growing technique used is to double the list size when it becomes
too small.
There are also other array-related convenience methods; e.g. finding
item indices, inserting items at any position, removing items (and
shrink the array), copying of arrays, etc.
\sa SbPList
*/
// FIXME: all methods on this class is now inlined. This probably adds
// quite a few (hundred) kBytes to the total size of the
// library. Several methods on this class should therefore be
// "de-inlined". The problem with this is that compilers seems to
// differ on whether or not subclasses or template instances then need
// to explicitly "declare themselves". This is not too hard to fix,
// but it involves _some_ pain as it needs some nifty configure
// checking. 20000227 mortene.
/*!
\fn SbList<Type>::SbList(const int sizehint)
Default constructor.
The \a sizehint argument hints about how many elements the list will
contain, so memory allocation can be done efficiently.
Important note: explicitly specifying an \a sizehint value does \e
not mean that the list will initially contain this number of values.
After construction, the list will contain zero items, just as for
the default constructor. Here's a good example on how to give
yourself hard to find bugs:
\code
SbList<SbBool> flags(2); // Assume we need only 2 elements. Note
// that the list is still 0 elements long.
flags[0] = TRUE; // Ouch. List is still 0 elements long.
\endcode
Since this conceptual misunderstanding is so easy to make, you're
probably better (or at least safer) off leaving the \a sizehint
argument to its default value by not explicitly specifying it.
It improves performance if you know the approximate total size of
the list in advance before adding list elements, as the number of
reallocations will be minimized.
*/
/*!
\fn SbList<Type>::SbList(const SbList<Type> & l)
Copy constructor. Creates a complete copy of the given list.
*/
/*!
\fn SbList<Type>::~SbList()
Destructor, frees all internal resources used by the list container.
*/
/*!
\fn void SbList<Type>::copy(const SbList<Type> & l)
Make this list a copy of \a l.
*/
/*!
\fn SbList<Type> & SbList<Type>::operator=(const SbList<Type> & l)
Make this list a copy of \a l.
*/
/*!
\fn void SbList<Type>::fit(void)
Fit the allocated array exactly around the length of the list,
descarding memory spent on unused pre-allocated array cells.
You should normally not need or want to call this method, and it is
only available for the sake of having the option to optimize memory
usage for the unlikely event that you should throw around huge
SbList objects within your application.
*/
/*!
\fn void SbList<Type>::append(const Type item)
Append the \a item at the end of list, expanding the list array by
one.
*/
/*!
\fn int SbList<Type>::find(const Type item) const
Return index of first occurrence of \a item in the list, or -1 if \a
item is not present.
*/
/*!
\fn void SbList<Type>::insert(const Type item, const int insertbefore)
Insert \a item at index \a insertbefore.
\a insertbefore should not be larger than the current number of
items in the list.
*/
/*!
\fn void SbList<Type>::removeItem(const Type item)
Removes an \a item from the list. If there are several items with
the same value, removes the \a item with the lowest index.
*/
/*!
\fn void SbList<Type>::remove(const int index)
Remove the item at \a index, moving all subsequent items downwards
one place in the list.
*/
/*!
\fn void SbList<Type>::removeFast(const int index)
Remove the item at \a index, moving the last item into its place and
truncating the list.
*/
/*!
\fn int SbList<Type>::getLength(void) const
Returns number of items in the list.
*/
/*!
\fn void SbList<Type>::truncate(const int length, const int fit)
Shorten the list to contain \a length elements, removing items from
\e index \a length and onwards.
If \a fit is non-zero, will also shrink the internal size of the
allocated array. Note that this is much less efficient than not
re-fitting the array size.
*/
/*!
\fn void SbList<Type>::push(const Type item)
This appends \a item at the end of the list in the same fashion as
append() does. Provided as an abstraction for using the list class
as a stack.
*/
/*!
\fn Type SbList<Type>::pop(void)
Pops off the last element of the list and returns it.
*/
/*!
\fn const Type * SbList<Type>::getArrayPtr(const int start = 0) const
Returns pointer to a non-modifiable array of the lists elements.
\a start specifies an index into the array.
The caller is \e not responsible for freeing up the array, as it is
just a pointer into the internal array used by the list.
*/
/*!
\fn Type SbList<Type>::operator[](const int index) const
Returns a copy of item at \a index.
*/
/*!
\fn Type & SbList<Type>::operator[](const int index)
Returns a reference to item at \a index.
*/
/*!
\fn SbBool SbList<Type>::operator==(const SbList<Type> & l) const
Equality operator. Returns \c TRUE if this list and \a l are
identical, containing the exact same set of elements.
*/
/*!
\fn SbBool SbList<Type>::operator!=(const SbList<Type> & l) const
Inequality operator. Returns \c TRUE if this list and \a l are not
equal.
*/
/*!
\fn void SbList<Type>::expand(const int size)
Expand the list to contain \a size items. The new items added at the
end have undefined value.
*/
/*!
\fn int SbList<Type>::getArraySize(void) const
Return number of items there's allocated space for in the array.
\sa getLength()
*/
/*!
\fn void SbList<Type>::ensureCapacity(const int size)
Ensure that the internal buffer can hold at least \a size
elements. SbList will automatically resize itself to make room for
new elements, but this method can be used to improve performance
(and avoid memory fragmentation) if you know approximately the
number of elements that is going to be added to the list.
\since Coin 2.5
*/
| 31.721014 | 76 | 0.716848 | skrat |
f8591fdced8db9de69105f3667cccb4a95bb4aa5 | 27,481 | cc | C++ | content/child/runtime_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/child/runtime_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/child/runtime_features.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/runtime_features.h"
#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/content_switches_internal.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/referrer.h"
#include "device/fido/features.h"
#include "gpu/config/gpu_switches.h"
#include "media/base/media_switches.h"
#include "net/base/features.h"
#include "services/device/public/cpp/device_features.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/base/ui_base_features.h"
#include "ui/events/blink/blink_features.h"
#include "ui/gfx/switches.h"
#include "ui/gl/gl_switches.h"
#include "ui/native_theme/native_theme_features.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
#endif
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using blink::WebRuntimeFeatures;
namespace {
// Sets blink runtime features for specific platforms.
// This should be a last resort vs runtime_enabled_features.json5.
void SetRuntimeFeatureDefaultsForPlatform(
const base::CommandLine& command_line) {
// Please consider setting up feature defaults for different platforms
// in runtime_enabled_features.json5 instead of here
// TODO(rodneyding): Move the more common cases here
// to baseFeature/switch functions below and move more complex
// ones to special case functions.
#if defined(USE_AURA)
WebRuntimeFeatures::EnableCompositedSelectionUpdate(true);
#endif
#if defined(OS_WIN)
if (base::win::GetVersion() >= base::win::Version::WIN10)
WebRuntimeFeatures::EnableWebBluetooth(true);
#endif
#if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT)
if (command_line.HasSwitch(switches::kEnableWebGL2ComputeContext)) {
WebRuntimeFeatures::EnableWebGL2ComputeContext(true);
}
#endif
#if defined(OS_MACOSX)
const bool enable_canvas_2d_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisable2dCanvasImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kCanvas2DImageChromium);
#else
constexpr bool enable_canvas_2d_image_chromium = false;
#endif
WebRuntimeFeatures::EnableCanvas2dImageChromium(
enable_canvas_2d_image_chromium);
#if defined(OS_MACOSX)
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisableWebGLImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kWebGLImageChromium);
#else
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(switches::kEnableWebGLImageChromium);
#endif
WebRuntimeFeatures::EnableWebGLImageChromium(enable_web_gl_image_chromium);
#if defined(OS_ANDROID)
if (command_line.HasSwitch(switches::kDisableMediaSessionAPI))
WebRuntimeFeatures::EnableMediaSession(false);
#endif
#if defined(OS_ANDROID)
// APIs for Web Authentication are not available prior to N.
WebRuntimeFeatures::EnableWebAuth(
base::FeatureList::IsEnabled(features::kWebAuth) &&
base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_NOUGAT);
#else
WebRuntimeFeatures::EnableWebAuth(
base::FeatureList::IsEnabled(features::kWebAuth));
#endif
WebRuntimeFeatures::EnableWebAuthenticationFeaturePolicy(
base::FeatureList::IsEnabled(device::kWebAuthFeaturePolicy));
#if defined(OS_ANDROID)
WebRuntimeFeatures::EnablePictureInPictureAPI(
base::FeatureList::IsEnabled(media::kPictureInPictureAPI));
#endif
#if defined(OS_ANDROID)
if (base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_P) {
// Display Cutout is limited to Android P+.
WebRuntimeFeatures::EnableDisplayCutoutAPI(true);
}
#endif
#if defined(OS_ANDROID)
WebRuntimeFeatures::EnableMediaControlsExpandGesture(
base::FeatureList::IsEnabled(media::kMediaControlsExpandGesture));
#endif
}
enum RuntimeFeatureEnableOptions {
// Always set the Blink feature to the enabled state of the base::Feature.
// Example: A run time feature that is completely controlled
// by base::Feature.
kUseFeatureState,
// Enables the Blink feature when the base::Feature is enabled,
// otherwise no change.
kEnableOnly,
// Enables the Blink feature when the base::Feature is enabled
// via an override on the command-line, otherwise no change.
kEnableOnlyIfOverriddenFromCommandLine,
// Disables the Blink feature when the base::Feature is *disabled*,
// otherwise no change.
kDisableOnly,
};
template <typename T>
// Helper class that describes the desired actions for the runtime feature
// depending on a check for chromium base::Feature.
struct RuntimeFeatureToChromiumFeatureMap {
// This can be either an enabler function defined in web_runtime_features.cc
// or the string name of the feature in runtime_enabled_features.json5.
T feature_enabler;
// The chromium base::Feature to check.
const base::Feature& chromium_feature;
const RuntimeFeatureEnableOptions option;
};
template <typename Enabler>
void SetRuntimeFeatureFromChromiumFeature(const base::Feature& chromium_feature,
RuntimeFeatureEnableOptions option,
const Enabler& enabler) {
using FeatureList = base::FeatureList;
const bool feature_enabled = FeatureList::IsEnabled(chromium_feature);
switch (option) {
case kEnableOnly:
if (feature_enabled)
enabler(true);
break;
case kEnableOnlyIfOverriddenFromCommandLine:
if (FeatureList::GetInstance()->IsFeatureOverriddenFromCommandLine(
chromium_feature.name, FeatureList::OVERRIDE_ENABLE_FEATURE)) {
DCHECK(feature_enabled);
enabler(true);
}
break;
case kDisableOnly:
if (!feature_enabled)
enabler(false);
break;
case kUseFeatureState:
enabler(feature_enabled);
break;
}
}
// Sets blink runtime features that are either directly
// controlled by Chromium base::Feature or are overridden
// by base::Feature states.
void SetRuntimeFeaturesFromChromiumFeatures() {
using wf = WebRuntimeFeatures;
// To add a runtime feature control, add a new
// RuntimeFeatureToChromiumFeatureMap entry here if there is a custom
// enabler function defined. Otherwise add the entry with string name
// in the next list.
const RuntimeFeatureToChromiumFeatureMap<void (*)(bool)>
blinkFeatureToBaseFeatureMapping[] =
{
// TODO(rodneyding): Sort features in alphabetical order
{wf::EnableWebUsb, features::kWebUsb, kDisableOnly},
{wf::EnableBlockingFocusWithoutUserActivation,
blink::features::kBlockingFocusWithoutUserActivation, kEnableOnly},
{wf::EnableNotificationContentImage, features::kNotificationContentImage,
kDisableOnly},
{wf::EnablePeriodicBackgroundSync, features::kPeriodicBackgroundSync,
kEnableOnly},
{wf::EnableWebXR, features::kWebXr, kUseFeatureState},
{wf::EnableWebXRARModule, features::kWebXrArModule, kUseFeatureState},
{wf::EnableWebXRHitTest, features::kWebXrHitTest, kUseFeatureState},
{wf::EnableWebXRIncubations, features::kWebXrIncubations, kEnableOnly},
{wf::EnableUserActivationPostMessageTransfer,
features::kUserActivationPostMessageTransfer, kUseFeatureState},
{wf::EnableUserActivationSameOriginVisibility,
features::kUserActivationSameOriginVisibility, kUseFeatureState},
{wf::EnableExpensiveBackgroundTimerThrottling,
features::kExpensiveBackgroundTimerThrottling, kUseFeatureState},
{wf::EnableTimerThrottlingForHiddenFrames,
features::kTimerThrottlingForHiddenFrames, kUseFeatureState},
{wf::EnableSendBeaconThrowForBlobWithNonSimpleType,
features::kSendBeaconThrowForBlobWithNonSimpleType, kEnableOnly},
{wf::EnablePaymentRequest, features::kWebPayments, kUseFeatureState},
{wf::EnablePaymentHandlerMinimalUI, features::kWebPaymentsMinimalUI,
kEnableOnly},
{wf::EnablePaymentApp, features::kServiceWorkerPaymentApps, kEnableOnly},
{wf::EnableGenericSensorExtraClasses, features::kGenericSensorExtraClasses,
kEnableOnly},
{wf::EnableMediaCastOverlayButton, media::kMediaCastOverlayButton,
kUseFeatureState},
{wf::EnableLazyInitializeMediaControls,
features::kLazyInitializeMediaControls, kUseFeatureState},
{wf::EnableMediaEngagementBypassAutoplayPolicies,
media::kMediaEngagementBypassAutoplayPolicies, kUseFeatureState},
{wf::EnableOverflowIconsForMediaControls,
media::kOverflowIconsForMediaControls, kUseFeatureState},
{wf::EnableAllowActivationDelegationAttr,
features::kAllowActivationDelegationAttr, kUseFeatureState},
{wf::EnableLazyFrameLoading, features::kLazyFrameLoading, kUseFeatureState},
{wf::EnableLazyFrameVisibleLoadTimeMetrics,
features::kLazyFrameVisibleLoadTimeMetrics, kUseFeatureState},
{wf::EnableLazyImageLoading, features::kLazyImageLoading, kUseFeatureState},
{wf::EnableLazyImageVisibleLoadTimeMetrics,
features::kLazyImageVisibleLoadTimeMetrics, kUseFeatureState},
{wf::EnablePictureInPicture, media::kPictureInPicture, kUseFeatureState},
{wf::EnableCacheInlineScriptCode, features::kCacheInlineScriptCode,
kUseFeatureState},
{wf::EnableExperimentalProductivityFeatures,
features::kExperimentalProductivityFeatures, kEnableOnly},
{wf::EnableFeaturePolicyForSandbox, features::kFeaturePolicyForSandbox,
kEnableOnly},
{wf::EnableAccessibilityExposeARIAAnnotations,
features::kEnableAccessibilityExposeARIAAnnotations, kEnableOnly},
{wf::EnableAccessibilityExposeDisplayNone,
features::kEnableAccessibilityExposeDisplayNone, kEnableOnly},
{wf::EnableAccessibilityExposeHTMLElement,
features::kEnableAccessibilityExposeHTMLElement, kUseFeatureState},
{wf::EnableAllowSyncXHRInPageDismissal,
blink::features::kAllowSyncXHRInPageDismissal, kEnableOnly},
{wf::EnableAutoplayIgnoresWebAudio, media::kAutoplayIgnoreWebAudio,
kUseFeatureState},
{wf::EnablePortals, blink::features::kPortals,
kEnableOnlyIfOverriddenFromCommandLine},
{wf::EnableImplicitRootScroller, blink::features::kImplicitRootScroller,
kUseFeatureState},
{wf::EnableCSSOMViewScrollCoordinates,
blink::features::kCSSOMViewScrollCoordinates, kEnableOnly},
{wf::EnableTextFragmentAnchor, blink::features::kTextFragmentAnchor,
kUseFeatureState},
{wf::EnableBackgroundFetch, features::kBackgroundFetch, kDisableOnly},
{wf::EnableForcedColors, features::kForcedColors, kUseFeatureState},
{wf::EnableFractionalScrollOffsets, features::kFractionalScrollOffsets,
kUseFeatureState},
{wf::EnableGetDisplayMedia, blink::features::kRTCGetDisplayMedia,
kUseFeatureState},
{wf::EnableSignedExchangePrefetchCacheForNavigations,
features::kSignedExchangePrefetchCacheForNavigations, kUseFeatureState},
{wf::EnableSignedExchangeSubresourcePrefetch,
features::kSignedExchangeSubresourcePrefetch, kUseFeatureState},
{wf::EnableIdleDetection, features::kIdleDetection, kDisableOnly},
{wf::EnableSkipTouchEventFilter, features::kSkipTouchEventFilter,
kUseFeatureState},
{wf::EnableSmsReceiver, features::kSmsReceiver, kDisableOnly},
{wf::EnableConsolidatedMovementXY, features::kConsolidatedMovementXY,
kUseFeatureState},
{wf::EnableCooperativeScheduling, features::kCooperativeScheduling,
kUseFeatureState},
{wf::EnableMouseSubframeNoImplicitCapture,
features::kMouseSubframeNoImplicitCapture, kUseFeatureState},
{wf::EnableCookieDeprecationMessages, features::kCookieDeprecationMessages,
kEnableOnly},
{wf::EnableSameSiteByDefaultCookies,
net::features::kSameSiteByDefaultCookies, kEnableOnly},
{wf::EnableCookiesWithoutSameSiteMustBeSecure,
net::features::kCookiesWithoutSameSiteMustBeSecure, kEnableOnly},
{wf::EnablePointerLockOptions, features::kPointerLockOptions, kEnableOnly},
{wf::EnableDocumentPolicy, features::kDocumentPolicy, kUseFeatureState},
{wf::EnableNeverSlowMode, features::kNeverSlowMode, kUseFeatureState},
{wf::EnableShadowDOMV0, blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{wf::EnableCustomElementsV0, blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{wf::EnableHTMLImports, blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{wf::EnableVideoPlaybackQuality, features::kVideoPlaybackQuality,
kUseFeatureState},
{wf::EnableBrowserVerifiedUserActivationKeyboard,
features::kBrowserVerifiedUserActivationKeyboard, kEnableOnly},
{wf::EnableBrowserVerifiedUserActivationMouse,
features::kBrowserVerifiedUserActivationMouse, kEnableOnly},
{wf::EnablePercentBasedScrolling, features::kPercentBasedScrolling,
kUseFeatureState},
#if defined(OS_ANDROID)
{wf::EnableWebNfc, features::kWebNfc, kDisableOnly},
#endif
{wf::EnableTrustTokens, network::features::kTrustTokens, kEnableOnly},
};
for (const auto& mapping : blinkFeatureToBaseFeatureMapping) {
SetRuntimeFeatureFromChromiumFeature(
mapping.chromium_feature, mapping.option, mapping.feature_enabler);
}
// TODO(crbug/832393): Cleanup the inconsistency between custom WRF enabler
// function and using feature string name with EnableFeatureFromString.
const RuntimeFeatureToChromiumFeatureMap<const char*>
runtimeFeatureNameToChromiumFeatureMapping[] = {
{"AddressSpace", network::features::kBlockNonSecureExternalRequests,
kEnableOnly},
{"AllowContentInitiatedDataUrlNavigations",
features::kAllowContentInitiatedDataUrlNavigations,
kUseFeatureState},
{"AppCache", blink::features::kAppCache, kDisableOnly},
{"AudioWorkletRealtimeThread",
blink::features::kAudioWorkletRealtimeThread, kEnableOnly},
{"BlockCredentialedSubresources",
features::kBlockCredentialedSubresources, kDisableOnly},
{"BlockHTMLParserOnStyleSheets",
blink::features::kBlockHTMLParserOnStyleSheets, kUseFeatureState},
{"ConversionMeasurement", features::kConversionMeasurement,
kEnableOnly},
{"CSSReducedFontLoadingInvalidations",
blink::features::kCSSReducedFontLoadingInvalidations,
kUseFeatureState},
{"CustomElementsV0", blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{"FeaturePolicyForClientHints",
features::kFeaturePolicyForClientHints, kUseFeatureState},
{"LayoutNGFlexBox", blink::features::kFlexNG, kEnableOnly},
{"FontAccess", blink::features::kFontAccess, kUseFeatureState},
{"FontSrcLocalMatching", features::kFontSrcLocalMatching,
kUseFeatureState},
{"HTMLImports", blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{"IgnoreCrossOriginWindowWhenNamedAccessOnWindow",
blink::features::kIgnoreCrossOriginWindowWhenNamedAccessOnWindow,
kEnableOnly},
{"LayoutNG", blink::features::kLayoutNG, kUseFeatureState},
{"LegacyWindowsDWriteFontFallback",
features::kLegacyWindowsDWriteFontFallback, kUseFeatureState},
{"OriginPolicy", features::kOriginPolicy, kUseFeatureState},
{"ShadowDOMV0", blink::features::kWebComponentsV0Enabled,
kEnableOnly},
{"StorageAccessAPI", blink::features::kStorageAccessAPI, kEnableOnly},
{"TrustedDOMTypes", features::kTrustedDOMTypes, kEnableOnly},
{"UserAgentClientHint", features::kUserAgentClientHint, kEnableOnly},
};
for (const auto& mapping : runtimeFeatureNameToChromiumFeatureMapping) {
SetRuntimeFeatureFromChromiumFeature(
mapping.chromium_feature, mapping.option, [&mapping](bool enabled) {
wf::EnableFeatureFromString(mapping.feature_enabler, enabled);
});
}
}
// Helper class that describes the desired enable/disable action
// for a runtime feature when a command line switch exists.
struct SwitchToFeatureMap {
// The enabler function defined in web_runtime_features.cc.
void (*feature_enabler)(bool);
// The switch to check for on command line.
const char* switch_name;
// This is the desired state for the runtime feature if the
// switch exists on command line.
bool target_enabled_state;
};
// Sets blink runtime features controlled by command line switches.
void SetRuntimeFeaturesFromCommandLine(const base::CommandLine& command_line) {
// To add a new switch-controlled runtime feature, add a new
// SwitchToFeatureMap entry to the initializer list below.
// Note: command line switches are now discouraged, please consider
// using base::Feature instead.
// https://chromium.googlesource.com/chromium/src/+/refs/heads/master/docs/configuration.md#switches
using wrf = WebRuntimeFeatures;
const SwitchToFeatureMap switchToFeatureMapping[] = {
// Stable Features
{wrf::EnablePermissionsAPI, switches::kDisablePermissionsAPI, false},
{wrf::EnablePresentationAPI, switches::kDisablePresentationAPI, false},
{wrf::EnableRemotePlaybackAPI, switches::kDisableRemotePlaybackAPI,
false},
{wrf::EnableTimerThrottlingForBackgroundTabs,
switches::kDisableBackgroundTimerThrottling, false},
// End of Stable Features
{wrf::EnableDatabase, switches::kDisableDatabases, false},
{wrf::EnableNotifications, switches::kDisableNotifications, false},
// Chrome's Push Messaging implementation relies on Web Notifications.
{wrf::EnablePushMessaging, switches::kDisableNotifications, false},
{wrf::EnableSharedWorker, switches::kDisableSharedWorkers, false},
{wrf::EnableScriptedSpeechRecognition, switches::kDisableSpeechAPI,
false},
{wrf::EnableScriptedSpeechSynthesis, switches::kDisableSpeechAPI, false},
{wrf::EnableScriptedSpeechSynthesis, switches::kDisableSpeechSynthesisAPI,
false},
{wrf::EnableFileSystem, switches::kDisableFileSystem, false},
{wrf::EnableWebGLDraftExtensions, switches::kEnableWebGLDraftExtensions,
true},
{wrf::EnableAutomationControlled, switches::kEnableAutomation, true},
{wrf::EnableAutomationControlled, switches::kHeadless, true},
{wrf::EnableAutomationControlled, switches::kRemoteDebuggingPipe, true},
{wrf::EnableAutomationControlled, switches::kRemoteDebuggingPort, true},
{wrf::ForceOverlayFullscreenVideo, switches::kForceOverlayFullscreenVideo,
true},
{wrf::EnablePreciseMemoryInfo, switches::kEnablePreciseMemoryInfo, true},
{wrf::EnableNetInfoDownlinkMax,
switches::kEnableNetworkInformationDownlinkMax, true},
{wrf::EnablePermissionsAPI, switches::kDisablePermissionsAPI, false},
{wrf::EnableWebGPU, switches::kEnableUnsafeWebGPU, true},
{wrf::EnablePresentationAPI, switches::kDisablePresentationAPI, false},
{wrf::EnableTextFragmentAnchor, switches::kDisableScrollToTextFragment,
false},
{wrf::EnableRemotePlaybackAPI, switches::kDisableRemotePlaybackAPI,
false},
{wrf::EnableTimerThrottlingForBackgroundTabs,
switches::kDisableBackgroundTimerThrottling, false},
{wrf::EnableAccessibilityObjectModel,
switches::kEnableAccessibilityObjectModel, true},
{wrf::EnableAllowSyncXHRInPageDismissal,
switches::kAllowSyncXHRInPageDismissal, true},
{wrf::EnableShadowDOMV0, switches::kWebComponentsV0Enabled, true},
{wrf::EnableCustomElementsV0, switches::kWebComponentsV0Enabled, true},
{wrf::EnableHTMLImports, switches::kWebComponentsV0Enabled, true},
};
for (const auto& mapping : switchToFeatureMapping) {
if (command_line.HasSwitch(mapping.switch_name))
mapping.feature_enabler(mapping.target_enabled_state);
}
}
// Sets blink runtime features controlled by FieldTrial parameter values.
void SetRuntimeFeaturesFromFieldTrialParams() {
// Automatic lazy frame loading by default is enabled and restricted to users
// with Lite Mode (aka Data Saver) turned on. Note that in practice, this also
// restricts automatic lazy loading by default to Android, since Lite Mode is
// only accessible through UI on Android.
WebRuntimeFeatures::EnableAutomaticLazyFrameLoading(
base::GetFieldTrialParamByFeatureAsBool(
features::kLazyFrameLoading, "automatic-lazy-load-frames-enabled",
true));
WebRuntimeFeatures::EnableRestrictAutomaticLazyFrameLoadingToDataSaver(
base::GetFieldTrialParamByFeatureAsBool(
features::kLazyFrameLoading,
"restrict-lazy-load-frames-to-data-saver-only", true));
WebRuntimeFeatures::EnableAutoLazyLoadOnReloads(
base::GetFieldTrialParamByFeatureAsBool(
features::kLazyFrameLoading, "enable-lazy-load-on-reload", false));
// Automatic lazy image loading by default is enabled and restricted to users
// with Lite Mode (aka Data Saver) turned on. Note that in practice, this also
// restricts automatic lazy loading by default to Android, since Lite Mode is
// only accessible through UI on Android.
WebRuntimeFeatures::EnableAutomaticLazyImageLoading(
base::GetFieldTrialParamByFeatureAsBool(
features::kLazyImageLoading, "automatic-lazy-load-images-enabled",
true));
WebRuntimeFeatures::EnableRestrictAutomaticLazyImageLoadingToDataSaver(
base::GetFieldTrialParamByFeatureAsBool(
features::kLazyImageLoading,
"restrict-lazy-load-images-to-data-saver-only", true));
}
// Sets blink runtime features that depend on a combination
// of args rather than a single check of base::Feature or switch.
// This can be a combination of both or custom checking logic
// not covered by other functions. In short, this should be used
// as a last resort.
void SetCustomizedRuntimeFeaturesFromCombinedArgs(
const base::CommandLine& command_line,
bool enable_experimental_web_platform_features) {
// CAUTION: Only add custom enabling logic here if it cannot
// be covered by the other functions.
if (!command_line.HasSwitch(switches::kDisableYUVImageDecoding) &&
base::FeatureList::IsEnabled(
blink::features::kDecodeJpeg420ImagesToYUV)) {
WebRuntimeFeatures::EnableDecodeJpeg420ImagesToYUV(true);
}
if (!command_line.HasSwitch(switches::kDisableYUVImageDecoding) &&
base::FeatureList::IsEnabled(
blink::features::kDecodeLossyWebPImagesToYUV)) {
WebRuntimeFeatures::EnableDecodeLossyWebPImagesToYUV(true);
}
WebRuntimeFeatures::EnableSharedArrayBuffer(
base::FeatureList::IsEnabled(features::kSharedArrayBuffer) ||
base::FeatureList::IsEnabled(features::kWebAssemblyThreads));
// These checks are custom wrappers around base::FeatureList::IsEnabled
// They're moved here to distinguish them from actual base checks
WebRuntimeFeatures::EnableOverlayScrollbars(ui::IsOverlayScrollbarEnabled());
if (base::FeatureList::GetInstance()->IsFeatureOverriddenFromCommandLine(
blink::features::kNativeFileSystemAPI.name,
base::FeatureList::OVERRIDE_ENABLE_FEATURE)) {
WebRuntimeFeatures::EnableFeatureFromString("NativeFileSystem", true);
WebRuntimeFeatures::EnableFeatureFromString(
"CloneableNativeFileSystemHandles", true);
WebRuntimeFeatures::EnableFeatureFromString("WritableFileStream", true);
}
if (base::FeatureList::IsEnabled(blink::features::kNativeFileSystemAPI) &&
base::FeatureList::IsEnabled(blink::features::kFileHandlingAPI)) {
WebRuntimeFeatures::EnableFeatureFromString("FileHandling", true);
}
// TODO(rodneyding): This is a rare case for a stable feature
// Need to investigate more to determine whether to refactor it.
if (command_line.HasSwitch(switches::kDisableV8IdleTasks))
WebRuntimeFeatures::EnableV8IdleTasks(false);
else
WebRuntimeFeatures::EnableV8IdleTasks(true);
// This is a hack to get the tests passing as they require
// these blink features to be enabled while they are disabled
// by base::Feature controls earlier in code.
// TODO(rodneyding): Investigate more on proper treatments of
// these features.
if (enable_experimental_web_platform_features) {
WebRuntimeFeatures::EnableNetInfoDownlinkMax(true);
}
WebRuntimeFeatures::EnableBackForwardCache(
content::IsBackForwardCacheEnabled());
// Gate the ReducedReferrerGranularity runtime feature depending on whether
// content is configured to force a no-referrer-when-downgrade default policy.
// TODO(crbug.com/1016541): After M82, remove when the corresponding
// enterprise policy has been deleted.
WebRuntimeFeatures::EnableReducedReferrerGranularity(
base::FeatureList::IsEnabled(features::kReducedReferrerGranularity) &&
!content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());
}
} // namespace
namespace content {
void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
const base::CommandLine& command_line) {
// Sets experimental features.
bool enable_experimental_web_platform_features =
command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
if (enable_experimental_web_platform_features)
WebRuntimeFeatures::EnableExperimentalFeatures(true);
SetRuntimeFeatureDefaultsForPlatform(command_line);
// Sets origin trial features.
if (command_line.HasSwitch(
switches::kDisableOriginTrialControlledBlinkFeatures)) {
WebRuntimeFeatures::EnableOriginTrialControlledFeatures(false);
}
if (!command_line.HasSwitch(
network::switches::kForceToDisableOutOfBlinkCors) &&
base::FeatureList::IsEnabled(network::features::kOutOfBlinkCors)) {
WebRuntimeFeatures::EnableOutOfBlinkCors(true);
}
// TODO(rodneyding): add doc explaining ways to add new runtime features
// controls in the following functions.
SetRuntimeFeaturesFromChromiumFeatures();
SetRuntimeFeaturesFromCommandLine(command_line);
SetRuntimeFeaturesFromFieldTrialParams();
SetCustomizedRuntimeFeaturesFromCombinedArgs(
command_line, enable_experimental_web_platform_features);
// Enable explicitly enabled features, and then disable explicitly disabled
// ones.
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kEnableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, true);
}
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kDisableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, false);
}
}
} // namespace content
| 45.348185 | 102 | 0.762163 | sarang-apps |
f859bebd724186d33d763504c385dacb0309ff7e | 4,430 | cpp | C++ | src/in_2sf/desmume/addons/slot1_retail.cpp | CyberBotX/in_xsf | 6d78469746b17bf1a9356c7a26ecd2850ba46eb3 | [
"BSD-3-Clause"
] | 15 | 2015-09-04T10:36:15.000Z | 2022-02-23T23:52:37.000Z | src/in_2sf/desmume/addons/slot1_retail.cpp | WACUP/in_xsf | 719f5b443af91e53f35f86055dd0b1b4851db2b0 | [
"BSD-3-Clause"
] | 3 | 2017-11-09T18:09:47.000Z | 2021-02-04T05:39:09.000Z | src/in_2sf/desmume/addons/slot1_retail.cpp | WACUP/in_xsf | 719f5b443af91e53f35f86055dd0b1b4851db2b0 | [
"BSD-3-Clause"
] | 9 | 2016-11-22T10:05:20.000Z | 2021-06-12T19:48:53.000Z | /* Copyright (C) 2010-2011 DeSmuME team
This file is part of DeSmuME
DeSmuME 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.
DeSmuME 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 DeSmuME; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "../slot1.h"
#include "../registers.h"
#include "../MMU.h"
#include "../NDSSystem.h"
static void info(char *info) { strcpy(info, "Slot1 Retail card emulation"); }
static void config() {}
static bool init() { return true; }
static void reset() {}
static void close() {}
static void write08(uint8_t, uint32_t, uint8_t) {}
static void write16(uint8_t, uint32_t, uint16_t) {}
static void write32_GCROMCTRL(uint8_t PROCNUM, uint32_t)
{
nds_dscard &card = MMU.dscard[PROCNUM];
switch (card.command[0])
{
case 0x00: // Data read
case 0xB7:
card.address = (card.command[1] << 24) | (card.command[2] << 16) | (card.command[3] << 8) | card.command[4];
card.transfer_count = 0x80;
break;
case 0xB8: // Chip ID
card.address = 0;
card.transfer_count = 1;
break;
default:
card.address = 0;
card.transfer_count = 0;
}
}
static void write32(uint8_t PROCNUM, uint32_t adr, uint32_t val)
{
switch (adr)
{
case REG_GCROMCTRL:
write32_GCROMCTRL(PROCNUM, val);
}
}
static uint8_t read08(uint8_t, uint32_t)
{
return 0xFF;
}
static uint16_t read16(uint8_t, uint32_t)
{
return 0xFFFF;
}
static uint32_t read32_GCDATAIN(uint8_t PROCNUM)
{
nds_dscard &card = MMU.dscard[PROCNUM];
switch (card.command[0])
{
// Get ROM chip ID
case 0x90:
case 0xB8:
{
// Note: the BIOS stores the chip ID in main memory
// Most games continuously compare the chip ID with
// the value in memory, probably to know if the card
// was removed.
// As DeSmuME normally boots directly from the game, the chip
// ID in main mem is zero and this value needs to be
// zero too.
// note that even if desmume was booting from firmware, and reading this chip ID to store in main memory,
// this still works, since it will have read 00 originally and then read 00 to validate.
// staff of kings verifies this (it also uses the arm7 IRQ 20)
if (nds.cardEjected) // TODO - handle this with ejected card slot1 device (and verify using this case)
return 0xFFFFFFFF;
else
return 0;
}
// Data read
case 0x00:
case 0xB7:
{
// it seems that etrian odyssey 3 doesnt work unless we mask this to cart size.
// but, a thought: does the internal rom address counter register wrap around? we may be making a mistake by keeping the extra precision
// but there is no test case yet
uint32_t address = card.address & gameInfo.mask;
// Make sure any reads below 0x8000 redirect to 0x8000+(adr&0x1FF) as on real cart
if (card.command[0] == 0xB7 && address < 0x8000)
{
// TODO - refactor this to include the PROCNUM, for debugging purposes if nothing else
// (can refactor gbaslot also)
//INFO("Read below 0x8000 (0x%04X) from: ARM%s %08X\n", card.address, (PROCNUM ? "7":"9"), (PROCNUM ? NDS_ARM7:NDS_ARM9).instruct_adr);
address = 0x8000 + (address & 0x1FF);
}
// as a sanity measure for funny-sized roms (homebrew and perhaps truncated retail roms)
// we need to protect ourselves by returning 0xFF for things still out of range
if (address >= gameInfo.romsize)
{
//DEBUG_Notify.ReadBeyondEndOfCart(address, gameInfo. romsize);
return 0xFFFFFFFF;
}
return T1ReadLong(MMU.CART_ROM, address);
}
default:
return 0;
} //switch(card.command[0])
} //read32_GCDATAIN
static uint32_t read32(uint8_t PROCNUM, uint32_t adr)
{
switch (adr)
{
case REG_GCDATAIN:
return read32_GCDATAIN(PROCNUM);
default:
return 0;
}
}
SLOT1INTERFACE slot1Retail =
{
"Retail",
init,
reset,
close,
config,
write08,
write16,
write32,
read08,
read16,
read32,
info
};
| 26.369048 | 140 | 0.688713 | CyberBotX |
f85d695eed711dbf2fc70ef58615aa9d44d562b1 | 799 | cpp | C++ | arc060_b/Main.cpp | s-shirayama/AtCoder | 8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8 | [
"MIT"
] | null | null | null | arc060_b/Main.cpp | s-shirayama/AtCoder | 8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8 | [
"MIT"
] | null | null | null | arc060_b/Main.cpp | s-shirayama/AtCoder | 8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define REP(i, n, s) for (LL i = (s); i < (n); i++)
#define SIZE 1
using namespace std;
typedef long long int LL;
typedef long double LD;
LL func(LL b, LL n) {
if (n < b) return n;
return func(b, floor(n/b)) + (n % b);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
LL N, S;
cin >> N >> S;
LL res = -1;
LL _N = ceil(sqrt((double)N));
REP(i, _N+1, 2) {
if (func(i, N) == S && res == -1) {
res = i;
break;
}
}
if (res != -1) {
cout << res << endl;
return 0;
}
for (LL p = _N - 1; p > 0; p--) {
if (S < p) continue;
LL q = S - p, b = (N - q) / p;
if ((N - q)%p == 0 && q < b && b > _N) {
res = (N - q) / p;
break;
}
}
if (res == -1 && N == S) {
cout << (N+1) << endl;
return 0;
}
cout << res << endl;
return 0;
}
| 15.365385 | 51 | 0.459324 | s-shirayama |
f86122b64e73a12002a05e074d397c9ae9536865 | 26 | cc | C++ | examples/POSIX/json-rpc-server/jsonRpcServer.cc | PetroShevchenko/lib-coap-cpp | f99bff174925257ea63480f598f5753ece0f392d | [
"Apache-2.0"
] | null | null | null | examples/POSIX/json-rpc-server/jsonRpcServer.cc | PetroShevchenko/lib-coap-cpp | f99bff174925257ea63480f598f5753ece0f392d | [
"Apache-2.0"
] | null | null | null | examples/POSIX/json-rpc-server/jsonRpcServer.cc | PetroShevchenko/lib-coap-cpp | f99bff174925257ea63480f598f5753ece0f392d | [
"Apache-2.0"
] | null | null | null | #include "jsonRpcServer.h" | 26 | 26 | 0.807692 | PetroShevchenko |
f861ec595025bdb258c2ae0cb3f416f88b0a6742 | 1,583 | cpp | C++ | C++/Valid Sudoku.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | 3 | 2015-08-29T15:25:13.000Z | 2015-08-29T15:25:21.000Z | C++/Valid Sudoku.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | null | null | null | C++/Valid Sudoku.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | null | null | null | // Valid Sudoku
// Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
// The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
// A partially filled sudoku which is valid.
// Note:
// A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
//My solution
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board)
{
if(board.size() != 9 || board[0].size() != 9)
return false;
for(int i = 0; i< 9 ; i++)
{
if(checkNine(board,i,i,0,8) == false)
return false;
if(checkNine(board,0,8,i,i) == false)
return false;
}
for (int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if (!checkNine(board,i*3,i*3+2,j*3,j*3+2)) return false;
}
return true;
}
bool checkNine(vector<vector<char>>& board,int x1,int x2,int y1,int y2)
{
vector<int> countArray(board.size(),0);
for(int i = x1;i<=x2;i++)
for(int j = y1;j<=y2;j++)
{
if(board[i][j] != '.')
{
int k = board[i][j] - '1';
if(countArray[k] == 0)
{
countArray[k] = 1;
}
else
return false;
}
}
return true;
}
}; | 25.532258 | 115 | 0.44662 | mafia1989 |
d379c1471b7caf3cdbf0d0efade3bd5a414b6754 | 1,437 | cpp | C++ | tests/TestMain.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | 2 | 2021-01-27T15:49:04.000Z | 2021-01-28T07:40:30.000Z | tests/TestMain.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | null | null | null | tests/TestMain.cpp | RaygenEngine/Raygen | 2e61afd35f594d06186c16397b536412ebf4298d | [
"MIT"
] | 1 | 2021-03-07T23:17:31.000Z | 2021-03-07T23:17:31.000Z | #include "pch.h"
#include "engine/Logger.h"
#define CATCH_CONFIG_RUNNER
#include <catch2/catch.hpp>
int main(int argc, char* argv[])
{
Catch::Session session; // There must be exactly one instance
int height = 0; // Some user variable you want to be able to set
Log.Init(LogLevel::Error);
// Build a new parser on top of Catch's
using namespace Catch::clara;
auto cli = session.cli() // Get Catch's composite command line parser
| Opt(height, "height") // bind variable to a new option, with a hint string
["-g"]["--height"] // the option names it will respond to
("how high?"); // description string for the help output
// Now pass the new composite back to Catch so it uses that
session.cli(cli);
// Let Catch (using Clara) parse the command line
int returnCode = session.applyCommandLine(argc, argv);
if (returnCode != 0) // Indicates a command line error
return returnCode;
// if set on the command line then 'height' is now set at this point
if (height > 0)
std::cout << "height: " << height << std::endl;
return session.run();
}
/*
#include "pch/pch.h"
#include "AppBase.h"
#include "engine/Logger.h"
#include <iostream>
int32 main(int32 argc, char* argv[])
{
std::cout << "Hello Test!\n";
// Init logger (global access, not engine, app or window bound)
LOGGER_INIT(LogLevel::INFO);
App app;
app.PreMainInit(argc, argv);
return app.Main(argc, argv);
}
*/
| 26.127273 | 82 | 0.673626 | RaygenEngine |
d379d8ce06495b08d7e48b8db08585337b63ea5a | 2,968 | tpp | C++ | core/src/function_space/03_function_space_partition_composite.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | core/src/function_space/03_function_space_partition_composite.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | core/src/function_space/03_function_space_partition_composite.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #include "function_space/03_function_space_partition.h"
#include <cmath>
#include <array>
#include <sstream>
#include "easylogging++.h"
#include "utility/python_utility.h"
namespace FunctionSpace
{
// forward declaration
template<typename MeshType,typename BasisFunctionType>
class FunctionSpace;
template<int D,typename BasisFunctionType>
FunctionSpacePartition<Mesh::CompositeOfDimension<D>,BasisFunctionType>::
FunctionSpacePartition(std::shared_ptr<Partition::Manager> partitionManager,
std::vector<std::shared_ptr<FunctionSpace<Mesh::StructuredDeformableOfDimension<D>,BasisFunctionType>>> subFunctionSpaces) :
FunctionSpacePartitionBase<Mesh::CompositeOfDimension<D>,BasisFunctionType>::FunctionSpacePartitionBase(partitionManager, PythonConfig()),
subFunctionSpaces_(subFunctionSpaces)
{
// the subFunctionSpaces have been created and initialized by the mesh manager
}
//! constructor dummy with node positions vector
template<int D,typename BasisFunctionType>
FunctionSpacePartition<Mesh::CompositeOfDimension<D>,BasisFunctionType>::
FunctionSpacePartition(std::shared_ptr<Partition::Manager> partitionManager, std::vector<double> &nodePositions,
std::vector<std::shared_ptr<FunctionSpace<Mesh::StructuredDeformableOfDimension<D>,BasisFunctionType>>> subFunctionSpaces) :
FunctionSpacePartitionBase<Mesh::CompositeOfDimension<D>,BasisFunctionType>::FunctionSpacePartitionBase(partitionManager, PythonConfig()),
subFunctionSpaces_(subFunctionSpaces)
{
}
template<int D,typename BasisFunctionType>
void FunctionSpacePartition<Mesh::CompositeOfDimension<D>,BasisFunctionType>::
initialize()
{
VLOG(1) << "FunctionSpacePartition<Composite>::initialize()";
// initialize number of local and global elements
this->nElementsLocal_ = 0;
this->nElementsGlobal_ = 0;
// iterate over submeshes
for(std::shared_ptr<SubFunctionSpaceType> &subFunctionSpace : subFunctionSpaces_)
{
subFunctionSpace->initialize();
// count number of elements
this->nElementsLocal_ += subFunctionSpace->nElementsLocal();
this->nElementsGlobal_ += subFunctionSpace->nElementsGlobal();
}
// create partitioning
assert(this->partitionManager_ != nullptr);
std::vector<int> rankNos;
if (this->specificSettings_.hasKey("rankNos"))
this->specificSettings_.template getOptionVector<int>("rankNos", rankNos);
this->meshPartition_ = this->partitionManager_->template createPartitioningComposite<BasisFunctionType,D>(subFunctionSpaces_, rankNos);
assert(this->meshPartition_);
// set initalized_ to true which indicates that initialize has been called
this->initialized_ = true;
}
template<int D,typename BasisFunctionType>
const std::vector<std::shared_ptr<FunctionSpace<Mesh::StructuredDeformableOfDimension<D>,BasisFunctionType>>> &
FunctionSpacePartition<Mesh::CompositeOfDimension<D>,BasisFunctionType>::
subFunctionSpaces()
{
return subFunctionSpaces_;
}
} // namespace
| 37.1 | 148 | 0.790768 | maierbn |
d37bb5937797e26b8648e5cd79d5d1c5f0f70e42 | 1,217 | cpp | C++ | src/mt-options.cpp | chrmoritz/lzma-native | 313fb09ede27bed1c4e7f189b5fc99eadfddb5c2 | [
"MIT"
] | 20 | 2019-09-02T02:14:47.000Z | 2022-02-23T23:13:50.000Z | src/mt-options.cpp | chrmoritz/lzma-native | 313fb09ede27bed1c4e7f189b5fc99eadfddb5c2 | [
"MIT"
] | 7 | 2019-09-06T08:23:55.000Z | 2021-03-19T11:59:39.000Z | node_modules/lzma-native/src/mt-options.cpp | 96vksingh/nodejs_action | 675a6bd8dfd3aa25c0863d1cec9597b71fbdac58 | [
"MIT"
] | 3 | 2019-09-22T20:57:13.000Z | 2022-01-03T16:59:03.000Z | #include "liblzma-node.hpp"
namespace lzma {
MTOptions::MTOptions() : filters_(NULL), ok_(false) { }
MTOptions::~MTOptions() {
delete filters_;
}
MTOptions::MTOptions(Local<Object> opt) : filters_(NULL), ok_(true) {
opts_.flags = 0;
opts_.filters = NULL;
opts_.block_size = Nan::To<int64_t>(Nan::Get(opt, NewString("blockSize")).ToLocalChecked()).ToChecked();
opts_.timeout = Nan::To<uint32_t>(Nan::Get(opt, NewString("timeout")).ToLocalChecked())
.FromMaybe(0);
opts_.preset = Nan::To<uint32_t>(Nan::Get(opt, NewString("preset")).ToLocalChecked())
.FromMaybe(LZMA_PRESET_DEFAULT);
opts_.check = (lzma_check)Nan::To<int32_t>(Nan::Get(opt, NewString("check")).ToLocalChecked())
.FromMaybe((int)LZMA_CHECK_CRC64);
opts_.threads = Nan::To<uint32_t>(Nan::Get(opt, NewString("threads")).ToLocalChecked())
.FromMaybe(0);
if (opts_.threads == 0) {
opts_.threads = lzma_cputhreads();
}
Local<Value> filters = Nan::Get(opt, NewString("filters")).ToLocalChecked();
if (filters->IsArray()) {
filters_ = new FilterArray(Local<Array>::Cast(filters));
if (filters_->ok()) {
opts_.filters = filters_->array();
} else {
ok_ = false;
}
}
}
}
| 29.682927 | 106 | 0.657354 | chrmoritz |
d37c1e9430bcf7605b43ebd233675f37195dea3d | 3,642 | cpp | C++ | src/GameOptionsManager.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | src/GameOptionsManager.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | src/GameOptionsManager.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | #include "../include/GameOptionsManager.hpp"
GameOptionsManager* GameOptionsManager::instance = nullptr;
GameOptionsManager* GameOptionsManager::getInstance()
{
if(instance == nullptr)
{
instance = new GameOptionsManager();
}
return instance;
}
void GameOptionsManager::setGameStartingPlayer(const GameParticipant& PLAYER)
{
gameStartingPlayer = PLAYER;
}
void GameOptionsManager::switchHumanAndComputerChar()
{
char tempHumanChar = humanChar;
humanChar = computerChar;
computerChar = tempHumanChar;
}
void GameOptionsManager::setPointsRequiredForVictory(const int NEW_POINTS)
{
if (NEW_POINTS < MIN_POINTS_FOR_VICTORY || NEW_POINTS > boardSize)
{
std::string exceptionMessage = "Invalid new amount of points required for victory. Recived argument = "
+ std::to_string(NEW_POINTS) + "\n";
throw std::invalid_argument( exceptionMessage );
}
pointsRequiredForVictory = NEW_POINTS;
}
void GameOptionsManager::setBoardSize(const int NEW_BOARD_SIZE)
{
if (NEW_BOARD_SIZE < MIN_BOARD_SIZE || NEW_BOARD_SIZE > MAX_BOARD_SIZE)
{
std::string exceptionMessage = "Invalid new board size. Recived argument = " + std::to_string(NEW_BOARD_SIZE) + "\n";
throw std::invalid_argument( exceptionMessage );
}
boardSize = NEW_BOARD_SIZE;
}
const Participant GameOptionsManager::getEnumAssignedTo(const char CHAR) const
{
if ( (CHAR != EMPTY_SLOT_CHAR) && (CHAR != humanChar) && (CHAR != computerChar) )
{
std::string exceptionMessage = "Invalid char. There is no Game Participant assigned to " + std::to_string(CHAR) + "\n";
throw std::invalid_argument( exceptionMessage );
}
if (CHAR == humanChar)
{
return HUMAN;
}
else if (CHAR == computerChar)
{
return COMPUTER;
}
else
{
return NONE;
}
}
const char GameOptionsManager::getCharAssignedTo(const Participant& PLAYER) const
{
if (PLAYER == NONE)
{
return EMPTY_SLOT_CHAR;
}
else if (PLAYER == HUMAN)
{
return humanChar;
}
else
{
return computerChar;
}
}
const int GameOptionsManager::getDepthBound(const int BOARD_SIZE) const
{
switch (BOARD_SIZE)
{
case 3:
return DEPTH_BOUND_3x3;
case 4:
return DEPTH_BOUND_4x4;
case 5:
return DEPTH_BOUND_5x5;
case 6:
return DEPTH_BOUND_6x6;
case 7:
return DEPTH_BOUND_7x7;
case 8:
return DEPTH_BOUND_8x8;
case 9:
return DEPTH_BOUND_9x9;
case 10:
return DEPTH_BOUND_10x10;
default:
break;
}
throw std::invalid_argument("Invalid argument. Recived argument = " + std::to_string(BOARD_SIZE) +"\n");
}
const Participant GameOptionsManager::getGameStartingPlayer() const
{
return gameStartingPlayer;
}
const Participant GameOptionsManager::getOppositePlayer(const Participant& PLAYER) const
{
return static_cast<Participant>( PLAYER*(-1) );
}
const int GameOptionsManager::getPointsRequiredForVictory() const
{
return pointsRequiredForVictory;
}
const int GameOptionsManager::getBoardSize() const
{
return boardSize;
}
const int GameOptionsManager::getMinBoardSize() const
{
return MIN_BOARD_SIZE;
}
const int GameOptionsManager::getMinPointsForVictory() const
{
return MIN_POINTS_FOR_VICTORY;
}
const int GameOptionsManager::getMaxBoardSize() const
{
return MAX_BOARD_SIZE;
} | 24.119205 | 127 | 0.654036 | psobow |
d380deef0233914b2b3a1961cd6f31b477311473 | 1,021 | cpp | C++ | COGengine/src/Core/AsyncProcess.cpp | dodoknight/CogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 3 | 2016-06-01T10:14:00.000Z | 2016-10-11T15:53:45.000Z | COGengine/src/Core/AsyncProcess.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | null | null | null | COGengine/src/Core/AsyncProcess.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 1 | 2020-08-15T17:01:00.000Z | 2020-08-15T17:01:00.000Z | #include "AsyncProcess.h"
#include "Scene.h"
#include "Stage.h"
#include "ComponentStorage.h"
namespace Cog {
SceneLoader::SceneLoader(Scene* scene, stenum tweenDir)
: scene(scene), tweenDir(tweenDir) {
}
void SceneLoader::DoJob() {
spt<xml_document> scenes = CogPreloadXMLFile(ofToDataPath(PATH_SCENES));
auto scenesNode = scenes->children("scene");
for (auto sceneNode : scenesNode) {
// just load scene from XML and switch to it
string name = sceneNode.attribute("name").as_string();
if (name.compare(scene->GetName()) == 0) {
scene->LoadFromXml(sceneNode);
break;
}
}
// switch to scene
auto stage = GETCOMPONENT(Stage);
scene->GetSceneNode()->SubmitChanges(true);
stage->SwitchToScene(scene, tweenDir);
}
void AsyncProcess::threadedFunction()
{
COGLOGDEBUG("AsyncProcess", "Running threaded job %s", typeid(this->job).name());
job->DoJob();
COGLOGDEBUG("AsyncProcess", "Finishing threaded job %s", typeid(this->job).name());
delete job;
}
} // namespace | 25.525 | 85 | 0.691479 | dodoknight |
d3827fa9bb01a457c202c7e679efccf122e45d32 | 481 | hpp | C++ | source/standalone/config/chimera/chimeraPort.hpp | brandonbraun653/Loki | 65c9472a81f66c13b729d7c2047013d1198f0c3c | [
"MIT"
] | 1 | 2020-02-23T09:55:46.000Z | 2020-02-23T09:55:46.000Z | source/standalone/config/chimera/chimeraPort.hpp | brandonbraun653/Loki | 65c9472a81f66c13b729d7c2047013d1198f0c3c | [
"MIT"
] | 28 | 2019-04-02T17:12:19.000Z | 2020-12-13T15:12:23.000Z | source/standalone/config/chimera/chimeraPort.hpp | brandonbraun653/Loki | 65c9472a81f66c13b729d7c2047013d1198f0c3c | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* chimeraPort.hpp
*
* Description:
* Implements the Chimera back end driver redirects into simulator variants
*
* 2020 | Brandon Braun | brandonbraun653@gmail.com
********************************************************************************/
#pragma once
#ifndef CHIMERA_PORT_STANDALONE_HPP
#define CHIMERA_PORT_STANDALONE_HPP
#endif /* !CHIMERA_PORT_MOCK_HPP */
| 30.0625 | 82 | 0.492723 | brandonbraun653 |
d382b5597aee79eda902a1f3a0059f942078e317 | 975 | cpp | C++ | chapter_1/ex-35.cpp | chwit/DSAA_by_CPP | 5038de5229a098107e6861c17df088b8b85c711e | [
"BSD-2-Clause"
] | null | null | null | chapter_1/ex-35.cpp | chwit/DSAA_by_CPP | 5038de5229a098107e6861c17df088b8b85c711e | [
"BSD-2-Clause"
] | null | null | null | chapter_1/ex-35.cpp | chwit/DSAA_by_CPP | 5038de5229a098107e6861c17df088b8b85c711e | [
"BSD-2-Clause"
] | null | null | null | //
// Created by user on 2019/4/10.
// Copyright © 2019 user. All rights reserved.
//
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//next_permutation
//只有排序之后的数组才能只用next_permutation获得全排列
int count_my = 0;
//输出范围[start,end)内的全排列
template<typename T>
void permutations(T list[], int k , int m)
{
//sort(list + k, list + m );
int num = m - k;
int count = 1;
for (int i = 2; i <= num; i++) // 计算总数 用 next & prev共同输出全排列 也可以判断数组是否相同 (用equal)
count *= i;
do {
count_my++;
count--;
copy(list + k,list + m , ostream_iterator<T>(cout," "));
cout << endl;
} while (next_permutation(list + k, list + m ));
while (count)
{
count_my++;
count--;
copy(list + k, list + m, ostream_iterator<T>(cout, " "));
cout << endl;
prev_permutation(list + k, list + m);
}
}
int main()
{
int arr[] = { 1, 3, 2, 4, 5 };
permutations(arr, 0, 3);
cout << count_my << endl;
getchar();
getchar();
return 0;
}
| 18.055556 | 83 | 0.610256 | chwit |
d383ec12679fb011994fb8de43f92751bf8d8534 | 1,595 | hpp | C++ | include/text_view_detail/basic_view.hpp | tahonermann/text_view | 65740356488d0dd98b65f221c71c7b7377c813de | [
"MIT"
] | 144 | 2015-10-10T10:12:53.000Z | 2021-12-31T16:07:27.000Z | include/text_view_detail/basic_view.hpp | Quuxplusone/text_view | 65740356488d0dd98b65f221c71c7b7377c813de | [
"MIT"
] | 34 | 2016-01-22T03:52:53.000Z | 2018-08-04T01:56:06.000Z | include/text_view_detail/basic_view.hpp | Quuxplusone/text_view | 65740356488d0dd98b65f221c71c7b7377c813de | [
"MIT"
] | 19 | 2016-02-10T11:29:20.000Z | 2021-06-28T11:11:36.000Z | // Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef TEXT_VIEW_BASIC_VIEW_HPP // {
#define TEXT_VIEW_BASIC_VIEW_HPP
#include <utility>
#include <experimental/ranges/concepts>
namespace std {
namespace experimental {
inline namespace text {
namespace text_detail {
template<ranges::Iterator IT, ranges::Sentinel<IT> ST = IT>
class basic_view : public ranges::view_base
{
public:
using iterator = IT;
using sentinel = ST;
basic_view() = default;
basic_view(IT first, ST last)
: first{first}, last{last} {}
template<typename IT2, typename ST2>
requires ranges::Constructible<IT, IT2&&>
&& ranges::Constructible<ST, ST2&&>
basic_view(IT2 first, ST2 last)
: first(std::move(first)), last(std::move(last)) {}
template<typename IT2, typename ST2>
requires ranges::Constructible<IT, IT2&&>
&& ranges::Constructible<ST, ST2&&>
basic_view(const basic_view<IT2, ST2> &o)
: first(o.begin()), last(o.end()) {}
IT begin() const { return first; }
ST end() const { return last; }
private:
IT first = {};
ST last = {};
};
template<ranges::Iterator IT, ranges::Sentinel<IT> ST>
auto make_basic_view(IT first, ST last) {
return basic_view<IT, ST>{std::move(first), std::move(last)};
}
} // namespace text_detail
} // inline namespace text
} // namespace experimental
} // namespace std
#endif // } TEXT_VIEW_BASIC_VIEW_HPP
| 24.538462 | 78 | 0.673981 | tahonermann |
d3854495041606d4beb6c602b9c1bedf5808541e | 1,960 | cpp | C++ | rmw_dds_common/src/security.cpp | ros2/rmw_dds_common | 42d86b736a7292ae0ab926f818afc28e3d64aebd | [
"Apache-2.0"
] | 5 | 2020-02-18T22:54:06.000Z | 2021-12-26T08:48:51.000Z | rmw_dds_common/src/security.cpp | ros2/rmw_dds_common | 42d86b736a7292ae0ab926f818afc28e3d64aebd | [
"Apache-2.0"
] | 33 | 2020-04-03T15:49:56.000Z | 2022-03-31T00:35:12.000Z | rmw_dds_common/src/security.cpp | ros2/rmw_dds_common | 42d86b736a7292ae0ab926f818afc28e3d64aebd | [
"Apache-2.0"
] | 11 | 2020-04-03T14:42:19.000Z | 2021-07-01T06:39:11.000Z | // Copyright 2021 Open Source Robotics Foundation, Inc.
//
// 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 <string>
#include <utility>
#include <unordered_map>
#include "rcpputils/filesystem_helper.hpp"
#include "rmw_dds_common/security.hpp"
namespace rmw_dds_common
{
bool get_security_files(
const std::string & prefix, const std::string & secure_root,
std::unordered_map<std::string, std::string> & result)
{
const std::unordered_map<std::string, std::string> required_files{
{"IDENTITY_CA", "identity_ca.cert.pem"},
{"CERTIFICATE", "cert.pem"},
{"PRIVATE_KEY", "key.pem"},
{"PERMISSIONS_CA", "permissions_ca.cert.pem"},
{"GOVERNANCE", "governance.p7s"},
{"PERMISSIONS", "permissions.p7s"},
};
const std::unordered_map<std::string, std::string> optional_files{
{"CRL", "crl.pem"},
};
for (const std::pair<const std::string, std::string> & el : required_files) {
rcpputils::fs::path full_path(secure_root);
full_path /= el.second;
if (!full_path.is_regular_file()) {
result.clear();
return false;
}
result[el.first] = prefix + full_path.string();
}
for (const std::pair<const std::string, std::string> & el : optional_files) {
rcpputils::fs::path full_path(secure_root);
full_path /= el.second;
if (full_path.is_regular_file()) {
result[el.first] = prefix + full_path.string();
}
}
return true;
}
} // namespace rmw_dds_common
| 30.153846 | 79 | 0.690816 | ros2 |
d387a96b0da99eb463484c940d8f899aec583257 | 150 | cpp | C++ | tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp | oktonion/STL | e2fce45b9ca899f3887b7fa48e24de95859a7b8e | [
"Apache-2.0"
] | 2 | 2021-01-19T02:43:19.000Z | 2021-11-20T05:21:42.000Z | tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | null | null | null | tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | 4 | 2020-04-24T05:04:54.000Z | 2020-05-17T22:48:58.000Z | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "type_asserts.hpp"
#include <cmath>
| 25 | 59 | 0.733333 | oktonion |
d3898cc4b2eaeeb41b0bcae89c516391864463f8 | 1,553 | cpp | C++ | firmware/library/L3_HAL/test/buzzer_test.cpp | Jeremy-Chau/SJSU-Dev2 | b3c0b008f9f19a12fe70d319760459b4b2111003 | [
"Apache-2.0"
] | null | null | null | firmware/library/L3_HAL/test/buzzer_test.cpp | Jeremy-Chau/SJSU-Dev2 | b3c0b008f9f19a12fe70d319760459b4b2111003 | [
"Apache-2.0"
] | null | null | null | firmware/library/L3_HAL/test/buzzer_test.cpp | Jeremy-Chau/SJSU-Dev2 | b3c0b008f9f19a12fe70d319760459b4b2111003 | [
"Apache-2.0"
] | 2 | 2018-07-27T20:48:40.000Z | 2018-08-02T21:32:05.000Z | #include "L3_HAL/buzzer.hpp"
#include "L1_Drivers/pwm.hpp"
#include "L5_Testing/testing_frameworks.hpp"
TEST_CASE("Testing buzzer", "[buzzer]")
{
// Create mock for PWM class
Mock<PwmInterface> mock_pwm_pin;
Fake(
Method(mock_pwm_pin, Initialize),
Method(mock_pwm_pin, SetDutyCycle),
Method(mock_pwm_pin, SetFrequency),
Method(mock_pwm_pin, GetDutyCycle),
Method(mock_pwm_pin, GetFrequency));
PwmInterface & pwm = mock_pwm_pin.get();
// Instantiate buzzer test objects
Buzzer test1(&pwm);
SECTION("Check Initialize")
{
constexpr uint32_t kFrequency = 500;
constexpr float kVolume = 0.0;
test1.Initialize();
Verify(
Method(mock_pwm_pin, Initialize).Using(500),
Method(mock_pwm_pin, SetDutyCycle).Using(kVolume)),
Method(mock_pwm_pin, SetFrequency).Using(kFrequency);
}
SECTION("Check Beep")
{
constexpr uint32_t kFrequency = 0;
constexpr float kVolume = 0.0;
test1.Beep(kFrequency, kVolume);
float vol_error = kVolume - test1.GetVolume();
CHECK((-0.1f <= vol_error && vol_error <= 0.1f));
uint32_t freq_error = kFrequency - test1.GetFrequency();
CHECK(freq_error == 0);
}
SECTION("Check Stop")
{
constexpr uint32_t kFrequency = 500;
constexpr float kVolume = 0.0;
test1.Stop();
float vol_error = kVolume - test1.GetVolume();
CHECK((-0.1f <= vol_error && vol_error <= 0.1f));
}
}
| 27.245614 | 65 | 0.62009 | Jeremy-Chau |
d389a37275dcfd0fb9414cd69117d9011c92b6a3 | 2,320 | hxx | C++ | com/ole32/com/dcomrem/stream.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/dcomrem/stream.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/dcomrem/stream.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------
//
// File: stream.hxx
//
// Contents: Implements the IStream interface on a memory buffer.
//
//--------------------------------------------------------------------
#ifndef _STREAM_HXX_
#define _STREAM_HXX_
class CNdrStream : public IStream
{
public:
virtual HRESULT STDMETHODCALLTYPE
QueryInterface(
IN REFIID riid,
OUT void **ppvObj);
virtual ULONG STDMETHODCALLTYPE
AddRef();
virtual ULONG STDMETHODCALLTYPE
Release();
virtual HRESULT STDMETHODCALLTYPE
Read(
IN void * pv,
IN ULONG cb,
OUT ULONG * pcbRead);
virtual HRESULT STDMETHODCALLTYPE
Write(
IN void const *pv,
IN ULONG cb,
OUT ULONG * pcbWritten);
virtual HRESULT STDMETHODCALLTYPE
Seek(
IN LARGE_INTEGER dlibMove,
IN DWORD dwOrigin,
OUT ULARGE_INTEGER *plibNewPosition);
virtual HRESULT STDMETHODCALLTYPE
SetSize(
IN ULARGE_INTEGER libNewSize);
virtual HRESULT STDMETHODCALLTYPE
CopyTo(
IN IStream * pstm,
IN ULARGE_INTEGER cb,
OUT ULARGE_INTEGER *pcbRead,
OUT ULARGE_INTEGER *pcbWritten);
virtual HRESULT STDMETHODCALLTYPE
Commit(
IN DWORD grfCommitFlags);
virtual HRESULT STDMETHODCALLTYPE
Revert();
virtual HRESULT STDMETHODCALLTYPE
LockRegion(
IN ULARGE_INTEGER libOffset,
IN ULARGE_INTEGER cb,
IN DWORD dwLockType);
virtual HRESULT STDMETHODCALLTYPE
UnlockRegion(
IN ULARGE_INTEGER libOffset,
IN ULARGE_INTEGER cb,
IN DWORD dwLockType);
virtual HRESULT STDMETHODCALLTYPE
Stat(
OUT STATSTG * pstatstg,
IN DWORD grfStatFlag);
virtual HRESULT STDMETHODCALLTYPE
Clone(
OUT IStream **ppstm);
CNdrStream(
IN unsigned char * pData,
IN unsigned long cbMax);
private:
long RefCount;
unsigned char * pBuffer;
unsigned long cbBufferLength;
unsigned long position;
};
#endif // _STREAM_HXX_
| 24.421053 | 71 | 0.550431 | npocmaka |
d38fcd266b8d2c9e2344810afc71ad502341d39d | 2,653 | cpp | C++ | tools/mcrl3linearize/mcrl3linearize.cpp | wiegerw/mcrl3 | 15260c92ab35930398d6dfb34d31351b05101ca9 | [
"BSL-1.0"
] | 1 | 2021-02-22T09:16:39.000Z | 2021-02-22T09:16:39.000Z | tools/mcrl3linearize/mcrl3linearize.cpp | wiegerw/mcrl3 | 15260c92ab35930398d6dfb34d31351b05101ca9 | [
"BSL-1.0"
] | null | null | null | tools/mcrl3linearize/mcrl3linearize.cpp | wiegerw/mcrl3 | 15260c92ab35930398d6dfb34d31351b05101ca9 | [
"BSL-1.0"
] | null | null | null | // Copyright: Wieger Wesselink
//
// 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)
//
/// \file mcrl3linearize.cpp
#define NAME "mcrl3linearize"
#define AUTHOR "Wieger Wesselink"
#include <iostream>
#include "mcrl2/lps/detail/lps_io.h"
#include "mcrl2/process/detail/process_io.h"
#include "mcrl2/process/linearize.h"
#include "mcrl2/utilities/detail/io.h"
#include "mcrl2/utilities/input_output_tool.h"
using namespace mcrl2;
class mcrl3linearize_tool: public utilities::tools::input_output_tool
{
protected:
typedef utilities::tools::input_output_tool super;
bool expand_structured_sorts = false;
int max_equation_usage = 0;
bool use_groote_implementation;
void parse_options(const utilities::command_line_parser& parser) override
{
super::parse_options(parser);
expand_structured_sorts = parser.options.count("expand-structured-sorts") > 0;
max_equation_usage = parser.option_argument_as<int>("max-equation-usage");
use_groote_implementation = parser.options.count("use-groote-implementation") > 0;
}
void add_options(utilities::interface_description& desc) override
{
super::add_options(desc);
desc.add_option("expand-structured-sorts", "expand structured sorts", 'e');
desc.add_option("max-equation-usage", utilities::make_optional_argument("NAME", "1"),
"The maximum times an equation may be duplicated", 'm');
desc.add_option("use-groote-implementation", "Use the implementation of J.F.Groote", 'g');
}
public:
mcrl3linearize_tool()
: super(NAME, AUTHOR,
"linearize process specifications",
"Linearizes the process specification in INFILE. N.B. Supports a very limited class of\n"
"process specifications!"
)
{}
bool run() override
{
timer().start("parse + type check process specification");
process::process_specification procspec = process::detail::parse_process_specification(input_filename());
timer().finish("parse + type check process specification");
lps::specification lpsspec;
if (use_groote_implementation)
{
lpsspec = process::mcrl32lps(procspec, expand_structured_sorts, max_equation_usage);
}
else
{
lpsspec = linearize(procspec, expand_structured_sorts, max_equation_usage);
}
lps::detail::save_lps(lpsspec, output_filename());
return true;
}
};
int main(int argc, char* argv[])
{
return mcrl3linearize_tool().execute(argc, argv);
}
| 33.582278 | 111 | 0.698078 | wiegerw |