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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ec4fcdf2bcc951a27ba495a8edaa1a6c512fa79
| 905
|
cpp
|
C++
|
src/pwc.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | 1
|
2021-12-12T22:08:23.000Z
|
2021-12-12T22:08:23.000Z
|
src/pwc.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | null | null | null |
src/pwc.cpp
|
CardinalModules/TheXOR
|
910b76622c9100d9755309adf76542237c6d3a77
|
[
"CC0-1.0"
] | 1
|
2021-12-12T22:08:29.000Z
|
2021-12-12T22:08:29.000Z
|
#include "../include/pwc.hpp"
void pwc::process(const ProcessArgs &args)
{
float vOut = 0;
if(trigger.process(inputs[IN].getVoltage()))
{
float v = (0.001f+params[PW].getValue()) * 0.01f; // valore in secondi
pulsed.trigger(v);
vOut = LVL_MAX;
} else
{
float deltaTime = 1.0 / args.sampleRate;
int pulseStatus = pulsed.process(deltaTime);
if (pulseStatus == -1)
{
vOut = 0;
} else
{
vOut = pulsed.inProgress ? LVL_MAX : 0;
}
}
outputs[OUT].setVoltage(vOut);
}
pwcWidget::pwcWidget(pwc *module)
{
CREATE_PANEL(module, this, 3, "res/modules/pwc.svg");
addInput(createInput<portRSmall>(Vec(mm2px(4.678), yncscape(97.491, 5.885)), module, pwc::IN));
addParam(createParam<Davies1900hFixWhiteKnobSmall>(Vec(mm2px(3.620), yncscape(55.82, 8)), module, pwc::PW));
addOutput(createOutput<portRSmall>(Vec(mm2px(4.678), yncscape(9.385, 5.885)), module, pwc::OUT));
}
| 24.459459
| 109
| 0.666298
|
CardinalModules
|
2eca4984678648b60563a603980246481717f2a0
| 11,470
|
cc
|
C++
|
src/argh/argh.cc
|
shrimpster00/argh
|
e9570ec712573156b04b0b29395877cf8d76da10
|
[
"MIT"
] | 1
|
2021-09-25T03:31:58.000Z
|
2021-09-25T03:31:58.000Z
|
src/argh/argh.cc
|
shrimpster00/argh
|
e9570ec712573156b04b0b29395877cf8d76da10
|
[
"MIT"
] | null | null | null |
src/argh/argh.cc
|
shrimpster00/argh
|
e9570ec712573156b04b0b29395877cf8d76da10
|
[
"MIT"
] | null | null | null |
// src/argh/argh.cc
// v0.3.2
//
// Author: Cayden Lund
// Date: 09/28/2021
//
// This file contains the argh implementation.
// Use this utility to parse command line arguments.
//
// Copyright (C) 2021 Cayden Lund <https://github.com/shrimpster00>
// License: MIT <opensource.org/licenses/MIT>
#include "argh.h"
#include "positional_arg.h"
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_set>
#include <vector>
// The argh namespace contains all of the argh functionality
// and utility functions.
namespace argh
{
// The argh::argh class is the main class for the argh utility.
// Use this class to parse command line arguments from the argv vector.
//
// We follow the GNU style of arguments, and define two types of arguments:
//
// 1. Options.
// These may be defined as a single dash followed by a single letter,
// or by a double dash followed by a single word.
// A list of single-letter options may be given at once, following a single dash without spaces.
// These are usually not required arguments.
// There are two kinds of options:
// a. Flags. These are boolean arguments that are either present or not present.
// b. Parameters. These are arguments that take a value.
// If a parameter contains the character '=', its value is the rest of the string.
// Otherwise, the value is the next argument in the argv vector.
// 2. Positional arguments.
// These are arguments that are interpreted by the program.
// Positional arguments are often required.
//
// Usage is quite simple.
//
// Pass the argv vector to the constructor.
//
// argh::argh args(argv);
//
// Access flags using the operator[] with a string.
//
// if (args["-h"] || args["--help"])
// {
// std::cout << "Help message." << std::endl;
// return 0;
// }
//
// Access parameters using the operator() with a string.
//
// std::string output_file = args("--output");
//
// Access positional arguments using the operator[] with an integer.
//
// std::string filename = args[0];
//
// The argh constructor.
//
// * int argc - The count of command line arguments.
// * char *argv[] - The command line arguments.
argh::argh(int argc, char *argv[])
{
initialize();
for (int i = 1; i < argc; i++)
{
parse_argument(argv[i]);
}
}
// The argh constructor, as above, but with an array of strings.
//
// * int argc - The count of command line arguments.
// * std::string argv[] - The command line arguments.
argh::argh(int argc, std::string argv[])
{
initialize();
for (int i = 0; i < argc; i++)
{
parse_argument(argv[i]);
}
}
// A zero-argument method for initializing the instance variables.
void argh::initialize()
{
this->args = std::vector<std::string>();
this->flags = std::unordered_set<std::string>();
this->parameters = std::unordered_map<std::string, std::string>();
this->positional_arguments = std::vector<positional_arg>();
this->double_dash_set = false;
this->last_flag = "";
}
// A private method for parsing a single argument.
//
// * std::string arg - The argument to parse.
void argh::parse_argument(std::string arg)
{
// Make sure the argument is not empty.
if (arg.length() == 0)
return;
// If we've seen a double dash, we're parsing positional arguments.
if (double_dash_set)
{
this->args.push_back(arg);
positional_arg arg_obj(arg);
this->positional_arguments.push_back(arg_obj);
return;
}
// Is the argument a single dash?
if (arg == "-")
{
// A single dash is a positional argument.
parse_positional_argument(arg);
this->last_flag = "";
return;
}
// Is the argument a double dash?
if (arg == "--")
{
// A double dash means that all following arguments are positional arguments.
this->args.push_back(arg);
this->double_dash_set = true;
this->last_flag = "";
return;
}
// Is the argument a flag?
if (is_flag(arg))
{
parse_flag(arg);
return;
}
// If we've made it this far, the argument is either the value of a parameter
// or a positional argument.
parse_positional_argument(arg);
}
// A helper method for parsing a single flag.
//
// * std::string arg - The argument to parse.
void argh::parse_flag(std::string arg)
{
// Does the argument contain '='?
if (arg.find('=') != std::string::npos)
{
// If so, it's a parameter.
std::string key = arg.substr(0, arg.find('='));
std::string value = arg.substr(arg.find('=') + 1);
this->parameters[key] = value;
this->flags.insert(key);
this->args.push_back(arg);
this->last_flag = "";
return;
}
// Does the flag start with a double dash?
if (arg.length() >= 2 && arg.substr(0, 2) == "--")
{
this->flags.insert(arg);
this->args.push_back(arg);
this->last_flag = arg;
return;
}
else
{
// Treat each character following the single dash as a flag.
for (long unsigned int i = 1; i < arg.length(); i++)
{
std::string flag = "-" + arg.substr(i, 1);
this->flags.insert(flag);
this->last_flag = flag;
}
this->args.push_back(arg);
return;
}
}
// A helper method for parsing a single positional argument.
//
// * std::string arg - The argument to parse.
void argh::parse_positional_argument(std::string arg)
{
if (this->last_flag.length() > 0)
{
this->parameters[this->last_flag] = arg;
positional_arg arg_obj(this->last_flag, arg);
this->positional_arguments.push_back(arg_obj);
}
else
{
positional_arg arg_obj(arg);
this->positional_arguments.push_back(arg_obj);
}
this->last_flag = "";
this->args.push_back(arg);
}
// A method to determine whether an argument is a flag.
//
// * std::string arg - The argument to check.
//
// * return (bool) - True if the argument is a flag, false otherwise.
bool argh::is_flag(std::string arg)
{
if (arg.length() < 2)
return false;
if (arg == "--")
return false;
return arg[0] == '-';
}
// A method to mark an argument as a parameter, not a positional argument.
// Note: This method runs in O(N) time, where N is the number of arguments,
// provided that there is only one of the given parameter.
//
// * std::string arg - The argument to mark as a parameter.
void argh::mark_parameter(std::string arg)
{
for (long unsigned int i = 0; i < this->positional_arguments.size(); i++)
{
if (this->positional_arguments[i].get_owner() == arg)
{
this->positional_arguments.erase(this->positional_arguments.begin() + i);
mark_parameter(arg);
return;
}
}
}
// Overload the [] operator to access a flag by name.
//
// * std::string name - The name of the flag.
//
// * return (bool) - The value of the flag.
bool argh::operator[](std::string name)
{
return this->flags.count(name);
}
// Overload the () operator to access a parameter by name.
//
// * std::string name - The name of the parameter.
//
// * return (std::string) - The value of the parameter.
std::string argh::operator()(std::string name)
{
mark_parameter(name);
if (this->parameters.count(name))
return this->parameters[name];
return "";
}
// Overload the [] operator to access the positional arguments by index.
//
// ==============================================================================================================
// | |
// | It's important to note that the parser does not understand the difference |
// | between a positional argument and the value of a parameter! |
// | |
// | For instance: |
// | "program -o output.txt file.txt" |
// | Should "output.txt" be interpreted as a positional argument, or as the value of the "-o" parameter? |
// | "program -v file.txt" |
// | Should "file.txt" be interpreted as a positional argument, or as the value of the "-v" parameter? |
// | |
// | For this reason, all arguments that are not flags or parameters |
// | are considered positional arguments by default. |
// | If you want to change this behavior, you can use one of the following approaches: |
// | 1. Use the argh::set_parameter(parameter) function to mark the argument |
// | following a given parameter as the parameter's value. |
// | 2. Use the argh::operator(parameter) operater to query the value of a parameter |
// | before using the argh::operator[] to access the positional arguments. |
// | |
// ==============================================================================================================
//
// * int index - The index of the positional argument.
//
// * return (std::string) - The value of the positional argument.
std::string argh::operator[](int index)
{
if ((long unsigned int)index < this->positional_arguments.size())
return this->positional_arguments[index].get_value();
return "";
}
// Returns the number of positional arguments.
//
// * return (int) - The number of positional arguments.
int argh::size()
{
return this->positional_arguments.size();
}
}
| 36.762821
| 117
| 0.498344
|
shrimpster00
|
2eca7bea048f63ca5a67b6620d40a90d3213291b
| 48,187
|
cpp
|
C++
|
src/common.cpp
|
vadimostanin2/sneeze-detector
|
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
|
[
"MIT"
] | 11
|
2015-04-18T23:42:44.000Z
|
2021-04-03T18:23:44.000Z
|
src/common.cpp
|
vadimostanin2/sneeze-detector
|
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
|
[
"MIT"
] | null | null | null |
src/common.cpp
|
vadimostanin2/sneeze-detector
|
2bac0d08cb4960b7dc16492b8c69ff1459dd9334
|
[
"MIT"
] | 3
|
2017-06-02T17:07:08.000Z
|
2019-04-18T05:59:48.000Z
|
/*
* common.c
*
* Created on: Nov 12, 2014
* Author: vostanin
*/
#include "common.h"
#include <unistd.h>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include "Mfcc.h"
#include "dtw.h"
RangeDistance global_ranges[] = {
{RANGE_1_E, 1},
{RANGE_2_E, 2},
{RANGE_4_E, 4},
{RANGE_8_E, 8},
{RANGE_16_E, 16},
{RANGE_32_E, 32},
{RANGE_64_E, 64},
{RANGE_128_E, 128},
{RANGE_256_E, 256},
{RANGE_512_E, 512},
{RANGE_1024_E, 1024},
{RANGE_2048_E, 2048},
{RANGE_4096_E, 4096},
{RANGE_8192_E, 8192},
{RANGE_16384_E, 16384},
{RANGE_32768_E, 32768},
{RANGE_65536_E, 65536},
};
//
//void dump( vector<signal_type> & input )
//{
// ofstream file( "dump.txt", ios_base::app );
//
// for( size_t i = 0 ; i < input.size() ; i++ )
// {
// file << input[i] << " " << flush;
// }
// file << endl;
// file.close();
//}
void dump( vector_mfcc_level_1 & input )
{
ofstream file( "dump.txt", ios_base::app );
for( size_t i = 0 ; i < input.size() ; i++ )
{
file << input[i] << " " << std::flush;
}
file << endl;
file.close();
}
void dump( vector<freq_magn_type> & input )
{
ofstream file( "dump.txt", ios_base::app );
for( size_t i = 0 ; i < input.size() ; i++ )
{
file << input[i].freq << "=" << input[i].magnitude << " " << flush;
}
file << endl;
file.close();
}
void save_mfcc_coefficients( vector<vector<vector<float> > > & all_mfcc_v )
{
size_t all_mfcc_v_count = all_mfcc_v.size();
for( int all_mfcc_v_i = 0 ; all_mfcc_v_i < all_mfcc_v_count ; all_mfcc_v_i++ )
{
char str_num[] = { (char)(all_mfcc_v_i + 48), '\0' };
string filename = string( "mfcc_" ) + str_num;
ofstream file( filename.c_str(), ios_base::trunc );
file << all_mfcc_v[all_mfcc_v_i].size() << endl;
for( size_t mfcc_v_i = 0 ; mfcc_v_i < all_mfcc_v[all_mfcc_v_i].size() ; mfcc_v_i++ )
{
size_t mfcc_v_count = all_mfcc_v[all_mfcc_v_i][mfcc_v_i].size();
for( size_t mfcc_i = 0 ; mfcc_i < mfcc_v_count ; mfcc_i++ )
{
file << all_mfcc_v[all_mfcc_v_i][mfcc_v_i][mfcc_i] << flush;
if( ( mfcc_i + 1 ) < mfcc_v_count )
{
file << " " << flush;
}
}
file << endl;
}
file.close();
}
}
void load_mfcc_coefficients( vector<vector<vector<float> > > & all_mfcc_v )
{
all_mfcc_v.clear();
for( size_t file_i = 0 ; ; file_i++ )
{
char str_num[] = { (char)(file_i + 48), '\0' };
string filename = string( "mfcc_" ) + str_num;
ifstream infile( filename.c_str() );
if( false == infile.is_open() )
{
break;
}
vector<vector<float> > mfcc_v;
int mfcc_count = 0;
infile >> mfcc_count;
string line;
while (getline(infile, line, '\n'))
{
if( true == line.empty() )
{
continue;
}
vector<float> mfcc;
stringstream str_stream( line );
while(str_stream.eof() != true)
{
float cc = 0;
str_stream >> cc;
mfcc.push_back( cc );
}
mfcc_v.push_back( mfcc );
}
all_mfcc_v.push_back( mfcc_v );
}
}
void get_mean_two_mfcc( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, vector_mfcc_level_1 & mean )
{
size_t mfcc_1_size = mfcc_1.size();
size_t mfcc_2_size = mfcc_2.size();
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
mean.resize( mfcc_1_size, 0.0 );
for( unsigned int mfcc_i = 0 ; mfcc_i < mfcc_1_size ; mfcc_i++ )
{
mean[mfcc_i] = (mfcc_1[mfcc_i] + mfcc_2[mfcc_i]) / 2;
}
}
void mfcc_meaning( vector_mfcc_level_3 & sounds, unsigned int merging_count, float threshold, vector_mfcc_level_3 & sounds_result )
{
size_t sound_count_size = sounds.size();
for( unsigned int sound_i = 0 ; sound_i < sound_count_size ; sound_i++ )
{
vector_mfcc_level_2 & mfcc_v = sounds[sound_i];
vector_mfcc_level_2 mfcc_v_result;
mfcc_meaning( mfcc_v, merging_count, threshold, mfcc_v_result );
sounds_result.push_back( mfcc_v_result );
}
}
void mfcc_meaning( vector_mfcc_level_2 & mfcc_v, unsigned int merging_count, float threshold, vector_mfcc_level_2 & mfcc_v_result )
{
size_t count = mfcc_v.size();
size_t mfcc_size = mfcc_v[0].size();
vector<unsigned int> used_mfcc;
for( unsigned int mfcc_i = 0 ; mfcc_i < count ; mfcc_i++ )
{
vector_mfcc_level_1 last_mean = mfcc_v[mfcc_i];
if( std::find( used_mfcc.begin(), used_mfcc.end(), mfcc_i) == used_mfcc.end() )
{
for( unsigned int merging_i = 0 ; merging_i < merging_count ; merging_i++ )
{
double min_value = 1000.0;
unsigned int min_index = 0;
double distance = 0.0;
for( unsigned int mfcc_j = 0 ; mfcc_j < count ; mfcc_j++ )
{
if( std::find( used_mfcc.begin(), used_mfcc.end(), mfcc_j) == used_mfcc.end() )
{
mfcc_get_distance( mfcc_v[mfcc_i], mfcc_v[mfcc_j], distance );
if( distance < min_value )
{
min_value = distance;
min_index = mfcc_j;
}
}
}
used_mfcc.push_back( min_index );
vector_mfcc_level_1 mean;
get_mean_two_mfcc( last_mean, mfcc_v[min_index], mean );
last_mean = mean;
}
mfcc_v_result.push_back( last_mean );
}
}
}
double complex_magnitude( complex_type cpx )
{
double real = cpx[0];
double im = cpx[1];
return sqrt( ( real * real ) + ( im * im ) );
}
void zero( complex_type & cpx )
{
cpx[0] = 0.0;
cpx[1] = 0.0;
}
void freqfilter(vector<complex_type> & complexes, double samplerate, unsigned int left_freq, unsigned int right_freq)
{
sf_count_t i;
sf_count_t samples2;
size_t count = complexes.size();
samples2 = count / 2;
for( i=0; i < count ; i++ )
{
double freq = ((double)i * samplerate / (double)count);
if( freq < left_freq || freq > right_freq )
{
zero( complexes[i] );
}
}
}
bool filename_pattern_match( string & filename, string & pattern )
{
bool result = true;
const char * str_filename = filename.c_str();
const char * str_pattern = pattern.c_str();
const char delim[2] = { '*', '\0' };
char * pch = NULL;
pch = strtok( (char*)str_pattern, delim );
while (pch != NULL)
{
if( strstr( str_filename, pch ) == NULL )
{
result = false;
break;
}
pch = strtok( NULL, "*" );
}
return result;
}
void read_wav_data( string & wav_file, vector<signal_type> & wav_raw, int & channels_count )
{
SF_INFO info_in;
SNDFILE * fIn = sf_open( wav_file.c_str(), SFM_READ, &info_in );
if( fIn == NULL )
{
return;
}
int nTotalRead = 0;
int nRead = 0;
channels_count = info_in.channels;
do
{
vector<signal_type> temp;
temp.resize(info_in.frames * info_in.channels);
nRead = sf_readf_float( fIn, &temp[0], info_in.frames - nTotalRead );
wav_raw.insert( wav_raw.end(), temp.begin(), temp.begin() + nRead * info_in.channels );
nTotalRead += nRead;
}
while( nTotalRead < info_in.frames );
sf_close(fIn);
}
void evarage_channels( vector<signal_type> & wav_raw, unsigned int channels_count, vector<signal_type> & chunk_merged )
{
if( channels_count == 1 )
{
chunk_merged.clear();
chunk_merged.assign( wav_raw.begin(), wav_raw.end() );
}
else
{
unsigned int wav_raw_size = wav_raw.size();
chunk_merged.resize( wav_raw_size / channels_count );
for( unsigned int wav_raw_i = 0 ; wav_raw_i < wav_raw_size ; wav_raw_i += channels_count )
{
float sum_amplitude = 0.0;
for( unsigned int channel_i = 0 ; channel_i < channels_count ; channel_i ++ )
{
double val = wav_raw[wav_raw_i + channel_i];
sum_amplitude += val;
}
chunk_merged[ wav_raw_i / channels_count ] = sum_amplitude / channels_count;
}
}
}
void save_chunk_data(vector<signal_type> & chunk_data, int index )
{
SF_INFO info_out = { 0 };
info_out.channels = 1;
info_out.samplerate = 16000;
unsigned int minutes = 60*24;
int seconds = minutes * 60;
info_out.frames = info_out.samplerate * info_out.channels * seconds;
info_out.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16 | SF_ENDIAN_LITTLE;
char outfilepath[BUFSIZ] = {'\0'};
sprintf(outfilepath, "%d.wav", index);
SNDFILE * fOut = NULL;
fOut = sf_open( outfilepath, SFM_WRITE, &info_out );
sf_writef_float( fOut, &chunk_data[0], chunk_data.size() );
sf_close(fOut);
}
void normalize( vector<signal_type> & signal, float max_val)
{
// recherche de la valeur max du signal
float max=0.f;
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
if (abs(signal[i])>max) max=abs(signal[i]);
}
// ajustage du signal
float ratio = max_val/max;
for(size_t i=0 ; i<size ; i++)
{
signal[i] = signal[i]*ratio;
}
}
void movesignal_to_value( vector<signal_type> & signal, float val)
{
// recherche de la valeur max du signal
float max=0.f;
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
signal[i] += val;
}
}
void negative_values_zeroes( vector<float> & signal )
{
size_t size = signal.size();
for(size_t i=0 ; i<size ; i++)
{
if( signal[i] < 0 )
{
signal[i] = 0;
}
}
}
void cut_zeroes( vector<float> & signal )
{
size_t size = signal.size();
unsigned int insert_i = 0;
size_t search_i = 0;
for( search_i = 0 ; search_i < size ; search_i++)
{
if( signal[search_i] != 0 )
{
signal[insert_i] = signal[search_i];
insert_i++;
}
}
}
void get_current_folder( string & folder )
{
char cwd[BUFSIZ] = { '\0' };
getcwd( cwd, BUFSIZ );
folder = cwd;
}
void movesignal_to_0_1( vector<signal_type> & signal )
{
normalize( signal, 0.5f );
movesignal_to_value( signal, 0.5f );
}
void period_start_get( vector<signal_type> & signal, size_t & signal_index )
{
size_t signal_length = signal.size();
float last_value = 0.0;
for( size_t signal_i = 0 ; signal_i < signal_length ; signal_i++ )
{
signal_type value = signal[signal_i];
if( value >= 0 && last_value < 0 )
{
signal_index = signal_i;
break;
}
last_value = value;
}
}
bool period_next_get( vector<signal_type> & signal, unsigned int index, unsigned int & estimate_signals, vector<signal_type> & perioded_chunk )
{
size_t signal_length = signal.size();
float last_value = 0.0;
estimate_signals = 0;
bool found = false;
size_t zero_counter = 0;
for( size_t signal_i = index ; signal_i < signal_length ; signal_i++ )
{
signal_type value = signal[signal_i];
if( zero_counter >= 2 )
{
found = true;
perioded_chunk.clear();
break;
}
if( ( value >= 0 && last_value < 0 ) )
{
size_t chunk_size = perioded_chunk.size();
if( chunk_size >= 1 )
{
found = true;
}
else
{
perioded_chunk.clear();
}
break;
}
else if ( value != 0 )
{
perioded_chunk.push_back( value );
estimate_signals++;
zero_counter = 0;
}
else if ( value == 0 )
{
zero_counter++;
}
last_value = value;
}
return found;
}
bool period_prev_get( vector<signal_type> & signal, unsigned int index, unsigned int & estimate_signals, vector<signal_type> & perioded_chunk )
{
float last_value = 0.0;
estimate_signals = 0;
bool found = false;
for( int signal_i = index ; signal_i >= 0 ; signal_i-- )
{
signal_type value = signal[signal_i];
if( ( value >= 0 && last_value < 0 ) || ( last_value == 0 && value == 0 ) )
{
size_t chunk_size = perioded_chunk.size();
if( chunk_size >= 1 )
{
found = true;
}
else
{
perioded_chunk.clear();
}
break;
}
else
{
perioded_chunk.push_back( value );
estimate_signals++;
}
last_value = value;
}
return found;
}
void divide_on_perioded_chunks( vector<signal_type> & signal, vector<vector<signal_type> > & perioded_chunks, size_t periods_count, size_t threshold_signals_per_chunk )
{
size_t signal_length = signal.size();
size_t signal_start = 0;
period_start_get( signal, signal_start );
for( size_t signal_i = signal_start ; signal_i < signal_length ; )
{
vector<signal_type> chunk;
for( size_t period_i = 0 ; period_i < periods_count ; period_i++ )
{
vector<signal_type> period;
unsigned int estimate_signals = 0;
period_next_get( signal, signal_i, estimate_signals, period );
if( false == period.empty() )
{
chunk.insert( chunk.end(), period.begin(), period.end() );
}
signal_i += estimate_signals;
}
size_t chunk_size = chunk.size();
size_t perioded_chunks_count = perioded_chunks.size();
if( chunk_size >= threshold_signals_per_chunk )
{
perioded_chunks.push_back( chunk );
}
else
{
break;
}
}
}
void divide_on_seconds_chunks( vector<signal_type> & signal, vector<vector<signal_type> > & perioded_chunks, size_t samplerate )
{
size_t signal_length = signal.size();
unsigned int seconds_count = signal_length/samplerate;
for( size_t signal_i = 0 ; signal_i < seconds_count ; signal_i ++ )
{
vector<signal_type> chunk( samplerate );
memcpy( &chunk[0], &signal[ signal_i * samplerate ], samplerate * sizeof( float ) );
perioded_chunks.push_back( chunk );
}
}
bool make_train_file_with_vector( vector<signal_type> & magnitudes, unsigned int num_input_neurons, unsigned int num_output_neurons, vector<int> & outputs )
{
string header_out_file_name = "freqs_train_header.txt";
string data_out_file_name = "freqs_train_data.txt";
int num_data = 0;
static bool global_first_open = true;
if( true == global_first_open )
{
unlink( header_out_file_name.c_str() );
unlink( data_out_file_name.c_str() );
unlink( "../freqs_train.txt" );
}
else
{
ifstream header_file( header_out_file_name.c_str(), ios_base::in );
if( true == header_file.is_open() )
{
header_file >> num_data;
header_file.close();
}
else
{
cout << strerror(errno) << endl;
}
}
ofstream header_out_file( header_out_file_name.c_str(), ios_base::out );
ofstream data_out_file( data_out_file_name.c_str(), ios_base::app );
ofstream train_file( "../freqs_train.txt", ios_base::trunc );
if( false == header_out_file.is_open() )
{
return false;
}
if( false == data_out_file.is_open() )
{
return false;
}
if( false == train_file.is_open() )
{
return false;
}
////////////PREPARE HEADER
if( true == global_first_open )
{
num_data = 1;
header_out_file<<num_data << " " << num_input_neurons << " " << num_output_neurons << endl << flush;
}
else
{
string line;
stringstream str_stream;
num_data = num_data + 1;
str_stream << num_data << " " << num_input_neurons << " " << num_output_neurons;
line = str_stream.str();
// cout<< line << endl;
header_out_file << line << endl << flush;
}
////////////PREPARE DATA
data_out_file << flush;
unsigned int directions_count = magnitudes.size();
for( unsigned int direction_i = 0 ; direction_i < directions_count ; direction_i++ )
{
vector<signal_type>::value_type val = magnitudes[direction_i];
data_out_file << val << flush;
if( ( direction_i + 1) < directions_count )
{
data_out_file << " " << flush;
}
}
data_out_file << endl;
const size_t outputs_count = outputs.size();
for( size_t output_i = 0 ; output_i < outputs_count ; output_i++ )
{
if( true == outputs[output_i] )
{
data_out_file << 1 << flush;
}
else if( false == outputs[output_i] )
{
data_out_file << 0 << flush;
}
if( ( output_i + 1) < outputs_count )
{
data_out_file << " " << flush;
}
}
data_out_file << endl;
data_out_file << flush;
data_out_file.close();
std::string line;
{
ifstream header_in_file( header_out_file_name.c_str(), ios_base::in );
while (std::getline(header_in_file, line))
{
train_file << line << endl << flush;
}
}
{
ifstream data_in_file( data_out_file_name.c_str(), ios_base::in );
while (std::getline(data_in_file, line))
{
train_file << line << endl << flush;
}
}
global_first_open = false;
return true;
}
bool freq_range_template_equal( vector_mfcc_level_1 & freq_range_template_1, vector_mfcc_level_1 & freq_range_template_2, unsigned int threshold_failed )
{
size_t freq_count_1 = freq_range_template_1.size();
size_t freq_count_2 = freq_range_template_2.size();
if( freq_count_1 != freq_count_2 )
{
return false;
}
if( freq_count_1 == 0 )
{
return false;
}
int res = memcmp( &freq_range_template_1[0], &freq_range_template_2[0], freq_count_1 * sizeof( freq_range_template_1[0] ) );
if( res != 0 )
{
return false;
}
/*
int sum_diff = 0;
for( size_t range_i = 0 ; range_i < freq_count_1 ; range_i++ )
{
vector_mfcc_level_1::value_type * freq_range_template_2_ptr = &freq_range_template_2[0];
vector_mfcc_level_1::value_type type_1 = freq_range_template_1[range_i];
vector_mfcc_level_1::value_type type_2 = freq_range_template_2[range_i];
double pow_1 = log2( type_1 );
double pow_2 = log2( type_2 );
if( type_1 != type_2 )
{
int diff_pow = (int)pow_1 - pow_2;
sum_diff += diff_pow;
if( sum_diff > threshold_failed )
{
return false;
}
}
}
*/
return true;
}
bool compare( const freq_magn_type & _1, const freq_magn_type & _2 )
{
return _1.freq < _2.freq;
}
void template_freq_range_fill_distance_from_each_to_next( vector<signal_type> & signal, vector_mfcc_level_1 & freq_range_template )
{
freq_range_template.clear();
complex_type * complexes = NULL;
fftwf_plan plan;
make_fft( signal, &complexes, &plan );
const int freqs_range_count = FREQUENCY_PROCESSED_COUNT;
size_t complex_count = signal.size();
vector<complex_type> complexes_v( complexes, complexes + complex_count );
freqfilter( complexes_v, 16000, 50, 8000 );
vector<freq_magn_type> max_freqs_v;
getFrequencesWithHigherMagnitudes( freqs_range_count, complexes_v, max_freqs_v, 16000 );
if( max_freqs_v.empty() == true )
{
return;
}
std::sort(max_freqs_v.begin(), max_freqs_v.end(), compare );
signal_type prev_freq = max_freqs_v[0].freq;
size_t freq_count = max_freqs_v.size();
size_t range_count = sizeof( global_ranges )/ sizeof( global_ranges[0] );
for( size_t freq_i = 0 ; freq_i < freq_count ; freq_i++ )
{
freq_magn_type & curr_freq_magn = max_freqs_v[freq_i];
float distance = abs( curr_freq_magn.freq - prev_freq );
bool found = false;
for( size_t range_i = 0 ; range_i < range_count ; range_i++ )
{
const int distance_threshold = global_ranges[range_i].distance;
if( distance < distance_threshold )
{
found = true;
freq_range_template.push_back( global_ranges[range_i].range_type );
// cout<< distance_threshold << ", " << flush;
break;
}
}
prev_freq = curr_freq_magn.freq;
}
// cout << endl;
freq_count = freq_range_template.size();
destroy_fft( &complexes, &plan );
}
void template_freq_range_fill_distance_from_each_to_max( vector<signal_type> & signal, vector_mfcc_level_1 & freq_range_template )
{
freq_range_template.clear();
complex_type * complexes = NULL;
fftwf_plan plan;
make_fft( signal, &complexes, &plan );
const int freqs_range_count = FREQUENCY_PROCESSED_COUNT;
size_t complex_count = signal.size();
vector<complex_type> complexes_v( complexes, complexes + complex_count );
freqfilter( complexes_v, 16000, 50, 8000 );
vector<freq_magn_type> max_freqs_v;
getFrequencesWithHigherMagnitudes( freqs_range_count, complexes_v, max_freqs_v, 16000 );
if( max_freqs_v.empty() == true )
{
return;
}
signal_type prev_freq = max_freqs_v[0].freq;
size_t freq_count = max_freqs_v.size();
size_t range_count = sizeof( global_ranges )/ sizeof( global_ranges[0] );
for( size_t freq_i = 0 ; freq_i < freq_count ; freq_i++ )
{
freq_magn_type & curr_freq_magn = max_freqs_v[freq_i];
float distance = abs( curr_freq_magn.freq - prev_freq );
for( size_t range_i = 0 ; range_i < range_count ; range_i++ )
{
const int distance_threshold = global_ranges[range_i].distance;
if( distance < distance_threshold )
{
freq_range_template.push_back( global_ranges[range_i].range_type );
break;
}
}
}
freq_count = freq_range_template.size();
destroy_fft( &complexes, &plan );
}
void make_fft( vector<signal_type> & data, complex_type ** fft_result, fftwf_plan * plan_forward )
{
size_t data_count = data.size();
*fft_result = ( complex_type* ) fftwf_malloc( sizeof( complex_type ) * 2 * data_count );
*plan_forward = fftwf_plan_dft_r2c_1d( data_count, &data[0], *fft_result, FFTW_ESTIMATE );
// Perform the FFT on our chunk
fftwf_execute( *plan_forward );
}
void destroy_fft( complex_type ** fft_result, fftwf_plan * plan_forward )
{
fftwf_destroy_plan( *plan_forward );
*plan_forward = 0;
fftwf_free( *fft_result );
*fft_result = NULL;
}
void getFrequencesWithHigherMagnitudes( size_t frequencyCount, vector<complex_type> & complexes, vector<freq_magn_type> & freqs, size_t samplerate )
{
double prev_max_magnitude = 1000000.0;
size_t prev_max_magnitude_index = 0.0;
size_t freqs_count = complexes.size();
if( freqs_count < frequencyCount )
{
return;
}
static signal_type * freqs_ptr = (signal_type*)calloc( samplerate, sizeof( signal_type ) );
memset( freqs_ptr, 0, samplerate * sizeof( signal_type ) );
for( size_t bins_counter_i = 0 ; bins_counter_i < frequencyCount ; bins_counter_i++ )
{
float max_magnitude = 0.0;
size_t max_magnitude_index = 0.0;
for( size_t freq_i = 0 ; freq_i < freqs_count ; freq_i++ )
{
float magnitude = complex_magnitude( complexes[freq_i] );
if( max_magnitude < magnitude && magnitude < prev_max_magnitude )
{
max_magnitude = magnitude;
max_magnitude_index = freq_i;
}
}
float freq = ((float)max_magnitude_index * samplerate / (float)freqs_count);
freq_magn_type value = { freq, max_magnitude };
freqs.push_back( value );
prev_max_magnitude = max_magnitude;
prev_max_magnitude_index = max_magnitude_index;
}
freqs_count = freqs.size();
// free( freqs_ptr );
}
float get_minimum_amplitude( vector<float> & signal, float & peak_value, unsigned int & peak_index)
{
unsigned int count_i = 0;
float minimum = 1000.0;
int maximum_index = 0.0;
unsigned int count = signal.size();
for( count_i = 1 ; count_i < count ; count_i++ )
{
if(signal[count_i] < 0)
{
float curr = signal[count_i];
if( minimum < curr )
{
minimum = curr;
maximum_index = count_i;
}
}
}
peak_value = minimum;
peak_index = maximum_index;
return minimum;
}
float get_maximum_amplitude( vector<float> & signal, float & peak_value, unsigned int & peak_index)
{
int count_i = 0;
float maximum = 0.0;
int maximum_index = 0.0;
int count = signal.size();
for( count_i = 1 ; count_i < ( count - 1 ) ; count_i++ )
{
if(signal[count_i] > 0)
{
float prev = signal[count_i - 1];
float curr = signal[count_i];
float next = signal[count_i + 1];
if( prev < curr && next < curr)
{
if( maximum < curr )
{
maximum = curr;
maximum_index = count_i;
}
}
}
}
peak_value = maximum;
peak_index = maximum_index;
return maximum;
}
void trim_sides_periods_bellow_threshold( vector<signal_type> & perioded_signal, float threshold_amplitude, vector<signal_type> & perioded_signal_result )
{
unsigned int estimate_signals_sum = 0;
unsigned int signal_count = perioded_signal.size();
{
vector<signal_type> copy_src_signal = perioded_signal;
bool found_first_above_threshold = false;
for( unsigned int period_i = 0 ; ; period_i++ )
{
int start_index = (signal_count - estimate_signals_sum - 1);
vector<signal_type> period;
if( (start_index < 0) )
{
break;
}
unsigned int estimate_signals = 0;
period_prev_get( copy_src_signal, start_index, estimate_signals, period );
estimate_signals_sum += estimate_signals;
if( true == period.empty() )
{
break;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( true == condition_check_signal_threshold( period, threshold_amplitude, max_value, max_index ) )
{
found_first_above_threshold = true;
}
if( true == found_first_above_threshold )
{
perioded_signal_result.clear();
perioded_signal_result.assign( copy_src_signal.begin(), copy_src_signal.begin() + ( signal_count - estimate_signals_sum ) );
break;
}
}
}
std::reverse( perioded_signal_result.begin(), perioded_signal_result.end() );
{
vector<signal_type> copy_src_signal = perioded_signal_result;
bool found_first_above_threshold = false;
estimate_signals_sum = -1;
for( unsigned int period_i = 0 ; ; period_i++ )
{
unsigned int start_index = ( estimate_signals_sum + 1 );
vector<signal_type> period;
if( (start_index >= signal_count) )
{
break;
}
unsigned int estimate_signals = 0;
period_next_get( copy_src_signal, start_index, estimate_signals, period );
estimate_signals_sum += estimate_signals;
if( true == period.empty() )
{
break;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( true == condition_check_signal_threshold( period, threshold_amplitude, max_value, max_index ) )
{
found_first_above_threshold = true;
}
if( true == found_first_above_threshold )
{
perioded_signal_result.clear();
size_t copy_src_signal_count = copy_src_signal.size();
perioded_signal_result.assign( copy_src_signal.begin() + estimate_signals_sum, copy_src_signal.end() );
break;
}
}
}
size_t copy_src_signal_count = perioded_signal_result.size();
// save_chunk_data( perioded_signal_result, 3 );
}
bool copy_periods_before_after_signal_index( vector<signal_type> & signal, float threshold_amplitude, unsigned int signal_index, unsigned int periods_count,
unsigned int max_perioded_chunks_count, vector<signal_type> & all_perioded_chunk, unsigned int & out_new_signal_index,
bool no_matter_bounds, COPY_SIGNAL_ERROR_E & error )
{
unsigned int estimate_signals = 0;
error = COPY_SIGNAL_ERROR_SUCCESS;
size_t signal_count = signal.size();
size_t all_perioded_chunk_count = 0;
unsigned int estimate_signals_sum = 0;
for( unsigned int periods_i = 0 ; periods_i < max_perioded_chunks_count ; periods_i++ )
{
bool need_break = false;
vector<signal_type> one_perioded_chunk;
for( unsigned int period_i = 0 ; period_i < periods_count ; period_i++ )
{
int start_index = (signal_index - estimate_signals_sum - 1);
vector<signal_type> period;
if( start_index < 0 )
{
if( false == no_matter_bounds )
{
error = COPY_SIGNAL_ERROR_NEED_PREV_SIGNAL;
all_perioded_chunk.clear();
return false;
}
else
{
need_break = true;
break;
}
}
period_prev_get( signal, start_index, estimate_signals, period );
if( false == period.empty() )
{
one_perioded_chunk.insert( one_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
need_break = true;
break;
}
estimate_signals_sum += estimate_signals;
}
float max_value = 0.0;
unsigned int max_index = 0;
if( false == condition_check_signal_threshold( one_perioded_chunk, threshold_amplitude, max_value, max_index ) )
{
break;
}
else
{
all_perioded_chunk.insert( all_perioded_chunk.end(), one_perioded_chunk.begin(), one_perioded_chunk.end() );
all_perioded_chunk_count = all_perioded_chunk.size();
}
if( true == need_break )
{
break;
}
}
all_perioded_chunk_count = all_perioded_chunk.size();
std::reverse( all_perioded_chunk.begin(), all_perioded_chunk.end() );
all_perioded_chunk.push_back( signal[signal_index] );
out_new_signal_index = all_perioded_chunk.size() - 1;
estimate_signals_sum = 0;
for( unsigned int periods_i = 0 ; periods_i < max_perioded_chunks_count ; periods_i++ )
{
bool need_break = false;
vector<signal_type> one_perioded_chunk;
for( unsigned int period_i = 0 ; period_i < periods_count ; period_i++ )
{
unsigned int start_index = (signal_index + estimate_signals_sum + 1);
vector<signal_type> period;
if( start_index >= signal_count )
{
if( false == no_matter_bounds )
{
error = COPY_SIGNAL_ERROR_NEED_NEXT_AND_PREV_SIGNAL;
all_perioded_chunk.clear();
return false;
}
else
{
need_break = true;
break;
}
}
period_next_get( signal, start_index, estimate_signals, period );
if( false == period.empty() )
{
one_perioded_chunk.insert( one_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
need_break = true;
break;
}
estimate_signals_sum += estimate_signals;
}
size_t one_perioded_chunk_count = one_perioded_chunk.size();
float max_value = 0.0;
unsigned int max_index = 0;
if( false == condition_check_signal_threshold( one_perioded_chunk, threshold_amplitude, max_value, max_index ) )
{
break;
}
else
{
all_perioded_chunk.insert( all_perioded_chunk.end(), one_perioded_chunk.begin(), one_perioded_chunk.end() );
}
if( true == need_break )
{
break;
}
}
vector<signal_type> trimmed_perioded_signal;
all_perioded_chunk_count = all_perioded_chunk.size();
trim_sides_periods_bellow_threshold( all_perioded_chunk, threshold_amplitude, trimmed_perioded_signal );
all_perioded_chunk.swap( trimmed_perioded_signal );
all_perioded_chunk_count = all_perioded_chunk.size();
error = COPY_SIGNAL_ERROR_SUCCESS;
return true;
}
void autoCorrelation( vector<signal_type> & signal, vector<signal_type> & correlated_signal )
{
size_t signal_length = signal.size();
correlated_signal.resize( signal_length );
float sum = 0;
size_t i = 0, j = 0;
for( i = 0 ; i < signal_length ; i++ )
{
sum=0;
for( j = 0 ; j < signal_length - i ; j++ )
{
sum += signal[ j ] * signal[ j + i ];
}
correlated_signal[ i ] = sum;
}
}
float get_average_amplitude( vector<float> & signal, unsigned int range_min_frame, unsigned int range_max_frame)
{
double average_amplitude_before_maximum = 0.0;
double sum_amplitudes_before_maximum = 0.0;
int significant_values_count_in_range_before = 0;
unsigned int count_i = 0;
for( count_i = range_min_frame ; count_i < ( range_max_frame - 1 ) ; count_i++ )
{
if(signal[count_i] > 0)
{
double prev = signal[count_i - 1];
double curr = signal[count_i];
double next = signal[count_i + 1];
if( prev < curr && next < curr)
{
significant_values_count_in_range_before++;
sum_amplitudes_before_maximum += signal[count_i];
}
}
}
average_amplitude_before_maximum = sum_amplitudes_before_maximum/significant_values_count_in_range_before;
return average_amplitude_before_maximum;
}
void get_time_chunk_signal_corner( vector<float> & signal, double maximum, int maximum_index, bool prev, int & corner)
{
{
size_t signal_count = signal.size();
int bound_frame_near_maximum = 0;
float average_amplitude_near_maximum = 0.0;
float sin_value = 0.0;
float katet_2 = 0.0;
float delta_katet_1 = 0.0;
float hipothenuze = 0.0;
if( prev )
{
bound_frame_near_maximum = 1;// cause of 0-1 in function bellow
average_amplitude_near_maximum = get_average_amplitude( signal, bound_frame_near_maximum, maximum_index);
katet_2 = 1;
delta_katet_1 = (maximum - average_amplitude_near_maximum) * katet_2;
hipothenuze = std::sqrt( delta_katet_1*delta_katet_1 + katet_2*katet_2);
sin_value = katet_2 / hipothenuze;
}
else
{
bound_frame_near_maximum = signal_count - 1;
average_amplitude_near_maximum = get_average_amplitude( signal, maximum_index, bound_frame_near_maximum);
katet_2 = (signal_count - maximum_index) / 2;
delta_katet_1 = (maximum - average_amplitude_near_maximum) * katet_2;
hipothenuze = std::sqrt( delta_katet_1*delta_katet_1 + katet_2*katet_2);
sin_value = katet_2 / hipothenuze;
}
corner = (asin(sin_value) * 180 / M_PI - 45 ) * 2;
}
}
bool condition_check_signal_threshold( vector<signal_type> & signal, float threshold_positive, float & peak_value, unsigned int & peak_index )
{
peak_index = 0;
get_maximum_amplitude( signal, peak_value, peak_index );
cout << "max_amplitude=" << peak_value << endl;
if( peak_value >= threshold_positive )
{
return true;
}
return false;
}
bool condition_check_signal_corner_shoulder_at_max( vector<signal_type> & signal, float maximum, unsigned int maximum_index )
{
float high_threshold = 60;
bool previous_corner = true;
int corner_before = 0;
get_time_chunk_signal_corner( signal, maximum, maximum_index, previous_corner, corner_before);
if( corner_before > high_threshold )
{
cout << "corner_before=" << corner_before << " FAILED" << endl;
return false;
}
previous_corner = false;
int corner_after = 0;
get_time_chunk_signal_corner( signal, maximum, maximum_index, previous_corner, corner_after);
if( corner_after > high_threshold )
{
cout<< "corner_after=" << corner_after << " FAILED" << endl;
return false;
}
cout<< "corner_after=" << corner_after << "; corner_before=" << corner_before << " SUCCESS" << endl;
return true;
}
// Generate window function (Hanning) see http://www.musicdsp.org/files/wsfir.h
void wHanning( int fftFrameSize, vector<float> & hanning )
{
hanning.resize( fftFrameSize );
for( int k = 0; k < fftFrameSize ; k++)
{
hanning[k] = (-1) * 0.5 * cos( 2.0 * M_PI * (double)k / (double)fftFrameSize) + 0.5;
}
}
void apply_hanning_window( vector<signal_type> & magnitudes )
{
vector<float> hanning;
const size_t magnitudes_count = magnitudes.size();
wHanning( magnitudes_count, hanning );
// float * hanning_pointer = &hanning[0];
signal_type * magn_ptr = &magnitudes[0];
for( size_t magnitude_i = 0; magnitude_i < magnitudes_count ; magnitude_i++)
{
float curr_magnitude = magnitudes[magnitude_i];
double hann = hanning[magnitude_i];
magnitudes[magnitude_i] = curr_magnitude * hann;
}
}
void get_spectrum_magnitudes( vector<signal_type> & signal_chunk, vector<signal_type> & magnitudes)
{
complex_type * fft_result = NULL;
fftwf_plan plan = NULL;
make_fft( signal_chunk, &fft_result, &plan );
size_t FFTLen = signal_chunk.size();
size_t specLen = FFTLen / 2;
magnitudes.resize( specLen );
for( size_t fft_i = 0 ; fft_i < specLen ; fft_i++ )
{
magnitudes[fft_i] = complex_magnitude( fft_result[fft_i] );
}
destroy_fft( &fft_result, &plan );
}
void get_mfcc_coefficients( vector<signal_type> & signal_chunk, vector<float> & mfcc_coefficients)
{
vector<signal_type> magnitudes;
get_spectrum_magnitudes( signal_chunk, magnitudes );
size_t specLen = magnitudes.size();
Mfcc mfcc;
int numCoeffs = 14; // number of MFCC coefficients to calculate
int numFilters = 32; // number of filters for MFCC calc
mfcc_coefficients.resize( numCoeffs );
mfcc.init( 16000, numFilters, specLen, numCoeffs );
mfcc.getCoefficients( &magnitudes[0], &mfcc_coefficients[0] );
}
void mfcc_get_distance( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
distance = 0.0f;
size_t mfcc_1_size = mfcc_1.size();
size_t mfcc_2_size = mfcc_2.size();
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
double square_sum = 0;
for( size_t mfcc_i = 0 ; mfcc_i < mfcc_1_size ; mfcc_i++ )
{
double delta = mfcc_1[mfcc_i] - mfcc_2[mfcc_i];
double square = delta * delta;
square_sum += square;
}
distance = sqrt( square_sum );
}
void dtw_get_distance( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
distance = 0.0f;
float * mfcc_1_ptr = &mfcc_1[0];
float * mfcc_2_ptr = &mfcc_2[0];
dtw_get_distance( mfcc_1_ptr, mfcc_2_ptr, mfcc_1.size(), mfcc_2.size(), distance );
}
void dtw_get_distance( float * mfcc_1, float * mfcc_2, unsigned int mfcc_1_size, unsigned int mfcc_2_size, double & distance )
{
distance = 0.0f;
if( mfcc_1_size == 0 )
{
return;
}
if( mfcc_1_size != mfcc_2_size )
{
return;
}
DTW dtw( mfcc_1_size, mfcc_2_size );
distance = dtw.run( mfcc_1, mfcc_2, mfcc_1_size, mfcc_2_size );
}
void hmm_get_propability( vector_mfcc_level_1 & mfcc_1, vector_mfcc_level_1 & mfcc_2, double & distance )
{
}
void prepare_signal_near_peak( vector<signal_type> & present_signal, vector<signal_type> & past_signal, vector<signal_type> & future_signal, float threshold, unsigned int max_index, unsigned int periods_count_per_chunk, unsigned int max_chunks_count, vector<signal_type> & prepared_signal, unsigned int & new_max_index )
{
COPY_SIGNAL_ERROR_E error = COPY_SIGNAL_ERROR_SUCCESS;
COPY_SIGNAL_ERROR_E last_error = error;
int temp_max_index = max_index;
vector<signal_type> signal = present_signal;
bool no_mater_bounds = false;
while( true )
{
vector<signal_type> perioded_signal;
bool bCopy = copy_periods_before_after_signal_index(signal, threshold, temp_max_index, periods_count_per_chunk, max_chunks_count, perioded_signal, new_max_index, no_mater_bounds, error );
if( bCopy == true && error == COPY_SIGNAL_ERROR_SUCCESS )
{
size_t perioded_signal_count = perioded_signal.size();
prepared_signal = perioded_signal;
last_error = error;
break;
}
else if( error == COPY_SIGNAL_ERROR_NEED_PREV_SIGNAL )
{
if( last_error == error )
{
no_mater_bounds = true;
}
else
{
no_mater_bounds = false;
}
signal.clear();
signal.insert( signal.begin(), past_signal.begin(), past_signal.end() );
signal.insert( signal.end(), present_signal.begin(), present_signal.end() );
temp_max_index = max_index + past_signal.size();
last_error = error;
}
else if( error == COPY_SIGNAL_ERROR_NEED_NEXT_AND_PREV_SIGNAL )
{
if( last_error == error )
{
no_mater_bounds = true;
}
else
{
no_mater_bounds = false;
}
signal.clear();
signal.insert( signal.begin(), past_signal.begin(), past_signal.end() );
signal.insert( signal.end(), present_signal.begin(), present_signal.end() );
signal.insert( signal.end(), future_signal.begin(), future_signal.end() );
last_error = error;
}
else
{
prepared_signal.clear();
last_error = error;
break;
}
}
}
void merge_and_split_with_cross( vector<vector<signal_type> > & perioded_chunks, unsigned int periods_count, vector<vector<signal_type> > & perioded_crossed_chunks )
{
vector<signal_type> signal;
size_t perioded_count = perioded_chunks.size();
for( size_t perioded_i = 0; perioded_i < perioded_count ; perioded_i++ )
{
vector<signal_type> & perioded_chunk = perioded_chunks[perioded_i];
signal.insert( signal.end(), perioded_chunk.begin(), perioded_chunk.end() );
}
size_t signal_length = signal.size();
unsigned int perioded_offset_signal_index = 0;
size_t signal_i = 0;
for( size_t perioded_i = 0 ; signal_i < signal_length ; perioded_i++ )
{
vector<signal_type> cross_perioded_chunk;
unsigned int start_copy_index = perioded_offset_signal_index;
for( size_t period_i = 0 ; period_i < periods_count ; period_i++ )
{
unsigned int estimate_signals = 0;
vector<signal_type> period;
signal_i = start_copy_index;
period_next_get( signal, start_copy_index, estimate_signals, period );
if( false == period.empty() )
{
cross_perioded_chunk.insert( cross_perioded_chunk.end(), period.begin(), period.end() );
}
else
{
break;
}
signal_i += estimate_signals;
start_copy_index += estimate_signals;
if( period_i == ( periods_count/2 - 1) )
{
perioded_offset_signal_index = signal_i;
}
}
if( false == cross_perioded_chunk.empty() )
{
perioded_crossed_chunks.push_back( cross_perioded_chunk );
}
else
{
continue;
}
}
}
struct CRange
{
double min_value;
double max_value;
CRange():min_value(0), max_value(0.1){}
};
int get_amplitude_range_index( vector<CRange> ranges, double amplitude)
{
int index = 0;
size_t range_count = ranges.size();
for( index = 0 ; index < range_count ; index++ )
{
if( amplitude > ranges[index].min_value && amplitude < ranges[index].max_value )
{
break;
}
}
return index;
}
void get_most_meet_amplitude_range( vector<signal_type> & signal, float & low_range, float & high_range )
{
float min_range_amplitude_value = 0.0;
float max_range_amplitude_value = 1.0;
float range_delta = 0.01;
const int ranges_count = (max_range_amplitude_value - min_range_amplitude_value) / range_delta;
vector<CRange> ranges( ranges_count );
for(int i = 0 ; i < ranges_count ; i++ )
{
ranges[i].min_value = min_range_amplitude_value + range_delta*i;
ranges[i].max_value = min_range_amplitude_value + range_delta*( i + 1 );
}
int most_meet_range_index = 0;
const unsigned int max_amplitude_ranges_count = ranges_count;
vector<int> range_arr( max_amplitude_ranges_count );
size_t count = signal.size();
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
int range_index = 0;
range_index = get_amplitude_range_index( ranges, signal[signal_i] );
range_arr[range_index]++;
}
}
}
double temp_max = 0.0;
for( unsigned int range_i = 0 ; range_i < max_amplitude_ranges_count ; range_i++ )
{
int range_meet = range_arr[range_i];
if( temp_max < range_meet )
{
temp_max = range_meet;
most_meet_range_index = range_i;
}
}
low_range = ranges[most_meet_range_index].min_value;
high_range = ranges[most_meet_range_index].max_value;
}
void get_atleast_meet_amplitude_range( vector<signal_type> & signal, unsigned int minimum_peaks_count, float & low_range, float & high_range )
{
float min_range_amplitude_value = 0.0;
float max_range_amplitude_value = 1.0;
float range_delta = 0.01;
const int ranges_count = (max_range_amplitude_value - min_range_amplitude_value) / range_delta;
vector<CRange> ranges( ranges_count );
for(int i = 0 ; i < ranges_count ; i++ )
{
ranges[i].min_value = min_range_amplitude_value + range_delta*i;
ranges[i].max_value = min_range_amplitude_value + range_delta*( i + 1 );
}
const int max_amplitude_ranges_count = ranges_count;
vector<int> range_arr( max_amplitude_ranges_count );
size_t count = signal.size();
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
int range_index = 0;
range_index = get_amplitude_range_index( ranges, signal[signal_i] );
range_arr[range_index]++;
}
}
}
int minimum_meet_range_index = 0;
for( int range_i = max_amplitude_ranges_count - 1 ; range_i >= 0 ; range_i-- )
{
int range_meet_count = range_arr[range_i];
if( range_meet_count >= minimum_peaks_count )
{
minimum_meet_range_index = range_i;
break;
}
}
low_range = ranges[minimum_meet_range_index].min_value;
high_range = ranges[minimum_meet_range_index].max_value;
}
float get_mean_peak_amplitude( vector<signal_type> & signal )
{
size_t count = signal.size();
double sum_peak = 0.0;
unsigned int peak_counter = 0;
for( unsigned int signal_i = 1 ; signal_i < ( count -1 ) ; signal_i++ )
{
if( signal[signal_i] > 0 )
{
double prev = signal[signal_i - 1];
double curr = signal[signal_i];
double next = signal[signal_i + 1];
if( prev < curr && next < curr)
{
sum_peak += curr;
peak_counter += 1;
}
}
}
return (float)sum_peak/peak_counter;
}
void training_sound_template_remove_same( vector_mfcc_level_3 & all_templates_ranges, size_t & removed_number, size_t & remain_number )
{
vector_mfcc_level_3::iterator sounds_begin_1 = all_templates_ranges.begin();
vector_mfcc_level_3::iterator sounds_end_1 = all_templates_ranges.end();
vector_mfcc_level_3::iterator sounds_iter_1 = sounds_begin_1;
removed_number = 0;
remain_number = 0;
size_t remove_counter = 0;
for( ; sounds_iter_1 != sounds_end_1 ; sounds_iter_1++ )
{
bool bErased_in_sound = false;
vector_mfcc_level_2 & templates = (*sounds_iter_1);
vector_mfcc_level_2::iterator templates_begin_1 = templates.begin();
vector_mfcc_level_2::iterator templates_end_1 = templates.end();
vector_mfcc_level_2::iterator templates_iter_1 = templates_begin_1;
for( ; templates_iter_1 != templates_end_1 ; )
{
vector_mfcc_level_1 & template_1 = (*templates_iter_1);
bool bErased = false;
vector_mfcc_level_3::iterator sounds_begin_2 = all_templates_ranges.begin();
vector_mfcc_level_3::iterator sounds_end_2 = all_templates_ranges.end();
vector_mfcc_level_3::iterator sounds_iter_2 = sounds_begin_2;
for( ; sounds_iter_2 != sounds_end_2 ; sounds_iter_2++ )
{
vector_mfcc_level_2 & templates = (*sounds_iter_2);
vector_mfcc_level_2::iterator templates_begin_2 = templates.begin();
vector_mfcc_level_2::iterator templates_end_2 = templates.end();
vector_mfcc_level_2::iterator templates_iter_2 = templates_begin_2;
for( ; templates_iter_2 != templates_end_2 ; )
{
if( templates_iter_1 == templates_iter_2 )
{
templates_iter_2++;
continue;
}
vector_mfcc_level_1 & template_2 = (*templates_iter_2);
if( freq_range_template_equal( template_1, template_2, 0 ) )
{
templates_iter_2 = templates.erase( templates_iter_2 );
remove_counter++;
bErased = true;
break;
}
else
{
templates_iter_2++;
}
}
if( true == bErased )
{
bErased_in_sound = true;
break;
}
}
if( true == bErased )
{
templates_begin_1 = templates.begin();
templates_iter_1 = templates_begin_1;
bErased_in_sound = false;
removed_number ++;
}
else
{
templates_iter_1++;
}
}
if( false == bErased_in_sound )
{
remain_number += templates.size();
}
}
}
void training_sound_template_remove_nearest( vector_mfcc_level_2 & templates_ranges_1, vector_mfcc_level_2 & templates_ranges_2, float min_distance, size_t & removed_number, size_t & remain_number )
{
removed_number = 0;
remain_number = 0;
size_t remove_counter = 0;
vector_mfcc_level_2::iterator templates_begin_1 = templates_ranges_1.begin();
vector_mfcc_level_2::iterator templates_end_1 = templates_ranges_1.end();
vector_mfcc_level_2::iterator templates_iter_1 = templates_begin_1;
for( ; templates_iter_1 != templates_end_1 ; )
{
vector_mfcc_level_1 & template_1 = (*templates_iter_1);
bool bErased = false;
vector_mfcc_level_2::iterator templates_begin_2 = templates_ranges_2.begin();
vector_mfcc_level_2::iterator templates_end_2 = templates_ranges_2.end();
vector_mfcc_level_2::iterator templates_iter_2 = templates_begin_2;
for( ; templates_iter_2 != templates_end_2 ; )
{
vector_mfcc_level_1 & template_2 = (*templates_iter_2);
double distance = 0;
mfcc_get_distance( template_1, template_2, distance );
if( distance < min_distance )
{
templates_iter_2 = templates_ranges_2.erase( templates_iter_2 );
templates_iter_1 = templates_ranges_1.erase( templates_iter_1 );
remove_counter++;
bErased = true;
break;
}
else
{
templates_iter_2++;
}
}
if( false == bErased )
{
templates_iter_1++;
}
}
remain_number = 0;
remain_number += templates_ranges_1.size();
remain_number += templates_ranges_2.size();
removed_number = remove_counter;
}
| 26.047027
| 320
| 0.672567
|
vadimostanin2
|
2ed50e6d8f1948cd6a2c2bc343aefc8919fb1b75
| 1,419
|
cpp
|
C++
|
8 Hashing/4 unordered map/main.cpp
|
AdityaVSM/algorithms
|
0ab0147a1e3905cf3096576a89cbce13de2673ed
|
[
"MIT"
] | null | null | null |
8 Hashing/4 unordered map/main.cpp
|
AdityaVSM/algorithms
|
0ab0147a1e3905cf3096576a89cbce13de2673ed
|
[
"MIT"
] | null | null | null |
8 Hashing/4 unordered map/main.cpp
|
AdityaVSM/algorithms
|
0ab0147a1e3905cf3096576a89cbce13de2673ed
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
/*
* used to store key-value pair
* unordered maps are implemented using hashing
* elements are arranged internally in any random order
* Repetitive elements can be stored
set.begin() -> O(1) in worst case
set.end() -> O(1) in worst case
set.size() -> O(1) in worst case
set.empty() -> O(1) in worst case
set.erase(it) -> O(1) on average
set.count() -> O(1) on average
set.find() -> O(1) on average
set.insert() -> O(1) on average
[] -> O(1) on average
at -> O(1) on average
*/
int main(){
unordered_map<string, int> m;
m["India"] = 1;
m["UK"] = 24;
m["NZ"] = 13;
m.insert({"US",10});
for (auto it:m)
cout<<"{"<<it.first<<","<<it.second<<"} ";
//find function return address if exists else it returns m.end()
//can also be used to find value of that key
if(m.find("Srilanka")!=m.end())
cout<<"\nSrilanka exists";
else
cout<<"\nSrilanka doesn't exists in map";
auto it1 = m.find("UK");
if(it1!=m.end())
cout<<"\nValue of UK = "<<it1->second;
//count(m) prints 1 if element m exists and 0 if it doesn't exist.
//return type is size_t
if(m.count("India"))
cout<<"\nIndia Exists in map";
else
cout<<"\nIndia doesn't exists in map";
cout<<"\nSize of map "<<m.size();
return 0;
}
| 24.465517
| 71
| 0.561663
|
AdityaVSM
|
2eeb73aac334c4959666b5084f63b760b01e46f7
| 791
|
cpp
|
C++
|
src/device_emulate.cpp
|
angainor/hwmalloc
|
2cab9d95f90cef21d3cb7497c2e0fce73e8cc571
|
[
"BSD-3-Clause"
] | null | null | null |
src/device_emulate.cpp
|
angainor/hwmalloc
|
2cab9d95f90cef21d3cb7497c2e0fce73e8cc571
|
[
"BSD-3-Clause"
] | null | null | null |
src/device_emulate.cpp
|
angainor/hwmalloc
|
2cab9d95f90cef21d3cb7497c2e0fce73e8cc571
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* ghex-org
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <hwmalloc/device.hpp>
#include <cstdlib>
#include <cstring>
namespace hwmalloc
{
int
get_num_devices()
{
return 1;
}
int
get_device_id()
{
return 0;
}
void
set_device_id(int /*id*/)
{
}
void*
device_malloc(std::size_t size)
{
return std::memset(std::malloc(size), 0, size);
}
void
device_free(void* ptr) noexcept
{
std::free(ptr);
}
void
memcpy_to_device(void* dst, void const* src, std::size_t count)
{
std::memcpy(dst, src, count);
}
void
memcpy_to_host(void* dst, void const* src, std::size_t count)
{
std::memcpy(dst, src, count);
}
} // namespace hwmalloc
| 13.637931
| 63
| 0.670038
|
angainor
|
2eeb80e260f7f969c492f7a386b7323d232ae4cd
| 391
|
hpp
|
C++
|
Game/Game/src/Result.hpp
|
ikuramikan/get_the_cats
|
58cebec03454a9fda246a20cdecb84ae41724ea4
|
[
"MIT"
] | 1
|
2021-02-24T12:08:30.000Z
|
2021-02-24T12:08:30.000Z
|
Game/Game/src/Result.hpp
|
ikuramikan/get_the_cats
|
58cebec03454a9fda246a20cdecb84ae41724ea4
|
[
"MIT"
] | null | null | null |
Game/Game/src/Result.hpp
|
ikuramikan/get_the_cats
|
58cebec03454a9fda246a20cdecb84ae41724ea4
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Common.hpp"
#include "Cat_anime.hpp"
class Result : public MyApp::Scene
{
private:
const Font font{30};
RectF end_buttom{ Arg::center = Vec2{600, 470}, 200, 60 };
int32 game_score = getData().game_score;
Transition transition{ 0.4s, 0.2s };
Cat_anime cat_anime;
public:
Result(const InitData& init);
void update() override;
void draw() const override;
};
| 17.772727
| 59
| 0.70844
|
ikuramikan
|
2eecf678bb3fb830e3786728008a85e6e3a5bd05
| 9,498
|
cpp
|
C++
|
src/afk/ui/Ui.cpp
|
christocs/ICT397
|
5ff6e4ed8757effad19b88fdb91f36504208f942
|
[
"ISC"
] | null | null | null |
src/afk/ui/Ui.cpp
|
christocs/ICT397
|
5ff6e4ed8757effad19b88fdb91f36504208f942
|
[
"ISC"
] | null | null | null |
src/afk/ui/Ui.cpp
|
christocs/ICT397
|
5ff6e4ed8757effad19b88fdb91f36504208f942
|
[
"ISC"
] | null | null | null |
#include "afk/ui/Ui.hpp"
#include <filesystem>
#include <vector>
#include <imgui/examples/imgui_impl_glfw.h>
#include <imgui/examples/imgui_impl_opengl3.h>
#include <imgui/imgui.h>
#include "afk/Afk.hpp"
#include "afk/debug/Assert.hpp"
#include "afk/io/Log.hpp"
#include "afk/io/Path.hpp"
#include "afk/renderer/Renderer.hpp"
#include "afk/ai/DifficultyManager.hpp"
#include "afk/ui/Unicode.hpp"
#include "cmake/Git.hpp"
#include "cmake/Version.hpp"
using Afk::Engine;
using Afk::Ui;
using std::vector;
using std::filesystem::path;
Ui::~Ui() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
auto Ui::initialize(Renderer::Window _window) -> void {
afk_assert(_window != nullptr, "Window is uninitialized");
afk_assert(!this->is_initialized, "UI already initialized");
this->ini_path = Afk::get_absolute_path(".imgui.ini").string();
this->window = _window;
IMGUI_CHECKVERSION();
ImGui::CreateContext();
auto &io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.IniFilename = this->ini_path.c_str();
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(this->window, true);
ImGui_ImplOpenGL3_Init("#version 410");
auto *noto_sans = io.Fonts->AddFontFromFileTTF(
Afk::get_absolute_path("res/font/NotoSans-Regular.ttf").string().c_str(),
Ui::FONT_SIZE, nullptr, Afk::unicode_ranges.data());
this->fonts["Noto Sans"] = noto_sans;
auto *source_code_pro = io.Fonts->AddFontFromFileTTF(
Afk::get_absolute_path("res/font/SourceCodePro-Regular.ttf").string().c_str(),
Ui::FONT_SIZE, nullptr, Afk::unicode_ranges.data());
this->fonts["Source Code Pro"] = source_code_pro;
auto &style = ImGui::GetStyle();
style.ScaleAllSizes(this->scale);
this->is_initialized = true;
}
auto Ui::prepare() const -> void {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
auto Ui::draw() -> void {
this->draw_stats();
if (this->show_menu) {
this->draw_menu_bar();
}
this->draw_about();
this->draw_log();
this->draw_model_viewer();
this->draw_terrain_controller();
this->draw_exit_screen();
if (this->show_imgui) {
ImGui::ShowDemoWindow(&this->show_imgui);
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
auto Ui::draw_about() -> void {
if (!this->show_about) {
return;
}
ImGui::Begin("About", &this->show_about);
ImGui::Text("afk engine version %s build %.6s (%s)", AFK_VERSION,
GIT_HEAD_HASH, GIT_IS_DIRTY ? "dirty" : "clean");
ImGui::Separator();
ImGui::Text("%s", GIT_COMMIT_SUBJECT);
ImGui::Text("Author: %s", GIT_AUTHOR_NAME);
ImGui::Text("Date: %s", GIT_COMMIT_DATE);
ImGui::End();
}
auto Ui::draw_menu_bar() -> void {
// auto &afk = Engine::get();
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("Tools")) {
if (ImGui::MenuItem("Log")) {
this->show_log = true;
}
if (ImGui::MenuItem("Model viewer")) {
this->show_model_viewer = true;
}
if (ImGui::MenuItem("Terrain controller")) {
this->show_terrain_controller = true;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Difficulty")) {
if (ImGui::MenuItem("Easy", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::EASY)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::EASY) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::EASY);
}
}
if (ImGui::MenuItem("Normal", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::NORMAL)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::NORMAL) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::NORMAL);
}
}
if (ImGui::MenuItem("Hard", nullptr, Afk::Engine::get().difficulty_manager.get_difficulty() == AI::DifficultyManager::Difficulty::HARD)) {
if (Afk::Engine::get().difficulty_manager.get_difficulty() != AI::DifficultyManager::Difficulty::HARD) {
Afk::Engine::get().difficulty_manager.set_difficulty(AI::DifficultyManager::Difficulty::HARD);
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help")) {
if (ImGui::MenuItem("About")) {
this->show_about = true;
}
if (ImGui::MenuItem("Imgui")) {
this->show_imgui = true;
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("Exit")) {
// afk.exit();
this->show_exit_screen = true;
}
ImGui::EndMainMenuBar();
}
}
auto Ui::draw_stats() -> void {
const auto offset_x = 10.0f;
const auto offset_y = 37.0f;
static auto corner = 1;
auto &io = ImGui::GetIO();
if (corner != -1) {
const auto window_pos =
ImVec2{(corner & 1) ? io.DisplaySize.x - offset_x : offset_x,
(corner & 2) ? io.DisplaySize.y - offset_y : offset_y};
const auto window_pos_pivot =
ImVec2{(corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f};
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
}
ImGui::SetNextWindowBgAlpha(0.35f);
ImGui::SetNextWindowSize({200, 100});
if (ImGui::Begin("Stats", &this->show_stats,
(corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDecoration |
ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) {
const auto &afk = Engine::get();
const auto pos = afk.camera.get_position();
const auto angles = afk.camera.get_angles();
ImGui::Text("%.1f fps (%.4f ms)", static_cast<double>(io.Framerate),
static_cast<double>(io.Framerate) / 1000.0);
ImGui::Separator();
ImGui::Text("Position {%.1f, %.1f, %.1f}", static_cast<double>(pos.x),
static_cast<double>(pos.y), static_cast<double>(pos.z));
ImGui::Text("Angles {%.1f, %.1f}", static_cast<double>(angles.x),
static_cast<double>(angles.y));
if (ImGui::BeginPopupContextWindow()) {
if (ImGui::MenuItem("Custom", nullptr, corner == -1)) {
corner = -1;
}
if (ImGui::MenuItem("Top left", nullptr, corner == 0)) {
corner = 0;
}
if (ImGui::MenuItem("Top right", nullptr, corner == 1)) {
corner = 1;
}
if (ImGui::MenuItem("Bottom left", nullptr, corner == 2)) {
corner = 2;
}
if (ImGui::MenuItem("Bottom right", nullptr, corner == 3)) {
corner = 3;
}
if (this->show_stats && ImGui::MenuItem("Close")) {
this->show_stats = false;
}
ImGui::EndPopup();
}
}
ImGui::End();
}
auto Ui::draw_log() -> void {
if (!this->show_log) {
return;
}
ImGui::SetNextWindowSize({500, 400});
this->log.draw("Log", &this->show_log);
}
auto Ui::draw_model_viewer() -> void {
if (!this->show_model_viewer) {
return;
}
auto &afk = Engine::get();
const auto &models = afk.renderer.get_models();
ImGui::SetNextWindowSize({700, 500});
if (ImGui::Begin("Models", &this->show_model_viewer)) {
static auto selected = models.begin()->first;
ImGui::BeginChild("left pane", ImVec2(250, 0), true);
for (const auto &[key, value] : models) {
if (ImGui::Selectable(key.string().c_str(), selected.lexically_normal() ==
key.lexically_normal())) {
selected = key;
}
}
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::BeginChild("item view", {0, -ImGui::GetFrameHeightWithSpacing()});
if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) {
if (ImGui::BeginTabItem("Details")) {
const auto &model = models.at(selected);
ImGui::TextWrapped("Total meshes: %zu\n", model.meshes.size());
ImGui::Separator();
auto i = 0;
for (const auto &mesh : model.meshes) {
ImGui::TextWrapped("Mesh %d:\n", i);
ImGui::TextWrapped("VAO: %u\n", mesh.ibo);
ImGui::TextWrapped("VBO: %u\n", mesh.vbo);
ImGui::TextWrapped("IBO: %u\n", mesh.ibo);
ImGui::TextWrapped("Indices: %zu\n", mesh.num_indices);
ImGui::Separator();
++i;
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
ImGui::EndGroup();
}
ImGui::End();
}
auto Ui::draw_terrain_controller() -> void {
if (!this->show_terrain_controller) {
return;
}
ImGui::SetNextWindowSize({300, 150});
if (ImGui::Begin("Terrain controller", &this->show_terrain_controller)) {
// ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
}
ImGui::End();
}
auto Ui::draw_exit_screen() -> void {
if (!this->show_exit_screen) {
return;
}
auto &afk = Engine::get();
const auto texture = afk.renderer.get_texture("res/ui/exit.png");
ImGui::SetNextWindowSize({525, 600});
ImGui::Begin("Exit screen", &this->show_exit_screen);
ImGui::Image(reinterpret_cast<void *>(texture.id),
{static_cast<float>(texture.width), static_cast<float>(texture.height)});
if (ImGui::Button("Exit")) {
afk.exit();
}
ImGui::End();
}
| 30.056962
| 148
| 0.619604
|
christocs
|
2eef26d831511ea853beb50ca153acb93feecd97
| 1,738
|
cpp
|
C++
|
src/apps/haikudepot/util/RatingUtils.cpp
|
chamalwr/haiku
|
b2bf76c43decc3fc2de50c4750f830b16807ddef
|
[
"MIT"
] | 2
|
2020-02-02T06:48:30.000Z
|
2020-04-05T13:58:32.000Z
|
src/apps/haikudepot/util/RatingUtils.cpp
|
honza1a/haiku
|
3959883f5047e803205668d4eb7d083b2d81e2da
|
[
"MIT"
] | null | null | null |
src/apps/haikudepot/util/RatingUtils.cpp
|
honza1a/haiku
|
3959883f5047e803205668d4eb7d083b2d81e2da
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2020, Andrew Lindesay <apl@lindesay.co.nz>.
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include <View.h>
#include "HaikuDepotConstants.h"
#include "RatingUtils.h"
BReference<SharedBitmap> RatingUtils::sStarBlueBitmap
= BReference<SharedBitmap>(new SharedBitmap(RSRC_STAR_BLUE));
BReference<SharedBitmap> RatingUtils::sStarGrayBitmap
= BReference<SharedBitmap>(new SharedBitmap(RSRC_STAR_GREY));
/*static*/ void
RatingUtils::Draw(BView* target, BPoint at, float value)
{
const BBitmap* star;
if (value < RATING_MIN)
star = sStarGrayBitmap->Bitmap(SharedBitmap::SIZE_16);
else
star = sStarBlueBitmap->Bitmap(SharedBitmap::SIZE_16);
if (star == NULL) {
debugger("no star icon found in application resources.");
return;
}
Draw(target, at, value, star);
}
/*static*/ void
RatingUtils::Draw(BView* target, BPoint at, float value,
const BBitmap* star)
{
BRect rect = BOUNDS_RATING;
rect.OffsetBy(at);
// a rectangle covering the whole area of the stars
target->FillRect(rect, B_SOLID_LOW);
if (star == NULL) {
debugger("no star icon found in application resources.");
return;
}
target->SetDrawingMode(B_OP_OVER);
float x = 0;
for (int i = 0; i < 5; i++) {
target->DrawBitmap(star, at + BPoint(x, 0));
x += SIZE_RATING_STAR + WIDTH_RATING_STAR_SPACING;
}
if (value >= RATING_MIN && value < 5.0f) {
target->SetDrawingMode(B_OP_OVER);
rect = BOUNDS_RATING;
rect.right = x - 2;
rect.left = ceilf(rect.left + (value / 5.0f) * rect.Width());
rect.OffsetBy(at);
rgb_color color = target->LowColor();
color.alpha = 190;
target->SetHighColor(color);
target->SetDrawingMode(B_OP_ALPHA);
target->FillRect(rect, B_SOLID_HIGH);
}
}
| 22.868421
| 71
| 0.706559
|
chamalwr
|
2eef9c9d94e6311eb3d54f2b401e764e2273b930
| 538
|
cpp
|
C++
|
tests/src/good/StaticInternalVariableAddress_test.cpp
|
Ybalrid/jet-live
|
14b909b00b98399d7e046cd8b7500a3fdfe0a0b1
|
[
"MIT"
] | 325
|
2019-01-05T12:40:46.000Z
|
2022-03-26T09:06:40.000Z
|
tests/src/good/StaticInternalVariableAddress_test.cpp
|
Ybalrid/jet-live
|
14b909b00b98399d7e046cd8b7500a3fdfe0a0b1
|
[
"MIT"
] | 23
|
2019-01-05T19:43:47.000Z
|
2022-01-10T20:11:06.000Z
|
tests/src/good/StaticInternalVariableAddress_test.cpp
|
Ybalrid/jet-live
|
14b909b00b98399d7e046cd8b7500a3fdfe0a0b1
|
[
"MIT"
] | 29
|
2019-01-05T18:49:08.000Z
|
2022-03-20T19:14:30.000Z
|
#include <catch.hpp>
#include <iostream>
#include <thread>
#include "utility/StaticInternalVariableAddress.hpp"
#include "Globals.hpp"
#include "WaitForReload.hpp"
TEST_CASE("Relocation of static internal variable, comparing address", "[variable]")
{
auto oldVariableAddress = getStaticInternalVariableAddress();
std::cout << "JET_TEST: disable(st_intern_var_addr:1)" << std::endl;
waitForReload();
auto newVariableAddress = getStaticInternalVariableAddress();
REQUIRE(oldVariableAddress == newVariableAddress);
}
| 28.315789
| 84
| 0.758364
|
Ybalrid
|
2ef53b08ed9cdd1c32c0d9e916268f7bcc1488b5
| 2,638
|
cpp
|
C++
|
src/Scheduling/E_Task.cpp
|
martinc2907/KENS3-1
|
f622c069da63b20102aee587209f288d0ff61292
|
[
"MIT"
] | 1
|
2020-11-19T11:23:32.000Z
|
2020-11-19T11:23:32.000Z
|
src/Scheduling/E_Task.cpp
|
martinc2907/KENS3-1
|
f622c069da63b20102aee587209f288d0ff61292
|
[
"MIT"
] | null | null | null |
src/Scheduling/E_Task.cpp
|
martinc2907/KENS3-1
|
f622c069da63b20102aee587209f288d0ff61292
|
[
"MIT"
] | 1
|
2019-09-02T07:52:52.000Z
|
2019-09-02T07:52:52.000Z
|
/*
* E_Task.cpp
*
* Created on: 2014. 12. 3.
* Author: Keunhong Lee
*/
#include <E/E_System.hpp>
#include <E/E_Module.hpp>
#include <E/Scheduling/E_Task.hpp>
#include <E/Scheduling/E_Computer.hpp>
#include <E/Scheduling/E_Job.hpp>
#include <E/Scheduling/E_Scheduler.hpp>
namespace E
{
PeriodicTask::PeriodicTask(Computer* computer, Time period, Time executionTime, Time startOffset) : Module(computer->getSystem()), Task()
{
this->period = period;
this->executionTime = executionTime;
this->computer = computer;
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, startOffset);
}
PeriodicTask::~PeriodicTask()
{
}
Module::Message* PeriodicTask::messageReceived(Module* from, Module::Message* message)
{
Message* selfMessage = dynamic_cast<Message*>(message);
switch(selfMessage->type)
{
case TIMER:
{
computer->raiseJob(this, this->executionTime, this->getSystem()->getCurrentTime() + this->period);
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, this->period);
break;
}
default:
assert(0);
}
return nullptr;
}
void PeriodicTask::messageCancelled(Module* to, Module::Message* message)
{
delete message;
}
void PeriodicTask::messageFinished(Module* to, Module::Message* message, Module::Message* response)
{
delete message;
}
SporadicTask::SporadicTask(Computer* computer, Time period, Time executionTime, Time startOffset) : Module(computer->getSystem()), Task()
{
this->minPeriod = period;
this->worstExecution = executionTime;
this->computer = computer;
this->startOffset = startOffset;
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, startOffset);
}
SporadicTask::~SporadicTask()
{
}
Time SporadicTask::getMinPeriod()
{
return minPeriod;
}
Time SporadicTask::getWorstExecution()
{
return worstExecution;
}
Module::Message* SporadicTask::messageReceived(Module* from, Module::Message* message)
{
Message* selfMessage = dynamic_cast<Message*>(message);
switch(selfMessage->type)
{
case TIMER:
{
computer->raiseJob(this, this->worstExecution, this->getSystem()->getCurrentTime() + this->minPeriod);
Message* selfMessage = new Message;
selfMessage->type = TIMER;
this->sendMessage(this, selfMessage, this->minPeriod);
break;
}
default:
assert(0);
}
return nullptr;
}
void SporadicTask::messageCancelled(Module* to, Module::Message* message)
{
delete message;
}
void SporadicTask::messageFinished(Module* to, Module::Message* message, Module::Message* response)
{
delete message;
}
}
| 19.984848
| 137
| 0.728961
|
martinc2907
|
2ef6f08b927c25b94c1db02d189c595db8dd0221
| 11,899
|
cpp
|
C++
|
src/CacheManager.cpp
|
MyunginLee/tinc
|
d5d681d6fddca5fe9c194df0ba25902d785c895f
|
[
"BSD-3-Clause"
] | null | null | null |
src/CacheManager.cpp
|
MyunginLee/tinc
|
d5d681d6fddca5fe9c194df0ba25902d785c895f
|
[
"BSD-3-Clause"
] | 2
|
2020-12-22T19:22:37.000Z
|
2020-12-22T19:44:09.000Z
|
src/CacheManager.cpp
|
MyunginLee/tinc
|
d5d681d6fddca5fe9c194df0ba25902d785c895f
|
[
"BSD-3-Clause"
] | 3
|
2020-07-23T00:16:54.000Z
|
2022-02-05T08:28:34.000Z
|
#include "tinc/CacheManager.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include "al/io/al_File.hpp"
#define TINC_META_VERSION_MAJOR 1
#define TINC_META_VERSION_MINOR 0
using namespace tinc;
// To regenerate this file run update_schema_cpp.sh
#include "tinc_cache_schema.cpp"
CacheManager::CacheManager(DistributedPath cachePath) : mCachePath(cachePath) {
auto person_schema = nlohmann::json::parse(
doc_tinc_cache_schema_json,
doc_tinc_cache_schema_json + doc_tinc_cache_schema_json_len);
try {
mValidator.set_root_schema(person_schema); // insert root-schema
} catch (const std::exception &e) {
std::cerr << "Validation of schema failed, here is why: " << e.what()
<< "\n";
}
if (!al::File::exists(mCachePath.rootPath + mCachePath.relativePath)) {
al::Dir::make(mCachePath.rootPath + mCachePath.relativePath);
}
if (!al::File::exists(mCachePath.filePath())) {
writeToDisk();
} else {
try {
updateFromDisk();
} catch (std::exception &e) {
std::string backupFilename = mCachePath.filePath() + ".old";
size_t count = 0;
while (al::File::exists(mCachePath.filePath() + std::to_string(count))) {
count++;
}
if (!al::File::copy(mCachePath.filePath(),
mCachePath.filePath() + std::to_string(count))) {
std::cerr << "Cache invalid and backup failed." << std::endl;
throw std::exception();
}
std::cerr << "Invalid cache format. Ignoring old cache." << std::endl;
}
}
}
void CacheManager::appendEntry(CacheEntry &entry) {
std::unique_lock<std::mutex> lk(mCacheLock);
mEntries.push_back(entry);
}
std::vector<std::string> CacheManager::findCache(const SourceInfo &sourceInfo,
bool verifyHash) {
std::unique_lock<std::mutex> lk(mCacheLock);
for (const auto &entry : mEntries) {
if (entry.sourceInfo.commandLineArguments ==
sourceInfo.commandLineArguments &&
entry.sourceInfo.tincId == sourceInfo.tincId &&
entry.sourceInfo.type == sourceInfo.type) {
auto entryArguments = entry.sourceInfo.arguments;
bool argsMatch = false;
if (sourceInfo.arguments.size() == entry.sourceInfo.arguments.size()) {
size_t matchCount = 0;
for (const auto &sourceArg : sourceInfo.arguments) {
for (auto arg = entryArguments.begin(); arg != entryArguments.end();
arg++) {
if (sourceArg.id == arg->id) {
if (sourceArg.value.type == arg->value.type) {
if (sourceArg.value.type == VARIANT_DOUBLE ||
sourceArg.value.type == VARIANT_FLOAT) {
if (sourceArg.value.valueDouble == arg->value.valueDouble) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else if (sourceArg.value.type == VARIANT_INT32 ||
sourceArg.value.type == VARIANT_INT64) {
if (sourceArg.value.valueInt64 == arg->value.valueInt64) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else if (sourceArg.value.type == VARIANT_STRING) {
if (sourceArg.value.valueStr == arg->value.valueStr) {
entryArguments.erase(arg);
matchCount++;
break;
}
} else {
std::cerr << "ERROR: Unsupported type for argument value"
<< std::endl;
}
} else {
std::cout << "ERROR: type mismatch for argument in cache. "
"Ignoring cache"
<< std::endl;
continue;
}
}
}
}
if (matchCount == sourceInfo.arguments.size() &&
entryArguments.size() == 0) {
return entry.filenames;
}
} else {
// TODO develop mechanisms to recover stale cache
std::cout << "Warning, cache entry found, but argument size mismatch"
<< std::endl;
}
}
}
return {};
}
std::string CacheManager::cacheDirectory() { return mCachePath.path(); }
void CacheManager::updateFromDisk() {
std::unique_lock<std::mutex> lk(mCacheLock);
// j["tincMetaVersionMajor"] = TINC_META_VERSION_MAJOR;
// j["tincMetaVersionMinor"] = TINC_META_VERSION_MINOR;
// j["entries"] = {};
std::ifstream f(mCachePath.filePath());
if (f.good()) {
nlohmann::json j;
f >> j;
try {
mValidator.validate(j);
} catch (const std::exception &e) {
std::cerr << "Validation failed, here is why: " << e.what() << std::endl;
return;
}
if (j["tincMetaVersionMajor"] != TINC_META_VERSION_MAJOR ||
j["tincMetaVersionMinor"] != TINC_META_VERSION_MINOR) {
std::cerr << "Incompatible schema version: " << j["tincMetaVersionMajor"]
<< "." << j["tincMetaVersionMinor"] << " .This binary uses "
<< TINC_META_VERSION_MAJOR << "." << TINC_META_VERSION_MINOR
<< "\n";
return;
}
mEntries.clear();
for (auto entry : j["entries"]) {
CacheEntry e;
e.timestampStart = entry["timestamp"]["start"];
e.timestampEnd = entry["timestamp"]["end"];
e.filenames = entry["filenames"].get<std::vector<std::string>>();
e.cacheHits = entry["cacheHits"];
e.stale = entry["stale"];
e.userInfo.userName = entry["userInfo"]["userName"];
e.userInfo.userHash = entry["userInfo"]["userHash"];
e.userInfo.ip = entry["userInfo"]["ip"];
e.userInfo.port = entry["userInfo"]["port"];
e.userInfo.server = entry["userInfo"]["server"];
e.sourceInfo.type = entry["sourceInfo"]["type"];
e.sourceInfo.tincId = entry["sourceInfo"]["tincId"];
e.sourceInfo.commandLineArguments =
entry["sourceInfo"]["commandLineArguments"];
e.sourceInfo.workingPath.relativePath =
entry["sourceInfo"]["workingPath"]["relativePath"];
e.sourceInfo.workingPath.rootPath =
entry["sourceInfo"]["workingPath"]["rootPath"];
e.sourceInfo.hash = entry["sourceInfo"]["hash"];
for (auto arg : entry["sourceInfo"]["arguments"]) {
SourceArgument newArg;
newArg.id = arg["id"];
if (arg["value"].is_number_float()) {
newArg.value = arg["value"].get<double>();
} else if (arg["value"].is_number_integer()) {
newArg.value = arg["value"].get<int64_t>();
} else if (arg["value"].is_string()) {
newArg.value = arg["value"].get<std::string>();
}
e.sourceInfo.arguments.push_back(newArg);
}
for (auto arg : entry["sourceInfo"]["dependencies"]) {
SourceArgument newArg;
newArg.id = arg["id"];
if (arg["value"].is_number_float()) {
newArg.value = arg["value"].get<double>();
} else if (arg["value"].is_number_integer()) {
newArg.value = arg["value"].get<int64_t>();
} else if (arg["value"].is_string()) {
newArg.value = arg["value"].get<std::string>();
}
e.sourceInfo.dependencies.push_back(newArg);
}
for (auto arg : entry["sourceInfo"]["fileDependencies"]) {
DistributedPath newArg(arg["filename"], arg["relativePath"],
arg["rootPath"]);
e.sourceInfo.fileDependencies.push_back(newArg);
}
mEntries.push_back(e);
}
} else {
std::cerr << "Error attempting to read cache: " << mCachePath.filePath()
<< std::endl;
}
}
// when creating the validator
void CacheManager::writeToDisk() {
std::unique_lock<std::mutex> lk(mCacheLock);
std::ofstream o(mCachePath.filePath());
if (o.good()) {
nlohmann::json j;
j["tincMetaVersionMajor"] = TINC_META_VERSION_MAJOR;
j["tincMetaVersionMinor"] = TINC_META_VERSION_MINOR;
j["entries"] = std::vector<nlohmann::json>();
for (auto &e : mEntries) {
nlohmann::json entry;
entry["timestamp"]["start"] = e.timestampStart;
entry["timestamp"]["end"] = e.timestampEnd;
entry["filenames"] = e.filenames;
entry["cacheHits"] = e.cacheHits;
entry["stale"] = e.stale;
entry["userInfo"]["userName"] = e.userInfo.userName;
entry["userInfo"]["userHash"] = e.userInfo.userHash;
entry["userInfo"]["ip"] = e.userInfo.ip;
entry["userInfo"]["port"] = e.userInfo.port;
entry["userInfo"]["server"] = e.userInfo.server;
entry["sourceInfo"]["type"] = e.sourceInfo.type;
entry["sourceInfo"]["tincId"] = e.sourceInfo.tincId;
entry["sourceInfo"]["commandLineArguments"] =
e.sourceInfo.commandLineArguments;
// TODO validate working path
entry["sourceInfo"]["workingPath"]["relativePath"] =
e.sourceInfo.workingPath.relativePath;
entry["sourceInfo"]["workingPath"]["rootPath"] =
e.sourceInfo.workingPath.rootPath;
entry["sourceInfo"]["hash"] = e.sourceInfo.hash;
entry["sourceInfo"]["arguments"] = std::vector<nlohmann::json>();
entry["sourceInfo"]["dependencies"] = std::vector<nlohmann::json>();
entry["sourceInfo"]["fileDependencies"] = std::vector<nlohmann::json>();
for (auto arg : e.sourceInfo.arguments) {
nlohmann::json newArg;
newArg["id"] = arg.id;
if (arg.value.type == VARIANT_DOUBLE ||
arg.value.type == VARIANT_FLOAT) {
newArg["value"] = arg.value.valueDouble;
} else if (arg.value.type == VARIANT_INT32 ||
arg.value.type == VARIANT_INT64) {
newArg["value"] = arg.value.valueInt64;
} else if (arg.value.type == VARIANT_STRING) {
newArg["value"] = arg.value.valueStr;
} else {
newArg["value"] = nlohmann::json();
}
entry["sourceInfo"]["arguments"].push_back(newArg);
}
for (auto arg : e.sourceInfo.dependencies) {
nlohmann::json newArg;
newArg["id"] = arg.id;
if (arg.value.type == VARIANT_DOUBLE ||
arg.value.type == VARIANT_FLOAT) {
newArg["value"] = arg.value.valueDouble;
} else if (arg.value.type == VARIANT_INT32 ||
arg.value.type == VARIANT_INT64) {
newArg["value"] = arg.value.valueInt64;
} else if (arg.value.type == VARIANT_STRING) {
newArg["value"] = arg.value.valueStr;
} else {
newArg["value"] = nlohmann::json();
}
entry["sourceInfo"]["dependencies"].push_back(newArg);
}
for (auto arg : e.sourceInfo.fileDependencies) {
nlohmann::json newArg;
newArg["fileName"] = arg.filename;
newArg["relativePath"] = arg.relativePath;
newArg["rootPath"] = arg.rootPath;
entry["sourceInfo"]["fileDependencies"].push_back(newArg);
}
j["entries"].push_back(entry);
}
o << j << std::endl;
o.close();
} else {
std::cerr << "ERROR: Can't create cache file: " << mCachePath.filePath()
<< std::endl;
throw std::runtime_error("Can't create cache file");
}
}
std::string CacheManager::dump() {
writeToDisk();
std::unique_lock<std::mutex> lk(mCacheLock);
std::ifstream f(mCachePath.filePath());
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
void CacheManager::tincSchemaFormatChecker(const std::string &format,
const std::string &value) {
if (format == "date-time") {
// TODO validate date time
return;
// throw std::invalid_argument("value is not a good something");
} else
throw std::logic_error("Don't know how to validate " + format);
}
| 36.612308
| 79
| 0.575763
|
MyunginLee
|
2efa49e56c80c9ecd4a078791134a409ab19f01a
| 360
|
cpp
|
C++
|
socket/tcp_socket.cpp
|
xqq/drawboard
|
993f0f90c127c51ad5837656fc1383b2d9e7ddde
|
[
"MIT"
] | 10
|
2020-01-18T09:28:47.000Z
|
2020-04-28T15:37:42.000Z
|
socket/tcp_socket.cpp
|
xqq/drawboard
|
993f0f90c127c51ad5837656fc1383b2d9e7ddde
|
[
"MIT"
] | 1
|
2020-04-28T15:29:52.000Z
|
2020-04-28T15:35:03.000Z
|
socket/tcp_socket.cpp
|
xqq/drawboard
|
993f0f90c127c51ad5837656fc1383b2d9e7ddde
|
[
"MIT"
] | 2
|
2020-01-20T06:54:26.000Z
|
2022-01-11T09:01:42.000Z
|
//
// @author magicxqq <xqq@xqq.im>
//
#include "tcp_socket.hpp"
#ifndef _WIN32
#include "tcp_socket_posix.hpp"
#else
#include "tcp_socket_winsock.hpp"
#endif
TcpSocket* TcpSocket::Create() {
TcpSocket* socket = nullptr;
#ifndef _WIN32
socket = new TcpSocketPosix();
#else
socket = new TcpSocketWinsock();
#endif
return socket;
}
| 14.4
| 37
| 0.677778
|
xqq
|
2efcae515c322a32f0824a5328284a24682d69e4
| 1,846
|
cpp
|
C++
|
main.cpp
|
fhwedel-hoe/ueye_mjpeg_streamer
|
3aec9638ffa764b22e798753a312ac5e8b61a468
|
[
"MIT"
] | 2
|
2020-03-13T01:56:32.000Z
|
2020-08-19T22:12:10.000Z
|
main.cpp
|
fhwedel-hoe/ueye_mjpeg_streamer
|
3aec9638ffa764b22e798753a312ac5e8b61a468
|
[
"MIT"
] | null | null | null |
main.cpp
|
fhwedel-hoe/ueye_mjpeg_streamer
|
3aec9638ffa764b22e798753a312ac5e8b61a468
|
[
"MIT"
] | 1
|
2021-02-06T19:49:33.000Z
|
2021-02-06T19:49:33.000Z
|
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <memory>
#include <dlfcn.h>
#include "publisher.hpp"
#include "compress.hpp"
#include "serve.hpp"
#include "camera.hpp"
void capture(IPC_globals & ipc) {
for (;;) { // stream forever
try { // do not break loop due to exceptions
ipc.readers.read(); // wait for reader
std::cerr << "Initializing camera for new recording session..." << std::endl;
std::unique_ptr<Camera> camera = init_camera();
std::cerr << "Camera initialized, starting stream..." << std::endl;
/* capture a single image and submit it to the streaming library */
while (ipc.readers.read_unsafe() > 0) {
/* grab raw image data frame */
RawImage raw_image = camera->grab_frame();
/* compress image data */
binary_data image_compressed =
compress(raw_image.data, raw_image.width, raw_image.height, raw_image.pixelFormat);
/* publish for readers */
ipc.data.publish(image_compressed);
}
std::cerr << "Stopping camera due to lack of viewers..." << std::endl;
// ^^ happens implicitly during destructor
} catch (std::exception & se) {
std::cerr << "Unexpected exception: " << se.what() << "\n";
}
}
}
IPC_globals ipc_globals;
const unsigned short server_port = 8080;
int main(int, char**) {
std::thread(capture, std::ref(ipc_globals)).detach();
try {
boost::asio::io_service io_service;
server(io_service, server_port, ipc_globals);
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
| 33.563636
| 103
| 0.582882
|
fhwedel-hoe
|
2efd72ac39f7a136a4318c3720610d7cbf173798
| 3,459
|
cpp
|
C++
|
src/coremods/core_modules.cpp
|
BerilBBJ/beryldb
|
6569b568796e4cea64fe7f42785b0319541a0284
|
[
"BSD-3-Clause"
] | 206
|
2021-04-27T21:44:24.000Z
|
2022-02-23T12:01:20.000Z
|
src/coremods/core_modules.cpp
|
BerilBBJ/beryldb
|
6569b568796e4cea64fe7f42785b0319541a0284
|
[
"BSD-3-Clause"
] | 10
|
2021-05-04T19:46:59.000Z
|
2021-10-01T23:43:07.000Z
|
src/coremods/core_modules.cpp
|
berylcorp/beryl
|
6569b568796e4cea64fe7f42785b0319541a0284
|
[
"BSD-3-Clause"
] | 7
|
2021-04-28T16:17:56.000Z
|
2021-12-10T01:14:42.000Z
|
/*
* BerylDB - A lightweight database.
* http://www.beryldb.com
*
* Copyright (C) 2021 - Carlos F. Ferry <cferry@beryldb.com>
*
* This file is part of BerylDB. BerylDB is free software: you can
* redistribute it and/or modify it under the terms of the BSD License
* version 3.
*
* More information about our licensing can be found at https://docs.beryl.dev
*/
#include "beryl.h"
#include "notifier.h"
#include "engine.h"
/*
* Loadmodule Loads a module. Keep in mind that given modules must
* exist in coremodules or modules in order to be loaded.
*
* @requires 'r'.
*
* @parameters:
*
* · string : module to load.
*
* @protocol:
*
* · protocol : OK, or ERR_UNLOAD_MOD.
*/
class CommandLoadmodule : public Command
{
public:
CommandLoadmodule(Module* parent) : Command(parent, "LOADMODULE", 1, 1)
{
flags = 'r';
syntax = "<modulename>";
}
COMMAND_RESULT Handle(User* user, const Params& parameters);
};
COMMAND_RESULT CommandLoadmodule::Handle(User* user, const Params& parameters)
{
if (Kernel->Modules->Load(parameters[0]))
{
sfalert(user, NOTIFY_DEFAULT, "Module %s loaded.", parameters[0].c_str());
user->SendProtocol(BRLD_OK, PROCESS_OK);
return SUCCESS;
}
else
{
user->SendProtocol(ERR_INPUT2, ERR_UNLOAD_MOD, Kernel->Modules->LastError());
return FAILED;
}
}
/*
* ULoadmodule UnLoads a module. Keep in mind that given modules must
* be loaded in order to be unloaded.
*
* @requires 'r'.
*
* @parameters:
*
* · string : module to unload.
*
* @protocol:
*
* · protocol : OK, ERR_UNLOAD_MOD, or ERROR.
*/
class CommandUnloadmodule : public Command
{
public:
CommandUnloadmodule(Module* parent) : Command(parent, "UNLOADMODULE", 1)
{
flags = 'r';
syntax = "<modulename>";
}
COMMAND_RESULT Handle(User* user, const Params& parameters);
};
COMMAND_RESULT CommandUnloadmodule::Handle(User* user, const Params& parameters)
{
if (Daemon::Match(parameters[0], "core_*", ascii_case_insensitive))
{
sfalert(user, NOTIFY_DEFAULT, "Warning: Unloading core module %s.", parameters[0].c_str());
}
Module* InUse = Kernel->Modules->Find(parameters[0]);
if (InUse == creator)
{
user->SendProtocol(ERR_INPUT, PROCESS_ERROR);
return FAILED;
}
if (InUse && Kernel->Modules->Unload(InUse))
{
sfalert(user, NOTIFY_DEFAULT, "Module %s loaded.", parameters[0].c_str());
user->SendProtocol(BRLD_OK, PROCESS_OK);
}
else
{
user->SendProtocol(ERR_INPUT2, ERR_UNLOAD_MOD, (InUse ? Kernel->Modules->LastError() : NOT_FOUND));
return FAILED;
}
return SUCCESS;
}
class ModuleCoreModule : public Module
{
private:
CommandLoadmodule cmdloadmod;
CommandUnloadmodule cmdunloadmod;
public:
ModuleCoreModule() : cmdloadmod(this), cmdunloadmod(this)
{
}
Version GetDescription()
{
return Version("Provides Load and Unload module commands.", VF_BERYLDB|VF_CORE);
}
};
MODULE_LOAD(ModuleCoreModule)
| 24.707143
| 113
| 0.583117
|
BerilBBJ
|
2c03da1dd464fbc37bff173f8f70e58cea01bf5d
| 562
|
cpp
|
C++
|
chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp
|
NorthFacing/step-by-c
|
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
|
[
"MIT"
] | 9
|
2019-05-10T05:39:21.000Z
|
2022-02-22T08:04:52.000Z
|
chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp
|
NorthFacing/step-by-c
|
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
|
[
"MIT"
] | null | null | null |
chapter01/1.4_Flow_of_Control/1.4.3_Reading_an_Unknown_Number_of_Inputs.cpp
|
NorthFacing/step-by-c
|
bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3
|
[
"MIT"
] | 6
|
2019-05-13T13:39:19.000Z
|
2022-02-22T08:05:01.000Z
|
/**
* 1.4.3 读取数量不定的输入数据
* @Author Bob
* @Eamil 0haizhu0@gmail.com
* @Date 2017/6/26
*/
#include <iostream>
/**
* 读取数量不定的输入数据,
* 只有输入换行符(比如:\n)或者非法字符(非数字,但直接回车不会停止)的时候才会停止接收数据,输出运算结果
* @EOF EOF 是 end of file 的缩写,windows环境是:ctrl+Z,unix 环境是:ctrl+D,即可模拟(?)EOF
*/
int main(){
std::cout << "数量不定的输入数据:输入一系列整数(想结束输入参数的时候输入 EOF 或者输入非数字字符即可):" << std::endl;
int sum = 0, value = 0;
// 在while循环中完成数据读取操作
while (std::cin >> value) { // 只要cin读取成功就返回true,读取结束或者非法则返回false
sum += value;
}
std::cout << "Sum is " << sum << std::endl;
return 0;
}
| 23.416667
| 79
| 0.635231
|
NorthFacing
|
2c03ebf0289ea27755cd98b27d0c4648d6331887
| 909
|
hpp
|
C++
|
libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
libctrpf/include/CTRPluginFrameworkImpl/Menu/GatewayRAMDumper.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
#ifndef CTRPLUGINFRAMEWORKIMPL_GATEWAYRAMDUMPER_HPP
#define CTRPLUGINFRAMEWORKIMPL_GATEWAYRAMDUMPER_HPP
#include "types.h"
#include "CTRPluginFrameworkImpl/Search/Search.hpp"
namespace CTRPluginFramework
{
class GatewayRAMDumper
{
public:
GatewayRAMDumper(void);
~GatewayRAMDumper(void){}
// Return true if finished
bool operator()(void);
bool _SelectRegion();
private:
void _OpenFile(void);
void _WriteHeader(void);
void _DrawProgress(void);
std::string _fileName;
File _file;
u32 _currentAddress;
u32 _endAddress;
u32 _regionIndex;
u32 _achievedSize;
u32 _totalSize;
std::vector<Region> _regions;
};
}
#endif
| 25.25
| 51
| 0.547855
|
MirayXS
|
2c089201d3bed722abb3d92e212d3fa43fe74a6e
| 10,469
|
cpp
|
C++
|
engine/hid/src/hid.cpp
|
Epitaph128/defold
|
554625a6438c38014b8f701c4a6e0ca684478618
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2020-11-13T09:03:39.000Z
|
2020-11-13T09:03:45.000Z
|
engine/hid/src/hid.cpp
|
Epitaph128/defold
|
554625a6438c38014b8f701c4a6e0ca684478618
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
engine/hid/src/hid.cpp
|
Epitaph128/defold
|
554625a6438c38014b8f701c4a6e0ca684478618
|
[
"ECL-2.0",
"Apache-2.0"
] | 1
|
2020-07-06T08:54:02.000Z
|
2020-07-06T08:54:02.000Z
|
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 <assert.h>
#include <dlib/log.h>
#include "hid.h"
#include "hid_private.h"
#include <string.h>
#include <dlib/dstrings.h>
#include <dlib/utf8.h>
namespace dmHID
{
NewContextParams::NewContextParams()
{
memset(this, 0, sizeof(NewContextParams));
}
Context::Context()
{
memset(this, 0, sizeof(Context));
}
HContext NewContext(const NewContextParams& params)
{
HContext context = new Context();
context->m_IgnoreMouse = params.m_IgnoreMouse;
context->m_IgnoreKeyboard = params.m_IgnoreKeyboard;
context->m_IgnoreGamepads = params.m_IgnoreGamepads;
context->m_IgnoreTouchDevice = params.m_IgnoreTouchDevice;
context->m_IgnoreAcceleration = params.m_IgnoreAcceleration;
context->m_FlipScrollDirection = params.m_FlipScrollDirection;
context->m_GamepadConnectivityCallback = params.m_GamepadConnectivityCallback;
return context;
}
void SetGamepadFuncUserdata(HContext context, void* userdata)
{
context->m_GamepadConnectivityUserdata = userdata;
}
void DeleteContext(HContext context)
{
delete context;
}
HGamepad GetGamepad(HContext context, uint8_t index)
{
if (index < MAX_GAMEPAD_COUNT)
return &context->m_Gamepads[index];
else
return INVALID_GAMEPAD_HANDLE;
}
uint32_t GetGamepadButtonCount(HGamepad gamepad)
{
return gamepad->m_ButtonCount;
}
uint32_t GetGamepadHatCount(HGamepad gamepad)
{
return gamepad->m_HatCount;
}
uint32_t GetGamepadAxisCount(HGamepad gamepad)
{
return gamepad->m_AxisCount;
}
bool IsKeyboardConnected(HContext context)
{
return context->m_KeyboardConnected;
}
bool IsMouseConnected(HContext context)
{
return context->m_MouseConnected;
}
bool IsGamepadConnected(HGamepad gamepad)
{
if (gamepad != 0x0)
return gamepad->m_Connected;
else
return false;
}
bool IsTouchDeviceConnected(HContext context)
{
return context->m_TouchDeviceConnected;
}
bool IsAccelerometerConnected(HContext context)
{
return context->m_AccelerometerConnected;
}
bool GetKeyboardPacket(HContext context, KeyboardPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_KeyboardPacket;
return true;
}
else
{
return false;
}
}
bool GetTextPacket(HContext context, TextPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_TextPacket;
context->m_TextPacket.m_Size = 0;
context->m_TextPacket.m_Text[0] = '\0';
return true;
}
else
{
return false;
}
}
void AddKeyboardChar(HContext context, int chr) {
if (context) {
char buf[5];
uint32_t n = dmUtf8::ToUtf8((uint16_t) chr, buf);
buf[n] = '\0';
TextPacket* p = &context->m_TextPacket;
p->m_Size = dmStrlCat(p->m_Text, buf, sizeof(p->m_Text));
}
}
bool GetMarkedTextPacket(HContext context, MarkedTextPacket* out_packet)
{
if (out_packet != 0x0 && context->m_KeyboardConnected)
{
*out_packet = context->m_MarkedTextPacket;
context->m_MarkedTextPacket.m_Size = 0;
context->m_MarkedTextPacket.m_HasText = 0;
context->m_MarkedTextPacket.m_Text[0] = '\0';
return true;
}
else
{
return false;
}
}
void SetMarkedText(HContext context, char* text) {
if (context) {
MarkedTextPacket* p = &context->m_MarkedTextPacket;
p->m_HasText = 1;
p->m_Size = dmStrlCpy(p->m_Text, text, sizeof(p->m_Text));
}
}
void SetGamepadConnectivity(HContext context, int gamepad, bool connected) {
assert(context);
GamepadPacket* p = &context->m_Gamepads[gamepad].m_Packet;
p->m_GamepadDisconnected = !connected;
p->m_GamepadConnected = connected;
}
bool GetMousePacket(HContext context, MousePacket* out_packet)
{
if (out_packet != 0x0 && context->m_MouseConnected)
{
*out_packet = context->m_MousePacket;
return true;
}
else
{
return false;
}
}
bool GetGamepadPacket(HGamepad gamepad, GamepadPacket* out_packet)
{
if (gamepad != 0x0 && out_packet != 0x0)
{
*out_packet = gamepad->m_Packet;
gamepad->m_Packet.m_GamepadDisconnected = false;
gamepad->m_Packet.m_GamepadConnected = false;
return true;
}
else
{
return false;
}
}
bool GetTouchDevicePacket(HContext context, TouchDevicePacket* out_packet)
{
if (out_packet != 0x0 && context->m_TouchDeviceConnected)
{
*out_packet = context->m_TouchDevicePacket;
return true;
}
else
{
return false;
}
}
bool GetAccelerationPacket(HContext context, AccelerationPacket* out_packet)
{
if (out_packet != 0x0)
{
*out_packet = context->m_AccelerationPacket;
return true;
}
else
{
return false;
}
}
bool GetKey(KeyboardPacket* packet, Key key)
{
if (packet != 0x0)
return packet->m_Keys[key / 32] & (1 << (key % 32));
else
return false;
}
void SetKey(HContext context, Key key, bool value)
{
if (context != 0x0)
{
if (value)
context->m_KeyboardPacket.m_Keys[key / 32] |= (1 << (key % 32));
else
context->m_KeyboardPacket.m_Keys[key / 32] &= ~(1 << (key % 32));
}
}
bool GetMouseButton(MousePacket* packet, MouseButton button)
{
if (packet != 0x0)
return packet->m_Buttons[button / 32] & (1 << (button % 32));
else
return false;
}
void SetMouseButton(HContext context, MouseButton button, bool value)
{
if (context != 0x0)
{
if (value)
context->m_MousePacket.m_Buttons[button / 32] |= (1 << (button % 32));
else
context->m_MousePacket.m_Buttons[button / 32] &= ~(1 << (button % 32));
}
}
void SetMousePosition(HContext context, int32_t x, int32_t y)
{
if (context != 0x0)
{
MousePacket& packet = context->m_MousePacket;
packet.m_PositionX = x;
packet.m_PositionY = y;
}
}
void SetMouseWheel(HContext context, int32_t value)
{
if (context != 0x0)
{
context->m_MousePacket.m_Wheel = value;
}
}
bool GetGamepadButton(GamepadPacket* packet, uint32_t button)
{
if (packet != 0x0)
return packet->m_Buttons[button / 32] & (1 << (button % 32));
else
return false;
}
void SetGamepadButton(HGamepad gamepad, uint32_t button, bool value)
{
if (gamepad != 0x0)
{
if (value)
gamepad->m_Packet.m_Buttons[button / 32] |= (1 << (button % 32));
else
gamepad->m_Packet.m_Buttons[button / 32] &= ~(1 << (button % 32));
}
}
bool GetGamepadHat(GamepadPacket* packet, uint32_t hat, uint8_t& hat_value)
{
if (packet != 0x0)
{
hat_value = packet->m_Hat[hat];
return true;
} else {
return false;
}
}
void SetGamepadAxis(HGamepad gamepad, uint32_t axis, float value)
{
if (gamepad != 0x0)
{
gamepad->m_Packet.m_Axis[axis] = value;
}
}
// NOTE: A bit contrived function only used for unit-tests. See AddTouchPosition
bool GetTouch(TouchDevicePacket* packet, uint32_t touch_index, int32_t* x, int32_t* y, uint32_t* id, bool* pressed, bool* released)
{
if (packet != 0x0
&& x != 0x0
&& y != 0x0
&& id != 0x0)
{
if (touch_index < packet->m_TouchCount)
{
const Touch& t = packet->m_Touches[touch_index];
*x = t.m_X;
*y = t.m_Y;
*id = t.m_Id;
if (pressed != 0x0) {
*pressed = t.m_Phase == dmHID::PHASE_BEGAN;
}
if (released != 0x0) {
*released = t.m_Phase == dmHID::PHASE_ENDED || t.m_Phase == dmHID::PHASE_CANCELLED;
}
return true;
}
}
return false;
}
// NOTE: A bit contrived function only used for unit-tests
// We should perhaps include additional relevant touch-arguments
void AddTouch(HContext context, int32_t x, int32_t y, uint32_t id, Phase phase)
{
if (context->m_TouchDeviceConnected)
{
TouchDevicePacket& packet = context->m_TouchDevicePacket;
if (packet.m_TouchCount < MAX_TOUCH_COUNT)
{
Touch& t = packet.m_Touches[packet.m_TouchCount++];
t.m_X = x;
t.m_Y = y;
t.m_Id = id;
t.m_Phase = phase;
}
}
}
void ClearTouches(HContext context)
{
if (context->m_TouchDeviceConnected)
{
context->m_TouchDevicePacket.m_TouchCount = 0;
}
}
}
| 27.47769
| 135
| 0.560512
|
Epitaph128
|
2c0a985f02c864619b7ede4d6f772be0853b8751
| 354
|
cpp
|
C++
|
ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp
|
suiyili/Algorithms
|
d6ddc8262c5d681ecc78938b6140510793a29d91
|
[
"MIT"
] | null | null | null |
ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp
|
suiyili/Algorithms
|
d6ddc8262c5d681ecc78938b6140510793a29d91
|
[
"MIT"
] | null | null | null |
ExpressionEvaluation/evaluation/operand/custom_function/custom_function.cpp
|
suiyili/Algorithms
|
d6ddc8262c5d681ecc78938b6140510793a29d91
|
[
"MIT"
] | null | null | null |
#include "custom_function.hpp"
namespace expression::evaluate {
custom_function::custom_function(evaluation_function user_function, const argument_compilers &compilers)
: operand(compilers),
user_function_(move(user_function)) {}
double custom_function::get_result(const std::valarray<double> &args) const {
return user_function_(args);
}
}
| 32.181818
| 104
| 0.788136
|
suiyili
|
2c0fab5d22ae16693a4679df1ace86e3d7ce5bb0
| 3,459
|
cpp
|
C++
|
Old/Source/SceneModule.cpp
|
TinoTano/Games_Factory_2D
|
116ec94f05eb805654f3d30735134e81eb873c60
|
[
"MIT"
] | 1
|
2020-02-07T04:50:57.000Z
|
2020-02-07T04:50:57.000Z
|
Old/Source/SceneModule.cpp
|
TinoTano/Games_Factory_2D
|
116ec94f05eb805654f3d30735134e81eb873c60
|
[
"MIT"
] | null | null | null |
Old/Source/SceneModule.cpp
|
TinoTano/Games_Factory_2D
|
116ec94f05eb805654f3d30735134e81eb873c60
|
[
"MIT"
] | 1
|
2020-02-07T04:51:00.000Z
|
2020-02-07T04:51:00.000Z
|
#include "SceneModule.h"
#include "GameObject.h"
#include "Application.h"
#include "CameraModule.h"
#include "ComponentTransform.h"
#include "Scene.h"
#include "Data.h"
#include "Log.h"
#include "FileSystemModule.h"
SceneModule::SceneModule(const char* moduleName, bool gameModule) : Module(moduleName, gameModule)
{
updateSceneVertices = false;
currentScene = nullptr;
clearScene = false;
}
SceneModule::~SceneModule()
{
}
bool SceneModule::Init(Data& settings)
{
NewScene();
return true;
}
bool SceneModule::PreUpdate(float delta_time)
{
if (clearScene)
{
NewScene();
clearScene = false;
}
return true;
}
bool SceneModule::Update(float delta_time)
{
return true;
}
bool SceneModule::CleanUp()
{
DestroyScene();
return true;
}
void SceneModule::NewScene()
{
DestroyScene();
currentScene = new Scene("Default", "", "");
sceneGameObjects.clear();
sceneGameObjects.emplace_back(currentScene->GetRootGameObject());
}
void SceneModule::DestroyScene()
{
if (currentScene != nullptr)
{
delete currentScene;
currentScene = nullptr;
}
}
void SceneModule::LoadScene(std::string path)
{
Data data;
if (data.LoadData(path))
{
int dataType = data.GetInt("Type");
if (dataType != Resource::RESOURCE_SCENE)
{
CONSOLE_ERROR("%s", "Failed to load a Scene. " + path + " Is not a valid Scene Path");
return;
}
NewScene();
int gameObjectCount = data.GetInt("GameObjectCount");
for (int i = 0; i < gameObjectCount; i++)
{
Data sectionData;
if (data.GetSectionData("GameObject" + std::to_string(i), sectionData))
{
GameObject* gameObject = nullptr;
if (i == 0)
{
gameObject = currentScene->GetRootGameObject();
}
else
{
gameObject = App->sceneModule->CreateNewObject();
}
gameObject->LoadData(sectionData);
}
}
}
}
void SceneModule::SaveScene(std::string path)
{
Data data;
data.AddInt("Type", Resource::RESOURCE_SCENE);
data.AddInt("GameObjectCount", sceneGameObjects.size());
for (int i = 0; i < sceneGameObjects.size(); i++)
{
data.CreateSection("GameObject" + std::to_string(i));
sceneGameObjects[i]->SaveData(data);
data.CloseSection("GameObject" + std::to_string(i));
}
if (App->fileSystemModule->GetExtension(path) != ".scene")
{
path += ".scene";
}
data.SaveData(path);
}
void SceneModule::ClearScene()
{
clearScene = true;
}
GameObject* SceneModule::CreateNewObject(GameObject* parent, std::string name)
{
if (name.empty()) name = "GameObject ";
GameObject* go = new GameObject(name + std::to_string(sceneGameObjects.size()), parent);
sceneGameObjects.emplace_back(go);
return go;
}
GameObject * SceneModule::DuplicateGameObject(GameObject & go)
{
Data data;
go.SaveData(data);
GameObject* duplicated = CreateNewObject();
std::string UID = duplicated->GetUID();
duplicated->LoadData(data);
duplicated->SetUID(UID);
return duplicated;
}
void SceneModule::RemoveGameObject(GameObject & gameObject)
{
GameObject* sceneRoot = currentScene->GetRootGameObject();
sceneRoot->RemoveChild(&gameObject);
for (int i = 0; i < sceneGameObjects.size(); i++)
{
if (sceneGameObjects[i] == &gameObject)
{
sceneGameObjects.erase(sceneGameObjects.begin() + i);
break;
}
}
}
GameObject * SceneModule::FindGameObject(std::string UID)
{
GameObject* ret = nullptr;
for (GameObject* gameObject : sceneGameObjects)
{
if (gameObject->GetUID() == UID)
{
ret = gameObject;
}
}
return ret;
}
| 19.432584
| 98
| 0.689217
|
TinoTano
|
2c0fb45aa4ab3d4f4eee4b6179bd5d949e05e07d
| 5,464
|
cpp
|
C++
|
editor/source/widget/debugger/pass/debugger_pass.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
editor/source/widget/debugger/pass/debugger_pass.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
editor/source/widget/debugger/pass/debugger_pass.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
#include "widget/debugger/pass/debugger_pass.h"
namespace coffee_editor
{
//-META---------------------------------------------------------------------------------------//
COFFEE_BeginType(widget::DebuggerPass);
COFFEE_Ancestor(graphics::FramePass);
COFFEE_EndType();
namespace widget
{
//-CONSTRUCTORS-------------------------------------------------------------------------------//
DebuggerPass::DebuggerPass() :
graphics::FramePass("Debugger"),
_PassType(DEBUGGER_PASS_TYPE_None)
{
}
//--------------------------------------------------------------------------------------------//
DebuggerPass::~DebuggerPass()
{
SetPassType(DEBUGGER_PASS_TYPE_None);
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::SetPassType(DEBUGGER_PASS_TYPE type)
{
graphics::FramePassSystem& system = graphics::FramePassSystem::Get();
if (_PassType!=DEBUGGER_PASS_TYPE_None)
{
system.GetPasses()[system.GetPasses().GetSize()-1] = NULL;
system.GetPasses().Remove(system.GetPasses().GetSize()-1);
Finalize(NULL);
}
_PassType = type;
if (_PassType!=DEBUGGER_PASS_TYPE_None)
{
system.GetPasses().AddItem(this);
Initialize(NULL);
}
}
//-OPERATIONS---------------------------------------------------------------------------------//
void DebuggerPass::Initialize(graphics::FramePass* previous_pass)
{
_Layer = COFFEE_New(graphics::FrameLayerBGRA, GetFrameBuffer().GetWidth(), GetFrameBuffer().GetHeight(), false);
GetFrameBuffer().AttachLayer(*_Layer);
switch (_PassType)
{
case DEBUGGER_PASS_TYPE_Depth:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_depth.material");
break;
case DEBUGGER_PASS_TYPE_LinearDepth:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_linear_depth.material");
break;
case DEBUGGER_PASS_TYPE_Normal:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_normal.material");
break;
case DEBUGGER_PASS_TYPE_Color:
case DEBUGGER_PASS_TYPE_Material:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_rgb8.material");
break;
case DEBUGGER_PASS_TYPE_Lightning:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_layer_lightning.material");
break;
case DEBUGGER_PASS_TYPE_DetectNAN:
_Material = resource::Manager::Get().Load("/coffee/import/editor/debugger/debug_detect_nan.material");
break;
}
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::Finalize(graphics::FramePass* previous_pass)
{
GetFrameBuffer().DetachLayer(*_Layer);
COFFEE_Delete(_Layer);
}
//--------------------------------------------------------------------------------------------//
void DebuggerPass::Render(graphics::Viewport& viewport, graphics::FramePass* previous_pass)
{
if (viewport.HasCamera() && _Material.IsAvailable())
{
graphics::FramePassSystem& system = graphics::FramePassSystem::Get();
switch(_PassType)
{
case DEBUGGER_PASS_TYPE_Depth: system.GetGBufferPass().GetDepth().Bind(0); break;
case DEBUGGER_PASS_TYPE_LinearDepth: system.GetGBufferPass().GetLinearDepth().Bind(0); break;
case DEBUGGER_PASS_TYPE_Normal: system.GetGBufferPass().GetNormal().Bind(0); break;
case DEBUGGER_PASS_TYPE_Color: system.GetGBufferPass().GetColor().Bind(0); break;
case DEBUGGER_PASS_TYPE_Material: system.GetGBufferPass().GetMaterial().Bind(0); break;
case DEBUGGER_PASS_TYPE_Lightning: system.GetLightningPass().GetFrameBuffer().GetLayer(0).Bind(0); break;
case DEBUGGER_PASS_TYPE_DetectNAN: system.GetSkyPass().GetFrameBuffer().GetLayer(0).Bind(0); break;
}
_Material.Bind();
RenderQuad(viewport);
_Material.UnBind();
switch(_PassType)
{
case DEBUGGER_PASS_TYPE_Depth: system.GetGBufferPass().GetDepth().UnBind(0); break;
case DEBUGGER_PASS_TYPE_LinearDepth: system.GetGBufferPass().GetLinearDepth().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Normal: system.GetGBufferPass().GetNormal().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Color: system.GetGBufferPass().GetColor().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Material: system.GetGBufferPass().GetMaterial().UnBind(0); break;
case DEBUGGER_PASS_TYPE_Lightning: system.GetLightningPass().GetFrameBuffer().GetLayer(0).UnBind(0); break;
case DEBUGGER_PASS_TYPE_DetectNAN: system.GetSkyPass().GetFrameBuffer().GetLayer(0).UnBind(0); break;
}
}
else
{
graphics::Renderer::Get().ClearColor();
}
}
}
}
| 40.474074
| 126
| 0.551428
|
skarab
|
2c12a8ac7a3f1da1e55f6a1229ed3f71ad14d6da
| 5,939
|
cpp
|
C++
|
src/array/service/io_locker/io_locker.cpp
|
poseidonos/poseidonos
|
1d4a72c823739ef3eaf86e65c57d166ef8f18919
|
[
"BSD-3-Clause"
] | 38
|
2021-04-06T03:20:55.000Z
|
2022-03-02T09:33:28.000Z
|
src/array/service/io_locker/io_locker.cpp
|
poseidonos/poseidonos
|
1d4a72c823739ef3eaf86e65c57d166ef8f18919
|
[
"BSD-3-Clause"
] | 19
|
2021-04-08T02:27:44.000Z
|
2022-03-23T00:59:04.000Z
|
src/array/service/io_locker/io_locker.cpp
|
poseidonos/poseidonos
|
1d4a72c823739ef3eaf86e65c57d166ef8f18919
|
[
"BSD-3-Clause"
] | 28
|
2021-04-08T04:39:18.000Z
|
2022-03-24T05:56:00.000Z
|
/*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* 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 Samsung Electronics Corporation nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "io_locker.h"
#include "src/include/array_mgmt_policy.h"
#include "src/include/pos_event_id.h"
#include "src/logger/logger.h"
namespace pos
{
bool
IOLocker::Register(vector<ArrayDevice*> devList)
{
group.AddDevice(devList);
size_t prevSize = lockers.size();
for (IArrayDevice* d : devList)
{
if (_Find(d) == nullptr)
{
IArrayDevice* m = group.GetMirror(d);
if (m != nullptr)
{
StripeLocker* locker = new StripeLocker();
lockers.emplace(d, locker);
lockers.emplace(m, locker);
}
}
}
size_t newSize = lockers.size();
POS_TRACE_INFO(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Register, {} devs added, size: {} -> {}",
devList.size(), prevSize, newSize);
return true;
}
void
IOLocker::Unregister(vector<ArrayDevice*> devList)
{
size_t prevSize = lockers.size();
for (IArrayDevice* d : devList)
{
StripeLocker* locker = _Find(d);
if (locker != nullptr)
{
lockers.erase(d);
IArrayDevice* m = group.GetMirror(d);
if (m != nullptr)
{
lockers.erase(m);
}
delete locker;
locker = nullptr;
}
}
group.RemoveDevice(devList);
size_t newSize = lockers.size();
POS_TRACE_INFO(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unregister, {} devs removed, size: {} -> {}",
devList.size(), prevSize, newSize);
}
bool
IOLocker::TryBusyLock(IArrayDevice* dev, StripeId from, StripeId to)
{
StripeLocker* locker = _Find(dev);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::TryBusyLock, no locker exists");
return true;
}
return locker->TryBusyLock(from, to);
}
bool
IOLocker::TryLock(set<IArrayDevice*>& devs, StripeId val)
{
set<StripeLocker*> lockersByGroup;
for (IArrayDevice* d : devs)
{
StripeLocker* locker = _Find(d);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::TryLock, no locker exists");
return true;
}
lockersByGroup.insert(locker);
}
int lockedCnt = 0;
for (auto it = lockersByGroup.begin(); it != lockersByGroup.end(); ++it)
{
bool ret = (*it)->TryLock(val);
if (ret == true)
{
lockedCnt++;
}
else
{
while (lockedCnt > 0)
{
--it;
(*it)->Unlock(val);
lockedCnt--;
}
return false;
}
}
return true;
}
void
IOLocker::Unlock(IArrayDevice* dev, StripeId val)
{
StripeLocker* locker = _Find(dev);
if (locker != nullptr)
{
locker->Unlock(val);
}
else
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unlock, no locker exists");
}
}
void
IOLocker::Unlock(set<IArrayDevice*>& devs, StripeId val)
{
set<StripeLocker*> lockersByGroup;
for (IArrayDevice* d : devs)
{
StripeLocker* locker = _Find(d);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::Unlock, no locker exists");
}
lockersByGroup.insert(locker);
}
for (StripeLocker* locker : lockersByGroup)
{
locker->Unlock(val);
}
}
bool
IOLocker::ResetBusyLock(IArrayDevice* dev)
{
StripeLocker* locker = _Find(dev);
if (locker == nullptr)
{
// TODO(SRM) expect a path that will not be reached
POS_TRACE_WARN(POS_EVENT_ID::LOCKER_DEBUG_MSG, "IOLocker::ResetBusyLock, no locker exists");
return true;
}
return locker->ResetBusyLock();
}
StripeLocker*
IOLocker::_Find(IArrayDevice* dev)
{
auto it = lockers.find(dev);
if (it == lockers.end())
{
return nullptr;
}
return it->second;
}
} // namespace pos
| 29.112745
| 107
| 0.619465
|
poseidonos
|
2c17838f1d68291992228e8ab36c0665aec6ae8b
| 690
|
cpp
|
C++
|
uva/11286.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | 3
|
2018-01-08T02:52:51.000Z
|
2021-03-03T01:08:44.000Z
|
uva/11286.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | null | null | null |
uva/11286.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | 1
|
2020-08-13T18:07:35.000Z
|
2020-08-13T18:07:35.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t, n[6];
char ch[20];
string s;
while(scanf("%d", &t) != EOF && t){
map<string, int> mp;
while(t--){
for(int i = 0; i < 5; scanf("%d", &n[i]), i++);
sort(n, n + 5);
sprintf(ch, "%d%d%d%d%d", n[0], n[1], n[2], n[3], n[4]);
s = ch;
mp[s]++;
}
int mn = 0, m = 0;
for(map<string, int> :: iterator it = mp.begin(); it != mp.end(); it++){
if((*it).second > m){
m = (*it).second;
mn = 0;
}
if((*it).second == m) mn += m;
}
printf("%d\n", mn);
}
return 0;
}
| 23
| 76
| 0.434783
|
cosmicray001
|
2c1d2ce066a00712239431ee98b984e96cd7c364
| 476
|
cpp
|
C++
|
src/RESTAPI_unknownRequestHandler.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
src/RESTAPI_unknownRequestHandler.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
src/RESTAPI_unknownRequestHandler.cpp
|
shimmy568/wlan-cloud-ucentralgw
|
806e24e1e666c31175c059373440ae029d9fff67
|
[
"BSD-3-Clause"
] | null | null | null |
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "RESTAPI_unknownRequestHandler.h"
void RESTAPI_UnknownRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response)
{
if(!IsAuthorized(Request,Response))
return;
BadRequest(Response);
}
| 28
| 129
| 0.754202
|
shimmy568
|
2c1eb109ecfb359f640fce24cc599ef65144777a
| 3,316
|
cpp
|
C++
|
test/unit/misc/bit_reversal.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | null | null | null |
test/unit/misc/bit_reversal.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | null | null | null |
test/unit/misc/bit_reversal.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | null | null | null |
/*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cds_test/ext_gtest.h>
#include <cds/algo/bit_reversal.h>
namespace {
template <typename UInt>
class bit_reversal: public ::testing::Test
{
typedef UInt uint_type;
static std::vector<uint_type> arr_;
static size_t const c_size = 100'000'000;
public:
static void SetUpTestCase()
{
arr_.resize( c_size );
for ( size_t i = 0; i < c_size; ++i )
arr_[i] = static_cast<uint_type>((i << 32) + (~i));
}
static void TearDownTestCase()
{
arr_.resize( 0 );
}
template <typename Algo>
void test()
{
Algo f;
for ( auto i : arr_ ) {
EXPECT_EQ( i, f( f( i )));
}
}
template <typename Algo>
void test_eq()
{
Algo f;
for ( auto i : arr_ ) {
EXPECT_EQ( cds::algo::bit_reversal::swar()( i ), f( i ) ) << "i=" << i;
}
}
};
template <typename UInt> std::vector<UInt> bit_reversal<UInt>::arr_;
typedef bit_reversal<uint32_t> bit_reversal32;
typedef bit_reversal<uint64_t> bit_reversal64;
#define TEST_32BIT( x ) \
TEST_F( bit_reversal32, x ) { test<cds::algo::bit_reversal::x>(); } \
TEST_F( bit_reversal32, x##_eq ) { test_eq<cds::algo::bit_reversal::x>(); }
#define TEST_64BIT( x ) \
TEST_F( bit_reversal64, x ) { test<cds::algo::bit_reversal::x>(); } \
TEST_F( bit_reversal64, x##_eq ) { test_eq<cds::algo::bit_reversal::x>(); }
TEST_32BIT( swar )
TEST_32BIT( lookup )
TEST_32BIT( muldiv )
TEST_64BIT( swar )
TEST_64BIT( lookup )
TEST_64BIT( muldiv )
} // namespace
| 34.185567
| 87
| 0.642039
|
Nemo1369
|
2c24b8af8865154153a12f626942b5190dbabeef
| 4,069
|
hpp
|
C++
|
methods/islet/islet_npx.hpp
|
ambrad/COMPOSE
|
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
|
[
"BSD-3-Clause"
] | 3
|
2018-12-30T20:01:25.000Z
|
2020-07-22T23:44:14.000Z
|
methods/islet/islet_npx.hpp
|
E3SM-Project/COMPOSE
|
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
|
[
"BSD-3-Clause"
] | 8
|
2019-02-06T19:08:31.000Z
|
2020-04-24T03:40:49.000Z
|
methods/islet/islet_npx.hpp
|
ambrad/COMPOSE
|
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
|
[
"BSD-3-Clause"
] | 2
|
2019-01-16T03:58:31.000Z
|
2019-02-06T22:45:43.000Z
|
#ifndef INCLUDE_ISLET_NPX_HPP
#define INCLUDE_ISLET_NPX_HPP
#include "islet_util.hpp"
#include "islet_types.hpp"
#include "islet_tables.hpp"
#include "islet_interpmethod.hpp"
template <typename Scalar>
void eval_lagrange_poly (const Scalar* x_gll, const Int& np, const Scalar& x,
Scalar* const y) {
for (int i = 0; i < np; ++i) {
Scalar f = 1;
for (int j = 0; j < np; ++j)
f *= (i == j) ?
1 :
(x - x_gll[j]) / (x_gll[i] - x_gll[j]);
y[i] = f;
}
}
template <typename Scalar=Real>
struct npx {
static void eval (const Int np, const Scalar& x, Scalar* const v) {
eval_lagrange_poly(islet::get_x_gll(np), np, x, v);
}
};
template <typename Scalar=Real>
struct npxstab : public npx<Scalar> {
template <int np, int nreg>
static void eval (const std::array<int, nreg>& order,
const std::array<int, nreg>& os,
const Scalar& x, Scalar* const v) {
if (x > 0) {
eval<np, nreg>(order, os, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
const auto x_gll = islet::get_x_gll(np);
bool done = false;
for (Int i = 0; i < nreg; ++i)
if (x < x_gll[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(x_gll + os[i], order[i], x, v + os[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(x_gll, np, x, v);
}
static void eval(const Int& np, const Scalar& x, Scalar* const v);
static int ooa_vs_np (const int np) {
if (np == 5) return 2;
return np - 1 - ((np-1)/3);
}
template <int np, int nreg, int alphanp>
static void eval (const std::array<int, nreg>& subnp,
const std::array<int, nreg>& os,
const std::array<Scalar, nreg*alphanp>& alphac,
const Scalar& x, Scalar* const v) {
if (x > 0) {
eval<np, nreg, alphanp>(subnp, os, alphac, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
const auto x_gll = islet::get_x_gll(np);
bool done = false;
for (int i = 0; i < nreg; ++i)
if (x < x_gll[i+1]) {
eval_lagrange_poly(x_gll, np, x, v);
if (subnp[i] < np) {
Real w[12] = {0};
eval_lagrange_poly(x_gll + os[i], subnp[i], x, w + os[i]);
Real alpha = 0;
if (alphanp == 1)
alpha = alphac[i];
else {
assert(alphanp <= 3);
const auto alpha_r_gll = islet::get_x_gll(alphanp);
const auto r = (x - x_gll[i]) / (x_gll[i+1] - x_gll[i]);
Real a[3];
eval_lagrange_poly(alpha_r_gll, alphanp, r, a);
for (int j = 0; j < alphanp; ++j)
alpha += alphac[alphanp*i + j] * a[j];
}
for (int j = 0; j < np; ++j)
v[j] = alpha*v[j] + (1 - alpha)*w[j];
}
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(x_gll, np, x, v);
}
};
struct InterpMethod {
typedef std::shared_ptr<InterpMethod> Ptr;
enum Type { notype, npx, npxstab, user };
Int np;
Type type;
std::shared_ptr<UserInterpMethod> uim;
static Type convert (const std::string& s) {
if (s == "npx") return npx;
if (s == "npxstab") return npxstab;
if (s == "user") return user;
throw std::runtime_error(std::string("Not an InterpMethod::Type: ") + s);
}
static std::string convert (const Type& t) {
if (t == npx) return "npx";
if (t == npxstab) return "npxstab";
if (t == user) return "user";
throw std::runtime_error("Not an InterpMethod::Type.");
}
InterpMethod () : np(-1), type(notype) {}
InterpMethod (Int inp, Type itype) : np(inp), type(itype) {}
InterpMethod (const std::shared_ptr<UserInterpMethod>& iuim)
: np(iuim->get_np()), type(user), uim(iuim) {}
const Real* get_xnodes() const {
return uim ? uim->get_xnodes() : islet::get_x_gll(np);
};
};
void op_eval(const InterpMethod& im, const Real a_src, Real* v);
#endif
| 29.485507
| 77
| 0.539936
|
ambrad
|
2c2772b33e1e11c89aba7847b2966eb1abf03591
| 2,085
|
cpp
|
C++
|
Codeforces/Goodbye 2020/1466E.cpp
|
ApocalypseMac/CP
|
b2db9aa5392a362dc0d979411788267ed9a5ff1d
|
[
"MIT"
] | null | null | null |
Codeforces/Goodbye 2020/1466E.cpp
|
ApocalypseMac/CP
|
b2db9aa5392a362dc0d979411788267ed9a5ff1d
|
[
"MIT"
] | null | null | null |
Codeforces/Goodbye 2020/1466E.cpp
|
ApocalypseMac/CP
|
b2db9aa5392a362dc0d979411788267ed9a5ff1d
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
typedef long long ll;
const int maxn = 500005;
const ll MOD = 1e9 + 7;
ll x[maxn];
int bitcnt[63];
int n, d, dm;
ll tmp, res, l, r;
ll m[63];
int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
for (int i = 0; i < 63; ++i){
m[i] = (1LL << i) % MOD;
}
int T;
cin >> T;
for (; T > 0; --T){
// int n;
cin >> n;
// ll x[n];
memset(bitcnt, 0, sizeof(bitcnt));
// ll bitcnt[63] = {0LL};
// int d;
// int dm = 0;
dm = 0;
// ll tmp;
for (int i = 0; i < n; ++i){
d = 0;
cin >> x[i];
tmp = x[i];
while (tmp){
if (tmp & 1){
++bitcnt[d];
}
++d;
tmp >>= 1;
}
dm = max(dm, d + 1);
}
// ll res = 0LL;
res = 0LL;
// for (int j = 0; j < 62; ++j){
// cout << bitcnt[j] << " ";
// }
// bool isone[dm] = {0};
for (int i = 0; i < n; ++i){
l = 0LL; r = 0LL;
// cout << " " << x[i] << " ";
tmp = x[i];
// memset(isone, 0, sizeof(isone));
// d = 0;
// while (tmp){
// if (tmp & 1){
// isone[d] = true;
// }
// ++d;
// tmp >>= 1;
// }
for (int j = 0; j < dm; ++j){
if (tmp & 1){
l += bitcnt[j] * m[j];
r += n * m[j];
}
else{
r += bitcnt[j] * m[j];
}
tmp >>= 1;
l %= MOD;
r %= MOD;
}
res += l * r;
res %= MOD;
// cout << " " << l << " " << r << " " << res << endl;
}
cout << res << endl;
}
return 0;
}
| 26.0625
| 76
| 0.302638
|
ApocalypseMac
|
2c2791889d601ee8bd542f686cdeb888398ab3c3
| 19,164
|
cpp
|
C++
|
src/SNC-Meister/SNC-Meister.cpp
|
timmyzhu/SNC-Meister
|
7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd
|
[
"MIT"
] | 5
|
2016-09-28T19:45:01.000Z
|
2020-04-19T08:01:28.000Z
|
src/SNC-Meister/SNC-Meister.cpp
|
timmyzhu/SNC-Meister
|
7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd
|
[
"MIT"
] | null | null | null |
src/SNC-Meister/SNC-Meister.cpp
|
timmyzhu/SNC-Meister
|
7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd
|
[
"MIT"
] | 4
|
2017-02-12T05:59:25.000Z
|
2020-06-15T08:18:49.000Z
|
// SNC-Meister.cpp - SNC-Meister admission control server.
// Performs admission control for a network based on Stochastic Network Calculus (SNC) using SNC-Library.
// When a set of tenants (a.k.a. clients) seeks admission, their latency is calculated using SNC and compared against their SLO.
// Also, other clients that are affected by the new clients are checked to see if they meet their SLOs.
// If the new clients and affected clients meet their SLOs, then the new clients are admitted.
// If admitted and enforcerAddr/dstAddr/srcAddr are set in a client's flow (see "addrPrefix" option in SNC-ConfigGen), then NetEnforcer will be updated with its network priority.
// Priority is determined with the BySLO policy (i.e., with the tightest SLO getting the highest priority).
//
// Copyright (c) 2016 Timothy Zhu.
// Licensed under the MIT License. See LICENSE file for details.
//
#include <cassert>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <sys/socket.h>
#include <netdb.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include "../prot/SNC_Meister_prot.h"
#include "../prot/NetEnforcer_prot.h"
#include "../json/json.h"
#include "../SNC-Library/NC.hpp"
#include "../SNC-Library/SNC.hpp"
#include "../SNC-Library/priorityAlgoBySLO.hpp"
using namespace std;
// Global network calculus calculator
NC* nc;
// Global storage for clientInfos
map<ClientId, Json::Value> clientInfoStore;
// Convert a string internet address to an IP address
unsigned long addrInfo(string addr)
{
unsigned long s_addr = 0;
struct addrinfo* result;
int err = getaddrinfo(addr.c_str(), NULL, NULL, &result);
if ((err != 0) || (result == NULL)) {
cerr << "Error in getaddrinfo: " << err << endl;
} else {
for (struct addrinfo* res = result; res != NULL; res = res->ai_next) {
if (result->ai_addr->sa_family == AF_INET) {
s_addr = ((struct sockaddr_in*)result->ai_addr)->sin_addr.s_addr;
break;
}
}
freeaddrinfo(result);
}
return s_addr;
}
// Send RPC to NetEnforcer to update client
void updateClient(string enforcerAddr, string dstAddr, string srcAddr, unsigned int priority)
{
// Connect to enforcer
CLIENT* cl;
if ((cl = clnt_create(enforcerAddr.c_str(), NET_ENFORCER_PROGRAM, NET_ENFORCER_V1, "tcp")) == NULL) {
clnt_pcreateerror(enforcerAddr.c_str());
return;
}
// Call RPC
NetClientUpdate arg;
arg.client.s_dstAddr = addrInfo(dstAddr);
arg.client.s_srcAddr = addrInfo(srcAddr);
arg.priority = priority;
NetUpdateClientsArgs args = {1, &arg};
if (net_enforcer_update_clients_1(args, cl) == NULL) {
clnt_perror(cl, "Failed network RPC");
}
// Destroy client
clnt_destroy(cl);
}
// Send RPC to NetEnforcer to remove client
void removeClient(string enforcerAddr, string dstAddr, string srcAddr)
{
// Connect to enforcer
CLIENT* cl;
if ((cl = clnt_create(enforcerAddr.c_str(), NET_ENFORCER_PROGRAM, NET_ENFORCER_V1, "tcp")) == NULL) {
clnt_pcreateerror(enforcerAddr.c_str());
return;
}
// Call RPC
NetClient arg;
arg.s_dstAddr = addrInfo(dstAddr);
arg.s_srcAddr = addrInfo(srcAddr);
NetRemoveClientsArgs args = {1, &arg};
if (net_enforcer_remove_clients_1(args, cl) == NULL) {
clnt_perror(cl, "Failed network RPC");
}
// Destroy client
clnt_destroy(cl);
}
// Check the JSON flowInfo objects.
// Returns error for invalid arguments.
SNCStatus checkFlowInfo(set<string>& flowNames, const Json::Value& flowInfo)
{
// Check name
if (!flowInfo.isMember("name")) {
return SNC_ERR_MISSING_ARGUMENT;
}
string name = flowInfo["name"].asString();
if (nc->getFlowIdByName(name) != InvalidFlowId) {
return SNC_ERR_FLOW_NAME_IN_USE;
}
if (flowNames.find(name) != flowNames.end()) {
return SNC_ERR_FLOW_NAME_IN_USE;
}
flowNames.insert(name);
// Check queues
if (!flowInfo.isMember("queues")) {
return SNC_ERR_MISSING_ARGUMENT;
}
const Json::Value& flowQueues = flowInfo["queues"];
if (!flowQueues.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
for (unsigned int index = 0; index < flowQueues.size(); index++) {
string queueName = flowQueues[index].asString();
if (nc->getQueueIdByName(queueName) == InvalidQueueId) {
return SNC_ERR_QUEUE_NAME_NONEXISTENT;
}
}
// Check arrivalInfo
if (!flowInfo.isMember("arrivalInfo")) {
return SNC_ERR_MISSING_ARGUMENT;
}
return SNC_SUCCESS;
}
// Check the JSON clientInfo objects.
// Returns error for invalid arguments.
SNCStatus checkClientInfo(set<string>& clientNames, set<string>& flowNames, const Json::Value& clientInfo)
{
// Check name
if (!clientInfo.isMember("name")) {
return SNC_ERR_MISSING_ARGUMENT;
}
string name = clientInfo["name"].asString();
if (nc->getClientIdByName(name) != InvalidClientId) {
return SNC_ERR_CLIENT_NAME_IN_USE;
}
if (clientNames.find(name) != clientNames.end()) {
return SNC_ERR_CLIENT_NAME_IN_USE;
}
clientNames.insert(name);
// Check SLO
if (!clientInfo.isMember("SLO")) {
return SNC_ERR_MISSING_ARGUMENT;
}
double SLO = clientInfo["SLO"].asDouble();
if (SLO <= 0) {
return SNC_ERR_INVALID_ARGUMENT;
}
// Check SLOpercentile
if (clientInfo.isMember("SLOpercentile")) {
double SLOpercentile = clientInfo["SLOpercentile"].asDouble();
if (!((0 < SLOpercentile) && (SLOpercentile < 100))) {
return SNC_ERR_INVALID_ARGUMENT;
}
}
// Check client's flows
if (!clientInfo.isMember("flows")) {
return SNC_ERR_MISSING_ARGUMENT;
}
const Json::Value& clientFlows = clientInfo["flows"];
if (!clientFlows.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
SNCStatus status = checkFlowInfo(flowNames, clientFlows[flowIndex]);
if (status != SNC_SUCCESS) {
return status;
}
}
return SNC_SUCCESS;
}
// Check list of JSON clientInfo objects.
// Returns error for invalid arguments.
SNCStatus checkClientInfos(const Json::Value& clientInfos)
{
// Check clientInfos is an array
if (!clientInfos.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
set<string> clientNames; // ensure no duplicate names
set<string> flowNames; // ensure no duplicate names
for (unsigned int i = 0; i < clientInfos.size(); i++) {
SNCStatus status = checkClientInfo(clientNames, flowNames, clientInfos[i]);
if (status != SNC_SUCCESS) {
return status;
}
}
return SNC_SUCCESS;
}
// Adds dependencies between clients based on the RPC arguments.
// Returns error for invalid arguments.
SNCStatus addDependencies(const Json::Value& clientInfo)
{
if (clientInfo.isMember("dependencies")) {
const Json::Value& dependencies = clientInfo["dependencies"];
if (!dependencies.isArray()) {
return SNC_ERR_INVALID_ARGUMENT;
}
ClientId clientId = nc->getClientIdByName(clientInfo["name"].asString());
assert(clientId != InvalidClientId);
for (unsigned int i = 0; i < dependencies.size(); i++) {
ClientId dependency = nc->getClientIdByName(dependencies[i].asString());
if (dependency == InvalidClientId) {
return SNC_ERR_CLIENT_NAME_NONEXISTENT;
}
nc->addDependency(clientId, dependency);
}
}
return SNC_SUCCESS;
}
// FlowIndex less than function
bool operator< (const FlowIndex& fi1, const FlowIndex& fi2)
{
if (fi1.flowId == fi2.flowId) {
return (fi1.index < fi2.index);
}
return (fi1.flowId < fi2.flowId);
}
// Mark flows affected at a priority level starting from a flow at a given index.
void markAffectedFlows(set<FlowIndex>& affectedFlows, const FlowIndex& fi, unsigned int priority)
{
const Flow* f = nc->getFlow(fi.flowId);
// If f is higher priority, it is unaffected
if (f->priority < priority) {
return;
}
// If we've already marked flow at given index, stop
if (affectedFlows.find(fi) != affectedFlows.end()) {
return;
}
affectedFlows.insert(fi);
// Loop through queues affected by flow starting at index
for (unsigned int index = fi.index; index < f->queueIds.size(); index++) {
const Queue* q = nc->getQueue(f->queueIds[index]);
// Try marking other flows sharing queue
for (vector<FlowIndex>::const_iterator itFi = q->flows.begin(); itFi != q->flows.end(); itFi++) {
markAffectedFlows(affectedFlows, *itFi, f->priority);
}
}
}
// AddClients RPC - performs admission control check on a set of clients and adds clients to system if admitted.
SNCAddClientsRes* snc_meister_add_clients_svc(SNCAddClientsArgs* argp, struct svc_req* rqstp)
{
static SNCAddClientsRes result;
// Initialize result
result.admitted = true;
result.status = SNC_SUCCESS;
// Parse input
Json::Reader reader;
Json::Value clientInfos;
string clientInfosStr(argp->clientInfos);
if (!reader.parse(clientInfosStr, clientInfos)) {
result.status = SNC_ERR_INVALID_ARGUMENT;
result.admitted = false;
return &result;
}
// Check parameters
result.status = checkClientInfos(clientInfos);
if (result.status != SNC_SUCCESS) {
result.admitted = false;
return &result;
}
// Add clients
set<ClientId> clientIds;
for (unsigned int i = 0; i < clientInfos.size(); i++) {
const Json::Value& clientInfo = clientInfos[i];
ClientId clientId = nc->addClient(clientInfo);
clientIds.insert(clientId);
clientInfoStore[clientId] = clientInfo;
}
// Add dependencies
for (unsigned int i = 0; i < clientInfos.size(); i++) {
result.status = addDependencies(clientInfos[i]);
if (result.status != SNC_SUCCESS) {
result.admitted = false;
break;
}
}
if (result.status == SNC_SUCCESS) {
// Configure priorities
configurePrioritiesBySLO(nc);
// Check latency of added clients
set<FlowIndex> affectedFlows;
for (set<ClientId>::const_iterator it = clientIds.begin(); it != clientIds.end(); it++) {
ClientId clientId = *it;
nc->calcClientLatency(clientId);
const Client* c = nc->getClient(clientId);
if (c->latency > c->SLO) {
result.admitted = false;
break;
}
// Add affected flows
for (vector<FlowId>::const_iterator itF = c->flowIds.begin(); itF != c->flowIds.end(); itF++) {
FlowIndex fi;
fi.flowId = *itF;
fi.index = 0;
markAffectedFlows(affectedFlows, fi, 0);
}
}
if (result.admitted) {
// Get clientIds of affected flows
set<ClientId> affectedClientIds;
for (set<FlowIndex>::const_iterator it = affectedFlows.begin(); it != affectedFlows.end(); it++) {
const Flow* f = nc->getFlow(it->flowId);
affectedClientIds.insert(f->clientId);
}
// Check latency of other affected clients
for (set<ClientId>::const_iterator it = affectedClientIds.begin(); it != affectedClientIds.end(); it++) {
ClientId clientId = *it;
if (clientIds.find(clientId) == clientIds.end()) {
nc->calcClientLatency(clientId);
const Client* c = nc->getClient(clientId);
if (c->latency > c->SLO) {
result.admitted = false;
break;
}
}
}
}
}
if (result.admitted) {
// Send RPC to NetEnforcer to update client
for (unsigned int i = 0; i < clientInfos.size(); i++) {
const Json::Value& clientInfo = clientInfos[i];
const Json::Value& clientFlows = clientInfo["flows"];
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
const Json::Value& flowInfo = clientFlows[flowIndex];
if (flowInfo.isMember("enforcerAddr") && flowInfo.isMember("dstAddr") && flowInfo.isMember("srcAddr")) {
FlowId flowId = nc->getFlowIdByName(flowInfo["name"].asString());
const Flow* f = nc->getFlow(flowId);
updateClient(flowInfo["enforcerAddr"].asString(), flowInfo["dstAddr"].asString(), flowInfo["srcAddr"].asString(), f->priority);
}
}
}
} else {
// Delete clients
for (set<ClientId>::const_iterator it = clientIds.begin(); it != clientIds.end(); it++) {
ClientId clientId = *it;
clientInfoStore.erase(clientId);
nc->delClient(clientId);
}
}
return &result;
}
// DelClient RPC - delete a client from system.
SNCDelClientRes* snc_meister_del_client_svc(SNCDelClientArgs* argp, struct svc_req* rqstp)
{
static SNCDelClientRes result;
string name(argp->name);
ClientId clientId = nc->getClientIdByName(name);
// Check that client exists
if (clientId == InvalidClientId) {
result.status = SNC_ERR_CLIENT_NAME_NONEXISTENT;
return &result;
}
// Send RPC to NetEnforcer to remove client
assert(clientInfoStore.find(clientId) != clientInfoStore.end());
const Json::Value& clientInfo = clientInfoStore[clientId];
const Json::Value& clientFlows = clientInfo["flows"];
for (unsigned int flowIndex = 0; flowIndex < clientFlows.size(); flowIndex++) {
const Json::Value& flowInfo = clientFlows[flowIndex];
if (flowInfo.isMember("enforcerAddr") && flowInfo.isMember("dstAddr") && flowInfo.isMember("srcAddr")) {
removeClient(flowInfo["enforcerAddr"].asString(), flowInfo["dstAddr"].asString(), flowInfo["srcAddr"].asString());
}
}
// Delete client
clientInfoStore.erase(clientId);
nc->delClient(clientId);
result.status = SNC_SUCCESS;
return &result;
}
// AddQueue RPC - add a queue to system.
SNCAddQueueRes* snc_meister_add_queue_svc(SNCAddQueueArgs* argp, struct svc_req* rqstp)
{
static SNCAddQueueRes result;
// Parse input
Json::Reader reader;
Json::Value queueInfo;
string queueInfoStr(argp->queueInfo);
if (!reader.parse(queueInfoStr, queueInfo)) {
result.status = SNC_ERR_INVALID_ARGUMENT;
return &result;
}
// Check for valid name
if (!queueInfo.isMember("name")) {
result.status = SNC_ERR_MISSING_ARGUMENT;
return &result;
}
if (nc->getQueueIdByName(queueInfo["name"].asString()) != InvalidQueueId) {
result.status = SNC_ERR_QUEUE_NAME_IN_USE;
return &result;
}
// Check for valid bandwidth
if (!queueInfo.isMember("bandwidth")) {
result.status = SNC_ERR_MISSING_ARGUMENT;
return &result;
}
if (queueInfo["bandwidth"].asDouble() <= 0) {
result.status = SNC_ERR_INVALID_ARGUMENT;
return &result;
}
// Add queue
nc->addQueue(queueInfo);
result.status = SNC_SUCCESS;
return &result;
}
// DelQueue RPC - delete a queue from system.
SNCDelQueueRes* snc_meister_del_queue_svc(SNCDelQueueArgs* argp, struct svc_req* rqstp)
{
static SNCDelQueueRes result;
string name(argp->name);
QueueId queueId = nc->getQueueIdByName(name);
// Check that queue exists
if (queueId == InvalidQueueId) {
result.status = SNC_ERR_QUEUE_NAME_NONEXISTENT;
return &result;
}
// Check that queue is empty
const Queue* q = nc->getQueue(queueId);
assert(q != NULL);
if (!q->flows.empty()) {
result.status = SNC_ERR_QUEUE_HAS_ACTIVE_FLOWS;
return &result;
}
// Delete queue
nc->delQueue(queueId);
result.status = SNC_SUCCESS;
return &result;
}
// Main RPC handler
void snc_meister_program(struct svc_req* rqstp, register SVCXPRT* transp)
{
union {
SNCAddClientsArgs snc_meister_add_clients_arg;
SNCDelClientArgs snc_meister_del_client_arg;
SNCAddQueueArgs snc_meister_add_queue_arg;
SNCDelQueueArgs snc_meister_del_queue_arg;
} argument;
char* result;
xdrproc_t _xdr_argument, _xdr_result;
char* (*local)(char*, struct svc_req*);
switch (rqstp->rq_proc) {
case SNC_MEISTER_NULL:
svc_sendreply(transp, (xdrproc_t)xdr_void, (caddr_t)NULL);
return;
case SNC_MEISTER_ADD_CLIENTS:
_xdr_argument = (xdrproc_t)xdr_SNCAddClientsArgs;
_xdr_result = (xdrproc_t)xdr_SNCAddClientsRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_add_clients_svc;
break;
case SNC_MEISTER_DEL_CLIENT:
_xdr_argument = (xdrproc_t)xdr_SNCDelClientArgs;
_xdr_result = (xdrproc_t)xdr_SNCDelClientRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_del_client_svc;
break;
case SNC_MEISTER_ADD_QUEUE:
_xdr_argument = (xdrproc_t)xdr_SNCAddQueueArgs;
_xdr_result = (xdrproc_t)xdr_SNCAddQueueRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_add_queue_svc;
break;
case SNC_MEISTER_DEL_QUEUE:
_xdr_argument = (xdrproc_t)xdr_SNCDelQueueArgs;
_xdr_result = (xdrproc_t)xdr_SNCDelQueueRes;
local = (char* (*)(char*, struct svc_req*))snc_meister_del_queue_svc;
break;
default:
svcerr_noproc(transp);
return;
}
memset((char*)&argument, 0, sizeof(argument));
if (!svc_getargs(transp, (xdrproc_t)_xdr_argument, (caddr_t)&argument)) {
svcerr_decode(transp);
return;
}
result = (*local)((char*)&argument, rqstp);
if (result != NULL && !svc_sendreply(transp, (xdrproc_t)_xdr_result, result)) {
svcerr_systemerr(transp);
}
if (!svc_freeargs(transp, (xdrproc_t)_xdr_argument, (caddr_t)&argument)) {
cerr << "Unable to free arguments" << endl;
}
}
int main(int argc, char** argv)
{
// Create NC
nc = new SNC();
// Unregister SNC-Meister RPC handlers
pmap_unset(SNC_MEISTER_PROGRAM, SNC_MEISTER_V1);
// Replace tcp RPC handlers
register SVCXPRT *transp;
transp = svctcp_create(RPC_ANYSOCK, 0, 0);
if (transp == NULL) {
cerr << "Failed to create tcp service" << endl;
delete nc;
return 1;
}
if (!svc_register(transp, SNC_MEISTER_PROGRAM, SNC_MEISTER_V1, snc_meister_program, IPPROTO_TCP)) {
cerr << "Failed to register tcp SNC-Meister" << endl;
delete nc;
return 1;
}
// Run proxy
svc_run();
cerr << "svc_run returned" << endl;
delete nc;
return 1;
}
| 35.554731
| 178
| 0.632749
|
timmyzhu
|
2c287d1d11f64b02c40201ad39367c8cf8ae089b
| 7,015
|
cc
|
C++
|
onnxruntime/core/optimizer/conv_bn_fusion.cc
|
csteegz/onnxruntime
|
a36810471b346ec862ac6e4de7f877653f49525e
|
[
"MIT"
] | 1
|
2020-07-12T15:23:49.000Z
|
2020-07-12T15:23:49.000Z
|
onnxruntime/core/optimizer/conv_bn_fusion.cc
|
ajinkya933/onnxruntime
|
0e799a03f2a99da6a1b87a2cd37facb420c482aa
|
[
"MIT"
] | null | null | null |
onnxruntime/core/optimizer/conv_bn_fusion.cc
|
ajinkya933/onnxruntime
|
0e799a03f2a99da6a1b87a2cd37facb420c482aa
|
[
"MIT"
] | 1
|
2020-09-09T06:55:51.000Z
|
2020-09-09T06:55:51.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/graph_utils.h"
#include "core/optimizer/initializer.h"
#include "core/optimizer/conv_bn_fusion.h"
using namespace ONNX_NAMESPACE;
using namespace ::onnxruntime::common;
namespace onnxruntime {
Status ConvBNFusion::Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect) const {
auto& conv_node = node;
const Node& bn_node = *conv_node.OutputNodesBegin();
// Get value of attribute epsilon
const onnxruntime::NodeAttributes& attributes = bn_node.GetAttributes();
const ONNX_NAMESPACE::AttributeProto* attr = &(attributes.find("epsilon")->second);
if (attr == nullptr || attr->type() != AttributeProto_AttributeType_FLOAT) {
return Status::OK();
}
float epsilon = static_cast<float>(attr->f());
// Get initializers of BatchNormalization
const auto& bn_inputs = bn_node.InputDefs();
const auto* bn_scale_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[1]->Name());
ORT_ENFORCE(bn_scale_tensor_proto);
const auto* bn_B_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[2]->Name());
ORT_ENFORCE(bn_B_tensor_proto);
const auto* bn_mean_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[3]->Name());
ORT_ENFORCE(bn_mean_tensor_proto);
const auto* bn_var_tensor_proto = graph_utils::GetConstantInitializer(graph, bn_inputs[4]->Name());
ORT_ENFORCE(bn_var_tensor_proto);
const auto& conv_inputs = conv_node.InputDefs();
const auto* conv_W_tensor_proto = graph_utils::GetConstantInitializer(graph, conv_inputs[1]->Name());
ORT_ENFORCE(conv_W_tensor_proto);
// Currently, fusion is only supported for float or double data type.
if (!Initializer::IsSupportedDataType(bn_scale_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_B_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_mean_tensor_proto) ||
!Initializer::IsSupportedDataType(bn_var_tensor_proto) ||
!Initializer::IsSupportedDataType(conv_W_tensor_proto) ||
bn_scale_tensor_proto->dims_size() != 1 ||
bn_B_tensor_proto->dims_size() != 1 ||
bn_mean_tensor_proto->dims_size() != 1 ||
bn_var_tensor_proto->dims_size() != 1 ||
bn_scale_tensor_proto->dims(0) != bn_B_tensor_proto->dims(0) ||
bn_B_tensor_proto->dims(0) != bn_mean_tensor_proto->dims(0) ||
bn_mean_tensor_proto->dims(0) != bn_var_tensor_proto->dims(0) ||
bn_scale_tensor_proto->data_type() != bn_B_tensor_proto->data_type() ||
bn_B_tensor_proto->data_type() != bn_mean_tensor_proto->data_type() ||
bn_mean_tensor_proto->data_type() != bn_var_tensor_proto->data_type() ||
conv_W_tensor_proto->data_type() != bn_scale_tensor_proto->data_type() ||
!(conv_W_tensor_proto->dims_size() > 2 && conv_W_tensor_proto->dims(0) == bn_scale_tensor_proto->dims(0))) {
return Status::OK();
}
auto bn_scale = onnxruntime::make_unique<Initializer>(bn_scale_tensor_proto);
auto bn_B = onnxruntime::make_unique<Initializer>(bn_B_tensor_proto);
auto bn_mean = onnxruntime::make_unique<Initializer>(bn_mean_tensor_proto);
auto bn_var = onnxruntime::make_unique<Initializer>(bn_var_tensor_proto);
auto conv_W = onnxruntime::make_unique<Initializer>(conv_W_tensor_proto);
std::unique_ptr<Initializer> conv_B = nullptr;
const ONNX_NAMESPACE::TensorProto* conv_B_tensor_proto = nullptr;
if (conv_inputs.size() == 3) {
conv_B_tensor_proto = graph_utils::GetConstantInitializer(graph, conv_inputs[2]->Name());
ORT_ENFORCE(conv_B_tensor_proto);
if (!Initializer::IsSupportedDataType(conv_B_tensor_proto) ||
conv_B_tensor_proto->dims_size() != 1 ||
conv_B_tensor_proto->dims(0) != bn_B_tensor_proto->dims(0) ||
conv_B_tensor_proto->data_type() != bn_B_tensor_proto->data_type()) {
return Status::OK();
}
conv_B = onnxruntime::make_unique<Initializer>(conv_B_tensor_proto);
}
// Calculate new value of initializers of conv node
bn_var->add(epsilon);
bn_var->sqrt();
bn_scale->div(*bn_var);
conv_W->scale_by_axis(*bn_scale, 1);
if (conv_inputs.size() == 3) {
conv_B->sub(*bn_mean);
conv_B->mul(*bn_scale);
conv_B->add(*bn_B);
} else {
bn_mean->mul(*bn_scale);
bn_B->sub(*bn_mean);
}
// Create new initializers of conv
ONNX_NAMESPACE::TensorProto new_conv_W_tensor_proto(*conv_W_tensor_proto);
conv_W->ToProto(&new_conv_W_tensor_proto);
ONNX_NAMESPACE::TensorProto new_conv_B_tensor_proto;
NodeArg* bn_B_node_arg = nullptr;
if (conv_inputs.size() == 3) {
conv_B->ToProto(&new_conv_B_tensor_proto);
} else {
bn_B->ToProto(&new_conv_B_tensor_proto);
bn_B_node_arg = graph.GetNodeArg(bn_B_tensor_proto->name());
if (bn_B_node_arg == nullptr) {
return Status::OK();
}
}
// Replace initializers of conv node
graph_utils::ReplaceInitializer(graph, conv_W_tensor_proto->name(), new_conv_W_tensor_proto);
if (conv_inputs.size() == 3) {
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 6011) // Not deferencing null pointer. conv_B_tensor_proto is set on line 93
#endif
graph_utils::ReplaceInitializer(graph, conv_B_tensor_proto->name(), new_conv_B_tensor_proto);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} else {
graph_utils::ReplaceInitializer(graph, bn_B_tensor_proto->name(), new_conv_B_tensor_proto);
conv_node.MutableInputDefs().push_back(bn_B_node_arg);
conv_node.MutableInputArgsCount()[2] = 1;
}
// Remove BN node.
auto* bn_node_to_remove = graph.GetNode(bn_node.Index());
if (graph_utils::RemoveNode(graph, *bn_node_to_remove)) {
rule_effect = RewriteRuleEffect::kModifiedRestOfGraph;
}
return Status::OK();
}
bool ConvBNFusion::SatisfyCondition(const Graph& graph, const Node& node) const {
if (!graph_utils::IsSupportedOptypeVersionAndDomain(node, "Conv", {1, 11}) ||
node.GetOutputEdgesCount() != 1) {
return false;
}
const auto& next_node = *node.OutputNodesBegin();
if (!graph_utils::IsSupportedOptypeVersionAndDomain(next_node, "BatchNormalization", {7, 9}) ||
next_node.GetInputEdgesCount() != 1 || graph.IsNodeOutputsInGraphOutputs(next_node) ||
// Make sure the two nodes do not span execution providers.
next_node.GetExecutionProviderType() != node.GetExecutionProviderType()) {
return false;
}
// Check that the appropriate inputs to the Conv and BN nodes are constants.
if (!graph_utils::NodeArgIsConstant(graph, *node.InputDefs()[1]) ||
(node.InputDefs().size() == 3 && !graph_utils::NodeArgIsConstant(graph, *node.InputDefs()[2])) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[1]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[2]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[3]) ||
!graph_utils::NodeArgIsConstant(graph, *next_node.InputDefs()[4])) {
return false;
}
return true;
}
} // namespace onnxruntime
| 41.023392
| 114
| 0.728154
|
csteegz
|
2c2e80972f9620a4a4cdcc2f888ae94e800545a3
| 1,530
|
cpp
|
C++
|
myoddtest/os/testipcdata_wstring.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 18
|
2016-03-04T15:44:24.000Z
|
2021-12-31T11:06:25.000Z
|
myoddtest/os/testipcdata_wstring.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 49
|
2016-02-29T17:59:52.000Z
|
2019-05-05T04:59:26.000Z
|
myoddtest/os/testipcdata_wstring.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 2
|
2016-07-30T10:17:12.000Z
|
2016-08-11T20:31:46.000Z
|
#include "os\ipcdata.h"
#include "..\testcommon.h"
#include <gtest/gtest.h>
const struct test_wstring
{
std::wstring uuid;
typedef std::vector<std::wstring> VALUE_TYPE;
VALUE_TYPE values;
};
struct MyoddOsWStringTest : testing::Test, testing::WithParamInterface<test_wstring>
{
myodd::os::IpcData* ipc;
MyoddOsWStringTest() : ipc(nullptr)
{
ipc = new myodd::os::IpcData(GetParam().uuid);
auto values = GetParam().values;
for (auto it = values.begin(); it != values.end(); ++it)
{
ipc->Add(*it);
}
}
~MyoddOsWStringTest()
{
delete ipc;
}
};
TEST_P(MyoddOsWStringTest, CheckWStringValues)
{
auto param = GetParam();
ASSERT_EQ(param.uuid, ipc->GetGuid());
auto values = GetParam().values;
unsigned int index = 0;
ASSERT_EQ(values.size(), ipc->GetNumArguments());
for (auto it = values.begin(); it != values.end(); ++it)
{
ASSERT_EQ(*it, ipc->Get<std::wstring>(index));
ASSERT_TRUE(ipc->IsString(index));
index++;
}
}
INSTANTIATE_TEST_CASE_P(Default_wstring, MyoddOsWStringTest,
testing::Values(
test_wstring{ Uuid(),{ L"" } },
test_wstring{ Uuid(),{ L"Hello world" } },
test_wstring{ Uuid(),{ L" " } },
test_wstring{ Uuid(),{ L" \n \t " } },
test_wstring{ Uuid(),{ L"\0" } }
));
INSTANTIATE_TEST_CASE_P(Multiple_stringValues, MyoddOsWStringTest,
testing::Values(
test_wstring{ Uuid(),{ L"", L" ", L"Hello", L"!@#$%^&*(" } },
test_wstring{ Uuid(),{ L"12345", L" ", L"Hello", L"!@#$%^&*(" } }
));
| 24.285714
| 84
| 0.615686
|
FFMG
|
2c2f0b90f898c860a18f98181ff9042b8d79f81f
| 9,794
|
cpp
|
C++
|
ic.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 46
|
2020-01-08T16:38:46.000Z
|
2022-03-30T21:08:07.000Z
|
ic.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 2
|
2020-03-28T08:26:29.000Z
|
2020-08-06T10:52:57.000Z
|
ic.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 9
|
2020-03-13T20:53:02.000Z
|
2021-08-31T08:50:20.000Z
|
//
// Created by ashcon on 10/5/19.
//
#include "ic.h"
#include "debug.h"
//#define START_IN_DIAG_MODE
/**
* Sets the refresh rate for scrolling text. If text is static (8 chars),
* refresh rate is locked to every 2 seconds
*
* @param rate Desired rate to scroll across text
*/
void IC_DISPLAY::setRefreshRate(int rate) {
this->scrollRefreshRate = rate;
// If text is shorter than MAX_STR_LENGTH, then leave the refresh rate as static interval
if (currText.length() > MAX_STR_LENGTH) {
this->currentRefreshRate = this->scrollRefreshRate;
} else {
this->currentRefreshRate = this->staticRefreshRate;
}
}
/**
* Static value to hold the current page displayed on the IC display
*/
IC_DISPLAY::clusterPage IC_DISPLAY::currentPage = Audio;
IC_DISPLAY::IC_DISPLAY(CanbusComm *c) {
this->diagData = "DIAG MODE";
#ifdef START_IN_DIAG_MODE
this->inDiagMode = true;
#else
this->inDiagMode = false;
#endif
this->sendFirst = false;
this->c = c;
this->staticRefreshRate = 1000;
this->scrollRefreshRate = 150;
this->currText = " ";
this->setBodyText("BT = NA!", true);
this->lastTime = millis();
this->diag = new DIAG_DISPLAY(this->c);
this->diagScreen = 0;
}
/**
* Displays the 3 character header text on the IC page
* @param text Chars to display as the header
*/
void IC_DISPLAY::sendHeader(char header[]) {
String msg = resize(header, 4, 8);
curr_frame.can_id = IC_SEND_PID;
curr_frame.can_dlc = 0x08;
uint8_t checkSumBit = calculateBodyCheckSum(header);
uint8_t buffer[14] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
buffer[0] = msg.length() + 5;
buffer[1] = msg.length() - 1;
buffer[2] = 0x29;
buffer[3] = 0x00;
for (int i = 0; i < msg.length(); i++) {
buffer[i+4] = msg[i];
}
buffer[msg.length()+4] = 0x00;
buffer[msg.length()+5] = checkSumBit;
curr_frame.data[0] = 0x10;
for (int i = 1; i < 7; i++) {
curr_frame.data[i+1] = buffer[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
curr_frame.data[0] = 0x21;
for (int i = 7; i < 14; i++) {
curr_frame.data[i-6] = buffer[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
}
String IC_DISPLAY::resize(String s, int lb, int ub) {
String ret = "";
if (s.length() < lb) {
ret = s;
for (int i = 0; i < lb - s.length(); i++) {
ret += " ";
}
}
// If text is longer than MAX_STR_LENGTH chars, crop it to MAX_STR_LENGTH chars long
else if (s.length() > ub) {
for (int i = 0; i < ub; i++) {
ret += s[i];
}
} else {
ret = s;
}
return ret;
}
/**
* Sends body packets to the IC display to display a maximum of MAX_STR_LENGTH characters at a lastTime
* @param text Text to be displayed. If longer than 8 characters, it is cropped to be 8 characters long
*/
void IC_DISPLAY::sendBody(char text[]) {
curr_frame.can_id = IC_SEND_PID;
curr_frame.can_dlc = 0x08;
if (strlen(text) == 7) {
text += ' ';
}
char msg[] = resize(text, 5, MAX_STR_LENGTH);
// Stores the Sum of all ASCII Chars in text. Needed for validation packet
int asciiTotal = 0;
// Stores the number of bytes for actual data for the IC to process. Message length (ASCII) + Validation byte + null termination byte
uint8_t totalMsgLength = msg.length() + 2;
// Number of bytes to send across multiple packets to the IC
uint8_t numberOfBytes = 7 + totalMsgLength;
// Buffer to hold datawe will send to the IC across 2 packets
uint8_t bodyData[14] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// Start of string
bodyData[0] = 0x10;
// fAdd in all the body text
for (int i = 0; i < msg.length(); i++) {
bodyData[i+1] = msg[i];
asciiTotal += msg[i];
}
// Add null termination to the bodydata
bodyData[msg.length()+1] = 0x00;
// Finally, add the validation byte to the bodyData
bodyData[msg.length() + 2] = calculateBodyCheckSum(msg);
// Pre-text packet for body text
curr_frame.data[0] = 0x10;
curr_frame.data[1] = numberOfBytes;
curr_frame.data[2] = 0x03;
curr_frame.data[3] = 0x26;
curr_frame.data[4] = 0x01;
curr_frame.data[5] = 0x00;
curr_frame.data[6] = 0x01;
curr_frame.data[7] = totalMsgLength;
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7); // Wait 5 MS for IC to process request (+2ms for time taken for the IC to receive packet)
curr_frame.data[0] = 0x21;
for (int i = 0; i < 7; i++) {
curr_frame.data[i+1] = bodyData[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(2);
curr_frame.data[0] = 0x22;
for (int i = 7; i < 14; i++) {
curr_frame.data[i-6] = bodyData[i];
}
c->sendFrame(CAN_BUS_B, &curr_frame);
delay(7);
}
/**
* calculates the header text validation byte
*/
uint8_t IC_DISPLAY::calculateHeaderCheckSum(const char *text) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += int(text[i]);
}
return 407 - (sum);
}
/**
* Calculates the body text validation byte
*/
uint8_t IC_DISPLAY::calculateBodyCheckSum(const char text[]){
uint8_t charCount = strlen(text);
// Lookup table valid checksum + ASCII Total values
uint16_t NINE_CHAR_TOTAL_LOOKUP[] = {1073, 817, 561, 561};
uint16_t EIGHT_CHAR_TOTAL_LOOKUP[] = {1090, 834, 578, 322};
uint16_t SEVEN_CHAR_TOTAL_LOOKUP[] = {1136, 880, 624, 368};
uint16_t SIX_CHAR_TOTAL_LOOKUP[] = {1121, 865, 609, 353};
uint16_t FIVE_CHAR_TOTAL_LOOKUP[] = {1135, 879, 623, 367};
uint16_t FOUR_CHAR_TOTAL_LOOKUP[] = {439, 439, 439, 439};
int strTotal = 0;
for(int i = 0; i < charCount; i++) {
strTotal += text[i];
}
if(charCount == 9) {
for(uint16_t k : NINE_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 9");
return (k-strTotal);
}
}
}else if(charCount == 8) {
for(uint16_t k : EIGHT_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 8");
return (k-strTotal);
}
}
} else if (charCount == 7) {
for(uint16_t k : SEVEN_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 7");
return (k-strTotal);
}
}
} else if (charCount == 6) {
for(uint16_t k : SIX_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 6");
return (k-strTotal);
}
}
} else if (charCount == 5) {
for(uint16_t k : FIVE_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 5");
return (k-strTotal);
}
}
} else if (charCount == 4) {
for(uint16_t k : FOUR_CHAR_TOTAL_LOOKUP) {
if(k - strTotal <= 256) {
DPRINTLN("K: "+String(k)+" SUM: "+String(strTotal)+" Num Chars: 4");
return (k-strTotal);
}
}
}
return 0;
}
/**
* Method to update the contents of the IC based on data within the class
*/
void IC_DISPLAY::update() {
if (!inDiagMode) {
if (millis() - lastTime > currentRefreshRate) {
lastTime = millis();
if(currentPage == clusterPage::Audio) {
sendBody(currText.c_str());
if(this->currText.length() > MAX_STR_LENGTH) {
this->currText = shiftString();
}
} else if (!sendFirst) {
sendBody(currText);
this->sendFirst = true;
}
}
} else {
switch (this->diagScreen)
{
case 0:
diagData = "DIAG MODE";
break;
case 1:
diagData = diag->getSpeed();
break;
case 2:
diagData = diag->getRPM();
break;
case 3:
diagData = diag->getCoolantTemp();
break;
default:
break;
}
if (millis() - lastTime > DIAG_REFRESH_RATE) {
lastTime = millis();
sendBody(diagData);
}
}
}
String IC_DISPLAY::getText() {
return this->currText;
}
/**
* Sets body text for the IC
*/
void IC_DISPLAY::setBodyText(String text, bool addSpace) {
this->currText = text;
if (text.length() > MAX_STR_LENGTH) {
if (addSpace) {
this->currText += " ";
}
this->currentRefreshRate = scrollRefreshRate;
} else {
this->sendBody(currText);
this->currentRefreshRate = staticRefreshRate;
}
this->sendFirst = false;
}
/**
* Shifts string by 1 to the left
*/
String IC_DISPLAY::shiftString() {
char x = currText[0];
String tmp;
for (int i = 1; i < currText.length(); i++) {
tmp += currText[i];
}
tmp += x;
return tmp;
}
void IC_DISPLAY::nextDiagScreen() {
if (diagScreen < diag->screens) {
diagScreen++;
} else if (diagScreen == diag->screens) {
diagScreen = 0;
}
}
void IC_DISPLAY::prevDiagScreen() {
if (diagScreen > 0) {
diagScreen--;
} else if (diagScreen == 0) {
diagScreen = diag->screens;
}
}
| 29.768997
| 137
| 0.559016
|
Allabakshu-shaik
|
2c37db840a6a20342a022d28eca3c2eb3d8cfe27
| 247
|
hpp
|
C++
|
intrusive/pair_fwd.hpp
|
awonnacott/data-structures
|
90bfa3994812b433a69ee0996952fcb874ca9184
|
[
"MIT"
] | 1
|
2021-04-27T19:12:27.000Z
|
2021-04-27T19:12:27.000Z
|
intrusive/pair_fwd.hpp
|
awonnacott/data-structures
|
90bfa3994812b433a69ee0996952fcb874ca9184
|
[
"MIT"
] | null | null | null |
intrusive/pair_fwd.hpp
|
awonnacott/data-structures
|
90bfa3994812b433a69ee0996952fcb874ca9184
|
[
"MIT"
] | null | null | null |
#pragma once
#include <utility> // pair
namespace intrusive {
template <typename A, typename B> class pair;
template <typename A, typename B>
constexpr std::pair<pair<A, B>, pair<B, A>> make_pair(const A&, const B&);
} // namespace intrusive
| 19
| 74
| 0.704453
|
awonnacott
|
2c3973599e108bbf66163a086cef4667593a6296
| 287
|
hpp
|
C++
|
src/Gui/single/Layouts/HBoxLayout.hpp
|
classix-ps/sfml-widgets
|
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
|
[
"MIT"
] | null | null | null |
src/Gui/single/Layouts/HBoxLayout.hpp
|
classix-ps/sfml-widgets
|
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
|
[
"MIT"
] | null | null | null |
src/Gui/single/Layouts/HBoxLayout.hpp
|
classix-ps/sfml-widgets
|
0556f9d95ee2c5a5bc34e2182cf7f16290c102cf
|
[
"MIT"
] | null | null | null |
#ifndef GUI_HBOXLAYOUT_SINGLE_HPP
#define GUI_HBOXLAYOUT_SINGLE_HPP
#include "Layout.hpp"
namespace guiSingle
{
/**
* Horizontally stacked layout
*/
class HBoxLayout: public Layout
{
public:
private:
void recomputeGeometry() override;
};
}
#endif // GUI_HBOXLAYOUT_SINGLE_HPP
| 13.045455
| 38
| 0.766551
|
classix-ps
|
2c3d51d5ad9f12e395c8d87e4a8bda13cc46f228
| 1,820
|
cc
|
C++
|
function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc
|
descender76/cpp_proposals
|
2eb7e2f59257b376dadd1b66464e076c3de23ab1
|
[
"BSL-1.0"
] | 1
|
2022-01-21T20:10:46.000Z
|
2022-01-21T20:10:46.000Z
|
function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc
|
descender76/cpp_proposals
|
2eb7e2f59257b376dadd1b66464e076c3de23ab1
|
[
"BSL-1.0"
] | null | null | null |
function_ref/snippets/snippet-member-function-without-type-erasure-usage.cc
|
descender76/cpp_proposals
|
2eb7e2f59257b376dadd1b66464e076c3de23ab1
|
[
"BSL-1.0"
] | null | null | null |
struct delegateTest
{
int state = 0;
long current(int i, long l, char c) const
{
return state + i + l;
}
long test(int i, long l, char c)
{
state += i;
return state + l;
}
};
int main()
{
delegateTest dt;
function_ref_prime<long(delegateTest*, int, long, char)> frp = this_as_pointer<&delegateTest::test>::make_function_ref();
std::cout << frp(&dt, 7800, 91, 'l') << std::endl;// 7891
frp = this_as_pointer<&delegateTest::current>::make_function_ref();
std::cout << frp(&dt, 7800, 91, 'l') << std::endl;// 15691
function_ref_prime<long(delegateTest&, int, long, char)> frp1 = this_as_ref<&delegateTest::test>::make_function_ref();
std::cout << frp1(dt, 7800, 91, 'l') << std::endl;// 15691
frp1 = this_as_ref<&delegateTest::current>::make_function_ref();
std::cout << frp1(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(delegateTest, int, long, char)> frp2 = this_as_value<&delegateTest::test>::make_function_ref();
std::cout << frp2(dt, 7800, 91, 'l') << std::endl;// 23491
frp2 = this_as_value<&delegateTest::current>::make_function_ref();
std::cout << frp2(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest*, int, long, char)> frp3 = this_as_cpointer<&delegateTest::current>::make_function_ref();
std::cout << frp3(&dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest&, int, long, char)> frp4 = this_as_cref<&delegateTest::current>::make_function_ref();
std::cout << frp4(dt, 7800, 91, 'l') << std::endl;// 23491
function_ref_prime<long(const delegateTest, int, long, char)> frp5 = this_as_cvalue<&delegateTest::current>::make_function_ref();
std::cout << frp5(dt, 7800, 91, 'l') << std::endl;// 23491
}
| 49.189189
| 136
| 0.642857
|
descender76
|
2c42b90f863c17c776d7db965a8e80f3db6cb20e
| 4,972
|
hpp
|
C++
|
txml/applications/json/include/SchemaSerializer.hpp
|
SergeyIvanov87/templatedXML
|
2873fff802979113de102cd6ff5c2184720ee107
|
[
"MIT"
] | 4
|
2020-09-30T10:41:44.000Z
|
2022-03-14T19:12:26.000Z
|
txml/applications/json/include/SchemaSerializer.hpp
|
SergeyIvanov87/templatedXML
|
2873fff802979113de102cd6ff5c2184720ee107
|
[
"MIT"
] | 3
|
2021-11-03T18:46:24.000Z
|
2021-11-03T18:47:09.000Z
|
txml/applications/json/include/SchemaSerializer.hpp
|
SergeyIvanov87/templatedXML
|
2873fff802979113de102cd6ff5c2184720ee107
|
[
"MIT"
] | null | null | null |
#ifndef TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
#define TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
#include <txml/include/engine/SchemaSerializerBase.hpp>
#include <txml/applications/json/include/fwd/SchemaSerializer.h>
#include <txml/applications/json/include/SerializerCore.hpp>
#include <txml/applications/json/include/utils.hpp>
namespace json
{
#define TEMPL_ARGS_DECL class Impl, class ...SerializedItems
#define TEMPL_ARGS_DEF Impl, SerializedItems...
template<TEMPL_ARGS_DECL>
SchemaToJSON<TEMPL_ARGS_DEF>::SchemaToJSON(std::shared_ptr<std::stack<json>> shared_object_stack) :
SerializerCore(shared_object_stack)
{
}
template<TEMPL_ARGS_DECL>
SchemaToJSON<TEMPL_ARGS_DEF>::~SchemaToJSON() = default;
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_impl(txml::details::SchemaTag<SerializedItem>, Tracer tracer)
{
static_cast<Impl*>(this)->template serialize_schema_tag_impl<SerializedItem>(typename SerializedItem::tags_t {}, tracer);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::ArrayTag&, Tracer &tracer)
{
//TODO
json cur_json_element = json::array();
auto mediator = get_shared_mediator_object();
size_t stack_size_before = mediator->size();
tracer.trace(__FUNCTION__, " - begin 'ArrayTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_before);
SerializedItem::schema_serialize_elements(* static_cast<Impl*>(this), tracer);
size_t stack_size_after = mediator->size();
tracer.trace(__FUNCTION__, " - end 'ArrayTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_after);
for (size_t i = stack_size_before; i < stack_size_after; i++)
{
json &serialized_element = mediator->top();
cur_json_element.insert(cur_json_element.end(), std::move(serialized_element));
mediator->pop();
}
mediator->push({{SerializedItem::class_name(), std::move(cur_json_element)}});
tracer.trace(__FUNCTION__, " - 'ArrayTag' merged: ", SerializedItem::class_name(),
", from elements count: ", stack_size_after - stack_size_before);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::ContainerTag&, Tracer &tracer)
{
json cur_json_element = json::object({});
auto mediator = get_shared_mediator_object();
size_t stack_size_before = mediator->size();
tracer.trace(__FUNCTION__, " - begin 'ContainerTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_before);
SerializedItem::schema_serialize_elements(* static_cast<Impl*>(this), tracer);
size_t stack_size_after = mediator->size();
tracer.trace(__FUNCTION__, " - end 'ContainerTag': ", SerializedItem::class_name(),
", stack size: ", stack_size_after);
for (size_t i = stack_size_before; i < stack_size_after; i++)
{
json &serialized_element = mediator->top();
if (serialized_element.type() == nlohmann::json::value_t::array)
{
tracer.trace(__FUNCTION__, " - ", SerializedItem::class_name(), "::emplace array");
cur_json_element.emplace(SerializedItem::class_name(), std::move(serialized_element));
}
else
{
auto f = serialized_element.begin();
auto l = serialized_element.end();
tracer.trace(__FUNCTION__, " - insert objects count: ", std::distance(f, l));
cur_json_element.insert(f, l);
}
mediator->pop();
}
mediator->push({{SerializedItem::class_name(), std::move(cur_json_element)}});
tracer.trace(__FUNCTION__, " - 'ContainerTag' merged: ", SerializedItem::class_name(),
", from elements count: ", stack_size_after - stack_size_before);
}
template<TEMPL_ARGS_DECL>
template<class SerializedItem, class Tracer>
void SchemaToJSON<TEMPL_ARGS_DEF>::serialize_schema_tag_impl(const txml::LeafTag&, Tracer &tracer)
{
auto mediator = get_shared_mediator_object();
tracer.trace(__FUNCTION__, " - begin 'LeafTag': ", SerializedItem::class_name(),
", stack size: ", mediator->size());
json element({{SerializedItem::class_name(),
utils::json_type_to_cstring(utils::type_to_json_type<typename SerializedItem::value_t>()) }});
tracer.trace("'", SerializedItem::class_name(), "' created, value: ", element.dump());
mediator->push(std::move(element));
tracer.trace(__FUNCTION__, " - end 'LeafTag': ", SerializedItem::class_name(),
", stack size: ", mediator->size());
}
} // namespace json
#endif // TXML_APPLICATION_JSON_SCHEMA_SERIALIZER_HPP
| 43.234783
| 125
| 0.684232
|
SergeyIvanov87
|
2c47b6b4bb3baaa25ce739a3f867f3876115a95c
| 2,697
|
cpp
|
C++
|
tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 2
|
2021-04-11T04:07:42.000Z
|
2021-04-11T05:07:54.000Z
|
tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 4
|
2018-06-04T20:26:40.000Z
|
2018-07-27T14:54:55.000Z
|
tests/Unit/Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 1
|
2019-01-03T21:47:04.000Z
|
2019-01-03T21:47:04.000Z
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Helpers/PointwiseFunctions/GeneralRelativity/TestHelpers.hpp"
#include "DataStructures/DataVector.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/Tensor.hpp" // IWYU pragma: keep
#include "Helpers/DataStructures/MakeWithRandomValues.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
namespace TestHelpers::gr {
template <typename DataType>
Scalar<DataType> random_lapse(const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(0.0, 3.0);
return make_with_random_values<Scalar<DataType>>(
generator, make_not_null(&distribution), used_for_size);
}
template <size_t Dim, typename DataType>
tnsr::I<DataType, Dim> random_shift(
const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(-1.0, 1.0);
return make_with_random_values<tnsr::I<DataType, Dim>>(
generator, make_not_null(&distribution), used_for_size);
}
template <size_t Dim, typename DataType, typename Fr>
tnsr::ii<DataType, Dim, Fr> random_spatial_metric(
const gsl::not_null<std::mt19937*> generator,
const DataType& used_for_size) noexcept {
std::uniform_real_distribution<> distribution(-0.05, 0.05);
auto spatial_metric = make_with_random_values<tnsr::ii<DataType, Dim, Fr>>(
generator, make_not_null(&distribution), used_for_size);
for (size_t d = 0; d < Dim; ++d) {
spatial_metric.get(d, d) += 1.0;
}
return spatial_metric;
}
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)
#define DIM(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATE_SCALARS(_, data) \
template Scalar<DTYPE(data)> random_lapse( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE_SCALARS, (double, DataVector))
#define INSTANTIATE_TENSORS(_, data) \
template tnsr::I<DTYPE(data), DIM(data)> random_shift( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept; \
template tnsr::ii<DTYPE(data), DIM(data)> random_spatial_metric( \
const gsl::not_null<std::mt19937*> generator, \
const DTYPE(data) & used_for_size) noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE_TENSORS, (double, DataVector), (1, 2, 3))
#undef INSTANTIATE_SCALARS
#undef INSTANTIATE_TENSORS
#undef DIM
#undef DTYPE
} // namespace TestHelpers::gr
| 39.661765
| 77
| 0.708194
|
macedo22
|
2c481bd2bd7b05816bcfae573030a18d98461e1e
| 890
|
inl
|
C++
|
src/Engine/Renderer/RenderTechnique/RenderParameters.inl
|
nmellado/Radium-Engine
|
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
|
[
"Apache-2.0"
] | null | null | null |
src/Engine/Renderer/RenderTechnique/RenderParameters.inl
|
nmellado/Radium-Engine
|
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
|
[
"Apache-2.0"
] | null | null | null |
src/Engine/Renderer/RenderTechnique/RenderParameters.inl
|
nmellado/Radium-Engine
|
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
|
[
"Apache-2.0"
] | null | null | null |
#include <Engine/Renderer/RenderTechnique/RenderParameters.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp>
namespace Ra
{
namespace Engine
{
template <typename T>
inline void RenderParameters::UniformBindableVector<T>::bind(const ShaderProgram* shader ) const
{
for ( auto& value : *this )
{
value.second.bind( shader );
}
}
template <typename T>
inline void RenderParameters::TParameter<T>::bind(const ShaderProgram* shader ) const
{
shader->setUniform( m_name, m_value );
}
inline void RenderParameters::TextureParameter::bind(const ShaderProgram* shader ) const
{
shader->setUniform( m_name, m_texture, m_texUnit );
}
} // namespace Engine
} // namespace Ra
| 28.709677
| 105
| 0.589888
|
nmellado
|
2c4c07131285fad5893fd08084a675afc9b15192
| 525
|
cpp
|
C++
|
Aula08/ex-02-16.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | null | null | null |
Aula08/ex-02-16.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | 1
|
2018-04-27T23:42:44.000Z
|
2018-04-27T23:42:44.000Z
|
Aula08/ex-02-16.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | null | null | null |
/*
Escreva um programa que solicita ao usuário inserir dois números, obtém os dois números do usuário imprime a soma, produto, diferença e quociente dos dois números.
Cassio
*/
#include <iostream>
using namespace std;
int main()
{
float a;
float b;
cout << "Informe o valor de A: ";
cin >> a;
cout << "Informe o valor de B: ";
cin >> b;
cout << "Soma= " << a + b << endl;
cout << "Produto= " << a * b << endl;
cout << "Diferença= " << a - b << endl;
cout << "Quociente= " << a / b << endl;
return 0;
}
| 16.935484
| 163
| 0.6
|
cgcosta
|
2c4ca4be579e70582211ec5ab8862f8bf4d2c3fe
| 4,008
|
cpp
|
C++
|
src/cpp/XMLParser.cpp
|
YuriySavchenko/Test_Task
|
206fd75800767ad18027a6d9934a3f5be50f7526
|
[
"Apache-2.0"
] | null | null | null |
src/cpp/XMLParser.cpp
|
YuriySavchenko/Test_Task
|
206fd75800767ad18027a6d9934a3f5be50f7526
|
[
"Apache-2.0"
] | null | null | null |
src/cpp/XMLParser.cpp
|
YuriySavchenko/Test_Task
|
206fd75800767ad18027a6d9934a3f5be50f7526
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by yuriy on 10/7/18.
//
#include "../headers/XMLParser.h"
/* implementation of method for parsing *.xml files */
void XMLParser::parseFile(std::vector<Interval> &intervals) {
if (fin.is_open()) {
std::vector<std::string> text = splitString(buffer, '\n');
// we are checking if first and second tags are <root>
if (cmpString(text[0], "<root>") && cmpString(text[text.size()], "</root>")) {
for (int i=1; i < text.size(); i++) {
if (cmpString(text[i], "<intervals>")) {
int endIntervals = 0;
// loop which allows looking for end of section { <intervals> ... </intervals> }
for (int j=i+1; j < text.size(); j++) {
if (cmpString(text[j], "</intervals>")) {
endIntervals = j;
break;
}
}
// revising each tag until end of section
for (int j=i+1; j < endIntervals; j++) {
if (cmpString(text[j], "<interval>")) {
// variables for saving integer values
std::string lowStr = "";
std::string highStr = "";
// if we have in first tag construction { <low> num </low> }
// we are transforming string between tags into number
int pos = indexString(5, (int) text[j+1].length(), '<', text[j+1]);
if (cmpString(text[j+1].substr(0, 5), "<low>") &&
cmpString(text[j+1].substr(pos, pos+8), "</low>"))
lowStr = digitString(text[j+1]);
// if we have in second tag construction { <high> num </high> }
// we are transforming string between tags into number
pos = indexString(6, (int) text[j+2].length(), '<', text[j+2]);
if (cmpString(text[j+2].substr(0, 6), "<high>") &&
cmpString(text[j+2].substr(pos, pos+6), "</high>"))
highStr = digitString(text[j+2]);
// if both strings can to be transforming into numbers, then add them into vector
int low = std::stoi(lowStr);
int high = std::stoi(highStr);
if ((low > 2) && (high > 2)) {
intervals.push_back(Interval{low, high});
}
}
// case which looking for others <interval> into <intervals>
if (cmpString(text[j], "</interval>")) {
continue;
}
}
}
}
}
}
}
/* implementation of particular constructor */
XMLParser::XMLParser(std::string name) {
this->name = name;
}
/* implementation of destructor */
XMLParser::~XMLParser() {
}
/* redefined function for opening file */
void XMLParser::openFile() {
if (!this->fin.is_open())
this->fin.open(this->name);
}
/* function for reading from file */
void XMLParser::readFile() {
if (this->fin.is_open()) {
std::string text = "";
std::string line;
while(std::getline(fin, line))
text += line + '\n';
this->buffer = text;
}
}
/* redefined function for closing file */
void XMLParser::closeFile() {
if (fin.is_open())
fin.close();
}
/* function which allows getting value from private variable { fin } */
const std::ifstream &XMLParser::getFin() const {
return fin;
}
/* function which allows getting value from private variable { buffer } */
const std::string &XMLParser::getBuffer() const {
return buffer;
}
| 30.830769
| 109
| 0.460329
|
YuriySavchenko
|
2c5449f1599c8e1b05acff2e28f6d6b8f2c18ac5
| 6,192
|
cxx
|
C++
|
c++/laolrt/laol/rt/array.cxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
c++/laolrt/laol/rt/array.cxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
c++/laolrt/laol/rt/array.cxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
/*
* The MIT License
*
* Copyright 2017 kpfalzer.
*
* 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 <algorithm>
#include <sstream>
#include "laol/rt/array.hxx"
#include "laol/rt/range.hxx"
#include "laol/rt/string.hxx"
#include "laol/rt/exception.hxx"
namespace laol {
namespace rt {
using std::to_string;
Laol::METHOD_BY_NAME IArray::stMethodByName;
Laol::METHOD_BY_NAME Array::stMethodByName;
IArray::~IArray() {
}
Array::Array() {
}
Array::Array(Args v)
: PTArray<LaolObj>(v) {
}
Array::Array(const LaolObj& v)
: Array(v.isA<Array>() ? v.toType<Array>().m_ar : toV(v)) {
}
const Laol::METHOD_BY_NAME&
IArray::getMethodByName() {
if (stMethodByName.empty()) {
stMethodByName = join(stMethodByName,
METHOD_BY_NAME({
{"length", reinterpret_cast<TPMethod> (&IArray::length)},
{"empty?", reinterpret_cast<TPMethod> (&IArray::empty_PRED)},
{"foreach", reinterpret_cast<TPMethod> (&IArray::foreach)}
}));
}
return stMethodByName;
}
Ref
IArray::empty_PRED(const LaolObj& self, const LaolObj& args) const {
return isEmpty();
}
Ref
IArray::length(const LaolObj& self, const LaolObj& args) const {
return xlength();
}
size_t
IArray::actualIndex(long int ix) const {
return laol::rt::actualIndex(ix, xlength());
}
const Laol::METHOD_BY_NAME&
Array::getMethodByName() {
if (stMethodByName.empty()) {
stMethodByName = join(stMethodByName,
IArray::getMethodByName(),
METHOD_BY_NAME({
{"left_shift", reinterpret_cast<TPMethod> (&Array::left_shift)},
{"right_shift", reinterpret_cast<TPMethod> (&Array::right_shift)},
{"reverse", reinterpret_cast<TPMethod> (&Array::reverse)},
{"reverse!", reinterpret_cast<TPMethod> (&Array::reverse_SELF)}
}));
}
return stMethodByName;
}
LaolObj
Array::left_shift(const LaolObj& self, const LaolObj& opB) const {
unconst(this)->m_ar.push_back(opB);
return self;
}
LaolObj
Array::right_shift(const LaolObj& self, const LaolObj& opB) const {
unconst(this)->m_ar.insert(m_ar.begin(), opB);
return self;
}
#ifdef TODO
LaolObj
Array::toString(const LaolObj& self, const LaolObj&) const {
std::ostringstream oss;
oss << "[";
bool doComma = false;
for (const LaolObj& ele : m_ar) {
if (doComma) {
oss << ", ";
}
oss << ele.toQString();
doComma = true;
}
oss << "]";
return new String(oss.str());
}
#endif
// Local iterator over int range
template<typename FUNC>
void iterate(const Range& rng, FUNC forEach) {
auto i = rng.m_begin.toLongInt(), end = rng.m_end.toLongInt();
const auto incr = (end > i) ? 1 : -1;
while (true) {
forEach(i);
if (i == end) {
return;
}
i += incr;
}
}
const Array::Vector
Array::toVector(const LaolObj& opB) {
return opB.isA<Array>() ? opB.toType<Array>().m_ar : toV(opB);
}
/*
* opB : scalar or Array of vals...
*/
Ref
Array::subscript(const LaolObj&, const LaolObj& opB) const {
const Vector args = toVector(opB);
//degenerate case of single index
if ((1 == args.size()) && args[0].isInt()) {
return &m_ar[actualIndex(args[0].toLongInt())];
}
//else, build up ArrayOfRef
ArrayOfRef* pRefs = new ArrayOfRef();
for (const LaolObj& ix : args) {
if (ix.isInt()) {
pRefs->push_back(&m_ar[actualIndex(ix.toLongInt())]);
} else if (ix.isA<Range>()) {
iterate(ix.toType<Range>(), [this, &pRefs](auto i) {
//this-> work around gcc 5.1.0 bug
pRefs->push_back(&m_ar[this->actualIndex(i)]);
});
} else {
ASSERT_NEVER; //todo: error
}
}
return LaolObj(pRefs);
}
Ref
ArrayOfRef::subscript(const LaolObj& self, const LaolObj& opB) const {
const Array::Vector args = Array::toVector(opB);
if ((1 == args.size()) && args[0].isInt()) {
return &m_ar[actualIndex(args[0].toLongInt())];
}
ASSERT_NEVER; //todo
return self; //todo
}
}
}
| 32.93617
| 86
| 0.531008
|
gburdell
|
2c55204f2eca4f64f796c17d14fba6d7b0fbd1d9
| 4,195
|
cpp
|
C++
|
tools/engine_hook/window_hooks.cpp
|
mouzedrift/alive
|
7c297a39c60e930933c0a93ea373226907f8b1c7
|
[
"MIT"
] | null | null | null |
tools/engine_hook/window_hooks.cpp
|
mouzedrift/alive
|
7c297a39c60e930933c0a93ea373226907f8b1c7
|
[
"MIT"
] | null | null | null |
tools/engine_hook/window_hooks.cpp
|
mouzedrift/alive
|
7c297a39c60e930933c0a93ea373226907f8b1c7
|
[
"MIT"
] | null | null | null |
#include "window_hooks.hpp"
#include "debug_dialog.hpp"
#include "resource.h"
#include <memory>
#include <vector>
#include "anim_logger.hpp"
#include <WinUser.h>
bool gCollisionsEnabled = true;
bool gGridEnabled = false;
static WNDPROC g_pOldProc = 0;
std::unique_ptr<DebugDialog> gDebugUi;
extern HMODULE gDllHandle;
namespace Hooks
{
Hook<decltype(&::SetWindowLongA)> SetWindowLong(::SetWindowLongA);
}
LRESULT CALLBACK NewWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (!gDebugUi)
{
gDebugUi = std::make_unique<DebugDialog>();
gDebugUi->Create(gDllHandle, MAKEINTRESOURCE(IDD_MAIN));
gDebugUi->Show();
CenterWnd(gDebugUi->Hwnd());
gDebugUi->OnReloadAnimJson([&]() { GetAnimLogger().ReloadJson(); });
}
switch (message)
{
case WM_CREATE:
abort();
break;
case WM_ERASEBKGND:
{
RECT rcWin;
HDC hDC = GetDC(hwnd);
GetClipBox((HDC)wParam, &rcWin);
FillRect(hDC, &rcWin, GetSysColorBrush(COLOR_DESKTOP)); // hBrush can be obtained by calling GetWindowLong()
}
return TRUE;
case WM_GETICON:
case WM_MOUSEACTIVATE:
case WM_NCLBUTTONDOWN:
case WM_NCMOUSELEAVE:
case WM_KILLFOCUS:
case WM_SETFOCUS:
case WM_ACTIVATEAPP:
case WM_NCHITTEST:
case WM_ACTIVATE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_NCCALCSIZE:
case WM_MOVE:
case WM_WINDOWPOSCHANGED:
case WM_WINDOWPOSCHANGING:
case WM_NCMOUSEMOVE:
case WM_MOUSEMOVE:
return DefWindowProc(hwnd, message, wParam, lParam);
case WM_KEYDOWN:
{
if (GetAsyncKeyState('G'))
{
gGridEnabled = !gGridEnabled;
}
if (GetAsyncKeyState('H'))
{
gCollisionsEnabled = !gCollisionsEnabled;
}
return g_pOldProc(hwnd, message, wParam, lParam);
}
case WM_SETCURSOR:
{
// Set the cursor so the resize cursor or whatever doesn't "stick"
// when we move the mouse over the game window.
static HCURSOR cur = LoadCursor(0, IDC_ARROW);
if (cur)
{
SetCursor(cur);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
}
return FALSE;
}
if (message == WM_DESTROY && gDebugUi)
{
gDebugUi->Destroy();
}
return g_pOldProc(hwnd, message, wParam, lParam);
}
void CenterWnd(HWND wnd)
{
RECT r, r1;
GetWindowRect(wnd, &r);
GetWindowRect(GetDesktopWindow(), &r1);
MoveWindow(wnd, ((r1.right - r1.left) - (r.right - r.left)) / 2,
((r1.bottom - r1.top) - (r.bottom - r.top)) / 2,
(r.right - r.left), (r.bottom - r.top), 0);
}
void SubClassWindow()
{
HWND wnd = FindWindow("ABE_WINCLASS", NULL);
g_pOldProc = (WNDPROC)SetWindowLong(wnd, GWL_WNDPROC, (LONG)NewWindowProc);
for (int i = 0; i < 70; ++i)
{
ShowCursor(TRUE);
}
SetWindowLongA(wnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
RECT rc;
SetRect(&rc, 0, 0, 640, 460);
AdjustWindowRectEx(&rc, WS_OVERLAPPEDWINDOW | WS_VISIBLE, TRUE, 0);
SetWindowPos(wnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top,
SWP_SHOWWINDOW);
ShowWindow(wnd, SW_HIDE);
CenterWnd(wnd);
ShowWindow(wnd, SW_SHOW);
InvalidateRect(GetDesktopWindow(), NULL, TRUE);
}
void PatchWindowTitle()
{
HWND wnd = FindWindow("ABE_WINCLASS", NULL);
if (wnd)
{
const int length = GetWindowTextLength(wnd) + 1;
std::vector< char > titleBuffer(length + 1);
if (GetWindowText(wnd, titleBuffer.data(), length))
{
std::string titleStr(titleBuffer.data());
titleStr += " under ALIVE hook";
SetWindowText(wnd, titleStr.c_str());
}
}
}
LONG WINAPI Hook_SetWindowLongA(HWND hWnd, int nIndex, LONG dwNewLong)
{
if (nIndex == GWL_STYLE)
{
dwNewLong = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
}
return Hooks::SetWindowLong.Real()(hWnd, nIndex, dwNewLong);
}
| 24.389535
| 117
| 0.618832
|
mouzedrift
|
2c57c5a03651bea61c96f288b8fec0f0d8f5d104
| 2,220
|
cpp
|
C++
|
acm-template/4 Math/FFT/lrj.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
acm-template/4 Math/FFT/lrj.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
acm-template/4 Math/FFT/lrj.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int prime = 999983;
const int INF = 0x7FFFFFFF;
const LL INFF =0x7FFFFFFFFFFFFFFF;
//const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-6;
const LL mod = 1e9 + 7;
int dr[2][4] = {1,-1,0,0,0,0,-1,1};
// UVa12298 Super Poker II
// Rujia Liu
const long double PI = acos(0.0) * 2.0;
typedef complex<double> CD;
// Cooley-Tukey的FFT算法,迭代实现。inverse = false时计算逆FFT
inline void FFT(vector<CD> &a, bool inverse) {
int n = a.size();
// 原地快速bit reversal
for(int i = 0, j = 0; i < n; i++) {
if(j > i) swap(a[i], a[j]);
int k = n;
while(j & (k >>= 1)) j &= ~k;
j |= k;
}
double pi = inverse ? -PI : PI;
for(int step = 1; step < n; step <<= 1) {
// 把每相邻两个“step点DFT”通过一系列蝴蝶操作合并为一个“2*step点DFT”
double alpha = pi / step;
// 为求高效,我们并不是依次执行各个完整的DFT合并,而是枚举下标k
// 对于一个下标k,执行所有DFT合并中该下标对应的蝴蝶操作,即通过E[k]和O[k]计算X[k]
// 蝴蝶操作参考:http://en.wikipedia.org/wiki/Butterfly_diagram
for(int k = 0; k < step; k++) {
// 计算omega^k. 这个方法效率低,但如果用每次乘omega的方法递推会有精度问题。
// 有更快更精确的递推方法,为了清晰起见这里略去
CD omegak = exp(CD(0, alpha*k));
for(int Ek = k; Ek < n; Ek += step << 1) { // Ek是某次DFT合并中E[k]在原始序列中的下标
int Ok = Ek + step; // Ok是该DFT合并中O[k]在原始序列中的下标
CD t = omegak * a[Ok]; // 蝴蝶操作:x1 * omega^k
a[Ok] = a[Ek] - t; // 蝴蝶操作:y1 = x0 - t
a[Ek] += t; // 蝴蝶操作:y0 = x0 + t
}
}
}
if(inverse)
for(int i = 0; i < n; i++) a[i] /= n;
}
// 用FFT实现的快速多项式乘法
inline vector<double> operator * (const vector<double>& v1, const vector<double>& v2) {
int s1 = v1.size(), s2 = v2.size(), S = 2;
while(S < s1 + s2) S <<= 1;
vector<CD> a(S,0), b(S,0); // 把FFT的输入长度补成2的幂,不小于v1和v2的长度之和
for(int i = 0; i < s1; i++) a[i] = v1[i];
FFT(a, false);
for(int i = 0; i < s2; i++) b[i] = v2[i];
FFT(b, false);
for(int i = 0; i < S; i++) a[i] *= b[i];
FFT(a, true);
vector<double> res(s1 + s2 - 1);
for(int i = 0; i < s1 + s2 - 1; i++) res[i] = a[i].real(); // 虚部均为0
return res;
}
| 30.410959
| 87
| 0.564414
|
joshua-xia
|
2c5fdd407fe564619ddb7888110d9c37b061f55f
| 1,498
|
cpp
|
C++
|
module05/ex01/Form.cpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
module05/ex01/Form.cpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
module05/ex01/Form.cpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
#include "Form.hpp"
/*
** Canonical Form
*/
Form::Form(int signGrad, int executionGrad)
: _signGrad(signGrad), _executionGrad(executionGrad) {}
Form::Form(const std::string& name, int signGrad, int executionGrad)
: _name(name), _signGrad(signGrad), _executionGrad(executionGrad), _isSigned(false) {
if (signGrad <= 0 || executionGrad <= 0)
throw Form::GradeTooLowException();
if (signGrad > 150 || executionGrad > 150)
throw Form::GradeTooHighException();
}
Form::Form(const Form& org)
:_name(org._name), _signGrad(org._signGrad), _executionGrad(org._executionGrad), _isSigned(org._isSigned) {}
Form& Form::operator=(const Form& org) {
_isSigned = org._isSigned;
return (*this);
}
Form::~Form() {}
/* *** */
std::string Form::getName() const { return (_name); }
bool Form::getIsSigned() const { return (_isSigned); }
int Form::getSignGrad() const { return (_signGrad); }
int Form::getExecutionGrad() const { return (_executionGrad); }
void Form::beSigned(const Bureaucrat& br) {
if (_signGrad < br.getGrade()) {
br.signForm(getName(), "grade is too low", false);
throw Form::GradeTooLowException();
}
_isSigned = true;
br.signForm(getName(), "", true);
}
std::ostream& operator<<(std::ostream& os, const Form& f) {
os << f.getName() << " is a ";
(f.getIsSigned()) ? os << "signed" : os << "non-signed";
os << " form. [signGrad : " << f.getSignGrad() << "]";
os << ", [executionGrad : " << f.getExecutionGrad() << "]" << std::endl;
return (os);
}
| 28.264151
| 108
| 0.655541
|
M-Philippe
|
2c6336949785352075fae63e49653788b7b3047e
| 964
|
cpp
|
C++
|
utils.cpp
|
caminek/Gilligan
|
c7546d647a1fa9e4add929fa813f62c227fcb600
|
[
"MIT"
] | null | null | null |
utils.cpp
|
caminek/Gilligan
|
c7546d647a1fa9e4add929fa813f62c227fcb600
|
[
"MIT"
] | null | null | null |
utils.cpp
|
caminek/Gilligan
|
c7546d647a1fa9e4add929fa813f62c227fcb600
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "utils.hpp"
Status status;
uint8_t Utils::rol(uint8_t nibble)
{
uint8_t retval;
bool previous_carry = status.carry_flag;
status.carry_flag = nibble >> 7;
retval = (nibble << 1) | previous_carry;
return retval;
}
uint8_t Utils::ror(uint8_t bit)
{
uint8_t retval;
bool previous_carry = status.carry_flag;
status.carry_flag = static_cast<bool>(bit & 0x01);
retval = bit >> 1;
retval = static_cast<uint8_t>(previous_carry ? retval | 0x80 : retval);
return retval;
}
uint8_t Utils::asl(uint8_t bit)
{
status.carry_flag = bit >> 7;
return bit << 1;
}
uint8_t Utils::adc(uint8_t val1, uint8_t val2)
{
uint8_t result = val1 + val2 + status.carry_flag;
if (result < val1 || result < val2)
status.carry_flag = true;
return result;
}
void Utils::output_password(const uint8_t password[])
{
for (int i = 0; i < 8; ++i)
std::cout << (int)password[i] << " ";
std::cout << std::endl;
}
| 16.338983
| 73
| 0.659751
|
caminek
|
2c63f1cde72b706915e05701a8f3c4a026b96846
| 861
|
cpp
|
C++
|
leetcode/72.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
leetcode/72.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
leetcode/72.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int sloveDP(string w1, string w2)
{
int w1Len = w1.size(), w2Len = w2.size();
vector<vector<int>> dp(w1Len+1, vector<int>(w2Len+1));
auto mins = [](int v1, int v2, int v3){
return min(min(v1,v2), v3);
};
for(int i = 0; i <= w1Len; i++) {
dp[i][0] = i;
}
for(int i = 0; i <= w2Len; i++) {
dp[0][i] = i;
}
for(int i = 1; i <= w1Len; i++){
for(int j = 1; j <= w2Len; j++) {
if(w1[i-1] == w2[j-1]) {
dp[i][j] = 1 + mins(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]-1);
}else{
dp[i][j] = 1 + mins(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
}
}
}
return dp[w1Len][w2Len];
}
int main()
{
string w1, w2;
cin >> w1 >> w2;
cout << sloveDP(w1, w2) << endl;
return 0;
}
| 23.916667
| 76
| 0.425087
|
freedomDR
|
2c673e1281ebca671c418f0740f114b73aeff04f
| 11,214
|
cpp
|
C++
|
tests/test_matrix_traits.cpp
|
fancidev/euler
|
a74e3ddf46034718253259eac4880472c58a7b22
|
[
"MIT"
] | null | null | null |
tests/test_matrix_traits.cpp
|
fancidev/euler
|
a74e3ddf46034718253259eac4880472c58a7b22
|
[
"MIT"
] | null | null | null |
tests/test_matrix_traits.cpp
|
fancidev/euler
|
a74e3ddf46034718253259eac4880472c58a7b22
|
[
"MIT"
] | null | null | null |
#include <array>
#include <cstdint>
#include <type_traits>
#include <vector>
//#include "euler/matrix.hpp"
#include "euler/matrix_traits.hpp"
//#include "euler/matrix_adaptor.hpp"
#include "euler/matrix_algorithm.hpp"
#include "gtest/gtest.h"
#define MYTEST(functionName, testAspect) \
TEST(matrix ## __ ## functionName, testAspect)
MYTEST(matrix_traits, non_matrix)
{
static_assert(!euler::is_matrix_v<int>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int[2]>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int&>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int&&>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int*>, "is_matrix_v fails");
static_assert(!euler::is_matrix_v<int**>, "is_matrix_v fails");
}
MYTEST(matrix_traits, static)
{
// Test matrix traits with static c array
using type = int[3][5];
using traits = euler::matrix_traits<type>;
static_assert(
traits::rank == 2,
"matrix_traits::rank failed");
static_assert(
std::is_same<typename traits::value_type, int>::value,
"matrix_traits::value_type failed");
static_assert(
std::is_same<typename traits::reference, int&>::value,
"matrix_traits::reference failed");
static_assert(
std::is_same<typename traits::const_reference, const int&>::value,
"matrix_traits::const_reference failed");
static_assert(euler::has_static_extent<type, 0>::value,
"has_static_extent<0>::value fails");
static_assert(euler::has_static_extent<type, 1>::value,
"has_static_extent<1>::value fails");
static_assert(euler::has_static_extent_v<type, 0>,
"has_static_extent_v<0> fails");
static_assert(euler::has_static_extent_v<type, 1>,
"has_static_extent_v<1> fails");
static_assert(!euler::has_dynamic_extent<type, 0>::value,
"has_dynamic_extent<0>::value fails");
static_assert(!euler::has_dynamic_extent<type, 1>::value,
"has_dynamic_extent<1>::value fails");
static_assert(!euler::has_dynamic_extent_v<type, 0>,
"has_dynamic_extent_v<0> fails");
static_assert(!euler::has_dynamic_extent_v<type, 1>,
"has_dynamic_extent_v<1> fails");
static_assert(euler::is_matrix<type>::value,
"is_matrix::value fails");
static_assert(euler::is_matrix_v<type>,
"is_matrix_v fails");
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::matrix_traits<decltype(a)>::at(a, 1, 0));
}
MYTEST(matrix_traits, mixed)
{
// Test matrix traits for matrix with fixed number of columns but variable
// number of rows.
using type = std::vector<std::array<int, 2>>;
using traits = euler::matrix_traits<type>;
static_assert(
traits::rank == 2,
"matrix_traits::rank failed");
static_assert(
std::is_same<typename traits::value_type, int>::value,
"matrix_traits::value_type failed");
static_assert(
std::is_same<typename traits::reference, int&>::value,
"matrix_traits::reference failed");
static_assert(
std::is_same<typename traits::const_reference, const int&>::value,
"matrix_traits::const_reference failed");
static_assert(!euler::has_static_extent<type, 0>::value,
"has_static_extent<0>::value fails");
static_assert(euler::has_static_extent<type, 1>::value,
"has_static_extent<1>::value fails");
static_assert(!euler::has_static_extent_v<type, 0>,
"has_static_extent_v<0> fails");
static_assert(euler::has_static_extent_v<type, 1>,
"has_static_extent_v<1> fails");
static_assert(euler::has_dynamic_extent<type, 0>::value,
"has_dynamic_extent<0>::value fails");
static_assert(!euler::has_dynamic_extent<type, 1>::value,
"has_dynamic_extent<1>::value fails");
static_assert(euler::has_dynamic_extent_v<type, 0>,
"has_dynamic_extent_v<0> fails");
static_assert(!euler::has_dynamic_extent_v<type, 1>,
"has_dynamic_extent_v<1> fails");
static_assert(euler::is_matrix<type>::value,
"is_matrix::value fails");
static_assert(euler::is_matrix_v<type>,
"is_matrix_v fails");
type a{ {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::matrix_traits<decltype(a)>::at(a, 1, 0));
}
MYTEST(extent, static)
{
// Static matrix
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
}
MYTEST(extent, mixed)
{
// Matrix with fixed number of columns but variable number of rows.
std::vector<std::array<int, 2>> a;
EXPECT_EQ(0, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
a.push_back(std::array<int, 2>{1, 2});
EXPECT_EQ(1, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
}
#if 0
TEST(matrix, common_extent)
{
int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int B[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(3u, euler::common_extent<0>(A, B));
EXPECT_EQ(2u, euler::common_extent<1>(A, B));
EXPECT_EQ(0u, euler::common_extent<2>(A, B));
const int C[1][2] { };
EXPECT_EQ(0u, euler::common_extent<0>(A, C));
EXPECT_EQ(2u, euler::common_extent<1>(B, C));
EXPECT_EQ(0u, euler::common_extent<2>(A, C));
}
#endif
MYTEST(diagonal_matrix, static)
{
auto a = euler::diagonal_matrix(2, 5);
static_assert(euler::is_matrix_v<decltype(a)>, "type mismatch");
EXPECT_EQ(2, euler::extent<0>(a));
EXPECT_EQ(2, euler::extent<1>(a));
EXPECT_EQ(5, euler::mat(a, 0, 0));
EXPECT_EQ(0, euler::mat(a, 0, 1));
EXPECT_EQ(0, euler::mat(a, 1, 0));
EXPECT_EQ(5, euler::mat(a, 1, 1));
}
MYTEST(msum, nonempty)
{
int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(21, euler::msum(a));
}
MYTEST(msum, empty)
{
std::vector<std::array<int, 5>> a;
EXPECT_EQ(0, euler::msum(a));
EXPECT_EQ(5, euler::msum(5, a));
}
#if 0
TEST(matrix, meq)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {1, 2}, {3, 4}, {5, 6} };
EXPECT_EQ(true, euler::mall(euler::meq(A, B)));
}
TEST(matrix, madd)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {7, 8}, {9, 0}, {3, 5} };
int A_add_B[3][2] = { {8, 10}, {12, 4}, {8, 11} };
EXPECT_EQ(true, euler::mall(euler::meq(A_add_B, euler::madd(A, B))));
}
TEST(matrix, msub)
{
const int A[3][2] = { {1, 2}, {3, 4}, {5, 6} };
const int B[3][2] = { {7, 8}, {9, 0}, {3, 5} };
int A_sub_B[3][2] = { {-6, -6}, {-6, 4}, {2, 1} };
EXPECT_EQ(true, euler::mall(euler::meq(A_sub_B, euler::msub(A, B))));
}
MYTEST(make_lazy_vector, basic)
{
// basic usage
auto v = euler::make_lazy_vector(3, [](size_t i) { return i; });
EXPECT_EQ(0, v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
}
MYTEST(make_lazy_vector, mutable)
{
// elements in lazy vector are mutable if functor returns mutable object
int a[3] = { 1, 2, 3 };
auto v = euler::make_lazy_vector(3, [&a](size_t i) -> int&
{
return a[i];
});
v[1] = 4;
EXPECT_EQ(1, v[0]);
EXPECT_EQ(4, v[1]);
EXPECT_EQ(3, v[2]);
}
MYTEST(make_lazy_vector, void)
{
// functor may return void
int a[3] = { 1, 2, 3 };
auto v = euler::make_lazy_vector(3, [&a](size_t i) { ++a[i]; });
static_assert(std::is_same<void, decltype(v[0])>::value, "");
v[1];
v[1];
EXPECT_EQ(1, a[0]);
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3, a[2]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_lambda)
{
// cv-qualifier of vector does not propagate to lambda
int a[3] = { 1, 2, 3 };
const auto &v = euler::make_lazy_vector(3, [&a](size_t i) -> int&
{
return a[i];
});
v[1] = 4;
EXPECT_EQ(1, v[0]);
EXPECT_EQ(4, v[1]);
EXPECT_EQ(3, v[2]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_functor)
{
// cv-qualifier of vector does not propagate to functor
struct C
{
int *a;
double *b;
int &operator()(size_t i) { return a[i]; }
double &operator()(size_t i) const { return b[i]; }
};
int a[3] = { 1, 2, 3 };
double b[3] = { 1.25, 3.75, 5.50 };
auto v1 = euler::make_lazy_vector(3, C{a, b});
v1[2] *= 6;
EXPECT_EQ(18, a[2]);
EXPECT_EQ(5.50, b[2]);
const auto &v2 = euler::make_lazy_vector(3, C{a, b});
v2[1] *= 2;
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3.75, b[1]);
}
MYTEST(make_lazy_vector, cv_irrelevant_for_reference)
{
// cv-qualifier of vector is not propagated to reference of functor
struct C
{
int *a;
double *b;
int &operator()(size_t i) { return a[i]; }
double &operator()(size_t i) const { return b[i]; }
};
int a[4] = { 1, 2, 3, 4 };
double b[4] = { 1.25, 3.75, 5.50, 8.125 };
C c{a, b};
auto v1 = euler::make_lazy_vector<C&>(4, c);
v1[2] *= 6;
EXPECT_EQ(18, a[2]);
EXPECT_EQ(5.50, b[2]);
const auto &v2 = euler::make_lazy_vector<C&>(4, c);
v2[1] *= 2;
EXPECT_EQ(4, a[1]);
EXPECT_EQ(3.75, b[1]);
auto v3 = euler::make_lazy_vector<const C &>(4, c);
v3[3] *= 7;
EXPECT_EQ(4, a[3]);
EXPECT_EQ(8.125*7, b[3]);
const auto &v4 = euler::make_lazy_vector<const C &>(4, c);
v4[0] *= 11;
EXPECT_EQ(1, a[0]);
EXPECT_EQ(1.25*11, b[0]);
}
MYTEST(make_lazy_vector, reference)
{
// functor may be stored by reference (already implicitly tested above)
struct C
{
explicit C(int k) : k(k) { }
C(const C &) = delete;
C(C&&) = delete;
int operator()(size_t i) { return i * k; }
private:
int k;
};
C c(3);
auto v = euler::make_lazy_vector(100, c);
EXPECT_EQ(15, v[5]);
}
MYTEST(make_lazy_matrix, basic)
{
// basic usage of lazy matrix
auto a = euler::make_lazy_matrix(2, 3, std::plus<size_t>());
EXPECT_EQ(0, a[0][0]);
EXPECT_EQ(1, a[0][1]);
EXPECT_EQ(2, a[0][2]);
EXPECT_EQ(1, a[1][0]);
EXPECT_EQ(2, a[1][1]);
EXPECT_EQ(3, a[1][2]);
}
MYTEST(make_lazy_matrix, mutable)
{
// matrix elements are mutable if functor returns mutable object
int a[2][3] = { {10, 20, 30}, {40, 50, 60} };
auto v = euler::make_lazy_matrix(2, 3, [&a](size_t i, size_t j) -> int&
{
return a[i][j];
});
v[1][2] /= 5;
EXPECT_EQ(50, v[1][1]);
EXPECT_EQ(12, v[1][2]);
}
MYTEST(make_lazy_matrix, cv_irrelevant_for_lambda)
{
// cv-qualifier of matrix does not propagate to lambda
int a[2][3] = { {10, 20, 30}, {40, 50, 60} };
const auto &v = euler::make_lazy_matrix(2, 3,
[&a](size_t i, size_t j) -> int&
{
return a[i][j];
});
v[1][2] /= 5;
EXPECT_EQ(50, a[1][1]);
EXPECT_EQ(12, a[1][2]);
}
MYTEST(make_lazy_matrix, cv_irrelevant_for_functor)
{
// cv-qualifier of matrix does not propagate to functor
int a[5] = { 1, 2, 3, 4, 5 };
double b[5] = { 1.25, 3.75, 5.50, 8.125, 2.00 };
struct C
{
int *a;
double *b;
int &operator()(size_t i, size_t j) { return a[i + j]; }
double &operator()(size_t i, size_t j) const { return b[i + j]; }
};
auto v1 = euler::make_lazy_matrix(3, 3, C{a, b});
v1[2][1] *= 6;
EXPECT_EQ(24, a[3]);
EXPECT_EQ(8.125, b[3]);
const auto &v2 = euler::make_lazy_matrix(3, 3, C{a, b});
v2[2][2] *= 2;
EXPECT_EQ(10, a[4]);
EXPECT_EQ(2.0, b[4]);
}
MYTEST(make_lazy_matrix, reference)
{
// functor may be stored by reference (already implicitly tested above)
struct C
{
explicit C(int k) : k(k) { }
C(const C &) = delete;
C(C&&) = delete;
int operator()(size_t i) { return i * k; }
private:
int k;
};
C c(3);
auto v = euler::make_lazy_vector(100, c);
EXPECT_EQ(15, v[5]);
}
#endif
| 25.958333
| 76
| 0.618423
|
fancidev
|
ef1bb44fb921624b5cf6e776d8e9051d5afe4df9
| 3,845
|
hpp
|
C++
|
include/stl2/detail/concepts/object.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
include/stl2/detail/concepts/object.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
include/stl2/detail/concepts/object.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
// Copyright Eric Niebler 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_CONCEPTS_OBJECT_HPP
#define STL2_DETAIL_CONCEPTS_OBJECT_HPP
#include <stl2/detail/fwd.hpp>
#include <stl2/detail/meta.hpp>
#include <stl2/detail/concepts/core.hpp>
#include <stl2/detail/concepts/object/assignable.hpp>
#include <stl2/detail/concepts/object/regular.hpp>
STL2_OPEN_NAMESPACE {
///////////////////////////////////////////////////////////////////////////
// __f [Implementation detail, at least for now]
//
// Utility alias that simplifies the specification of forwarding functions
// whose target will eventually accept a parameter by value. E.g., the
// range overload of find:
//
// template<InputRange Rng, class T, class Proj = identity>
// requires IndirectRelation<equal_to<>,
// projected<iterator_t<Rng>, Proj>, const T*>()
// safe_iterator_t<Rng>
// find(Rng&& rng, const T& value, Proj proj = Proj{});
//
// can be implemented to perfect-forward to the iterator overload as:
//
// template<InputRange Rng, class T, class Proj = identity>
// requires IndirectRelation<equal_to<>,
// projected<iterator_t<Rng>, __f<Proj>>, // NW: __f<Proj>
// const T*>()
// safe_iterator_t<Rng>
// find(Rng&& rng, const T& value, Proj&& proj = Proj{}) {
// return find(begin(rng), end(rng), value, forward<Proj>(proj));
// }
//
// __f<Proj> is an alias for the decayed type that will eventually
// be used in the target function, and its constraints ensure that
// the decayed type can in fact be constructed from the actual type.
//
template<class T>
requires Constructible<decay_t<T>, T>
using __f = decay_t<T>;
namespace ext {
///////////////////////////////////////////////////////////////////////////
// 'structible object concepts
//
template<class T>
concept bool DestructibleObject = Object<T> && Destructible<T>;
template<class T, class... Args>
concept bool ConstructibleObject = Object<T> && Constructible<T, Args...>;
template<class T>
concept bool DefaultConstructibleObject = Object<T> && DefaultConstructible<T>;
template<class T>
concept bool MoveConstructibleObject = Object<T> && MoveConstructible<T>;
template<class T>
concept bool CopyConstructibleObject = Object<T> && CopyConstructible<T>;
///////////////////////////////////////////////////////////////////////////
// TriviallyFoo concepts
//
template<class T>
concept bool TriviallyDestructible =
Destructible<T> && _Is<T, is_trivially_destructible>;
template<class T, class... Args>
concept bool TriviallyConstructible =
Constructible<T, Args...> &&
_Is<T, is_trivially_constructible, Args...>;
template<class T>
concept bool TriviallyDefaultConstructible =
DefaultConstructible<T> &&
_Is<T, is_trivially_default_constructible>;
template<class T>
concept bool TriviallyMoveConstructible =
MoveConstructible<T> && _Is<T, is_trivially_move_constructible>;
template<class T>
concept bool TriviallyCopyConstructible =
CopyConstructible<T> &&
TriviallyMoveConstructible<T> &&
_Is<T, is_trivially_copy_constructible>;
template<class T>
concept bool TriviallyMovable =
Movable<T> &&
TriviallyMoveConstructible<T> &&
_Is<T, is_trivially_move_assignable>;
template<class T>
concept bool TriviallyCopyable =
Copyable<T> &&
TriviallyMovable<T> &&
TriviallyCopyConstructible<T> &&
_Is<T, is_trivially_copy_assignable>;
}
} STL2_CLOSE_NAMESPACE
#endif
| 32.863248
| 81
| 0.668661
|
marehr
|
ef1d20dd2d6215d9a198a449b4827b7db8ad6224
| 31,091
|
cpp
|
C++
|
circe/gl/graphics/ibl.cpp
|
gui-works/circe
|
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
|
[
"MIT"
] | 1
|
2021-09-17T18:12:47.000Z
|
2021-09-17T18:12:47.000Z
|
circe/gl/graphics/ibl.cpp
|
gui-works/circe
|
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
|
[
"MIT"
] | null | null | null |
circe/gl/graphics/ibl.cpp
|
gui-works/circe
|
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
|
[
"MIT"
] | 2
|
2021-09-17T18:13:02.000Z
|
2021-09-17T18:16:21.000Z
|
/// Copyright (c) 2021, FilipeCN.
///
/// The MIT License (MIT)
///
/// 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 irradiance_map.cpp.c
///\author FilipeCN (filipedecn@gmail.com)
///\date 2021-05-16
///
///\brief
#include "ibl.h"
#include <circe/gl/io/framebuffer.h>
#include <circe/gl/scene/scene_model.h>
#include <circe/gl/graphics/shader.h>
#include <circe/scene/shapes.h>
namespace circe::gl {
void renderToCube(Framebuffer &framebuffer,
Program &program,
const Texture &envmap,
Texture &cubemap,
GLint mip_level,
const hermes::size2 &resolution) {
SceneModel cube;
cube = circe::Shapes::box({{-1, -1, -1}, {1, 1, 1}});
auto projection = hermes::Transform::perspective(90, 1, 0.1, 10);
hermes::Transform views[] = {
hermes::Transform::lookAt({}, {1, 0, 0}, {0, -1, 0}),
hermes::Transform::lookAt({}, {-1, 0, 0}, {0, -1, 0}),
hermes::Transform::lookAt({}, {0, 1, 0}, {0, 0, -1}),
hermes::Transform::lookAt({}, {0, -1, 0}, {0, 0, 1}),
hermes::Transform::lookAt({}, {0, 0, -1}, {0, -1, 0}),
hermes::Transform::lookAt({}, {0, 0, 1}, {0, -1, 0}),
};
framebuffer.resize(resolution);
framebuffer.enable();
glViewport(0, 0, resolution.width, resolution.height);
envmap.bind(GL_TEXTURE0);
program.use();
program.setUniform("environmentMap", 0);
program.setUniform("projection", projection);
for (u32 i = 0; i < 6; ++i) {
program.setUniform("view", views[i]);
framebuffer.attachColorBuffer(cubemap.textureObjectId(),
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
GL_COLOR_ATTACHMENT0,
mip_level);
framebuffer.enable();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cube.draw();
}
Framebuffer::disable();
}
Texture IBL::irradianceMap(const Texture &texture, const hermes::size2 &resolution) {
Texture imap;
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"out vec3 localPos; \n"
"uniform mat4 projection; \n"
"uniform mat4 view; \n"
"void main() { \n"
" localPos = aPos; \n"
" gl_Position = projection * view * vec4(localPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec4 FragColor; \n"
"in vec3 localPos; \n"
"uniform samplerCube environmentMap; \n"
"const float PI = 3.14159265359; \n"
"void main(){ \n"
" // the sample direction equals the hemisphere's orientation \n"
" vec3 N = normalize(localPos); \n"
"vec3 irradiance = vec3(0.0); \n"
"vec3 up = vec3(0.0, 1.0, 0.0); \n"
"vec3 right = normalize(cross(up, N)); \n"
"up = normalize(cross(N, right)); \n"
"float sampleDelta = 0.025; \n"
"float nrSamples = 0.0; \n"
"for(float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta) { \n"
" for(float theta = 0.0; theta < 0.5 * PI; theta += sampleDelta) { \n"
" // spherical to cartesian (in tangent space) \n"
" vec3 tangentSample = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); \n"
" // tangent space to world \n"
" vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * N; \n"
" irradiance += texture(environmentMap, sampleVec).rgb * cos(theta) * sin(theta); \n"
" nrSamples++; \n"
" } \n"
"} \n"
"irradiance = PI * irradiance * (1.0 / float(nrSamples)); \n"
" FragColor = vec4(irradiance, 1.0); \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile irradiance map shader!\n" << program.err << std::endl;
// copy attributes
imap.setTarget(texture.target());
imap.setInternalFormat(texture.internalFormat());
imap.setFormat(texture.format());
imap.setType(texture.type());
imap.resize(resolution);
imap.bind();
Texture::View(GL_TEXTURE_CUBE_MAP).apply();
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
Framebuffer frambuffer;
frambuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
renderToCube(frambuffer, program, texture, imap, 0, resolution);
return imap;
}
Texture IBL::preFilteredEnvironmentMap(const Texture &input, const hermes::size2 &resolution) {
////////////////////////////////////// prepare texture //////////////////////////////////////////
Texture prefilter_map;
prefilter_map.setTarget(GL_TEXTURE_CUBE_MAP);
prefilter_map.setInternalFormat(input.internalFormat());
prefilter_map.setFormat(input.format());
prefilter_map.setType(input.type());
prefilter_map.resize(resolution);
prefilter_map.bind();
Texture::View view(GL_TEXTURE_CUBE_MAP);
view[GL_TEXTURE_MIN_FILTER] = GL_LINEAR_MIPMAP_LINEAR;
view.apply();
prefilter_map.generateMipmap();
prefilter_map.bind();
////////////////////////////////////// prepare shader //////////////////////////////////////////
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"out vec3 localPos; \n"
"uniform mat4 projection; \n"
"uniform mat4 view; \n"
"void main() { \n"
" localPos = aPos; \n"
" gl_Position = projection * view * vec4(localPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec4 FragColor; \n"
"in vec3 localPos; \n"
"uniform samplerCube environmentMap; \n"
"uniform float roughness; \n"
"const float PI = 3.14159265359; \n"
"float DistributionGGX(vec3 N, vec3 H, float roughness) { \n"
" float a = roughness*roughness; \n"
" float a2 = a*a; \n"
" float NdotH = max(dot(N, H), 0.0); \n"
" float NdotH2 = NdotH*NdotH; \n"
" float nom = a2; \n"
" float denom = (NdotH2 * (a2 - 1.0) + 1.0); \n"
" denom = PI * denom * denom; \n"
" return nom / denom; \n"
"} \n"
"float RadicalInverse_VdC(uint bits) { \n"
" bits = (bits << 16u) | (bits >> 16u); \n"
" bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); \n"
" bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); \n"
" bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); \n"
" bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); \n"
" return float(bits) * 2.3283064365386963e-10; // / 0x100000000 \n"
"} \n"
"vec2 Hammersley(uint i, uint N) { \n"
" return vec2(float(i)/float(N), RadicalInverse_VdC(i)); \n"
"} \n"
"vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { \n"
" float a = roughness*roughness; \n"
" float phi = 2.0 * PI * Xi.x; \n"
" float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); \n"
" float sinTheta = sqrt(1.0 - cosTheta*cosTheta); \n"
" // from spherical coordinates to cartesian coordinates \n"
" vec3 H; \n"
" H.x = cos(phi) * sinTheta; \n"
" H.y = sin(phi) * sinTheta; \n"
" H.z = cosTheta; \n"
" // from tangent-space vector to world-space sample vector \n"
" vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); \n"
" vec3 tangent = normalize(cross(up, N)); \n"
" vec3 bitangent = cross(N, tangent); \n"
" vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; \n"
" return normalize(sampleVec); \n"
"} \n"
"void main() { \n"
" vec3 N = normalize(localPos); \n"
" vec3 R = N; \n"
" vec3 V = R; \n"
" const uint SAMPLE_COUNT = 1024u; \n"
" float totalWeight = 0.0; \n"
" vec3 prefilteredColor = vec3(0.0); \n"
" for(uint i = 0u; i < SAMPLE_COUNT; ++i) { \n"
" vec2 Xi = Hammersley(i, SAMPLE_COUNT); \n"
" vec3 H = ImportanceSampleGGX(Xi, N, roughness); \n"
" vec3 L = normalize(2.0 * dot(V, H) * H - V); \n"
" float NdotL = max(dot(N, L), 0.0); \n"
" if(NdotL > 0.0) { \n"
" // sample from the environment's mip level based on roughness/pdf \n"
" float D = DistributionGGX(N, H, roughness); \n"
" float NdotH = max(dot(N, H), 0.0); \n"
" float HdotV = max(dot(H, V), 0.0); \n"
" float pdf = D * NdotH / (4.0 * HdotV) + 0.0001; \n"
" float resolution = 512.0; // resolution of source cubemap (per face) \n"
" float saTexel = 4.0 * PI / (6.0 * resolution * resolution); \n"
" float saSample = 1.0 / (float(SAMPLE_COUNT) * pdf + 0.0001); \n"
" float mipLevel = roughness == 0.0 ? 0.0 : 0.5 * log2(saSample / saTexel); \n"
" prefilteredColor += textureLod(environmentMap, L, mipLevel).rgb * NdotL; \n"
" totalWeight += NdotL; \n"
" } \n"
" } \n"
" prefilteredColor = prefilteredColor / totalWeight; \n"
" FragColor = vec4(prefilteredColor, 1.0); \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile IBL::prefilter map shader!\n" << program.err << std::endl;
////////////////////////////////////// prepare shader //////////////////////////////////////////
Framebuffer framebuffer;
framebuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
////////////////////////////////////// filter /////////////////////////////////////////////////
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
unsigned int max_mip_levels = 5;
for (unsigned int mip = 0; mip < max_mip_levels; ++mip) {
u32 mip_width = 128 * std::pow(0.5, mip);
u32 mip_height = 128 * std::pow(0.5, mip);
f32 roughness = (float) mip / (float) (max_mip_levels - 1);
program.use();
program.setUniform("roughness", roughness);
renderToCube(framebuffer, program, input, prefilter_map, mip, {mip_width, mip_height});
}
return prefilter_map;
}
Texture IBL::brdfIntegrationMap(const hermes::size2 &resolution) {
////////////////////////////////////// prepare shader //////////////////////////////////////////
std::string vs = "#version 330 core \n"
"layout (location = 0) in vec3 aPos; \n"
"layout (location = 1) in vec2 aTexCoords; \n"
"out vec2 TexCoords; \n"
"void main() { \n"
" TexCoords = aTexCoords; \n"
" gl_Position = vec4(aPos, 1.0); \n"
"}";
std::string fs = "#version 330 core \n"
"out vec2 FragColor; \n"
"in vec2 TexCoords; \n"
"const float PI = 3.14159265359; \n"
"float RadicalInverse_VdC(uint bits) { \n"
" bits = (bits << 16u) | (bits >> 16u); \n"
" bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); \n"
" bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); \n"
" bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); \n"
" bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); \n"
" return float(bits) * 2.3283064365386963e-10; // / 0x100000000 \n"
"} \n"
"vec2 Hammersley(uint i, uint N) { \n"
" return vec2(float(i)/float(N), RadicalInverse_VdC(i)); \n"
"} \n"
"vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) { \n"
" float a = roughness*roughness; \n"
" float phi = 2.0 * PI * Xi.x; \n"
" float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); \n"
" float sinTheta = sqrt(1.0 - cosTheta*cosTheta); \n"
" // from spherical coordinates to cartesian coordinates \n"
" vec3 H; \n"
" H.x = cos(phi) * sinTheta; \n"
" H.y = sin(phi) * sinTheta; \n"
" H.z = cosTheta; \n"
" // from tangent-space vector to world-space sample vector \n"
" vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); \n"
" vec3 tangent = normalize(cross(up, N)); \n"
" vec3 bitangent = cross(N, tangent); \n"
" vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; \n"
" return normalize(sampleVec); \n"
"} \n"
"float GeometrySchlickGGX(float NdotV, float roughness) { \n"
" // note that we use a different k for IBL \n"
" float a = roughness; \n"
" float k = (a * a) / 2.0; \n"
" float nom = NdotV; \n"
" float denom = NdotV * (1.0 - k) + k; \n"
" return nom / denom; \n"
"} \n"
"float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) { \n"
" float NdotV = max(dot(N, V), 0.0); \n"
" float NdotL = max(dot(N, L), 0.0); \n"
" float ggx2 = GeometrySchlickGGX(NdotV, roughness); \n"
" float ggx1 = GeometrySchlickGGX(NdotL, roughness); \n"
" return ggx1 * ggx2; \n"
"} \n"
"vec2 IntegrateBRDF(float NdotV, float roughness) { \n"
" vec3 V; \n"
" V.x = sqrt(1.0 - NdotV*NdotV); \n"
" V.y = 0.0; \n"
" V.z = NdotV; \n"
" float A = 0.0; \n"
" float B = 0.0; \n"
" vec3 N = vec3(0.0, 0.0, 1.0); \n"
" const uint SAMPLE_COUNT = 1024u; \n"
" for(uint i = 0u; i < SAMPLE_COUNT; ++i) { \n"
" // generates a sample vector that's biased towards the \n"
" // preferred alignment direction (importance sampling). \n"
" vec2 Xi = Hammersley(i, SAMPLE_COUNT); \n"
" vec3 H = ImportanceSampleGGX(Xi, N, roughness); \n"
" vec3 L = normalize(2.0 * dot(V, H) * H - V); \n"
" float NdotL = max(L.z, 0.0); \n"
" float NdotH = max(H.z, 0.0); \n"
" float VdotH = max(dot(V, H), 0.0); \n"
" if(NdotL > 0.0) { \n"
" float G = GeometrySmith(N, V, L, roughness); \n"
" float G_Vis = (G * VdotH) / (NdotH * NdotV); \n"
" float Fc = pow(1.0 - VdotH, 5.0); \n"
" A += (1.0 - Fc) * G_Vis; \n"
" B += Fc * G_Vis; \n"
" } \n"
" } \n"
" A /= float(SAMPLE_COUNT); \n"
" B /= float(SAMPLE_COUNT); \n"
" return vec2(A, B); \n"
"} \n"
"void main() { \n"
" vec2 integratedBRDF = IntegrateBRDF(TexCoords.x, TexCoords.y); \n"
" FragColor = integratedBRDF; \n"
"}";
Program program;
program.attach(Shader(GL_VERTEX_SHADER, vs));
program.attach(Shader(GL_FRAGMENT_SHADER, fs));
if (!program.link())
std::cerr << "failed to compile IBL::brdfIntegration map shader!\n" << program.err << std::endl;
////////////////////////////////////// prepare texture //////////////////////////////////////////
Texture brdf_i_map;
brdf_i_map.setTarget(GL_TEXTURE_2D);
brdf_i_map.setInternalFormat(GL_RG16F);
brdf_i_map.setFormat(GL_RG);
brdf_i_map.setType(GL_FLOAT);
brdf_i_map.resize(resolution);
brdf_i_map.bind();
Texture::View().apply();
////////////////////////////////////// generate texture /////////////////////////////////////////
SceneModel quad;
quad = Shapes::box({{-1, -1}, {1, 1}}, shape_options::uv);
program.use();
Framebuffer framebuffer;
framebuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24);
framebuffer.resize(resolution);
glViewport(0, 0, resolution.width, resolution.height);
framebuffer.attachTexture(brdf_i_map);
framebuffer.enable();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
quad.draw();
return brdf_i_map;
}
}
| 81.603675
| 119
| 0.298511
|
gui-works
|
ef1fc4f106139ad96d30385eb27447b40fdc5987
| 7,026
|
cxx
|
C++
|
source/boomhs/ui_debug.cxx
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 2
|
2016-07-22T10:09:21.000Z
|
2017-09-16T06:50:01.000Z
|
source/boomhs/ui_debug.cxx
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | 14
|
2016-08-13T22:45:56.000Z
|
2018-12-16T03:56:36.000Z
|
source/boomhs/ui_debug.cxx
|
bjadamson/BoomHS
|
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
|
[
"MIT"
] | null | null | null |
#include <boomhs/bounding_object.hpp>
#include <boomhs/camera.hpp>
#include <boomhs/components.hpp>
#include <boomhs/engine.hpp>
#include <boomhs/entity.hpp>
#include <boomhs/frame_time.hpp>
#include <boomhs/level_manager.hpp>
#include <boomhs/player.hpp>
#include <boomhs/tree.hpp>
#include <boomhs/view_frustum.hpp>
#include <extlibs/fmt.hpp>
#include <extlibs/glm.hpp>
#include <extlibs/imgui.hpp>
using namespace boomhs;
using namespace opengl;
using namespace gl_sdl;
namespace
{
void
draw_entity_editor(char const* prefix, int const window_flags, EngineState& es, LevelManager& lm,
EntityRegistry& registry, Camera& camera, glm::mat4 const& view_mat,
glm::mat4 const& proj_mat)
{
auto& logger = es.logger;
auto& zs = lm.active();
auto& gfx_state = zs.gfx_state;
auto& draw_handles = gfx_state.draw_handles;
auto& sps = gfx_state.sps;
auto& uistate = es.ui_state.debug;
auto const draw = [&]() {
std::optional<EntityID> selected;
for (auto const eid : find_all_entities_with_component<Selectable>(registry)) {
auto const& sel = registry.get<Selectable>(eid);
if (sel.selected) {
selected = eid;
break;
}
}
std::string const eid_str = selected ? std::to_string(*selected) : "none";
ImGui::Text("eid: %s", eid_str.c_str());
if (!selected) {
return;
}
ImGui::Checkbox("Lock Selected", &uistate.lock_debugselected);
auto const eid = *selected;
{
auto& isr = registry.get<IsRenderable>(eid).hidden;
ImGui::Checkbox("Hidden From Rendering", &isr);
}
if (registry.has<AABoundingBox>(eid) && registry.has<Transform>(eid)) {
auto const& tr = registry.get<Transform>(eid);
auto const& bbox = registry.get<AABoundingBox>(eid);
// TODO: view/proj matrix
bool const bbox_inside = ViewFrustum::bbox_inside(view_mat, proj_mat, tr, bbox);
std::string const msg = fmt::sprintf("In ViewFrustum: %i", bbox_inside);
ImGui::Text("%s", msg.c_str());
}
if (ImGui::Button("Inhabit Selected")) {
auto& transform = registry.get<Transform>(eid);
// camera.set_target(transform);
}
if (registry.has<Name>(eid)) {
auto& name = registry.get<Name>(eid).value;
char buffer[128] = {'0'};
FOR(i, name.size()) { buffer[i] = name[i]; }
ImGui::InputText(name.c_str(), buffer, IM_ARRAYSIZE(buffer));
}
if (registry.has<AABoundingBox>(eid)) {
if (ImGui::CollapsingHeader("BoundingBox Editor")) {
auto const& bbox = registry.get<AABoundingBox>(eid).cube;
ImGui::Text("min: %s", glm::to_string(bbox.min).c_str());
ImGui::Text("max: %s", glm::to_string(bbox.max).c_str());
}
}
if (ImGui::CollapsingHeader("Transform Editor")) {
auto& transform = registry.get<Transform>(eid);
ImGui::InputFloat3("pos:", glm::value_ptr(transform.translation));
{
glm::vec3 buffer = transform.get_rotation_degrees();
if (ImGui::InputFloat3("quat rot:", glm::value_ptr(buffer))) {
transform.rotation = glm::quat{glm::radians(buffer)};
}
ImGui::Text("euler rot:%s", glm::to_string(transform.get_rotation_degrees()).c_str());
}
ImGui::InputFloat3("scale:", glm::value_ptr(transform.scale));
}
if (registry.has<TreeComponent>(eid) && ImGui::CollapsingHeader("Tree Editor")) {
auto const make_str = [](char const* text, auto const num) {
return text + std::to_string(num);
};
auto& tc = registry.get<TreeComponent>(eid);
auto const edit_treecolor = [&](char const* name, auto const num_colors,
auto const& get_color) {
FOR(i, num_colors)
{
auto const text = make_str(name, i);
ImGui::ColorEdit4(text.c_str(), get_color(i), ImGuiColorEditFlags_Float);
}
};
edit_treecolor("Trunk", tc.num_trunks(),
[&tc](auto const i) { return tc.trunk_color(i).data(); });
edit_treecolor("Stem", tc.num_stems(),
[&tc](auto const i) { return tc.stem_color(i).data(); });
edit_treecolor("Leaves", tc.num_leaves(),
[&tc](auto const i) { return tc.leaf_color(i).data(); });
auto& sn = registry.get<ShaderName>(eid);
auto& va = sps.ref_sp(logger, sn.value).va();
auto& dinfo = draw_handles.lookup_entity(logger, eid);
Tree::update_colors(logger, va, dinfo, tc);
}
if (registry.has<PointLight>(eid) && ImGui::CollapsingHeader("Pointlight")) {
auto& transform = registry.get<Transform>(eid);
auto& pointlight = registry.get<PointLight>(eid);
auto& light = pointlight.light;
ImGui::InputFloat3("position:", glm::value_ptr(transform.translation));
ImGui::ColorEdit3("diffuse:", light.diffuse.data());
ImGui::ColorEdit3("specular:", light.specular.data());
ImGui::Separator();
ImGui::Text("Attenuation");
auto& attenuation = pointlight.attenuation;
ImGui::InputFloat("constant:", &attenuation.constant);
ImGui::InputFloat("linear:", &attenuation.linear);
ImGui::InputFloat("quadratic:", &attenuation.quadratic);
if (registry.has<LightFlicker>(eid)) {
ImGui::Separator();
ImGui::Text("Light Flicker");
auto& flicker = registry.get<LightFlicker>(eid);
ImGui::InputFloat("speed:", &flicker.current_speed);
FOR(i, flicker.colors.size())
{
auto& light = flicker.colors[i];
ImGui::ColorEdit4("color:", light.data(), ImGuiColorEditFlags_Float);
ImGui::Separator();
}
}
}
if (registry.has<Material>(eid) && ImGui::CollapsingHeader("Material")) {
auto& material = registry.get<Material>(eid);
ImGui::ColorEdit3("ambient:", glm::value_ptr(material.ambient));
ImGui::ColorEdit3("diffuse:", glm::value_ptr(material.diffuse));
ImGui::ColorEdit3("specular:", glm::value_ptr(material.specular));
ImGui::SliderFloat("shininess:", &material.shininess, 0.0f, 1.0f);
}
};
auto const title = std::string{prefix} + ":Entity Editor Window";
imgui_cxx::with_window(draw, title.c_str(), nullptr, window_flags);
}
} // namespace
namespace boomhs::ui_debug
{
void
draw(char const* prefix, int const window_flags, EngineState& es, LevelManager& lm, Camera& camera,
FrameTime const& ft)
{
auto& uistate = es.ui_state.debug;
auto& zs = lm.active();
auto& registry = zs.registry;
auto& ldata = zs.level_data;
auto& player = find_player(registry);
if (uistate.show_entitywindow) {
auto const fs = FrameState::from_camera(es, zs, camera, camera.view_settings_ref(), es.frustum);
auto const& view_mat = fs.view_matrix();
auto const& proj_mat = fs.projection_matrix();
draw_entity_editor(prefix, window_flags, es, lm, registry, camera, view_mat, proj_mat);
}
}
} // namespace boomhs::ui_debug
| 35.846939
| 100
| 0.62895
|
bjadamson
|
ef32badf6a2beccf2075ac54bfaf5f610cd2c05f
| 19,139
|
cpp
|
C++
|
MathTL/numerics/w_method.cpp
|
kedingagnumerikunimarburg/Marburg_Software_Library
|
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
|
[
"MIT"
] | 3
|
2018-05-20T15:25:58.000Z
|
2021-01-19T18:46:48.000Z
|
MathTL/numerics/w_method.cpp
|
agnumerikunimarburg/Marburg_Software_Library
|
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
|
[
"MIT"
] | null | null | null |
MathTL/numerics/w_method.cpp
|
agnumerikunimarburg/Marburg_Software_Library
|
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
|
[
"MIT"
] | 2
|
2019-04-24T18:23:26.000Z
|
2020-09-17T10:00:27.000Z
|
// implementation for w_method.h
#include <cmath>
#include <iostream>
#include <utils/array1d.h>
using std::cout;
using std::endl;
namespace MathTL
{
//template <class VECTOR>
template <class VECTOR, class IVP>
WMethodStageEquationHelper<VECTOR, IVP>::~WMethodStageEquationHelper()
{
}
template <class VECTOR>
WMethodPreprocessRHSHelper<VECTOR>::~WMethodPreprocessRHSHelper()
{
}
template <class VECTOR, class IVP>
WMethod<VECTOR, IVP>::WMethod(const Method method,
const WMethodStageEquationHelper<VECTOR,IVP>* s)
: stage_equation_helper(s), preprocessor(0)
{
LowerTriangularMatrix<double> Alpha, Gamma;
Vector<double> b, bhat;
double gamma;
switch(method)
{
case ROS2:
Alpha.resize(2,2);
Alpha.set_entry(1, 0, 1.0);
Gamma.resize(2,2);
gamma = 1.0 + M_SQRT1_2;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -2*gamma);
Gamma.set_entry(1, 1, gamma);
b.resize(2);
b[0] = b[1] = 0.5;
bhat.resize(2);
bhat[0] = 1.0;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 2;
break;
case RODAS3:
Alpha.resize(4,4);
Alpha.set_entry(2, 0, 1.);
Alpha.set_entry(3, 0, 3./4.);
Alpha.set_entry(3, 1, -1./4.);
Alpha.set_entry(3, 2, 1./2.);
Gamma.resize(4,4);
gamma = 0.5;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, 1.);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -1./4.);
Gamma.set_entry(2, 1, -1./4.);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, 1./12.);
Gamma.set_entry(3, 1, 1./12.);
Gamma.set_entry(3, 2, -2./3.);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 5./6.;
b[1] = b[2] = -1./6.;
b[3] = 1./2.;
bhat.resize(4);
bhat[0] = 3./4.;
bhat[1] = -1./4.;
bhat[2] = 1./2.;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3P:
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 1.);
Alpha.set_entry(2, 0, 1.);
Gamma.resize(3,3);
gamma = 0.5 + sqrt(3.)/6.;
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -1.);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -gamma);
Gamma.set_entry(2, 1, 0.5-2*gamma);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 2./3.;
b[2] = 1./3.;
bhat.resize(3);
bhat[0] = bhat[1] = bhat[2] = 1./3.;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROWDA3:
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 0.7);
Alpha.set_entry(2, 0, 0.7);
Gamma.resize(3,3);
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, 0.1685887625570998);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, 4.943922277836421);
Gamma.set_entry(2, 1, 1.);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 0.3197278911564624;
b[1] = 0.7714777906171382;
b[2] = -0.09120568177360061;
bhat.resize(3);
bhat[0] = 0.926163587124091;
bhat[1] = 0.073836412875909;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(3,3);
Alpha.set_entry(1, 0, gamma);
Alpha.set_entry(2, 0, gamma);
Gamma.resize(3,3);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -0.19294655696029095575009695436041);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 1, 1.74927148125794685173529749738960);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = -0.75457412385404315829818998646589;
b[1] = 1.94100407061964420292840123379419;
b[2] = -0.18642994676560104463021124732829;
bhat.resize(3);
bhat[0] = -1.53358745784149585370766523913002;
bhat[1] = 2.81745131148625772213931745457622;
bhat[2] = -0.28386385364476186843165221544619;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROS3Pw:
gamma = 0.5 + sqrt(3.)/6.;
Alpha.resize(3,3);
Alpha.set_entry(1, 0, 2*gamma);
Alpha.set_entry(2, 0, 0.5);
Gamma.resize(3,3);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -2*gamma);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -.67075317547305480);
Gamma.set_entry(2, 1, -.17075317547305482);
Gamma.set_entry(2, 2, gamma);
b.resize(3);
b[0] = 0.10566243270259355;
b[1] = 0.049038105676657971;
b[2] = 0.84529946162074843;
bhat.resize(3);
bhat[0] = -0.17863279495408180;
bhat[1] = 1./3.;
bhat[2] = 0.84529946162074843;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROSI2P2:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(4,4);
Alpha.set_entry(1, 0, 0.5);
Alpha.set_entry(2, 0, -0.51983699657507165);
Alpha.set_entry(2, 1, 1.5198369965750715);
Alpha.set_entry(3, 0, -0.51983699657507165);
Alpha.set_entry(3, 1, 1.5198369965750715);
Gamma.resize(4,4);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -0.5);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, -0.40164172503011392);
Gamma.set_entry(2, 1, 1.174271852697665);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, 1.1865036632417383);
Gamma.set_entry(3, 1, -1.5198369965750715);
Gamma.set_entry(3, 2, -0.10253318817512568);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 2./3.;
b[2] = -0.10253318817512568;
b[3] = 0.435866521508459;
bhat.resize(4);
bhat[0] = -0.95742384859111473;
bhat[1] = 2.9148476971822297;
bhat[2] = 0.5;
bhat[3] = -1.4574238485911146;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case ROSI2PW:
gamma = 0.43586652150845899941601945119356; // gamma^3-3*gamma^2+1.5*gamma-1/6=0
Alpha.resize(4,4);
Alpha.set_entry(1, 0, 8.7173304301691801e-1);
Alpha.set_entry(2, 0, -7.9937335839852708e-1);
Alpha.set_entry(2, 1, -7.9937335839852708e-1);
Alpha.set_entry(3, 0, 7.0849664917601007e-1);
Alpha.set_entry(3, 1, 3.1746327955312481e-1);
Alpha.set_entry(3, 2, -2.5959928729134892e-2);
Gamma.resize(4,4);
Gamma.set_entry(0, 0, gamma);
Gamma.set_entry(1, 0, -8.7173304301691801e-1);
Gamma.set_entry(1, 1, gamma);
Gamma.set_entry(2, 0, 3.0647867418622479);
Gamma.set_entry(2, 1, 3.0647867418622479);
Gamma.set_entry(2, 2, gamma);
Gamma.set_entry(3, 0, -1.0424832458800504e-1);
Gamma.set_entry(3, 1, -3.1746327955312481e-1);
Gamma.set_entry(3, 2, -1.4154917367329144e-2);
Gamma.set_entry(3, 3, gamma);
b.resize(4);
b[0] = 6.0424832458800504e-1;
b[2] = -4.0114846096464034e-2;
b[3] = 4.3586652150845900e-1;
bhat.resize(4);
bhat[0] = bhat[1] = 4.4315753191688778e-1;
bhat[3] = 1.1368493616622447e-1;
transform_coefficients(Alpha, Gamma, b, bhat,
A, C, m, e, alpha_vector, gamma_vector);
p = 3;
break;
case GRK4T:
A.resize(4,4); // corresponds to the [HW] notation
A(1,0) = 0.2000000000000000e+01;
A(2,0) = A(3,0) = 0.4524708207373116e+01;
A(2,1) = A(3,1) = 0.4163528788597648e+01;
C.resize(4,4); // corresponds to the [HW] notation
C(0,0) = C(1,1) = C(2,2) = C(3,3) = 0.231; // gamma
C(1,0) = -0.5071675338776316e+01;
C(2,0) = 0.6020152728650786e+01;
C(2,1) = 0.1597506846727117e+00;
C(3,0) = -0.1856343618686113e+01;
C(3,1) = -0.8505380858179826e+01;
C(3,2) = -0.2084075136023187e+01;
gamma_vector.resize(4); // corresponds to Di in [HW]
gamma_vector[0] = 0.2310000000000000e+00;
gamma_vector[1] = -0.3962966775244303e-01;
gamma_vector[2] = 0.5507789395789127e+00;
gamma_vector[3] = -0.5535098457052764e-01;
alpha_vector.resize(4); // corresponds to Ci in [HW]
alpha_vector[1] = 0.4620000000000000e+00;
alpha_vector[2] = alpha_vector[3]
= 0.8802083333333334e+00;
m.resize(4); // corresponds to Bi in [HW] (the m_i in the [HW II] book)
m[0] = 0.3957503746640777e+01;
m[1] = 0.4624892388363313e+01;
m[2] = 0.6174772638750108e+00;
m[3] = 0.1282612945269037e+01;
e.resize(4);
e[0] = 0.2302155402932996e+01;
e[1] = 0.3073634485392623e+01;
e[2] = -0.8732808018045032e+00;
e[3] = -0.1282612945269037e+01;
p = 4;
break;
case RODAS:
A.resize(6,6);
// values from KARDOS:
A(1,0) = 1.5440000000000000;
A(2,0) = 0.9466785281022800;
A(2,1) = 0.2557011699000000;
A(3,0) = 3.3148251870787937;
A(3,1) = 2.8961240159798773;
A(3,2) = 0.9986419140000000;
A(4,0) = 1.2212245090707980;
A(4,1) = 6.0191344810926299;
A(4,2) = 12.5370833291149566;
A(4,3) = -0.6878860361200000;
A(5,0) = 1.2212245092986209;
A(5,1) = 6.0191344813485754;
A(5,2) = 12.5370833293196604;
A(5,3) = -0.6878860360800001;
A(5,4) = 1.0000000000000000;
C.resize(6, 6);
C(0,0) = C(1,1) = C(2,2) = C(3,3)
= C(4,4) = C(5,5) = 0.25; // = gamma
C(1,0) = -5.6688000000000000;
C(2,0) = -2.4300933568670464;
C(2,1) = -0.2063599157120000;
C(3,0) = -0.1073529065055983;
C(3,1) = -9.5945622510667228;
C(3,2) = -20.4702861487999996;
C(4,0) = 7.4964433159050206;
C(4,1) = -10.2468043146053738;
C(4,2) = -33.9999035259299589;
C(4,3) = 11.7089089319999999;
C(5,0) = 8.0832467990118602;
C(5,1) = -7.9811329880455499;
C(5,2) = -31.5215943254324245;
C(5,3) = 16.3193054312706352;
C(5,4) = -6.0588182388799998;
// values from KARDOS:
gamma_vector.resize(6);
gamma_vector[0] = 0.2500000000000000;
gamma_vector[1] = -0.1043000000000000;
gamma_vector[2] = 0.1034999999980000;
gamma_vector[3] = -0.0362000000000000;
gamma_vector[4] = 0.0000000000000000;
gamma_vector[5] = 0.0000000000000000;
// values from KARDOS:
alpha_vector.resize(6);
alpha_vector[0] = 0.0000000000000000;
alpha_vector[1] = 0.3860000000000000;
alpha_vector[2] = 0.2100000000000000;
alpha_vector[3] = 0.6300000000000000;
alpha_vector[4] = 1.0000000000000000;
alpha_vector[5] = 1.0000000000000000;
// values from KARDOS:
m.resize(6);
m[0] = 1.2212245092981915;
m[1] = 6.0191344813101981;
m[2] = 12.5370833292377792;
m[3] = -0.6878860360960002;
m[4] = 1.0000000000000000;
m[5] = 1.0000000000000000;
e.resize(6);
e[0] = 0.0;
e[1] = 0.0;
e[2] = 0.0;
e[3] = 0.0;
e[4] = 0.0;
e[5] = m[5];
p = 4;
break;
case RODASP:
A.resize(6, 6);
// values from KARDOS:
A(1,0) = 3.0000000000000000;
A(2,0) = 1.8310367935359999;
A(2,1) = 0.4955183967600000;
A(3,0) = 2.3043765826379414;
A(3,1) = -0.0524927524844542;
A(3,2) = -1.1767987618400000;
A(4,0) = -7.1704549640449367;
A(4,1) = -4.7416366720041934;
A(4,2) = -16.3100263134518535;
A(4,3) = -1.0620040441200000;
A(5,0) = -7.1704549641649340;
A(5,1) = -4.7416366720441925;
A(5,2) = -16.3100263134518570;
A(5,3) = -1.0620040441200000;
A(5,4) = 1.0000000000000000;
C.resize(6, 6);
C(0,0) = C(1,1) = C(2,2) = C(3,3)
= C(4,4) = C(5,5) = 0.25; // = gamma
// values from KARDOS:
C(1,0) = -12.0000000000000000;
C(2,0) = -8.7917951740800000;
C(2,1) = -2.2078655870400000;
C(3,0) = 10.8179305689176530;
C(3,1) = 6.7802706116824574;
C(3,2) = 19.5348594463999987;
C(4,0) = 34.1909500739412096;
C(4,1) = 15.4967115394459682;
C(4,2) = 54.7476087604061235;
C(4,3) = 14.1600539214399994;
C(5,0) = 34.6260583162319335;
C(5,1) = 15.3008497633150125;
C(5,2) = 56.9995557863878588;
C(5,3) = 18.4080700977581699;
C(5,4) = -5.7142857142399999;
// values from KARDOS:
gamma_vector.resize(6);
gamma_vector[0] = 0.2500000000000000;
gamma_vector[1] = -0.5000000000000000;
gamma_vector[2] = -0.0235040000000000;
gamma_vector[3] = -0.0362000000000000;
gamma_vector[4] = 0.0 ;
gamma_vector[5] = 0.0 ;
// values from KARDOS:
alpha_vector.resize(6);
alpha_vector[0] = 0.0;
alpha_vector[1] = 0.75;
alpha_vector[2] = 0.21;
alpha_vector[3] = 0.63;
alpha_vector[4] = 1.0;
alpha_vector[5] = 1.0;
// values from KARDOS:
m.resize(6);
m[0] = -7.1704549641649322;
m[1] = -4.7416366720441925;
m[2] = -16.3100263134518570;
m[3] = -1.0620040441200000;
m[4] = 1.0000000000000000;
m[5] = 1.0000000000000000;
e.resize(6);
e[0] = 0.0;
e[1] = 0.0;
e[2] = 0.0;
e[3] = 0.0;
e[4] = 0.0;
e[5] = m[5];
p = 4;
break;
default:
break;
}
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::transform_coefficients(const LowerTriangularMatrix<double>& Alpha,
const LowerTriangularMatrix<double>& Gamma,
const Vector<double>& b,
const Vector<double>& bhat,
LowerTriangularMatrix<double>& A,
LowerTriangularMatrix<double>& C,
Vector<double>& m,
Vector<double>& e,
Vector<double>& alpha_vector,
Vector<double>& gamma_vector)
{
const unsigned int s = Alpha.row_dimension();
alpha_vector.resize(s, true);
for (unsigned int i = 0; i < s; i++) {
double alphai = 0;
for (unsigned int j = 0; j < i; j++) alphai += Alpha.get_entry(i, j);
alpha_vector[i] = alphai;
}
gamma_vector.resize(s, true);
for (unsigned int i = 0; i < s; i++) {
double gammai = 0;
// note that here, we use "j<=i" (compare order condition check below):
for (unsigned int j = 0; j <= i; j++) gammai += Gamma.get_entry(i, j);
gamma_vector[i] = gammai;
}
Gamma.inverse(C);
A.resize(s, s);
A = Alpha * C; // A = Alpha * Gamma^{-1}
m.resize(s, false);
C.apply_transposed(b, m); // m^T = b^T * Gamma^{-1}
e.resize(s, true);
C.apply_transposed(bhat, e);
e.sadd(-1.0, m); // e = m-mhat
C.scale(-1.0);
for (unsigned int i = 0; i < s; i++)
C.set_entry(i, i, Gamma.get_entry(0,0)); // gamma
// cout << "* coefficients after transform_coefficients():" << endl;
// cout << "alpha_vector=" << alpha_vector << endl;
// cout << "gamma_vector=" << gamma_vector << endl;
// cout << "A=" << endl << A;
// cout << "C=" << endl << C;
// cout << "m=" << m << endl;
// cout << "e=" << e << endl;
// check_order_conditions(Alpha, Gamma, b, bhat, false);
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::check_order_conditions(const LowerTriangularMatrix<double>& Alpha,
const LowerTriangularMatrix<double>& Gamma,
const Vector<double>& b,
const Vector<double>& bhat,
const bool wmethod)
{
cout << "* checking algebraic order conditions for a ROW method:" << endl;
const unsigned int s = Alpha.row_dimension();
double help, gamma = Gamma.get_entry(0,0);
LowerTriangularMatrix<double> Beta(s, s);
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
Beta.set_entry(i, j, Alpha.get_entry(i, j) + Gamma.get_entry(i, j));
Vector<double> alpha_vector(s);
for (unsigned int i = 0; i < s; i++) {
double alphai = 0;
for (unsigned int j = 0; j < i; j++) alphai += Alpha.get_entry(i, j);
alpha_vector[i] = alphai;
}
cout << " alpha_vector=" << alpha_vector << endl;
Vector<double> gamma_vector(s);
for (unsigned int i = 0; i < s; i++) {
double gammai = 0;
// for the order conditions, we use gamma_i=sum_{j<i}gamma_j (not "<=" as in transform_coefficients())
for (unsigned int j = 0; j < i; j++) gammai += Gamma.get_entry(i, j);
gamma_vector[i] = gammai;
}
cout << " gamma_vector=" << gamma_vector << endl;
Vector<double> beta_vector(alpha_vector+gamma_vector);
cout << " beta_vector=" << beta_vector << endl;
cout << " (A1) (sum_i b_i)-1=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i];
cout << help-1 << endl;
cout << " (A2) (sum_i b_i beta_i)-(1/2-gamma)=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i] * beta_vector[i];
cout << help-(0.5-gamma) << endl;
cout << " (A3a) (sum_i b_i alpha_i^2)-1/3=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += b[i] * alpha_vector[i] * alpha_vector[i];
cout << help-1./3. << endl;
cout << " (A3b) (sum_{i,j} b_i beta_{i,j} beta_j)-(1/6-gamma+gamma^2)=";
help = 0;
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
help += b[i] * Beta.get_entry(i,j) * beta_vector[j];
cout << help-1./6.+gamma-gamma*gamma << endl;
cout << " (A1) (sum_i bhat_i)-1=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i];
cout << help-1 << endl;
cout << " (A2) (sum_i bhat_i beta_i)-(0.5-gamma)=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i] * beta_vector[i];
cout << help-(0.5-gamma) << endl;
cout << " (A3a) (sum_i bhat_i alpha_i^2)-1/3=";
help = 0;
for (unsigned int i = 0; i < s; i++) help += bhat[i] * alpha_vector[i] * alpha_vector[i];
cout << help-1./3. << endl;
cout << " (A3b) (sum_{i,j} bhat_i beta_{i,j} beta_j)-(1/6-gamma+gamma^2)=";
help = 0;
for (unsigned int i = 0; i < s; i++)
for (unsigned int j = 0; j < i; j++)
help += bhat[i] * Beta.get_entry(i,j) * beta_vector[j];
cout << help-1./6.+gamma-gamma*gamma << endl;
}
template <class VECTOR, class IVP>
void
WMethod<VECTOR, IVP>::increment(IVP* ivp,
const double t_m, const VECTOR& u_m,
const double tau,
VECTOR& u_mplus1,
VECTOR& error_estimate,
const double tolerance) const
{
const unsigned int stages = A.row_dimension(); // for readability
Array1D<VECTOR> u(stages);
u[0] = u_m; u[0].scale(0.0); // ensures correct size
for (unsigned int i = 1; i < stages; i++)
u[i] = u[0];
VECTOR rhs(u[0]), help(u[0]); // ensures correct size
// solve stage equations (TODO: adjust the tolerances appropriately)
for (unsigned int i(0); i < stages; i++) {
// setup i-th right-hand side
// f(t_m + \tau * \alpha_i, u^{(m)} + \sum_{j=1}^{i-1} a_{i,j} * u_j)
// + \sum_{j=1}^{i-1} \frac{c_{i,j}}{\tau} * u_j
// + \tau * \gamma_i * g
help = u_m;
for (unsigned int j(0); j < i; j++)
help.add(A(i,j), u[j]);
ivp->evaluate_f(t_m+tau*alpha_vector[i], help, tolerance/(4*stages), rhs);
if (preprocessor == 0) { // no preprocessing necessary
for (unsigned int j(0); j < i; j++)
rhs.add(C(i,j)/tau, u[j]);
} else {
help.scale(0.0);
for (unsigned int j(0); j < i; j++)
help.add(C(i,j)/tau, u[j]);
preprocessor->preprocess_rhs_share(help, tolerance/(4*stages));
rhs.add(help);
}
stage_equation_helper->approximate_ft(ivp, t_m, u_m, tolerance/(4*stages), help);
rhs.add(tau*gamma_vector[i], help);
// solve i-th stage equation
// (\tau*\gamma_{i,i})^{-1}I - T) u_i = rhs
stage_equation_helper->solve_W_stage_equation(ivp, t_m, u_m, 1./(tau*C(i,i)), rhs, tolerance/(4*stages), u[i]);
}
// update u^{(m)} -> u^{(m+1)} by the k_i
u_mplus1 = u_m;
for (unsigned int i(0); i < stages; i++)
u_mplus1.add(m[i], u[i]);
// error estimate
error_estimate = u_m; error_estimate.scale(0.0); // ensures correct size
for (unsigned int i = 0; i < stages; i++)
error_estimate.add(e[i], u[i]);
}
}
| 28.27031
| 117
| 0.613512
|
kedingagnumerikunimarburg
|
ef394300d536a95e9ba8a0a364041c1b17a7529e
| 1,047
|
hpp
|
C++
|
NYPR/CharacterSegment/NYCharacterPartition.hpp
|
iwwee/PLR_Vision
|
bda2384c10546479860bcc351757737385c9a251
|
[
"Apache-2.0"
] | 3
|
2021-04-30T06:05:38.000Z
|
2022-02-16T08:06:33.000Z
|
NYPR/CharacterSegment/NYCharacterPartition.hpp
|
iwwee/PLR_Vision
|
bda2384c10546479860bcc351757737385c9a251
|
[
"Apache-2.0"
] | null | null | null |
NYPR/CharacterSegment/NYCharacterPartition.hpp
|
iwwee/PLR_Vision
|
bda2384c10546479860bcc351757737385c9a251
|
[
"Apache-2.0"
] | 1
|
2021-04-30T06:05:51.000Z
|
2021-04-30T06:05:51.000Z
|
//
// NYCharacterPartition.hpp
// NYPlateRecognition
//
// Created by NathanYu on 28/01/2018.
// Copyright © 2018 NathanYu. All rights reserved.
//
#ifndef NYCharacterPartition_hpp
#define NYCharacterPartition_hpp
#include <stdio.h>
#include <algorithm>
#include "NYPlateDetect.hpp"
class NYCharacterPartition {
public:
// 划分车牌上的字符
vector<NYCharacter> divideCharacters(NYPlate &plate);
private:
void sortCharsRects(vector<cv::Rect> rectVec, vector<cv::Rect> &outRect);
// 清除车牌上的柳钉
bool clearLiuDing(Mat &src);
// 清除车牌上下边框并记录字符上下边缘
void clearTopAndBottomBorder(Mat &src, vector<int> &borderVec);
// 清除车牌左右边框,并记录每个字符的左右侧位置
void clearLeftAndRightBorder(Mat &src, vector<int> &borderVec);
// 判断车牌字符尺寸
bool verifyCharSizes(Mat src);
// 寻找字符分割点
void findSplitPoints(Mat src, vector<int> &charsLoc);
// 将字符Mat调整为标准尺寸
Mat resizeToNormalCharSize(Mat char_mat);
};
#endif /* NYCharacterPartition_hpp */
| 13.96
| 77
| 0.663801
|
iwwee
|
ef3aefc073928005abc8d0961302b01c4a423a88
| 682
|
cpp
|
C++
|
kattis/problems/the_easiest_problem_is_this_one.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-07-16T01:46:38.000Z
|
2020-07-16T01:46:38.000Z
|
kattis/problems/the_easiest_problem_is_this_one.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | null | null | null |
kattis/problems/the_easiest_problem_is_this_one.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-05-27T14:30:43.000Z
|
2020-05-27T14:30:43.000Z
|
#include <iostream>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
unsigned int digits_sum(unsigned int number)
{
unsigned int sum {0};
for (unsigned int i {number}; i > 0; i /= 10)
{
sum += i % 10;
}
return sum;
}
int main()
{
use_io_optimizations();
for (unsigned int number; cin >> number && number != 0; )
{
unsigned int sum {digits_sum(number)};
unsigned int multiplier {11};
while (sum != digits_sum(number * multiplier))
{
++multiplier;
}
cout << multiplier << '\n';
}
return 0;
}
| 15.860465
| 61
| 0.555718
|
Rkhoiwal
|
ef3bcf31d6bf69c0f6f86ef376438b0dbeb757d7
| 5,115
|
hpp
|
C++
|
src/main/generic_format/helper.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
src/main/generic_format/helper.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
src/main/generic_format/helper.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
/**
@file
@copyright
Copyright Sebastien Wagener 2014
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)
*/
#pragma once
#include <type_traits>
#include <functional>
namespace generic_format {
/// @brief Depending on the value of the bool, return T1 or T2.
template <bool b, typename T1, typename T2>
struct conditional_type {
using type = T1;
};
template <typename T1, typename T2>
struct conditional_type<false, T1, T2> {
using type = T2;
};
namespace detail {
// This will get easier with C++14.
template <class Operator, typename... Ts>
struct folder;
template <class Operator>
struct folder<Operator> {
using value_type = typename Operator::result_type;
constexpr folder(Operator)
: result{} { }
value_type result;
};
template <class Operator, typename T>
struct folder<Operator, T> {
using value_type = typename Operator::result_type;
constexpr folder(Operator, T t)
: result{t} { }
value_type result;
};
template <class Operator, typename T1, typename T2, typename... Ts>
struct folder<Operator, T1, T2, Ts...> {
using value_type = typename Operator::result_type;
constexpr folder(Operator op, T1 t1, T2 t2, Ts... ts)
: result{folder<Operator, value_type, Ts...>(op, op(t1, t2), ts...).result} { }
value_type result;
};
template <class T>
struct constexpr_plus {
constexpr T operator()(const T& x, const T& y) const {
return x + y;
}
typedef T first_argument_type;
typedef T second_argument_type;
typedef T result_type;
};
} // end namespace detail
template <class Operator, typename... Ts>
constexpr typename Operator::result_type fold_left(Operator op, Ts... ts) {
return detail::folder<Operator, Ts...>(op, ts...).result;
}
template <class T, typename... Ts>
constexpr T sum(T initial_value, Ts... ts) {
return fold_left(detail::constexpr_plus<T>(), initial_value, ts...);
}
namespace variadic {
template <class... Elements>
struct generic_list { };
/// @brief Insert an element at the end of a generic list.
template <class List, class NewElement>
struct append_element;
template <class NewElement, class... Elements>
struct append_element<generic_list<Elements...>, NewElement> {
using type = generic_list<Elements..., NewElement>;
};
/// @brief Merge two generic lists
template <class List1, class List2>
struct merge_generic_lists;
template <class... Elements>
struct merge_generic_lists<generic_list<Elements...>, generic_list<>> {
using type = generic_list<Elements...>;
};
template <class List1, class Element2, class... Elements2>
struct merge_generic_lists<List1, generic_list<Element2, Elements2...>> {
using new_list1 = typename append_element<List1, Element2>::type;
using new_list2 = generic_list<Elements2...>;
using type = typename merge_generic_lists<new_list1, new_list2>::type;
};
// TODO(sw) document
template <template <class> class Function, class List, class Acc = generic_list<>>
struct transform;
template <template <class> class Function, class Acc>
struct transform<Function, generic_list<>, Acc> {
using type = Acc;
};
template <template <class> class Function, class Acc, class Element, class... Elements>
struct transform<Function, generic_list<Element, Elements...>, Acc> {
private:
using new_acc = typename append_element<Acc, typename Function<Element>::type>::type;
using new_list = generic_list<Elements...>;
public:
using type = typename transform<Function, new_list, new_acc>::type;
};
/** @brief Tests whether a predicate holds for some variadic arguments.
*
* Provides the member constant value equal true if Predicate holds for at least one argument, else value is false.
*/
template <template <class> class Predicate, class... Args>
struct for_any : std::false_type { };
template <template <class> class Predicate, class Arg, class... Args>
struct for_any<Predicate, Arg, Args...> : std::integral_constant<bool, Predicate<Arg>::value || for_any<Predicate, Args...>::value> { };
namespace detail {
template <template <class> class Predicate, std::size_t N, class... Args>
struct index_of_helper : std::integral_constant<std::size_t, N> { };
template <template <class> class Predicate, std::size_t N, class Arg, class... Args>
struct index_of_helper<Predicate, N, Arg, Args...>
: std::integral_constant<std::size_t, Predicate<Arg>::value ? N : index_of_helper<Predicate, N + 1, Args...>::value> { };
} // end namespace detail
/** @brief Finds an argument matching a predicate.
*
* Provides the index of the first occurrence of Args satisfying Predicate.
* Fails at compile-time if not argument matches the predicate.
*/
template <template <class> class Predicate, class... Args>
struct index_of {
static constexpr auto value = detail::index_of_helper<Predicate, 0, Args...>::value;
static_assert(value < sizeof...(Args), "Item not found in variadic argument list!");
};
} // end namespace variadic
} // end namespace generic_format
| 31.189024
| 136
| 0.709677
|
foobar27
|
ef3c43278e3760f822c1bea5894813bae7deb9b6
| 94
|
cpp
|
C++
|
bin/lib/base/main.cpp
|
johnsonyl/cpps
|
ed91be2c1107e3cfa8e91d159be81931eacfec19
|
[
"MIT"
] | 18
|
2017-09-01T04:59:23.000Z
|
2021-09-23T06:42:50.000Z
|
bin/lib/base/main.cpp
|
johnsonyl/cpps
|
ed91be2c1107e3cfa8e91d159be81931eacfec19
|
[
"MIT"
] | null | null | null |
bin/lib/base/main.cpp
|
johnsonyl/cpps
|
ed91be2c1107e3cfa8e91d159be81931eacfec19
|
[
"MIT"
] | 4
|
2017-06-15T08:46:07.000Z
|
2021-06-09T15:03:55.000Z
|
#include <lib/base/colorprint.cpp>
#include <lib/base/io.cpp>
#include <lib/base/thread.cpp>
| 31.333333
| 35
| 0.734043
|
johnsonyl
|
ef4236b6fc400ab751ba4cfcec44914237579f1c
| 1,080
|
cpp
|
C++
|
external/keko_enhanced_movement/babe_em/func/config.cpp
|
kellerkompanie/kellerkompanie-mods
|
f15704710f77ba6c018c486d95cac4f7749d33b8
|
[
"MIT"
] | 6
|
2018-05-05T22:28:57.000Z
|
2019-07-06T08:46:51.000Z
|
external/keko_enhanced_movement/babe_em/func/config.cpp
|
Schwaggot/kellerkompanie-mods
|
7a389e49e3675866dbde1b317a44892926976e9d
|
[
"MIT"
] | 107
|
2018-04-11T19:42:27.000Z
|
2019-09-13T19:05:31.000Z
|
external/keko_enhanced_movement/babe_em/func/config.cpp
|
kellerkompanie/kellerkompanie-mods
|
f15704710f77ba6c018c486d95cac4f7749d33b8
|
[
"MIT"
] | 3
|
2018-10-03T11:54:46.000Z
|
2019-02-28T13:30:16.000Z
|
////////////////////////////////////////////////////////////////////
//DeRap: babe_em\func\config.bin
//Produced from mikero's Dos Tools Dll version 6.44
//'now' is Tue Jun 12 14:55:49 2018 : 'file' last modified on Thu May 10 19:35:42 2018
//http://dev-heaven.net/projects/list_files/mikero-pbodll
////////////////////////////////////////////////////////////////////
#define _ARMA_
class DefaultEventhandlers;
class CfgPatches
{
class BABE_EM_FNC
{
units[] = {};
weapons[] = {};
requiredVersion = 0.1;
requiredAddons[] = {"A3_BaseConfig_F","babe_core_fnc"};
};
};
class CfgFunctions
{
class BABE_EM
{
tag = "BABE_EM";
class core
{
file = "\babe_em\func\core";
class init{};
};
class EH
{
file = "\babe_em\func\EH";
class handledamage_nofd{};
class animdone{};
};
class move
{
file = "\babe_em\func\mov";
class em{};
class exec_em{};
class finish_em{};
class exec_drop{};
class finish_drop{};
class jump{};
class jump_only{};
class detect{};
class detect_cl_only{};
class walkonstuff{};
};
};
};
| 20.377358
| 86
| 0.558333
|
kellerkompanie
|
ef48161b9469a60d2066b60b1488814f11acffaf
| 7,616
|
hpp
|
C++
|
Source/FFTMeter.hpp
|
hotwatermorning/LevelMeter
|
b052f51445870ea9135fcd65bc64542e237ac81c
|
[
"MIT"
] | 7
|
2016-08-04T08:30:01.000Z
|
2021-07-13T02:16:20.000Z
|
Source/FFTMeter.hpp
|
hotwatermorning/LevelMeter
|
b052f51445870ea9135fcd65bc64542e237ac81c
|
[
"MIT"
] | null | null | null |
Source/FFTMeter.hpp
|
hotwatermorning/LevelMeter
|
b052f51445870ea9135fcd65bc64542e237ac81c
|
[
"MIT"
] | null | null | null |
/*
==============================================================================
FFTMeter.h
Created: 19 Jan 2016 4:11:43pm
Author: yuasa
==============================================================================
*/
#ifndef FFTMETER_H_INCLUDED
#define FFTMETER_H_INCLUDED
#include <limits>
#include "./ILevelMeter.hpp"
#include "../JuceLibraryCode/JuceHeader.h"
#include "./ZeroIterator.hpp"
#include "./PeakHoldValue.hpp"
#include "./MovingAverageValue.hpp"
#include "./Linear_dB.hpp"
//! FFTメーターを実現するクラス
struct FFTMeter
: public ILevelMeter
{
typedef int millisec;
typedef double dB_t;
static int const kDefaultReleaseSpeed = -96 / 2;
static dB_t GetLowestLevel()
{
return std::numeric_limits<dB_t>::lowest();
}
//! コンストラクタ
/*!
@param release_speed ピークホールドしたピーク値が、peak_hold_time後に一秒間に下降するスピード
*/
FFTMeter(int sampling_rate, int order, int moving_average, millisec peak_hold_time, dB_t release_speed = kDefaultReleaseSpeed)
: order_(order)
, fft_()
{
sampling_rate_ = sampling_rate;
moving_average_ = moving_average;
peak_hold_time_ = peak_hold_time;
release_speed_ = release_speed;
SetFFTOrder(order);
}
size_t GetSize() const
{
return fft_->getSize();
}
void SetSamples(float const *samples, size_t num_samples) override
{
doSetSample(samples, samples + num_samples);
}
void SetSamples(double const *samples, size_t num_samples) override
{
doSetSample(samples, samples + num_samples);
}
void Consume(size_t num_samples) override
{
doSetSample(ZeroIterator(num_samples), ZeroIterator());
}
void SetFFTOrder(int order)
{
fft_ = std::make_unique<juce::dsp::FFT>(order);
assert(order >= 6); // 64サンプル以上
fft_work_.clear();
fft_output_.clear();
fft_work_.reserve(pow(2, order));
fft_output_.resize(pow(2, order));
window_.resize(pow(2, order));
bool use_window_function = true;
if(use_window_function) {
//! hanning window
for(int i = 0; i < window_.size(); ++i) {
window_[i] = 0.5 - 0.5 * cos(2 * juce::MathConstants<double>::pi * i / (window_.size() - 1));
}
double amplitude_correction_factor = 0;
double power_correction_factor = 0;
for(int i = 0; i < window_.size(); ++i) {
amplitude_correction_factor += window_[i];
power_correction_factor += (window_[i] * window_[i]);
}
amplitude_correction_factor = amplitude_correction_factor / GetSize();
power_correction_factor = power_correction_factor / GetSize();
//! 窓関数を掛けたことでFFT後の信号のパワーが変わってしまうのを補正
for(int i = 0; i < window_.size(); ++i) {
window_[i] /= amplitude_correction_factor;
}
enbw_correction_factor_ = power_correction_factor / (amplitude_correction_factor * amplitude_correction_factor);
} else {
std::fill(window_.begin(), window_.end(), 1.0);
enbw_correction_factor_ = 1.0;
}
current_spectrum_.resize(pow(2, order), MovingAverageValue<float>(moving_average_, -640));
peak_spectrum_.resize(pow(2, order), PeakHoldValue(sampling_rate_, peak_hold_time_, release_speed_));
}
int GetMovingAverage() const
{
return moving_average_;
}
void SetMovingAverage(int moving_average)
{
moving_average_ = moving_average;
for(auto &a: current_spectrum_) {
a = MovingAverageValue<float>(moving_average, -640);
}
}
void SetPeakHoldTime(millisec peak_hold_time)
{
peak_hold_time_ = peak_hold_time;
for(auto &peak: peak_spectrum_) {
peak.SetPeakHoldTime(peak_hold_time_);
}
}
millisec GetPeakHoldTime() const
{
return peak_hold_time_;
}
dB_t GetReleaseSpeed() const
{
return release_speed_;
}
void SetReleaseSpeed(dB_t release_speed)
{
release_speed_ = release_speed;
}
//! 指定した周波数ビンの移動平均されたパワースペクトルを取得
dB_t GetSpectrum(int index)
{
return current_spectrum_[index].GetAverage();
}
//! 指定した周波数ビンのパワースペクトルのピークホールド値を取得
dB_t GetPeakSpectrum(int index)
{
return peak_spectrum_[index].GetPeak();
}
private:
template<class RandomAccessIterator>
void doSetSample(RandomAccessIterator begin, RandomAccessIterator end)
{
for(auto it = begin; it != end; ++it) {
juce::dsp::Complex<float> c = { (float)(*it), 0.0 };
fft_work_.push_back(c);
if(fft_work_.size() == GetSize()) {
double const power_scaling = GetSize() * GetSize();
double const freq_step = sampling_rate_ / (double)GetSize();
//! 虚数部分のデータには0を埋める
static juce::dsp::Complex<float> const zero = { 0.0, 0.0 };
std::fill(fft_output_.begin(), fft_output_.end(), zero);
//! windowing
for(int i = 0; i < GetSize(); ++i) {
fft_work_[i].real(fft_work_[i].real() * window_[i]);
}
//! FFT実行
fft_->perform(fft_work_.data(), fft_output_.data(), false);
for(int i = 0; i < GetSize() / 2; ++i) {
//! スペクトルの絶対値を計算
auto point_abs = juce_hypot(fft_output_[i].real(), fft_output_[i].imag());
//! FFTの次数や窓関数によるパワー値のズレを補正
float power = point_abs / (power_scaling * freq_step * enbw_correction_factor_);
//! 片側パワースペクトルにする
if(i != 0 && i != GetSize() / 2 - 1) {
power *= 2;
}
float const spectrum = sqrt(power);
current_spectrum_[i].Push(linear_to_dB(spectrum));
peak_spectrum_[i].PushPeakValue(linear_to_dB(spectrum));
}
fft_work_.clear();
} else {
//! FFTを実行していないときは、ピークホールドの状態のみ更新する
for(int i = 0; i < GetSize() / 2; ++i) {
peak_spectrum_[i].PushPeakValue(GetLowestLevel());
}
}
}
}
int sampling_rate_;
int order_;
std::unique_ptr<juce::dsp::FFT> fft_;
std::vector<juce::dsp::Complex<float>> fft_work_;
std::vector<juce::dsp::Complex<float>> fft_output_;
std::vector<float> window_;
double amplitude_correction_factor_;
// 参考: http://ecd-assist.com/index.php?%E7%AA%93%E9%96%A2%E6%95%B0%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6
double enbw_correction_factor_;
std::vector<MovingAverageValue<float>> current_spectrum_;
std::vector<PeakHoldValue> peak_spectrum_;
dB_t release_speed_;
millisec peak_hold_time_;
int moving_average_;
};
#endif // FFTMETER_H_INCLUDED
| 31.733333
| 131
| 0.531119
|
hotwatermorning
|
ef4c6326f5e4f95cbc981302de52df5defec4561
| 1,777
|
cpp
|
C++
|
tests/TcpServer_test.cpp
|
yangzecai/Web-Server
|
8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f
|
[
"MIT"
] | 2
|
2021-08-24T00:35:42.000Z
|
2022-02-23T13:20:23.000Z
|
tests/TcpServer_test.cpp
|
yangzecai/Web-Server
|
8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f
|
[
"MIT"
] | null | null | null |
tests/TcpServer_test.cpp
|
yangzecai/Web-Server
|
8a26bc1ad7db5c3e4825fc8c37d83f53d0c98f7f
|
[
"MIT"
] | null | null | null |
#include "Address.h"
#include "EventLoop.h"
#include "Log.h"
#include "TcpConnection.h"
#include "TcpServer.h"
#include <cstdio>
#include <chrono>
#include <unistd.h>
EventLoop* g_loop;
std::string message1;
std::string message2;
void onConnection(const TcpConnectionPtr& conn)
{
printf("onConnection(): new connection from %s\n",
conn->getClientAddr().getAddressStr().c_str());
conn->send(message1);
}
void onClose(const TcpConnectionPtr& conn)
{
printf("onClose() : disconnect connection from %s\n",
conn->getClientAddr().getAddressStr().c_str());
}
void onMessage(const TcpConnectionPtr& conn, Buffer& recvBuffer)
{
printf("onMessage(): received %zd bytes from connection [%s]\n",
recvBuffer.getReadableBytes(),
conn->getClientAddr().getAddressStr().c_str());
recvBuffer.retrieveAll();
}
void onWriteComplete(const TcpConnectionPtr& conn)
{
// printf("onWriteComplete()\n");
conn->send(message1);
}
int main(int argc, char* argv[])
{
log::setLevel(log::TRACE);
printf("main(): pid = %d\n", ::getpid());
int len1 = 100;
int len2 = 200;
if (argc > 2) {
len1 = atoi(argv[1]);
len2 = atoi(argv[2]);
}
message1.resize(len1);
message2.resize(len2);
std::fill(message1.begin(), message2.end(), 'A');
std::fill(message2.begin(), message2.end(), 'B');
Address listenAddr(Address::createIPv4Address(9981));
EventLoop loop;
g_loop = &loop;
TcpServer server(&loop, listenAddr);
server.setConnectionCallback(onConnection);
server.setWriteCompleteCallback(onWriteComplete);
server.setCloseCallback(onClose);
server.setMessageCallback(onMessage);
server.setThreadNum(1);
server.start();
loop.loop();
}
| 23.381579
| 68
| 0.65785
|
yangzecai
|
ef4fb0837a804f8aa1b82254932d0c1492cd9418
| 20
|
cpp
|
C++
|
vendor/kult/kult.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2019-02-11T12:18:39.000Z
|
2019-02-11T12:18:39.000Z
|
vendor/kult/kult.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2021-11-11T07:27:58.000Z
|
2021-11-11T07:27:58.000Z
|
vendor/kult/kult.cpp
|
emdavoca/wee
|
60344dd646a2e27d1cfdb1131dd679558d9cfa2b
|
[
"MIT"
] | 1
|
2021-11-11T07:22:12.000Z
|
2021-11-11T07:22:12.000Z
|
#include "kult.hpp"
| 10
| 19
| 0.7
|
emdavoca
|
ef513d30412be923701d932668aa2e1a39d3828c
| 3,012
|
hh
|
C++
|
src/faodel-common/BootstrapImplementation.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-01-25T21:21:07.000Z
|
2021-04-29T17:24:00.000Z
|
src/faodel-common/BootstrapImplementation.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 8
|
2018-10-09T14:35:30.000Z
|
2020-09-30T20:09:42.000Z
|
src/faodel-common/BootstrapImplementation.hh
|
faodel/faodel
|
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
|
[
"MIT"
] | 2
|
2019-04-23T19:01:36.000Z
|
2021-05-11T07:44:55.000Z
|
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
#define FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
#include <string>
#include <map>
#include <vector>
#include "faodel-common/Bootstrap.hh"
#include "faodel-common/Configuration.hh"
#include "faodel-common/LoggingInterface.hh"
namespace faodel {
namespace bootstrap {
namespace internal {
//Holds info on each component
typedef struct {
std::string name;
std::vector<std::string> requires;
std::vector<std::string> optional;
fn_init init_function;
fn_start start_function;
fn_fini fini_function;
BootstrapInterface *optional_component_ptr;
} bstrap_t;
/**
* @brief A class for registering how FAODEL components are started/stopped
*/
class Bootstrap
: public LoggingInterface {
public:
Bootstrap();
~Bootstrap() override;
void SetNodeID(NodeID nodeid) { my_node_id = nodeid; }
void RegisterComponent(std::string name,
std::vector<std::string> requires,
std::vector<std::string> optional,
fn_init init_function,
fn_start start_function,
fn_fini fini_function,
bool allow_overwrites);
void RegisterComponent(BootstrapInterface *component, bool allow_overwrites);
BootstrapInterface * GetComponentPointer(std::string name);
bool CheckDependencies(std::string *info_message=nullptr);
std::vector<std::string> GetStartupOrder();
bool Init(const Configuration &config);
void Start();
void Start(const Configuration &config); //Init and Start
void Finish(bool clear_list_of_bootstrap_users);
std::string GetState() const;
bool IsStarted() const { return state==State::STARTED; }
Configuration GetConfiguration() const { return configuration; }
int GetNumberOfUsers() const;
bool HasComponent(const std::string &component_name) const;
void dumpStatus() const;
void dumpInfo(faodel::ReplyStream &rs) const;
private:
void finish_(bool clear_list_of_bootstrap_users);
Configuration configuration;
bool show_config_at_init;
bool halt_on_shutdown;
bool status_on_shutdown;
bool mpisyncstop_enabled;
uint64_t sleep_seconds_before_shutdown;
nodeid_t my_node_id;
bool expandDependencies(std::map<std::string, std::set<std::string>> &dep_lut,
std::stringstream &emsg);
bool sortDependencies(std::stringstream &emsg);
std::vector<bstrap_t> bstraps;
faodel::MutexWrapper *state_mutex; //!< Protects num_init_callers and State
int num_init_callers; //!< Number of entities that have called init (or start)
enum class State { UNINITIALIZED, INITIALIZED, STARTED };
State state;
};
} // namespace internal
} // namespace bootstrap
} // namespace faodel
#endif // FAODEL_COMMON_BOOTSTRAPINTERNAL_HH
| 28.149533
| 80
| 0.722112
|
faodel
|
ef571c5b57d325d297c173d275539cd1416142e0
| 1,117
|
cpp
|
C++
|
eventset.cpp
|
rao1219/qt-SON
|
b8a28c8358dda55c3e5e01d199f2276b71dc2646
|
[
"MIT"
] | 11
|
2015-08-31T15:53:43.000Z
|
2021-12-24T13:25:05.000Z
|
eventset.cpp
|
rao1219/qt-SON
|
b8a28c8358dda55c3e5e01d199f2276b71dc2646
|
[
"MIT"
] | null | null | null |
eventset.cpp
|
rao1219/qt-SON
|
b8a28c8358dda55c3e5e01d199f2276b71dc2646
|
[
"MIT"
] | 5
|
2017-06-30T07:18:44.000Z
|
2020-04-17T16:08:15.000Z
|
#include "eventset.h"
#include "ui_eventset.h"
#include <QDebug>
eventSet::eventSet(QWidget *parent) :
QDialog(parent),
ui(new Ui::eventSet)
{
ui->setupUi(this);
QPalette bgpal = palette();
bgpal.setColor (QPalette::Background, QColor (29, 15, 29));
//bgpal.setColor (QPalette::Background, Qt::transparent);
bgpal.setColor (QPalette::Foreground, QColor(255,255,255,255));
setPalette (bgpal);
this->accepted=false;
ui->comboBox->addItem("User number increases suddenly in some area.");
ui->comboBox->addItem("User number decreases suddenly in some area.");
ui->comboBox->addItem("Signals dies away suddenly in some area.");
ui->comboBox->addItem("AP's frequency changes suddenly in some area");
ui->comboBox_2->addItem("轻微");
ui->comboBox_2->addItem("正常");
ui->comboBox_2->addItem("严重");
}
eventSet::~eventSet()
{
delete ui;
}
void eventSet::on_buttonBox_accepted()
{
this->accepted=true;
this->eventitem=ui->comboBox->currentText();
this->serious=ui->comboBox_2->currentIndex();
this->eventType=ui->comboBox->currentIndex();
}
| 27.925
| 74
| 0.678603
|
rao1219
|
ef58705892b12d6d7b05589554de923073d5681b
| 3,331
|
cpp
|
C++
|
src/base/logger.cpp
|
wanchuanheng/wtaf
|
90410ecb6b9e8213c0e2b2b87f72438d24ef8836
|
[
"Apache-2.0"
] | null | null | null |
src/base/logger.cpp
|
wanchuanheng/wtaf
|
90410ecb6b9e8213c0e2b2b87f72438d24ef8836
|
[
"Apache-2.0"
] | null | null | null |
src/base/logger.cpp
|
wanchuanheng/wtaf
|
90410ecb6b9e8213c0e2b2b87f72438d24ef8836
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdarg>
#include <unistd.h>
#include <chrono>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#include <thread>
#include "base/logger.h"
namespace wtaf {
namespace base {
void Logger::init(LOG_LEVEL level, const std::string &app, const std::string &path)
{
m_level = level;
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm tm;
localtime_r(&tv.tv_sec, &tm);
m_year.store(1900 + tm.tm_year, std::memory_order_relaxed);
m_month.store(1 + tm.tm_mon, std::memory_order_relaxed);
m_day.store(tm.tm_mday, std::memory_order_relaxed);
m_file_name = path + app;
m_file_full_name = path + app + ".log";
m_file = fopen(m_file_full_name.c_str(), "rb");
if(m_file != NULL)
{
int32 fd = fileno(m_file);
struct stat st;
fstat(fd, &st);
struct tm tm_1;
localtime_r(&st.st_mtim.tv_sec, &tm_1);
uint32 year = 1900 + tm_1.tm_year;
uint32 month = 1 + tm_1.tm_mon;
uint32 day = tm_1.tm_mday;
if(year != m_year.load(std::memory_order_relaxed)
|| month != m_month.load(std::memory_order_relaxed)
|| day != m_day.load(std::memory_order_relaxed))
{
char file_name[64];
sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), year, month, day);
fclose(m_file);
std::rename(m_file_full_name.c_str(), file_name);
}
}
m_file = fopen(m_file_full_name.c_str(), "ab");
}
void Logger::_log(uint32 year, uint32 month, uint32 day, const char *format, ...)
{
if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed)
|| day != m_day.load(std::memory_order_relaxed))
{
m_enter_num.fetch_sub(1, std::memory_order_relaxed);
while(m_enter_num.load(std::memory_order_relaxed) > 0)
{
std::this_thread::yield();
};
std::lock_guard<std::mutex> guard(m_mutex);
uint32 y = m_year.load(std::memory_order_relaxed);
uint32 m = m_month.load(std::memory_order_relaxed);
uint32 d = m_day.load(std::memory_order_relaxed);
//double-checked
if(year != y || month != m || day != d)
{
char file_name[64];
sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), y, m, d);
fclose(m_file);
std::rename(m_file_full_name.c_str(), file_name);
m_file = fopen(m_file_full_name.c_str(), "ab");
m_year.store(year, std::memory_order_relaxed);
m_month.store(month, std::memory_order_relaxed);
m_day.store(day, std::memory_order_relaxed);
}
va_list args;
va_start(args, format);
vfprintf(m_file, format, args);
va_end(args);
fflush(m_file);
}
else
{
va_list args;
va_start(args, format);
vfprintf(m_file, format, args);
va_end(args);
fflush(m_file);
m_enter_num.fetch_sub(1, std::memory_order_relaxed);
}
/**************** for debug ******************/
va_list args;
va_start(args, format);
vfprintf(stdout, format, args);
va_end(args);
/******************* for debug ******************/
}
}
}
| 30.842593
| 105
| 0.576704
|
wanchuanheng
|
ef59a5a79969c9e6a25ec6bbd597e3381684b289
| 201
|
hpp
|
C++
|
include/test_language_features.hpp
|
jdtaylor7/quetzal
|
23d2dfe1c6620c6dc115710445307ddc241d4456
|
[
"MIT"
] | null | null | null |
include/test_language_features.hpp
|
jdtaylor7/quetzal
|
23d2dfe1c6620c6dc115710445307ddc241d4456
|
[
"MIT"
] | null | null | null |
include/test_language_features.hpp
|
jdtaylor7/quetzal
|
23d2dfe1c6620c6dc115710445307ddc241d4456
|
[
"MIT"
] | null | null | null |
#ifndef TEST_LANGUAGE_FEATURES_HPP
#define TEST_LANGUAGE_FEATURES_HPP
bool test_uninit_globals();
bool test_init_globals();
bool test_all_language_features();
#endif /* TEST_LANGUAGE_FEATURES_HPP */
| 22.333333
| 39
| 0.840796
|
jdtaylor7
|
ef61347ea66adf304ba1a46f6ddb0c243f63cf81
| 11,863
|
cpp
|
C++
|
AADC/src/adtfUser/dev/src/util/history.cpp
|
AADC-Fruit/AADC_2015_FRUIT
|
88bd18871228cb48c46a3bd803eded6f14dbac08
|
[
"BSD-3-Clause"
] | 1
|
2018-05-10T22:35:25.000Z
|
2018-05-10T22:35:25.000Z
|
AADC/src/adtfUser/dev/src/util/history.cpp
|
AADC-Fruit/AADC_2015_FRUIT
|
88bd18871228cb48c46a3bd803eded6f14dbac08
|
[
"BSD-3-Clause"
] | null | null | null |
AADC/src/adtfUser/dev/src/util/history.cpp
|
AADC-Fruit/AADC_2015_FRUIT
|
88bd18871228cb48c46a3bd803eded6f14dbac08
|
[
"BSD-3-Clause"
] | null | null | null |
#include "history.h"
#include <assert.h>
// -------------------------------------------------------------------------------------------------
bool History::insert(HistoryEntry new_entry) {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > history_size_){
entries_.pop_back();
entries_.insert(entries_.begin(), new_entry);
} else entries_.insert(entries_.begin(), new_entry);
return true;
}
// -------------------------------------------------------------------------------------------------
int History::left_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
weighted_x += entries_.at(i).left_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::left_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
weighted_slope += entries_.at(i).left_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::left_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).left_available_){
length += entries_.at(i).left_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
weighted_x += entries_.at(i).mid_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
weighted_slope += entries_.at(i).mid_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::mid_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_available_){
length += entries_.at(i).mid_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_next_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_next_available_){
weighted_x += entries_.at(i).mid_next_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_next_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_next_available_){
weighted_slope += entries_.at(i).mid_next_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::mid_prev_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_prev_available_){
weighted_x += entries_.at(i).mid_prev_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::mid_prev_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).mid_prev_available_){
weighted_slope += entries_.at(i).mid_prev_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
int History::right_get_weighted_x() {
// -------------------------------------------------------------------------------------------------
double weighted_x = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
weighted_x += entries_.at(i).right_x_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (int)(weighted_x/devisor);
}
// -------------------------------------------------------------------------------------------------
double History::right_get_weighted_slope() {
// -------------------------------------------------------------------------------------------------
double weighted_slope = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
weighted_slope += entries_.at(i).right_slope_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (weighted_slope/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
double History::right_get_length() {
// -------------------------------------------------------------------------------------------------
double length = 0;
int devisor = 0;
for(size_t i = 0; i < entries_.size(); i++){
if(entries_.at(i).right_available_){
length += entries_.at(i).right_length_ * (double)(entries_.size() - i);
devisor += (entries_.size() - i);
}
}
return (length/(double)(devisor));
}
// -------------------------------------------------------------------------------------------------
bool History::left_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).left_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_next_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_next_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::mid_prev_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).mid_prev_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
bool History::right_empty() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++) if(entries_.at(i).right_available_) return false;
return true;
}
// -------------------------------------------------------------------------------------------------
int History::get_size() {
// -------------------------------------------------------------------------------------------------
return entries_.size();
}
// -------------------------------------------------------------------------------------------------
bool History::jumpSegment() {
// -------------------------------------------------------------------------------------------------
for(size_t i = 0; i < entries_.size(); i++){
entries_.at(i).passDataOn();
}
return true;
}
// -------------------------------------------------------------------------------------------------
int History::get_left_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].left_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_left_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].left_avg_y_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_mid_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].mid_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_mid_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].mid_avg_y_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_right_x() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].right_avg_x_;
return 0;
}
// -------------------------------------------------------------------------------------------------
int History::get_right_y() {
// -------------------------------------------------------------------------------------------------
if(entries_.size() > 0) return entries_[0].right_avg_y_;
return 0;
}
| 41.190972
| 101
| 0.33811
|
AADC-Fruit
|
ef6459388f3b5ed605e46e28d1055259b9dafa26
| 1,824
|
cpp
|
C++
|
prog/prj/src/MacierzOb.cpp
|
MarutTomasz/ZadaniePodwodnyDron
|
669ac1d10be228cd2d2e1517e5b56f9742abd421
|
[
"MIT"
] | null | null | null |
prog/prj/src/MacierzOb.cpp
|
MarutTomasz/ZadaniePodwodnyDron
|
669ac1d10be228cd2d2e1517e5b56f9742abd421
|
[
"MIT"
] | null | null | null |
prog/prj/src/MacierzOb.cpp
|
MarutTomasz/ZadaniePodwodnyDron
|
669ac1d10be228cd2d2e1517e5b56f9742abd421
|
[
"MIT"
] | null | null | null |
#include "MacierzOb.hh"
/*!
* \file
* \brief Definicja metod klasy MacierzOb
*
* Plik zawiera definicje metod działających
* na macierzach obrotu.
*/
MacierzOb::MacierzOb(const Macierz3D &M) : Macierz3D(M) {
double epsilon = 0.000000001;
if(abs(tab[0] * tab[1]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs(tab[1] * tab[2]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs(tab[0] * tab[2]) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
if(abs((*this).wyznacznik(Laplace) - 1) > epsilon){
cout << "Macierz nie jest ortonormalna" << endl;
exit(1);
}
}
MacierzOb::MacierzOb(){
(*this).MacierzJednostkowa();
}
MacierzOb::MacierzOb(char os, double stopnie){
switch(os){
case 'z' : {
tab[0][0] = cos(stopnie * PI/180);
tab[0][1] = -sin(stopnie * PI/180);
tab[0][2] = 0.0;
tab[1][0] = sin(stopnie * PI/180);
tab[1][1] = cos(stopnie * PI/180);
tab[1][2] = 0.0;
tab[2][0] = 0.0;
tab[2][1] = 0.0;
tab[2][2] = 1.0;
break;
}
case 'x' : {
tab[0][0] = 1.0;
tab[0][1] = 0.0;
tab[0][2] = 0.0;
tab[1][0] = 0.0;
tab[1][1] = cos(stopnie * PI/180);
tab[1][2] = -sin(stopnie * PI/180);
tab[2][0] = 0.0;
tab[2][1] = sin(stopnie * PI/180);
tab[2][2] = cos(stopnie * PI/180);
break;
}
case 'y' : {
tab[0][0] = cos(stopnie * PI/180);
tab[0][1] = 0.0;
tab[0][2] = sin(stopnie * PI/180);
tab[1][0] = 0.0;
tab[1][1] = 1.0;
tab[1][2] = 0.0;
tab[2][0] = -sin(stopnie * PI/180);
tab[2][1] = 0.0;
tab[2][2] = cos(stopnie * PI/180);
break;
}
default: {
cout << "Nieprawidlowa os obtoru. Nie mozna stworzyc macierzy." << endl;
exit(1);
break;
}
}
}
| 22.518519
| 76
| 0.524123
|
MarutTomasz
|
ef6a4232e6f2491c3b33091fce6da0f114e5fe9b
| 4,118
|
ipp
|
C++
|
include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
include/External/stlib/packages/shortest_paths/GraphDijkstra.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
// -*- C++ -*-
#if !defined(__GraphDijkstra_ipp__)
#error This file is an implementation detail of the class GraphDijkstra.
#endif
namespace shortest_paths {
//
// Mathematical operations
//
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
build() {
// Allocate memory for the half edges.
{
half_edge_container temp(edges().size());
_half_edges.swap(temp);
_half_edges.clear();
}
// Sort the edges by source vertex.
EdgeSourceCompare<edge_type> comp;
std::sort(edges().begin(), edges().end(), comp);
// Add the half edges.
edge_const_iterator edge_iter = edges().begin();
edge_const_iterator edge_end = edges().end();
vertex_iterator vert_iter = vertices().begin();
const vertex_iterator vert_end = vertices().end();
for (; vert_iter != vert_end; ++vert_iter) {
vert_iter->set_adjacent_edges(&*_half_edges.end());
while (edge_iter != edge_end &&
edge_iter->source() == &*vert_iter) {
_half_edges.push_back(half_edge_type(edge_iter->target(),
edge_iter->weight()));
++edge_iter;
}
}
// Clear the edges.
{
edge_container temp;
edges().swap(temp);
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
initialize(const int source_index) {
// Initialize the data in each vertex.
vertex_iterator
iter = vertices().begin(),
iter_end = vertices().end();
for (; iter != iter_end; ++iter) {
iter->initialize();
}
// Set the source vertex to known.
vertex_type& source = vertices()[source_index];
source.set_status(KNOWN);
source.set_distance(0);
source.set_predecessor(0);
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
dijkstra(const int root_vertex_index) {
// Initialize the graph.
initialize(root_vertex_index);
// The heap of labeled unknown vertices.
heap_type labeled;
// Label the adjacent neighbors of the root vertex.
label_adjacent(labeled, &vertices()[root_vertex_index]);
// All vertices are known when there are no labeled vertices left.
// Loop while there are labeled vertices left.
vertex_type* min_vertex;
while (labeled.size()) {
// The labeled vertex with minimum distance becomes known.
min_vertex = labeled.top();
labeled.pop();
min_vertex->set_status(KNOWN);
// Label the adjacent neighbors of the known vertex.
label_adjacent(labeled, min_vertex);
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
label(heap_type& heap, vertex_type& vertex, const vertex_type& known_vertex,
weight_type edge_weight) {
if (vertex.status() == UNLABELED) {
vertex.set_status(LABELED);
vertex.set_distance(known_vertex.distance() + edge_weight);
vertex.set_predecessor(&known_vertex);
heap.push(&vertex);
}
else { // _status == LABELED
weight_type new_distance = known_vertex.distance() + edge_weight;
if (new_distance < vertex.distance()) {
vertex.set_distance(new_distance);
vertex.set_predecessor(&known_vertex);
heap.decrease(vertex.heap_ptr());
}
}
}
template <typename WeightType, typename HeapType>
inline
void
GraphDijkstra<WeightType, HeapType>::
label_adjacent(heap_type& heap, const vertex_type* known_vertex) {
vertex_type* adjacent;
half_edge_const_iterator iter(known_vertex->adjacent_edges());
half_edge_const_iterator iter_end((known_vertex + 1)->adjacent_edges());
// Loop over the adjacent edges.
for (; iter != iter_end; ++iter) {
adjacent = static_cast<vertex_type*>(iter->vertex());
if (adjacent->status() != KNOWN) {
label(heap, *adjacent, *known_vertex, iter->weight());
}
}
}
} // namespace shortest_paths
// End of file.
| 29.625899
| 77
| 0.654201
|
bxl295
|
ef724a5fee6c341680ca5427d5697d2fe7cf8fba
| 2,445
|
inl
|
C++
|
GLShader.inl
|
ffhighwind/DeferredShading
|
c8b765c5d1126ef8f337047db50e2eb63308baf9
|
[
"Apache-2.0"
] | 1
|
2019-10-18T13:45:05.000Z
|
2019-10-18T13:45:05.000Z
|
GLShader.inl
|
ffhighwind/DeferredShading
|
c8b765c5d1126ef8f337047db50e2eb63308baf9
|
[
"Apache-2.0"
] | 1
|
2019-10-18T13:44:49.000Z
|
2019-11-29T23:26:27.000Z
|
GLShader.inl
|
ffhighwind/DeferredShading
|
c8b765c5d1126ef8f337047db50e2eb63308baf9
|
[
"Apache-2.0"
] | null | null | null |
/*
* GLShader class for OpenGL 4.3
*
* Copyright (c) 2013 Wesley Hamilton
*
* 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
#ifndef GLSHADER_INL
#define GLSHADER_INL
#include "GLShader.hpp"
namespace opengl {
inline bool GLShader::operator==(const GLShader &other) const {
return _id == other._id;
}
inline void GLShader::Create(ShaderType shaderType) {
_id = glCreateShader((GLenum)shaderType);
}
inline void GLShader::Destroy() {
glDeleteShader(_id);
_id = 0;
}
inline int GLShader::Id() const {
return _id;
}
inline ShaderType GLShader::Type() const {
ShaderType _type = (ShaderType)0;
glGetShaderiv(_id, GL_SHADER_TYPE, (int *)&_type);
return _type;
}
inline bool GLShader::Exists() const {
return _id != 0 && glIsShader(_id) != GL_FALSE;
}
inline void GLShader::GetVertexPrecision(ShaderPrecision format, int &min, int &max, int &precision) {
int minMax[2] = { 0, 0 };
precision = 0;
glGetShaderPrecisionFormat(GL_VERTEX_SHADER, (GLenum)format, minMax, &precision);
min = minMax[0];
max = minMax[1];
}
inline void GLShader::GetFragmentPrecision(ShaderPrecision format, int &min, int &max, int &precision) {
int minMax[2] = { 0, 0 };
precision = 0;
glGetShaderPrecisionFormat(GL_FRAGMENT_SHADER, (GLenum)format, minMax, &precision);
min = minMax[0];
max = minMax[1];
}
inline void GLShader::ReleaseCompiler() {
glReleaseShaderCompiler();
}
} // namespace opengl
#endif // GLSHADER_INL
| 29.817073
| 104
| 0.745603
|
ffhighwind
|
ef72922217abbf859e05423495f1e87fc30d3ce5
| 2,870
|
cpp
|
C++
|
trains/train.cpp
|
mtlbaur/coursework_cpp
|
e86670df99a7e283c86bf702c708f92db6cfe0bf
|
[
"MIT"
] | null | null | null |
trains/train.cpp
|
mtlbaur/coursework_cpp
|
e86670df99a7e283c86bf702c708f92db6cfe0bf
|
[
"MIT"
] | null | null | null |
trains/train.cpp
|
mtlbaur/coursework_cpp
|
e86670df99a7e283c86bf702c708f92db6cfe0bf
|
[
"MIT"
] | null | null | null |
// Name: Matthias Baur
// File Name: train.cpp
// Date: 3 October, 2017
// This is the source file for the header file "train.h".
#include "train.h"
using namespace std;
// This function is responsible for adding a car the the end of a train.
void addToEnd(TrainCar* &head, TrainCar* carToAdd)
{
if (head == NULL)
{
head = carToAdd;
head->next = NULL;
}
else
{
TrainCar* preCar = findEnd(head);
preCar->next = carToAdd;
preCar->next->next = NULL;
preCar = NULL;
}
}
// This function is responsible for adding a car to the beginning of a train.
void addToBeginning(TrainCar* &head, TrainCar* carToAdd)
{
carToAdd->next = head;
head = carToAdd;
}
// This function is responsible for adding a car in the correct spot in a train.
// The correct spot is determined by weight - it is sorted into ascending order.
// It utilizes the weight_findCar and addToBeginning functions.
void addInAscendingWeight(TrainCar* &head, TrainCar* carToAdd)
{
TrainCar* preCar = weight_findCar(head, carToAdd); // Finds the car after which to add the new car.
if (preCar == NULL)
addToBeginning(head, carToAdd);
else
{
carToAdd->next = preCar->next;
preCar->next = carToAdd;
}
}
// This function is responsible for switching a car from one train to another.
// It utilizes the addToBeginning functions.
void switchTrains(TrainCar* &srcHead, TrainCar* &dstHead)
{
TrainCar* switchCar = srcHead;
if (switchCar != NULL)
{
srcHead = srcHead->next;
addToBeginning(dstHead, switchCar);
}
switchCar = NULL;
}
// This functions simply displays a the current configuration of a train.
void displayTrain(TrainCar* head)
{
TrainCar* walker = head;
while(walker != NULL)
{
cout << walker->id;
if (walker->next != NULL)
cout << "->";
walker = walker->next;
}
walker = NULL;
}
// This function simply displays the weight of a train.
void printTrainWeight(TrainCar* head)
{
float totalWeight = 0;
TrainCar* walker = head;
while(walker != NULL)
{
totalWeight += walker->weight;
walker = walker->next;
}
cout << totalWeight;
walker = NULL;
}
// This function returns the location of the last car in a train.
TrainCar* findEnd(TrainCar* head)
{
TrainCar* walker = head;
if (walker == NULL)
return walker;
else
{
while(walker->next != NULL)
walker = walker->next;
return walker;
}
}
// This function returns the car after which to add the new car.
// It is integral to the addInAscendingWeight() function.
TrainCar* weight_findCar(TrainCar* head, TrainCar* carToAdd)
{
bool found = false;
TrainCar* walker = head;
TrainCar* preCar = NULL;
while (!found)
{
if (walker == NULL)
found = true;
else if (walker->weight > carToAdd->weight)
found = true;
else
{
preCar = walker;
walker = walker->next;
}
}
walker = NULL;
return preCar;
}
| 18.75817
| 101
| 0.677352
|
mtlbaur
|
ef74fc893c803120b15a589f3a0539fe520fed3b
| 59,119
|
cpp
|
C++
|
meshoptimizer/demo/miniz.cpp
|
FAETHER/VEther
|
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
|
[
"MIT"
] | 3
|
2019-12-07T23:57:47.000Z
|
2019-12-31T19:46:41.000Z
|
meshoptimizer/demo/miniz.cpp
|
FAETHER/VEther
|
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
|
[
"MIT"
] | null | null | null |
meshoptimizer/demo/miniz.cpp
|
FAETHER/VEther
|
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
|
[
"MIT"
] | null | null | null |
/* This is miniz.c with removal of all zlib/zip like functionality - only tdefl/tinfl APIs are left
For maximum compatibility unaligned load/store and 64-bit register paths have been removed so this is slower than miniz.c
miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
*/
// clang-format off
#include "miniz.h"
#ifndef MINIZ_HEADER_FILE_ONLY
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
#include <string.h>
#include <assert.h>
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void)x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a,b) (((a)>(b))?(a):(b))
#define MZ_MIN(a,b) (((a)<(b))?(a):(b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
mz_uint32 mz_adler32(mz_uint32 adler, const unsigned char *ptr, size_t buf_len)
{
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr) return MZ_ADLER32_INIT;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
void mz_free(void *p)
{
MZ_FREE(p);
}
// ------------------- Low-level Decompression (completely independent from all compression API's)
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN switch(r->m_state) { case 0:
#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for ( ; ; ) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else c = *pIn_buf_cur++; } MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
} TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
int temp; mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
} sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
{
static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
static const int s_min_table_sizes[3] = { 257, 1, 4 };
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start))
{
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (mz_uint32)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter)
{
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do
{
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0)
{
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter)
{
if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8))))
{
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits))
{
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter)
{
size_t n;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end)
{
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
{
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
}
else
{
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
}
else if (r->m_type == 3)
{
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
}
else
{
if (r->m_type == 1)
{
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for ( i = 0; i <= 143; ++i) *p++ = 8;
for ( ; i <= 255; ++i) *p++ = 9;
for ( ; i <= 279; ++i) *p++ = 7;
for ( ; i <= 287; ++i) *p++ = 8;
}
else
{
for (counter = 0; counter < 3; counter++)
{
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++)
{
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for ( ; (int)r->m_type >= 0; r->m_type--)
{
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i)
{
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1))
{
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
{
mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index];
if (!code_size) continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS)
{
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE)
{
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)]))
{
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
{
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1])
{
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
else tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2)
{
for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
{
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16)
{
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter))
{
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
{
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
}
}
for ( ; ; )
{
mz_uint8 *pSrc;
for ( ; ; )
{
if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
{
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
}
else
{
int sym2;
mz_uint code_len;
if (num_bits < 15)
{
bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
}
while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256)
break;
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
}
while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256)
{
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256) break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
{
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
{
while (counter--)
{
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
}
continue;
}
do
{
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
}
while ((int)(counter -= 3) > 2);
if ((int)counter > 0)
{
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
}
while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_SKIP_BITS(32, num_bits & 7);
for (counter = 0; counter < 4; ++counter)
{
mz_uint s;
if (num_bits) TINFL_GET_BITS(41, s, 8);
else TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf;
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
{
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for ( ; ; )
{
size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
{
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
// ------------------- Low-level Compression (independent from all decompression API's)
// Purposely making these tables static for faster init and thread safety.
static const mz_uint16 s_tdefl_len_sym[256] =
{
257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285
};
static const mz_uint8 s_tdefl_len_extra[256] =
{
0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0
};
static const mz_uint8 s_tdefl_small_dist_sym[512] =
{
0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17
};
static const mz_uint8 s_tdefl_small_dist_extra[512] =
{
0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7
};
static const mz_uint8 s_tdefl_large_dist_sym[128] =
{
0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29
};
static const mz_uint8 s_tdefl_large_dist_extra[128] =
{
0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13
};
// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
typedef struct
{
mz_uint16 m_key, m_sym_index;
} tdefl_sym_freq;
static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
{
mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1;
MZ_CLEAR_OBJ(hist);
for (i = 0; i < num_syms; i++)
{
mz_uint freq = pSyms0[i].m_key;
hist[freq & 0xFF]++;
hist[256 + ((freq >> 8) & 0xFF)]++;
}
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
{
const mz_uint32* pHist = &hist[pass << 8];
mz_uint offsets[256], cur_ofs = 0;
for (i = 0; i < 256; i++)
{
offsets[i] = cur_ofs;
cur_ofs += pHist[i];
}
for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
{
tdefl_sym_freq* t = pCur_syms;
pCur_syms = pNew_syms;
pNew_syms = t;
}
}
return pCur_syms;
}
// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
{
int root, leaf, next, avbl, used, dpth;
if (n==0) return;
else if (n==1)
{
A[0].m_key = 1;
return;
}
A[0].m_key += A[1].m_key;
root = 0;
leaf = 2;
for (next=1; next < n-1; next++)
{
if (leaf>=n || A[root].m_key<A[leaf].m_key)
{
A[next].m_key = A[root].m_key;
A[root++].m_key = (mz_uint16)next;
}
else A[next].m_key = A[leaf++].m_key;
if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key))
{
A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
A[root++].m_key = (mz_uint16)next;
}
else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
}
A[n-2].m_key = 0;
for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
avbl = 1;
used = dpth = 0;
root = n-2;
next = n-1;
while (avbl>0)
{
while (root>=0 && (int)A[root].m_key==dpth)
{
used++;
root--;
}
while (avbl>used)
{
A[next--].m_key = (mz_uint16)(dpth);
avbl--;
}
avbl = 2*used;
dpth++;
used = 0;
}
}
// Limits canonical Huffman code table's max code size.
enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
{
int i;
mz_uint32 total = 0;
if (code_list_len <= 1) return;
for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
while (total != (1UL << max_code_size))
{
pNum_codes[max_code_size]--;
for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i])
{
pNum_codes[i]--;
pNum_codes[i + 1] += 2;
break;
}
total--;
}
}
static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
{
int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
MZ_CLEAR_OBJ(num_codes);
if (static_table)
{
for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
}
else
{
tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
int num_used_syms = 0;
const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
for (i = 0; i < table_len; i++) if (pSym_count[i])
{
syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
}
pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
}
next_code[1] = 0;
for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
for (i = 0; i < table_len; i++)
{
mz_uint rev_code = 0, code, code_size;
if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
code = next_code[code_size]++;
for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
}
}
#define TDEFL_PUT_BITS(b, l) do { \
mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
while (d->m_bits_in >= 8) { \
if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
d->m_bit_buffer >>= 8; \
d->m_bits_in -= 8; \
} \
} MZ_MACRO_END
#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
if (rle_repeat_count < 3) { \
d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
} else { \
d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
} rle_repeat_count = 0; } }
#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
if (rle_z_count < 3) { \
d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
} else if (rle_z_count <= 10) { \
d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
} else { \
d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
} rle_z_count = 0; } }
static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static void tdefl_start_dynamic_block(tdefl_compressor *d)
{
int num_lit_codes, num_dist_codes, num_bit_lengths;
mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
d->m_huff_count[0][256] = 1;
tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
num_packed_code_sizes = 0;
rle_z_count = 0;
rle_repeat_count = 0;
memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
for (i = 0; i < total_code_sizes_to_pack; i++)
{
mz_uint8 code_size = code_sizes_to_pack[i];
if (!code_size)
{
TDEFL_RLE_PREV_CODE_SIZE();
if (++rle_z_count == 138)
{
TDEFL_RLE_ZERO_CODE_SIZE();
}
}
else
{
TDEFL_RLE_ZERO_CODE_SIZE();
if (code_size != prev_code_size)
{
TDEFL_RLE_PREV_CODE_SIZE();
d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1);
packed_code_sizes[num_packed_code_sizes++] = code_size;
}
else if (++rle_repeat_count == 6)
{
TDEFL_RLE_PREV_CODE_SIZE();
}
}
prev_code_size = code_size;
}
if (rle_repeat_count)
{
TDEFL_RLE_PREV_CODE_SIZE();
}
else
{
TDEFL_RLE_ZERO_CODE_SIZE();
}
tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
TDEFL_PUT_BITS(2, 2);
TDEFL_PUT_BITS(num_lit_codes - 257, 5);
TDEFL_PUT_BITS(num_dist_codes - 1, 5);
for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;
num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
{
mz_uint code = packed_code_sizes[packed_code_sizes_index++];
MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
}
}
static void tdefl_start_static_block(tdefl_compressor *d)
{
mz_uint i;
mz_uint8 *p = &d->m_huff_code_sizes[0][0];
for (i = 0; i <= 143; ++i) *p++ = 8;
for ( ; i <= 255; ++i) *p++ = 9;
for ( ; i <= 279; ++i) *p++ = 7;
for ( ; i <= 287; ++i) *p++ = 8;
memset(d->m_huff_code_sizes[1], 5, 32);
tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
TDEFL_PUT_BITS(1, 2);
}
static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
{
mz_uint flags;
mz_uint8 *pLZ_codes;
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
{
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1)
{
mz_uint sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
if (match_dist < 512)
{
sym = s_tdefl_small_dist_sym[match_dist];
num_extra_bits = s_tdefl_small_dist_extra[match_dist];
}
else
{
sym = s_tdefl_large_dist_sym[match_dist >> 8];
num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
}
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
}
else
{
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
}
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
{
if (static_block)
tdefl_start_static_block(d);
else
tdefl_start_dynamic_block(d);
return tdefl_compress_lz_codes(d);
}
static int tdefl_flush_block(tdefl_compressor *d, int flush)
{
mz_uint saved_bit_buf, saved_bits_in;
mz_uint8 *pSaved_output_buf;
mz_bool comp_block_succeeded = MZ_FALSE;
int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;
d->m_pOutput_buf = pOutput_buf_start;
d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
MZ_ASSERT(!d->m_output_flush_remaining);
d->m_output_flush_ofs = 0;
d->m_output_flush_remaining = 0;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
{
TDEFL_PUT_BITS(0x78, 8);
TDEFL_PUT_BITS(0x01, 8);
}
TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
pSaved_output_buf = d->m_pOutput_buf;
saved_bit_buf = d->m_bit_buffer;
saved_bits_in = d->m_bits_in;
if (!use_raw_block)
comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
// If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
{
mz_uint i;
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
TDEFL_PUT_BITS(0, 2);
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
{
TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
}
for (i = 0; i < d->m_total_lz_bytes; ++i)
{
TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
}
}
// Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
else if (!comp_block_succeeded)
{
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
tdefl_compress_block(d, MZ_TRUE);
}
if (flush)
{
if (flush == TDEFL_FINISH)
{
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER)
{
mz_uint i, a = d->m_adler32;
for (i = 0; i < 4; i++)
{
TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
a <<= 8;
}
}
}
else
{
mz_uint i, z = 0;
TDEFL_PUT_BITS(0, 3);
if (d->m_bits_in)
{
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, z ^= 0xFFFF)
{
TDEFL_PUT_BITS(z & 0xFFFF, 16);
}
}
}
MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
d->m_total_lz_bytes = 0;
d->m_block_index++;
if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
{
if (d->m_pPut_buf_func)
{
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
}
else if (pOutput_buf_start == d->m_output_buf)
{
int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
d->m_out_buf_ofs += bytes_to_copy;
if ((n -= bytes_to_copy) != 0)
{
d->m_output_flush_ofs = bytes_to_copy;
d->m_output_flush_remaining = n;
}
}
else
{
d->m_out_buf_ofs += n;
}
}
return d->m_output_flush_remaining;
}
static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
{
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint8 *s = d->m_dict + pos, *p, *q;
mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len) return;
for ( ; ; )
{
for ( ; ; )
{
if (--num_probes_left == 0) return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist) break;
p = s;
q = d->m_dict + probe_pos;
for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break;
if (probe_len > match_len)
{
*pMatch_dist = dist;
if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
c0 = d->m_dict[pos + match_len];
c1 = d->m_dict[pos + match_len - 1];
}
}
}
static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
{
d->m_total_lz_bytes++;
*d->m_pLZ_code_buf++ = lit;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
if (--d->m_num_flags_left == 0)
{
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
}
static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
{
mz_uint32 s0, s1;
MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
d->m_total_lz_bytes += match_len;
d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
match_dist -= 1;
d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
d->m_pLZ_code_buf += 3;
*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
if (--d->m_num_flags_left == 0)
{
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
s0 = s_tdefl_small_dist_sym[match_dist & 511];
s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
}
static mz_bool tdefl_compress_normal(tdefl_compressor *d)
{
const mz_uint8 *pSrc = d->m_pSrc;
size_t src_buf_left = d->m_src_buf_left;
tdefl_flush flush = d->m_flush;
while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
{
mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
// Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
{
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
src_buf_left -= num_bytes_to_process;
d->m_lookahead_size += num_bytes_to_process;
while (pSrc != pSrc_end)
{
mz_uint8 c = *pSrc++;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
ins_pos++;
}
}
else
{
while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
{
mz_uint8 c = *pSrc++;
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
src_buf_left--;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
{
mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
}
}
}
d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
break;
// Simple lazy/greedy parsing state machine.
len_to_move = 1;
cur_match_dist = 0;
cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
{
if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
{
mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
cur_match_len = 0;
while (cur_match_len < d->m_lookahead_size)
{
if (d->m_dict[cur_pos + cur_match_len] != c) break;
cur_match_len++;
}
if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0;
else cur_match_dist = 1;
}
}
else
{
tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
}
if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))
{
cur_match_dist = cur_match_len = 0;
}
if (d->m_saved_match_len)
{
if (cur_match_len > d->m_saved_match_len)
{
tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
if (cur_match_len >= 128)
{
tdefl_record_match(d, cur_match_len, cur_match_dist);
d->m_saved_match_len = 0;
len_to_move = cur_match_len;
}
else
{
d->m_saved_lit = d->m_dict[cur_pos];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
}
else
{
tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
len_to_move = d->m_saved_match_len - 1;
d->m_saved_match_len = 0;
}
}
else if (!cur_match_dist)
tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
{
tdefl_record_match(d, cur_match_len, cur_match_dist);
len_to_move = cur_match_len;
}
else
{
d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
// Move the lookahead forward by len_to_move bytes.
d->m_lookahead_pos += len_to_move;
MZ_ASSERT(d->m_lookahead_size >= len_to_move);
d->m_lookahead_size -= len_to_move;
d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (int)TDEFL_LZ_DICT_SIZE);
// Check if it's time to flush the current LZ codes to the internal output buffer.
if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )
{
int n;
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
}
}
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
return MZ_TRUE;
}
static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
{
if (d->m_pIn_buf_size)
{
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
}
if (d->m_pOut_buf_size)
{
size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
d->m_output_flush_ofs += (mz_uint)n;
d->m_output_flush_remaining -= (mz_uint)n;
d->m_out_buf_ofs += n;
*d->m_pOut_buf_size = d->m_out_buf_ofs;
}
return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)
{
if (!d)
{
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return TDEFL_STATUS_BAD_PARAM;
}
d->m_pIn_buf = pIn_buf;
d->m_pIn_buf_size = pIn_buf_size;
d->m_pOut_buf = pOut_buf;
d->m_pOut_buf_size = pOut_buf_size;
d->m_pSrc = (const mz_uint8 *)(pIn_buf);
d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
d->m_out_buf_ofs = 0;
d->m_flush = flush;
if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
(d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
{
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
}
d->m_wants_to_finish |= (flush == TDEFL_FINISH);
if ((d->m_output_flush_remaining) || (d->m_finished))
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
if (!tdefl_compress_normal(d))
return d->m_prev_return_status;
if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
{
if (tdefl_flush_block(d, flush) < 0)
return d->m_prev_return_status;
d->m_finished = (flush == TDEFL_FINISH);
if (flush == TDEFL_FULL_FLUSH)
{
MZ_CLEAR_OBJ(d->m_hash);
MZ_CLEAR_OBJ(d->m_next);
d->m_dict_size = 0;
}
}
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
}
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
{
MZ_ASSERT(d->m_pPut_buf_func);
return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
}
tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
d->m_pPut_buf_func = pPut_buf_func;
d->m_pPut_buf_user = pPut_buf_user;
d->m_flags = (mz_uint)(flags);
d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_pOutput_buf = d->m_output_buf;
d->m_pOutput_buf_end = d->m_output_buf;
d->m_prev_return_status = TDEFL_STATUS_OKAY;
d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
d->m_adler32 = 1;
d->m_pIn_buf = NULL;
d->m_pOut_buf = NULL;
d->m_pIn_buf_size = NULL;
d->m_pOut_buf_size = NULL;
d->m_flush = TDEFL_NO_FLUSH;
d->m_pSrc = NULL;
d->m_src_buf_left = 0;
d->m_out_buf_ofs = 0;
memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
return TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
{
return d->m_prev_return_status;
}
mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
{
return d->m_adler32;
}
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
tdefl_compressor *pComp;
mz_bool succeeded;
if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor));
if (!pComp) return MZ_FALSE;
succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
MZ_FREE(pComp);
return succeeded;
}
typedef struct
{
size_t m_size, m_capacity;
mz_uint8 *m_pBuf;
} tdefl_output_buffer;
static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
{
tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
size_t new_size = p->m_size + len;
if (new_size > p->m_capacity) return MZ_FALSE;
memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len);
p->m_size = new_size;
return MZ_TRUE;
}
size_t tdefl_compress_bound(size_t source_len)
{
// This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_buf) return 0;
out_buf.m_pBuf = (mz_uint8*)pOut_buf;
out_buf.m_capacity = out_buf_len;
if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
return out_buf.m_size;
}
static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
{
mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
return comp_flags;
}
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
| 37.679414
| 217
| 0.667907
|
FAETHER
|
ef783296e7654ad982da2ac3500b56fe53fec725
| 2,422
|
cpp
|
C++
|
WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp
|
cdragan/WinAPI-Wrapper
|
5d9b0a3f70932b55b08fbe2700e611f466af9f0b
|
[
"MIT"
] | 15
|
2015-10-09T04:26:12.000Z
|
2022-03-17T21:09:11.000Z
|
WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp
|
cdragan/WinAPI-Wrapper
|
5d9b0a3f70932b55b08fbe2700e611f466af9f0b
|
[
"MIT"
] | null | null | null |
WinAPIWrapperWiz/VCWizards/WinAPIWrapperWiz/templates/1033/document_window.cpp
|
cdragan/WinAPI-Wrapper
|
5d9b0a3f70932b55b08fbe2700e611f466af9f0b
|
[
"MIT"
] | 7
|
2015-10-09T04:33:23.000Z
|
2022-01-27T00:38:22.000Z
|
#include "StdAfx.h"
#include "document_window.h"
using namespace WinAPI;
[!if PURE_WRAPPER || ON_GENERIC]
int DocumentWindow::HandleMessage( int uMsg, int wParam, int lParam )
{
switch ( uMsg ) {
[!if !PURE_WRAPPER]
case WM_USER: // Replace this with your messages
[!endif]
[!if PURE_WRAPPER]
case WM_CREATE:
return 0;
[!if ON_COMMAND]
case WM_COMMAND:
return 0;
[!endif]
[!if ON_NOTIFY]
case WM_NOTIFY:
return 0;
[!endif]
[!if ON_PAINT]
case WM_PAINT:
{ PaintDC dc( *this );
dc.TextOut( WPoint(50,50), "Hello, World!" );
}
return 0;
[!endif]
[!if ON_SIZE]
case WM_SIZE:
return MDIChildWindow::HandleMessage( uMsg, wParam, lParam );
[!endif]
[!if ON_MOUSE_MOVE]
case WM_MOUSEMOVE:
return 0;
[!endif]
[!if ON_KEY_UP_DOWN]
case WM_KEYDOWN:
return 0;
case WM_KEYUP:
return 0;
[!endif]
[!endif]
default:
return MDIChildWindow::HandleMessage( uMsg, wParam, lParam );
}
}
[!endif]
[!if !PURE_WRAPPER]
[!if ON_CREATE]
bool DocumentWindow::OnCreate( LPCREATESTRUCT lpCreateStruct )
{
return true;
}
[!endif]
[!if ON_COMMAND]
void DocumentWindow::OnCommand( int nIdentifier, int nNotifyCode, HWND hwndControl )
{
switch ( nIdentifier ) {
case 50: // Replace this with your commands
default:
break;
}
}
[!endif]
[!if ON_NOTIFY]
int DocumentWindow::OnNotify( int nIdentifier, LPNMHDR pnmh )
{
return 0;
}
[!endif]
[!if ON_PAINT]
void DocumentWindow::OnPaint()
{
PaintDC dc( *this );
dc.TextOut( WPoint(50,50), "Hello, World!" );
}
[!endif]
[!if ON_SIZE]
void DocumentWindow::OnSize( int sizing, WSize new_size )
{
// Required for the child window to maximize properly
MDIChildWindow::OnSize( sizing, new_size );
}
[!endif]
[!if ON_MOUSE_MOVE]
void DocumentWindow::OnMouseMove( WPoint point, int keys )
{
}
[!endif]
[!if ON_MOUSE_DOWN]
void DocumentWindow::OnMouseDown( WPoint point, int keys, int button )
{
}
[!endif]
[!if ON_MOUSE_UP]
void DocumentWindow::OnMouseUp( WPoint point, int keys, int button )
{
}
[!endif]
[!if ON_MOUSE_DBL_CLK]
void DocumentWindow::OnMouseDblClk( WPoint point, int keys, int button )
{
}
[!endif]
[!if !DIALOG_APP]
[!if ON_KEY_UP_DOWN]
void DocumentWindow::OnKeyDown( int key, int keyData )
{
}
void DocumentWindow::OnKeyUp( int key, int keyData )
{
}
[!endif]
[!endif]
[!endif]
| 16.703448
| 85
| 0.656069
|
cdragan
|
ef82a602364d0663ddfc1520af0a05bce17e5979
| 14,810
|
cpp
|
C++
|
contracts/eosio.system/src/voting.cpp
|
guilledk/telos.contracts
|
eff3dc89c6904196f0cf0591df2c2313e2f57800
|
[
"MIT"
] | 11
|
2020-01-01T00:14:35.000Z
|
2022-03-08T10:50:32.000Z
|
contracts/eosio.system/src/voting.cpp
|
guilledk/telos.contracts
|
eff3dc89c6904196f0cf0591df2c2313e2f57800
|
[
"MIT"
] | 8
|
2020-11-28T06:16:09.000Z
|
2022-03-28T11:53:00.000Z
|
contracts/eosio.system/src/voting.cpp
|
guilledk/telos.contracts
|
eff3dc89c6904196f0cf0591df2c2313e2f57800
|
[
"MIT"
] | 11
|
2020-01-03T00:47:43.000Z
|
2022-01-23T10:07:40.000Z
|
#include <eosio.system/eosio.system.hpp>
#include <eosio/eosio.hpp>
#include <eosio/datastream.hpp>
#include <eosio/serialize.hpp>
#include <eosio/multi_index.hpp>
#include <eosio/privileged.hpp>
#include <eosio/singleton.hpp>
#include <eosio/transaction.hpp>
#include <eosio.token/eosio.token.hpp>
#include <boost/container/flat_map.hpp>
#include "system_rotation.cpp"
#include <algorithm>
#include <cmath>
namespace eosiosystem {
using eosio::const_mem_fun;
using eosio::current_time_point;
using eosio::indexed_by;
using eosio::microseconds;
using eosio::singleton;
void system_contract::regproducer( const name& producer, const eosio::public_key& producer_key, const std::string& url, uint16_t location ) {
check( url.size() < 512, "url too long" );
check( producer_key != eosio::public_key(), "public key should not be the default value" );
require_auth( producer );
const auto ct = current_time_point();
auto prod = _producers.find(producer.value);
if ( prod != _producers.end() ) {
_producers.modify( prod, producer, [&]( producer_info& info ) {
auto now = block_timestamp(current_time_point());
block_timestamp penalty_expiration_time = block_timestamp(info.last_time_kicked.to_time_point() + time_point(hours(int64_t(info.kick_penalty_hours))));
check(now.slot > penalty_expiration_time.slot,
std::string("Producer is not allowed to register at this time. Please fix your node and try again later in: "
+ std::to_string( uint32_t((penalty_expiration_time.slot - now.slot) / 2 ))
+ " seconds").c_str());
info.producer_key = producer_key;
info.url = url;
info.location = location;
info.is_active = true;
info.unreg_reason = "";
});
} else {
_producers.emplace( producer, [&]( producer_info& info ){
info.owner = producer;
info.total_votes = 0;
info.producer_key = producer_key;
info.is_active = true;
info.url = url;
info.location = location;
info.last_claim_time = ct;
info.unreg_reason = "";
});
}
}
void system_contract::unregprod( const name& producer ) {
require_auth( producer );
const auto& prod = _producers.get( producer.value, "producer not found" );
_producers.modify( prod, same_payer, [&]( producer_info& info ){
info.deactivate();
});
}
void system_contract::unregreason( name producer, std::string reason ) {
check( reason.size() < 255, "The reason is too long. Reason should not have more than 255 characters.");
require_auth( producer );
const auto& prod = _producers.get( producer.value, "producer not found" );
_producers.modify( prod, same_payer, [&]( producer_info& info ){
info.deactivate();
info.unreg_reason = reason;
});
}
void system_contract::update_elected_producers( const block_timestamp& block_time ) {
_gstate.last_producer_schedule_update = block_time;
auto idx = _producers.get_index<"prototalvote"_n>();
uint32_t totalActiveVotedProds = uint32_t(std::distance(idx.begin(), idx.end()));
totalActiveVotedProds = totalActiveVotedProds > MAX_PRODUCERS ? MAX_PRODUCERS : totalActiveVotedProds;
std::vector<eosio::producer_key> prods;
prods.reserve(size_t(totalActiveVotedProds));
for ( auto it = idx.cbegin(); it != idx.cend() && prods.size() < totalActiveVotedProds && it->total_votes > 0 && it->active(); ++it ) {
prods.emplace_back( eosio::producer_key{it->owner, it->producer_key} );
}
std::vector<eosio::producer_key> top_producers = check_rotation_state(prods, block_time);
/// sort by producer name
std::sort( top_producers.begin(), top_producers.end() );
auto schedule_version = set_proposed_producers(top_producers);
if (schedule_version >= 0) {
print("\n**new schedule was proposed**");
_gstate.last_proposed_schedule_update = block_time;
_gschedule_metrics.producers_metric.erase( _gschedule_metrics.producers_metric.begin(), _gschedule_metrics.producers_metric.end());
std::vector<producer_metric> psm;
std::for_each(top_producers.begin(), top_producers.end(), [&psm](auto &tp) {
auto bp_name = tp.producer_name;
psm.emplace_back(producer_metric{ bp_name, 12 });
});
_gschedule_metrics.producers_metric = psm;
_gstate.last_producer_schedule_size = static_cast<decltype(_gstate.last_producer_schedule_size)>(top_producers.size());
}
}
/*
* This function caculates the inverse weight voting.
* The maximum weighted vote will be reached if an account votes for the maximum number of registered producers (up to 30 in total).
*/
double system_contract::inverse_vote_weight(double staked, double amountVotedProducers) {
if (amountVotedProducers == 0.0) {
return 0;
}
double percentVoted = amountVotedProducers / MAX_VOTE_PRODUCERS;
double voteWeight = (sin(M_PI * percentVoted - M_PI_2) + 1.0) / 2.0;
return (voteWeight * staked);
}
void system_contract::voteproducer( const name& voter_name, const name& proxy, const std::vector<name>& producers ) {
require_auth( voter_name );
vote_stake_updater( voter_name );
update_votes( voter_name, proxy, producers, true );
// auto rex_itr = _rexbalance.find( voter_name.value ); Remove requirement to vote 21 BPs or select a proxy to stake to REX
// if( rex_itr != _rexbalance.end() && rex_itr->rex_balance.amount > 0 ) {
// check_voting_requirement( voter_name, "voter holding REX tokens must vote for at least 21 producers or for a proxy" );
// }
}
void system_contract::update_votes( const name& voter_name, const name& proxy, const std::vector<name>& producers, bool voting ) {
//validate input
if ( proxy ) {
check( producers.size() == 0, "cannot vote for producers and proxy at same time" );
check( voter_name != proxy, "cannot proxy to self" );
} else {
check( producers.size() <= 30, "attempt to vote for too many producers" );
for( size_t i = 1; i < producers.size(); ++i ) {
check( producers[i-1] < producers[i], "producer votes must be unique and sorted" );
}
}
auto voter = _voters.find( voter_name.value );
check( voter != _voters.end(), "user must stake before they can vote" ); /// staking creates voter object
check( !proxy || !voter->is_proxy, "account registered as a proxy is not allowed to use a proxy" );
auto totalStaked = voter->staked;
if(voter->is_proxy){
totalStaked += voter->proxied_vote_weight;
}
// when unvoting, set the stake used for calculations to 0
// since it is the equivalent to retracting your stake
if(voting && !proxy && producers.size() == 0){
totalStaked = 0;
}
// when a voter or a proxy votes or changes stake, the total_activated stake should be re-calculated
// any proxy stake handling should be done when the proxy votes or on weight propagation
// if(_gstate.thresh_activated_stake_time == 0 && !proxy && !voter->proxy){
if(!proxy && !voter->proxy){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
}
auto new_vote_weight = inverse_vote_weight((double)totalStaked, (double) producers.size());
boost::container::flat_map<name, std::pair< double, bool > > producer_deltas;
// print("\n Voter : ", voter->last_stake, " = ", voter->last_vote_weight, " = ", proxy, " = ", producers.size(), " = ", totalStaked, " = ", new_vote_weight);
//Voter from second vote
if ( voter->last_stake > 0 ) {
//if voter account has set proxy to another voter account
if( voter->proxy ) {
auto old_proxy = _voters.find( voter->proxy.value );
check( old_proxy != _voters.end(), "old proxy not found" ); //data corruption
_voters.modify( old_proxy, same_payer, [&]( auto& vp ) {
vp.proxied_vote_weight -= voter->last_stake;
});
// propagate weight here only when switching proxies
// otherwise propagate happens in the case below
if( proxy != voter->proxy ) {
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *old_proxy );
}
} else {
for( const auto& p : voter->producers ) {
auto& d = producer_deltas[p];
d.first -= voter->last_vote_weight;
d.second = false;
}
}
}
if( proxy ) {
auto new_proxy = _voters.find( proxy.value );
check( new_proxy != _voters.end(), "invalid proxy specified" ); //if ( !voting ) { data corruption } else { wrong vote }
check( !voting || new_proxy->is_proxy, "proxy not found" );
_voters.modify( new_proxy, same_payer, [&]( auto& vp ) {
vp.proxied_vote_weight += voter->staked;
});
if((*new_proxy).last_vote_weight > 0){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *new_proxy );
}
} else {
if( new_vote_weight >= 0 ) {
for( const auto& p : producers ) {
auto& d = producer_deltas[p];
d.first += new_vote_weight;
d.second = true;
}
}
}
for( const auto& pd : producer_deltas ) {
auto pitr = _producers.find( pd.first.value );
if( pitr != _producers.end() ) {
if( voting && !pitr->active() && pd.second.second /* from new set */ ) {
check( false, ( "producer " + pitr->owner.to_string() + " is not currently registered" ).data() );
}
_producers.modify( pitr, same_payer, [&]( auto& p ) {
p.total_votes += pd.second.first;
if ( p.total_votes < 0 ) { // floating point arithmetics can give small negative numbers
p.total_votes = 0;
}
_gstate.total_producer_vote_weight += pd.second.first;
//check( p.total_votes >= 0, "something bad happened" );
});
} else {
if( pd.second.second ) {
check( false, ( "producer " + pd.first.to_string() + " is not registered" ).data() );
}
}
}
_voters.modify( voter, same_payer, [&]( auto& av ) {
av.last_vote_weight = new_vote_weight;
av.last_stake = int64_t(totalStaked);
av.producers = producers;
av.proxy = proxy;
});
}
void system_contract::regproxy( const name& proxy, bool isproxy ) {
//require_auth( proxy );
check ( !isproxy, "proxy voting is disabled" );
auto pitr = _voters.find( proxy.value );
if ( pitr != _voters.end() ) {
check( isproxy != pitr->is_proxy, "action has no effect" );
check( !isproxy || !pitr->proxy, "account that uses a proxy is not allowed to become a proxy" );
_voters.modify( pitr, same_payer, [&]( auto& p ) {
p.is_proxy = isproxy;
});
update_votes(pitr->owner, pitr->proxy, pitr->producers, true);
} else {
_voters.emplace( proxy, [&]( auto& p ) {
p.owner = proxy;
p.is_proxy = isproxy;
});
}
}
void system_contract::propagate_weight_change( const voter_info& voter ) {
check( voter.proxy == name(0) || !voter.is_proxy, "account registered as a proxy is not allowed to use a proxy");
auto totalStake = voter.staked;
if(voter.is_proxy){
totalStake += voter.proxied_vote_weight;
}
double new_weight = inverse_vote_weight((double)totalStake, voter.producers.size());
double delta = new_weight - voter.last_vote_weight;
if (voter.proxy) { // this part should never happen since the function is called only on proxies
if(voter.last_stake != totalStake){
auto &proxy = _voters.get(voter.proxy.value, "proxy not found"); // data corruption
_voters.modify(proxy, same_payer, [&](auto &p) {
p.proxied_vote_weight += totalStake - voter.last_stake;
});
propagate_weight_change(proxy);
}
} else {
for (auto acnt : voter.producers) {
auto &pitr = _producers.get(acnt.value, "producer not found"); // data corruption
_producers.modify(pitr, same_payer, [&](auto &p) {
p.total_votes += delta;
_gstate.total_producer_vote_weight += delta;
});
}
}
_voters.modify(voter, same_payer, [&](auto &v) {
v.last_vote_weight = new_weight;
v.last_stake = totalStake;
});
}
void system_contract::recalculate_votes(){
if (_gstate.total_producer_vote_weight <= -0.1){ // -0.1 threshold for floating point calc ?
_gstate.total_producer_vote_weight = 0;
_gstate.total_activated_stake = 0;
for(auto producer = _producers.begin(); producer != _producers.end(); ++producer){
_producers.modify(producer, same_payer, [&](auto &p) {
p.total_votes = 0;
});
}
boost::container::flat_map< name, bool> processed_proxies;
for (auto voter = _voters.begin(); voter != _voters.end(); ++voter) {
if(voter->proxy && !processed_proxies[voter->proxy]){
auto proxy = _voters.find(voter->proxy.value);
_voters.modify( proxy, same_payer, [&]( auto& av ) {
av.last_vote_weight = 0;
av.last_stake = 0;
av.proxied_vote_weight = 0;
});
processed_proxies[voter->proxy] = true;
}
if(!voter->is_proxy || !processed_proxies[voter->owner]){
_voters.modify( voter, same_payer, [&]( auto& av ) {
av.last_vote_weight = 0;
av.last_stake = 0;
av.proxied_vote_weight = 0;
});
processed_proxies[voter->owner] = true;
}
update_votes(voter->owner, voter->proxy, voter->producers, true);
}
}
}
} /// namespace eosiosystem
| 41.836158
| 164
| 0.594261
|
guilledk
|
ef86603267050f3b4f30e94dfe5e4ada8d338f80
| 8,130
|
cc
|
C++
|
llcc/front-end/src/lexical_analyzer.cc
|
toy-compiler/toy_js_compiler
|
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
|
[
"MIT"
] | 2
|
2019-03-12T07:42:33.000Z
|
2019-03-12T07:42:41.000Z
|
llcc/front-end/src/lexical_analyzer.cc
|
toy-compiler/awesomeCC
|
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
|
[
"MIT"
] | null | null | null |
llcc/front-end/src/lexical_analyzer.cc
|
toy-compiler/awesomeCC
|
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
|
[
"MIT"
] | 1
|
2019-11-29T11:13:22.000Z
|
2019-11-29T11:13:22.000Z
|
/**
* @file lexical_analyzer.cc
* @brief 词法分析器,具体实现
*/
#include "../include/lexical_analyzer.h"
/**
* @brief LexicalAnalyzer类构造函数
*/
LexicalAnalyzer::LexicalAnalyzer() {
in_comment = false;
};
/**
* @brief 判断curPos处是否为空字符
* @return
* -<em>true</em> 是空字符
* -<em>false</em> 不是空字符
*/
bool LexicalAnalyzer::_isBlank() {
char cur_char = sentence[cur_pos];
return (cur_char == '\t' ||
cur_char == '\n' ||
cur_char == '\r' ||
cur_char == ' ');
}
/**
* @brief 判断curPos处是是不是备注开始
* @return
* -<em>true</em> 是备注开始
* -<em>false</em> 不是
*/
bool LexicalAnalyzer::_isCommentStart() {
return (sentence[cur_pos] == '/' &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '*');
}
/**
* @brief 判断curPos处是是不是备注结束
* @return
* -<em>true</em> 是备注结束
* -<em>false</em> 不是
*/
bool LexicalAnalyzer::_isCommentEnd() {
return (sentence[cur_pos] == '*' &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '/');
}
/**
* @brief 自增curPos直到不为空且不为注释中
*/
void LexicalAnalyzer::_skipBlank() {
while (cur_pos < len &&
(_isBlank() || // 是空字符
(in_comment && ! _isCommentEnd()))) // 或者在评论里
cur_pos ++;
if (cur_pos < len && _isCommentEnd()) { // 判断是不是评论的结束
in_comment = false; // 读取 `*/`
cur_pos += 2;
if (cur_pos < len)
_skipBlank(); // 读完注释后继续跳过
}
}
/**
* @brief 设置等待分析的句子,初始化
* @param _sentence string, 等待分析的句子
*/
void LexicalAnalyzer::_init(string _sentence) {
len = int(_sentence.length());
sentence = _sentence;
tokens.clear();
cur_pos = 0;
}
/**
* @brief 判断是否是关键词
* @param word string, 等待分析的词
* @return
* -<em>true</em> 是关键词
* -<em>false</em> 不是关键词
*/
bool LexicalAnalyzer::_isKeyword(string word) {
for (string kw: Token::KEYWORDS)
if (kw == word)
return true;
return false;
}
/**
* @brief 判断是否是分隔符
* @param ch char, 等待分析的字符
* @return
* -<em>true</em> 是分隔符
* -<em>false</em> 不是分隔符
*/
bool LexicalAnalyzer::_isSeparator(char ch) {
for (char sp: Token::SEPARATORS)
if (sp == ch)
return true;
return false;
}
/**
* @brief 判断是否是运算符
* @param ch char, 等待分析的字符
* @return
* -<em>true</em> 是运算符
* -<em>false</em> 不是运算符
*/
bool LexicalAnalyzer::_isOperator(char ch) {
for (auto o: Token::OPERATORS)
if (ch == o[0])
return true;
return false;
}
/**
* @brief 分析当前句子
*/
void LexicalAnalyzer::_analyze() {
char cur_char;
while (cur_pos < len) {
_skipBlank();
cur_char = sentence[cur_pos];
// 处理注释
if (_isCommentStart()) {
in_comment = true;
cur_pos += 2;
continue;
}
// 关键字 和 标识符
else if (isalpha(cur_char) || cur_char == '_') {
// 找结尾
int temp_len = 0;
while (cur_pos + temp_len <= len &&
(isalpha(sentence[cur_pos + temp_len]) || // 字母
sentence[cur_pos + temp_len] == '_' || // _
isdigit(sentence[cur_pos + temp_len]))) // 数字
temp_len ++;
// 截取 并 加入token列表
string temp_str = sentence.substr(cur_pos, temp_len);
tokens.emplace_back(Token(temp_str,
_isKeyword(temp_str) ? TOKEN_TYPE_ENUM::KEYWORD : TOKEN_TYPE_ENUM::IDENTIFIER,
cur_pos, cur_line_number));
cur_pos += temp_len;
continue;
}
// 数字常量
else if (isdigit(cur_char) || cur_char == '.') {
// 找结尾
int temp_len = 0;
bool hasDot = false;
while (cur_pos + temp_len <= len &&
(isdigit(sentence[cur_pos + temp_len]) || sentence[cur_pos + temp_len] == '.')) {
if (sentence[cur_pos + temp_len] == '.') {
if (not hasDot)
hasDot = true;
else
throw Error("in digit constant, too many dots in one number",
cur_line_number, cur_pos);
}
temp_len ++;
}
// 截取 并 加入token列表
tokens.emplace_back(Token(sentence.substr(cur_pos, temp_len),
TOKEN_TYPE_ENUM::DIGIT_CONSTANT,
cur_pos, cur_line_number));
cur_pos += temp_len;
continue;
}
// 分隔符 和 字符串常量
else if (_isSeparator(cur_char)) {
// 先加入token列表
string temp_str = sentence.substr(cur_pos, 1);
tokens.emplace_back(Token(temp_str, TOKEN_TYPE_ENUM::SEPARATOR,
cur_pos, cur_line_number));
// 如果是 `'`或者`"` 需要考虑一下匹配
int temp_len = 0;
if (cur_char == '\"' || cur_char == '\'') {
cur_pos ++;
while (cur_pos + temp_len < len &&
sentence[cur_pos + temp_len] != cur_char)
temp_len ++;
// 匹配不上
if (cur_pos + temp_len >= len || sentence[cur_pos + temp_len] != cur_char)
throw Error("in string constant, lack of " + char2string(cur_char),
cur_line_number, cur_pos);
tokens.emplace_back(Token(sentence.substr(cur_pos, temp_len),
TOKEN_TYPE_ENUM::STRING_CONSTANT,
cur_pos + 1, cur_line_number));
cur_pos += temp_len;
tokens.emplace_back(Token(temp_str, TOKEN_TYPE_ENUM::SEPARATOR,
cur_pos + 1, cur_line_number));
}
cur_pos ++;
continue;
}
// 运算符
else if (_isOperator(cur_char)) {
// ++ -- << >> && || ==
if ((cur_char == '+' || cur_char == '-' || cur_char == '<' || cur_char == '>' ||
cur_char == '&' || cur_char == '|' || cur_char == '=') &&
cur_pos + 1 < len && sentence[cur_pos + 1] == cur_char) {
tokens.emplace_back(Token(sentence.substr(cur_pos, 2), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos += 2;
}
// <= >= !=
else if ((cur_char == '<' || cur_char == '>' || cur_char == '!') &&
cur_pos + 1 < len &&
sentence[cur_pos + 1] == '=') {
tokens.emplace_back(Token(sentence.substr(cur_pos, 2), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos += 2;
}
// 一位的运算符
else {
tokens.emplace_back(Token(sentence.substr(cur_pos, 1), TOKEN_TYPE_ENUM::OPERATOR,
cur_pos, cur_line_number));
cur_pos ++;
}
continue;
}
cur_pos ++;
}
}
/**
* @brief 分析一个程序(很多句子),如果正确生成Token列表,如果错误生成错误列表
* @param _sentences vector string, 等待分析的程序
* @param verbose bool, 是否就地输出tokens
*/
void LexicalAnalyzer::analyze(vector<string> _sentences, bool verbose) {
cur_line_number = 0;
in_comment = false;
all_tokens.clear();
try {
for (auto _s: _sentences) {
cur_line_number ++;
_init(_s);
_analyze();
for (auto t: tokens)
all_tokens.emplace_back(t);
}
if (verbose) {
cout << "Tokens\n";
for (auto t: all_tokens)
cout << t;
}
}
catch (Error & e) {
cout << "Lexical analyze errors" << endl;
cout << e;
exit(0);
}
}
/**
* @brief 得到Token列表
* @return vector<Token>
*/
vector<Token> LexicalAnalyzer::getAllTokens() {
return all_tokens;
}
| 26.057692
| 116
| 0.473924
|
toy-compiler
|
ef8fb8f51b907e2072632953e558b3c0a16d7b9d
| 56
|
hpp
|
C++
|
src/boost_wave_grammars_cpp_expression_value.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_wave_grammars_cpp_expression_value.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_wave_grammars_cpp_expression_value.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/wave/grammars/cpp_expression_value.hpp>
| 28
| 55
| 0.839286
|
miathedev
|
ef9059aafa477bd01466cb3170654a32160d5cd4
| 12,745
|
cpp
|
C++
|
src/video_compress/dxt_glsl.cpp
|
thpryrchn/UltraGrid
|
f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289
|
[
"BSD-3-Clause"
] | 370
|
2016-10-05T15:19:00.000Z
|
2022-03-29T22:12:28.000Z
|
src/video_compress/dxt_glsl.cpp
|
thpryrchn/UltraGrid
|
f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289
|
[
"BSD-3-Clause"
] | 165
|
2016-11-21T13:01:36.000Z
|
2022-03-31T20:01:20.000Z
|
src/video_compress/dxt_glsl.cpp
|
thpryrchn/UltraGrid
|
f9fdd96ff73e05888d26c40aaaccdf4eb5fe7289
|
[
"BSD-3-Clause"
] | 63
|
2016-10-13T12:07:45.000Z
|
2022-03-23T19:46:10.000Z
|
/**
* @file video_compress/dxt_glsl.cpp
* @author Martin Pulec <pulec@cesnet.cz>
*/
/*
* Copyright (c) 2011-2014 CESNET, z. s. p. o.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of CESNET 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 AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED 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 AUTHORS 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#include "config_unix.h"
#include "config_win32.h"
#endif // HAVE_CONFIG_H
#include <stdlib.h>
#include "gl_context.h"
#include "debug.h"
#include "dxt_compress/dxt_encoder.h"
#include "dxt_compress/dxt_util.h"
#include "host.h"
#include "lib_common.h"
#include "module.h"
#include "utils/video_frame_pool.h"
#include "video.h"
#include "video_compress.h"
#include <memory>
using namespace std;
namespace {
struct state_video_compress_rtdxt {
struct module module_data;
struct dxt_encoder **encoder;
int encoder_count;
decoder_t decoder;
unique_ptr<char []> decoded;
unsigned int configured:1;
unsigned int interlaced_input:1;
codec_t color_spec;
int encoder_input_linesize;
struct gl_context gl_context;
video_frame_pool pool;
};
static int configure_with(struct state_video_compress_rtdxt *s, struct video_frame *frame);
static void dxt_glsl_compress_done(struct module *mod);
static int configure_with(struct state_video_compress_rtdxt *s, struct video_frame *frame)
{
unsigned int x;
enum dxt_format format;
for (x = 0; x < frame->tile_count; ++x) {
if (vf_get_tile(frame, x)->width != vf_get_tile(frame, 0)->width ||
vf_get_tile(frame, x)->width != vf_get_tile(frame, 0)->width) {
fprintf(stderr,"[RTDXT] Requested to compress tiles of different size!");
exit_uv(EXIT_FAILURE);
return FALSE;
}
}
if (get_bits_per_component(frame->color_spec) > 8) {
LOG(LOG_LEVEL_NOTICE) << "[RTDXT] Converting from " << get_bits_per_component(frame->color_spec) <<
" to 8 bits. You may directly capture 8-bit signal to improve performance.\n";
}
switch (frame->color_spec) {
case RGB:
s->decoder = vc_memcpy;
format = DXT_FORMAT_RGB;
break;
case RGBA:
s->decoder = vc_memcpy;
format = DXT_FORMAT_RGBA;
break;
case R10k:
s->decoder = (decoder_t) vc_copyliner10k;
format = DXT_FORMAT_RGBA;
break;
case YUYV:
s->decoder = (decoder_t) vc_copylineYUYV;
format = DXT_FORMAT_YUV422;
break;
case UYVY:
s->decoder = vc_memcpy;
format = DXT_FORMAT_YUV422;
break;
case v210:
s->decoder = (decoder_t) vc_copylinev210;
format = DXT_FORMAT_YUV422;
break;
case DVS10:
s->decoder = (decoder_t) vc_copylineDVS10;
format = DXT_FORMAT_YUV422;
break;
case DPX10:
s->decoder = (decoder_t) vc_copylineDPX10toRGBA;
format = DXT_FORMAT_RGBA;
break;
default:
fprintf(stderr, "[RTDXT] Unknown codec: %d\n", frame->color_spec);
exit_uv(EXIT_FAILURE);
return FALSE;
}
int data_len = 0;
s->encoder = (struct dxt_encoder **) calloc(frame->tile_count, sizeof(struct dxt_encoder *));
if(s->color_spec == DXT1) {
for(int i = 0; i < (int) frame->tile_count; ++i) {
s->encoder[i] =
dxt_encoder_create(DXT_TYPE_DXT1, frame->tiles[0].width, frame->tiles[0].height, format,
s->gl_context.legacy);
}
data_len = dxt_get_size(frame->tiles[0].width, frame->tiles[0].height, DXT_TYPE_DXT1);
} else if(s->color_spec == DXT5){
for(int i = 0; i < (int) frame->tile_count; ++i) {
s->encoder[i] =
dxt_encoder_create(DXT_TYPE_DXT5_YCOCG, frame->tiles[0].width, frame->tiles[0].height, format,
s->gl_context.legacy);
}
data_len = dxt_get_size(frame->tiles[0].width, frame->tiles[0].height, DXT_TYPE_DXT5_YCOCG);
}
s->encoder_count = frame->tile_count;
for(int i = 0; i < (int) frame->tile_count; ++i) {
if(s->encoder[i] == NULL) {
fprintf(stderr, "[RTDXT] Unable to create decoder.\n");
exit_uv(EXIT_FAILURE);
return FALSE;
}
}
s->encoder_input_linesize = frame->tiles[0].width;
switch(format) {
case DXT_FORMAT_RGBA:
s->encoder_input_linesize *= 4;
break;
case DXT_FORMAT_RGB:
s->encoder_input_linesize *= 3;
break;
case DXT_FORMAT_YUV422:
s->encoder_input_linesize *= 2;
break;
case DXT_FORMAT_YUV:
/* not used - just not compilator to complain */
abort();
break;
}
assert(data_len > 0);
assert(s->encoder_input_linesize > 0);
struct video_desc compressed_desc;
compressed_desc = video_desc_from_frame(frame);
compressed_desc.color_spec = s->color_spec;
/* We will deinterlace the output frame */
if(frame->interlacing == INTERLACED_MERGED) {
compressed_desc.interlacing = PROGRESSIVE;
s->interlaced_input = TRUE;
fprintf(stderr, "[DXT compress] Enabling automatic deinterlacing.\n");
} else {
s->interlaced_input = FALSE;
}
s->pool.reconfigure(compressed_desc, data_len);
s->decoded = unique_ptr<char []>(new char[4 * compressed_desc.width * compressed_desc.height]);
s->configured = TRUE;
return TRUE;
}
static bool dxt_is_supported()
{
struct gl_context gl_context;
if (!init_gl_context(&gl_context, GL_CONTEXT_ANY)) {
return false;
} else {
destroy_gl_context(&gl_context);
return true;
}
}
struct module *dxt_glsl_compress_init(struct module *parent, const char *opts)
{
struct state_video_compress_rtdxt *s;
if(strcmp(opts, "help") == 0) {
printf("DXT GLSL comperssion usage:\n");
printf("\t-c RTDXT:DXT1\n");
printf("\t\tcompress with DXT1\n");
printf("\t-c RTDXT:DXT5\n");
printf("\t\tcompress with DXT5 YCoCg\n");
return &compress_init_noerr;
}
s = new state_video_compress_rtdxt();
if (strcasecmp(opts, "DXT5") == 0) {
s->color_spec = DXT5;
} else if (strcasecmp(opts, "DXT1") == 0) {
s->color_spec = DXT1;
} else if (opts[0] == '\0') {
s->color_spec = DXT1;
} else {
fprintf(stderr, "Unknown compression: %s\n", opts);
delete s;
return NULL;
}
if(!init_gl_context(&s->gl_context, GL_CONTEXT_ANY)) {
fprintf(stderr, "[RTDXT] Error initializing GL context");
delete s;
return NULL;
}
gl_context_make_current(NULL);
module_init_default(&s->module_data);
s->module_data.cls = MODULE_CLASS_DATA;
s->module_data.priv_data = s;
s->module_data.deleter = dxt_glsl_compress_done;
module_register(&s->module_data, parent);
return &s->module_data;
}
shared_ptr<video_frame> dxt_glsl_compress(struct module *mod, shared_ptr<video_frame> tx)
{
struct state_video_compress_rtdxt *s = (struct state_video_compress_rtdxt *) mod->priv_data;
int i;
unsigned char *line1, *line2;
unsigned int x;
gl_context_make_current(&s->gl_context);
if(!s->configured) {
int ret;
ret = configure_with(s, tx.get());
if(!ret)
return NULL;
}
shared_ptr<video_frame> out_frame = s->pool.get_frame();
for (x = 0; x < tx->tile_count; ++x) {
struct tile *in_tile = vf_get_tile(tx.get(), x);
struct tile *out_tile = vf_get_tile(out_frame.get(), x);
line1 = (unsigned char *) in_tile->data;
line2 = (unsigned char *) s->decoded.get();
for (i = 0; i < (int) in_tile->height; ++i) {
s->decoder(line2, line1, s->encoder_input_linesize,
0, 8, 16);
line1 += vc_get_linesize(in_tile->width, tx->color_spec);
line2 += s->encoder_input_linesize;
}
if(s->interlaced_input)
vc_deinterlace((unsigned char *) s->decoded.get(), s->encoder_input_linesize,
in_tile->height);
dxt_encoder_compress(s->encoder[x],
(unsigned char *) s->decoded.get(),
(unsigned char *) out_tile->data);
}
gl_context_make_current(NULL);
return out_frame;
}
static void dxt_glsl_compress_done(struct module *mod)
{
struct state_video_compress_rtdxt *s = (struct state_video_compress_rtdxt *) mod->priv_data;
if(s->encoder) {
for(int i = 0; i < s->encoder_count; ++i) {
if(s->encoder[i])
dxt_encoder_destroy(s->encoder[i]);
}
}
destroy_gl_context(&s->gl_context);
delete s;
}
const struct video_compress_info rtdxt_info = {
"RTDXT",
dxt_glsl_compress_init,
dxt_glsl_compress,
NULL,
NULL,
NULL,
NULL,
NULL,
[] {
return dxt_is_supported() ? list<compress_preset>{
{ "DXT1", 35, [](const struct video_desc *d){return (long)(d->width * d->height * d->fps * 4.0);},
{75, 0.3, 25}, {15, 0.1, 10} },
{ "DXT5", 50, [](const struct video_desc *d){return (long)(d->width * d->height * d->fps * 8.0);},
{75, 0.3, 35}, {15, 0.1, 20} },
} : list<compress_preset>{};
},
NULL
};
REGISTER_MODULE(rtdxt, &rtdxt_info, LIBRARY_CLASS_VIDEO_COMPRESS, VIDEO_COMPRESS_ABI_VERSION);
} // end of anonymous namespace
| 36.104816
| 126
| 0.537466
|
thpryrchn
|
ef91c55817be5168e77058674085a768af6a087d
| 628
|
cpp
|
C++
|
5_lesson/run.cpp
|
JonMuehlst/INTROCPP
|
5f394c58c66a873bafb11dce54207a1dd580c916
|
[
"MIT"
] | null | null | null |
5_lesson/run.cpp
|
JonMuehlst/INTROCPP
|
5f394c58c66a873bafb11dce54207a1dd580c916
|
[
"MIT"
] | null | null | null |
5_lesson/run.cpp
|
JonMuehlst/INTROCPP
|
5f394c58c66a873bafb11dce54207a1dd580c916
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "binom.h"
#include "selection_sort.h"
#include "gtest/gtest.h"
int main(int argc, char **argv) {
/*
Selection sort
*/
int arr[MAX_ARR_SIZE]; // static allocation
int arr_size= getArrayFromInput(arr, MAX_ARR_SIZE);
printArr(arr, 0, arr_size);
sort(arr, arr_size);
printArr(arr, 0, arr_size);
/*
Binom
*/
int n = 5, k = 3, ans = 0;
ans = binom(n,k);
std::cout << "n choose k equals: " << ans << std::endl;
/*
run tests
*/
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 16.972973
| 59
| 0.55414
|
JonMuehlst
|
aab3d8b8a09a2743d0de5116ee225498ed961872
| 2,822
|
cpp
|
C++
|
Packer/RepetitionFinder.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | 67
|
2018-03-02T10:50:02.000Z
|
2022-03-23T18:20:29.000Z
|
Packer/RepetitionFinder.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | null | null | null |
Packer/RepetitionFinder.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | 9
|
2018-03-01T16:38:28.000Z
|
2021-03-02T16:17:09.000Z
|
//-------------------------------------
// (c) Reliable Software 1999-2003
// ------------------------------------
#include "precompiled.h"
#include "RepetitionFinder.h"
#include "Repetitions.h"
#include "ForgetfulHashTable.h"
#include "Statistics.h"
#include "Bucketizer.h"
#include <Ex/WinEx.h>
RepetitionFinder::RepetitionFinder (char const * buf,
File::Size size,
Repetitions & repetitions,
ForgetfulHashTable & hashtable)
: _buf (buf),
_size (size.Low ()),
_scanEnd (size.Low () - MinRepetitionLength - 1),
_repetitions (repetitions),
_hashtable (hashtable),
_current (0)
{
if (size.IsLarge ())
throw Win::Exception ("File size exceeds 4GB", 0, 0);
if (_size <= MinRepetitionLength)
_scanEnd = _size - 1;
}
void RepetitionFinder::Find (Statistics & stats)
{
while (_current < _scanEnd)
{
if (FoundRepetition ())
{
_repetitions.Add (_curRepetition);
stats.RecordRepetition (_curRepetition.GetLen (), _curRepetition.GetBackwardDist ());
_current += _curRepetition.GetLen ();
}
else
{
stats.RecordLiteral (_buf [_current++]);
}
}
while (_current < _size)
{
stats.RecordLiteral (_buf [_current++]);
}
}
bool RepetitionFinder::FoundRepetition ()
{
_curRepetition.SetTarget (_current);
_curRepetition.SetLen (MinRepetitionLength - 1);
ForgetfulHashTable::PositionListIter iter = _hashtable.Save (Hash (), _current);
// Go over all found so far repetitions and check if they match the current byte sequence
for ( ; !iter.AtEnd () && _curRepetition.GetLen () < 10; iter.Advance ())
{
unsigned int repStart = iter.GetPosition ();
Assert (_current > repStart);
unsigned int backwardDist = _current - repStart;
if (backwardDist > RepDistBucketizer::GetMaxRepetitionDistance ())
{
// Repetition is too far away from the current position in the buffer.
// Remove repetitions that are too far away from the hash table.
iter.ShortenList ();
break;
}
// Close enough -- check if long enough
if (_buf [_current + _curRepetition.GetLen ()] == _buf [repStart + _curRepetition.GetLen ()])
{
unsigned int thisRepLen = 0;
for ( ; thisRepLen < RepLenBucketizer::GetMaxRepetitionLength (); ++thisRepLen)
{
if ((_current + thisRepLen == _scanEnd) ||
(_buf [repStart + thisRepLen] != _buf [_current + thisRepLen]))
{
break;
}
}
if (thisRepLen > _curRepetition.GetLen ())
{
_curRepetition.SetLen (thisRepLen);
_curRepetition.SetFrom (repStart);
}
}
}
// We have found repetition if it is long enough and at economical
// distance for repetitions of lenght greater then 3
return _curRepetition.GetLen () >= MinRepetitionLength &&
(_curRepetition.GetLen () > 3 || _curRepetition.GetBackwardDist () < EconomicalDistanceFor3ByteRepetitionLength);
}
| 30.021277
| 118
| 0.668675
|
BartoszMilewski
|
aab3fb72d062e9215459ab412efd3751d795aac5
| 5,466
|
cpp
|
C++
|
editor/audio/Player.cpp
|
minhvien5059/congnghe_Vietnam
|
06d6efce856ba369db340a2d834e003fe5a99fa0
|
[
"BSD-3-Clause"
] | 40
|
2015-09-03T05:50:42.000Z
|
2022-02-25T10:00:01.000Z
|
editor/audio/Player.cpp
|
minhvien5059/congnghe_Vietnam
|
06d6efce856ba369db340a2d834e003fe5a99fa0
|
[
"BSD-3-Clause"
] | 1
|
2017-10-24T14:30:13.000Z
|
2017-11-07T02:14:10.000Z
|
editor/audio/Player.cpp
|
minhvien5059/congnghe_Vietnam
|
06d6efce856ba369db340a2d834e003fe5a99fa0
|
[
"BSD-3-Clause"
] | 7
|
2017-03-13T07:08:19.000Z
|
2021-06-01T01:06:05.000Z
|
/* Player.cpp from QTau http://github.com/qtau-devgroup/editor by digited, BSD license */
#include "audio/Player.h"
#include "audio/Source.h"
#include "audio/Mixer.h"
#include "Utils.h"
#include <QAudioOutput>
#include <QThread>
#include <QTimer>
#include <QDebug>
#include <QApplication>
qtmmPlayer::qtmmPlayer() :
audioOutput(nullptr), mixer(nullptr), stopTimer(nullptr), volume(50)
{
vsLog::d("QtMultimedia :: supported output devices and codecs:");
QList<QAudioDeviceInfo> advs = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
foreach (QAudioDeviceInfo i, advs)
vsLog::d(QString("%1 %2").arg(i.deviceName()).arg(i.supportedCodecs().join(' ')));
open(QIODevice::ReadOnly);
}
qtmmPlayer::~qtmmPlayer()
{
close();
delete stopTimer;
delete audioOutput;
delete mixer;
}
qint64 qtmmPlayer::size() const
{
return mixer->bytesAvailable();
}
void qtmmPlayer::threadedInit()
{
stopTimer = new QTimer();
stopTimer->setSingleShot(true);
connect(stopTimer, &QTimer::timeout, this, &qtmmPlayer::stop);
mixer = new qtauSoundMixer();
connect(mixer, &qtauSoundMixer::effectEnded, this, &qtmmPlayer::onEffectEnded);
connect(mixer, &qtauSoundMixer::trackEnded, this, &qtmmPlayer::onTrackEnded);
connect(mixer, &qtauSoundMixer::allEffectsEnded, this, &qtmmPlayer::onAllEffectsEnded);
connect(mixer, &qtauSoundMixer::allTracksEnded, this, &qtmmPlayer::onAllTracksEnded);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
QAudioFormat fmt = mixer->getAudioFormat();
if (info.isFormatSupported(fmt))
{
QAudioDeviceInfo di(QAudioDeviceInfo::defaultOutputDevice());
audioOutput = new QAudioOutput(di, fmt, this);
audioOutput->setVolume((qreal)volume / 100.f);
connect(audioOutput, SIGNAL(stateChanged(QAudio::State)), SLOT(onQtmmStateChanged(QAudio::State)));;
connect(audioOutput, SIGNAL(notify()), SLOT(onTick()));
}
else vsLog::e("Default audio format not supported by QtMultimedia backend, cannot play audio.");
}
void qtmmPlayer::addEffect(qtauAudioSource *e, bool replace, bool smoothly, bool copy)
{
qtauAudioSource *added = e;
if (copy)
added = new qtauAudioSource(e->data(), e->getAudioFormat());
effects.append(added);
mixer->addEffect(added, replace, smoothly);
}
void qtmmPlayer::addTrack (qtauAudioSource *t, bool replace, bool smoothly, bool copy)
{
qtauAudioSource *added = t;
if (copy)
added = new qtauAudioSource(t->data(), t->getAudioFormat());
tracks.append(added);
mixer->addTrack(added, replace, smoothly);
}
qint64 qtmmPlayer::readData(char *data, qint64 maxlen)
{
qint64 result = mixer->read(data, maxlen);
if (result < maxlen)
{
if (result == 0)
stopTimer->start(500);
memset(data + result, 0, maxlen - result); // silence
result = maxlen; // else it'll complain on "buffer underflow"... and will keep asking for more
}
return result;
}
void qtmmPlayer::play()
{
stopTimer->stop();
if (audioOutput->state() == QAudio::SuspendedState)
audioOutput->resume();
else
if (audioOutput->state() != QAudio::ActiveState)
{
audioOutput->reset();
audioOutput->start(this);
}
}
void qtmmPlayer::pause()
{
stopTimer->stop();
audioOutput->suspend();
}
void qtmmPlayer::stop()
{
stopTimer->stop();
audioOutput->stop();
if (!mixer->atEnd())
mixer->clear();
}
void qtmmPlayer::setVolume(int level)
{
level = qMax(qMin(level, 100), 0);
volume = level;
if (audioOutput)
audioOutput->setVolume((qreal)level / 100.f);
}
void qtmmPlayer::onEffectEnded(qtauAudioSource* e)
{
int ind = effects.indexOf(e);
if (ind != -1)
{
delete e;
effects.removeAt(ind);
}
}
void qtmmPlayer::onTrackEnded(qtauAudioSource* t)
{
int ind = tracks.indexOf(t);
if (ind != -1)
{
delete t;
tracks.removeAt(ind);
}
}
void qtmmPlayer::onAllEffectsEnded()
{
if (!effects.isEmpty())
{
for (auto &e: effects)
delete e;
effects.clear();
}
}
void qtmmPlayer::onAllTracksEnded()
{
if (!tracks.isEmpty())
{
for (auto &t: tracks)
delete t;
tracks.clear();
}
emit playbackEnded();
}
inline QString audioStatusToString(QAudio::State st)
{
QString result = QStringLiteral("unknown");
switch (st)
{
case QAudio::ActiveState: result = QStringLiteral("active"); break;
case QAudio::IdleState: result = QStringLiteral("idle"); break;
case QAudio::StoppedState: result = QStringLiteral("stopped"); break;
case QAudio::SuspendedState: result = QStringLiteral("suspended"); break;
default:
break;
}
return result;
}
void qtmmPlayer::onQtmmStateChanged(QAudio::State /*st*/)
{
// qDebug() << "audio status:" << audioStatusToString(st);
// switch (st) // doesn't really matter now
// {
// case QAudio::ActiveState:
// case QAudio::SuspendedState:
// break;
// case QAudio::StoppedState:
// case QAudio::IdleState:
// mixer->clear();
// break;
// default:
// vsLog::e(QString("Unknown Qtmm Audio state: %1").arg(st));
// break;
// }
}
void qtmmPlayer::onTick() { emit tick(audioOutput->processedUSecs()); }
| 23.973684
| 108
| 0.637029
|
minhvien5059
|
aab56c1cca596c00a4365ee563d586d8b22f860e
| 6,262
|
hpp
|
C++
|
tools/seec-view/ExplanationViewer.hpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 7
|
2018-06-25T12:06:13.000Z
|
2022-01-18T09:20:13.000Z
|
tools/seec-view/ExplanationViewer.hpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 20
|
2016-12-01T23:46:12.000Z
|
2019-08-11T02:41:04.000Z
|
tools/seec-view/ExplanationViewer.hpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 1
|
2020-10-19T03:20:05.000Z
|
2020-10-19T03:20:05.000Z
|
//===- tools/seec-trace-view/ExplanationViewer.hpp ------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
#define SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
#include "seec/Clang/MappedValue.hpp"
#include "seec/ClangEPV/ClangEPV.hpp"
#include "seec/Util/Observer.hpp"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include <wx/wx.h>
#include <wx/panel.h>
#include <wx/stc/stc.h>
#include <memory>
#include <string>
// Forward declarations.
namespace clang {
class Decl;
class Stmt;
} // namespace clang
namespace seec {
namespace cm {
class FunctionState;
class ProcessState;
}
}
class ActionRecord;
class ActionReplayFrame;
class ColourScheme;
class ContextNotifier;
class IndexedAnnotationText;
class OpenTrace;
class StateAccessToken;
/// \brief ExplanationViewer.
///
class ExplanationViewer final : public wxStyledTextCtrl
{
/// The trace that this viewer will display states from.
OpenTrace *Trace;
/// The central handler for context notifications.
ContextNotifier *Notifier;
/// Registration to ColourSchemeSettings changes.
seec::observer::registration m_ColourSchemeSettingsRegistration;
/// Used to record user interactions.
ActionRecord *Recording;
/// Holds the current annotation text.
std::unique_ptr<IndexedAnnotationText> Annotation;
/// Holds the byte length of displayed annotation text.
long AnnotationLength;
/// Hold current explanatory material.
std::unique_ptr<seec::clang_epv::Explanation> Explanation;
/// Caches the current mouse position.
int CurrentMousePosition;
/// Currently highlighted Decl.
::clang::Decl const *HighlightedDecl;
/// Currently highlighted Stmt.
::clang::Stmt const *HighlightedStmt;
/// Is the mouse currently hovering on a URL?
bool URLHover;
/// The URL that the mouse is hovering over.
std::string URLHovered;
/// Is the mouse on the same URL as when the left button was clicked?
bool URLClick;
/// \brief Get byte offset range from "whole character" range.
///
std::pair<int, int> getAnnotationByteOffsetRange(int32_t Start, int32_t End);
/// \brief Get byte offset range from "whole character" range.
///
std::pair<int, int> getExplanationByteOffsetRange(int32_t Start, int32_t End);
/// \brief Set the annotation text.
///
void setAnnotationText(wxString const &Value);
/// \brief Set the explanation text.
///
void setExplanationText(wxString const &Value);
/// \brief Set indicators for the interactive text areas in the current
/// \c Explanation.
///
void setExplanationIndicators();
/// \brief Handle mouse moving over a link to a \c clang::Decl.
///
void mouseOverDecl(clang::Decl const *);
/// \brief Handle mouse moving over a link to a \c clang::Stmt.
///
void mouseOverStmt(clang::Stmt const *);
/// \brief Handle mouse moving over a hyperlink.
///
void mouseOverHyperlink(UnicodeString const &);
/// \brief Clear the current information.
///
void clearCurrent();
/// \brief Update this viewer to the given \c ColourScheme.
///
void updateColourScheme(ColourScheme const &Scheme);
public:
/// \brief Construct without creating.
///
ExplanationViewer()
: wxStyledTextCtrl(),
Trace(nullptr),
Notifier(nullptr),
m_ColourSchemeSettingsRegistration(),
Recording(nullptr),
Annotation(nullptr),
AnnotationLength(0),
Explanation(),
CurrentMousePosition(wxSTC_INVALID_POSITION),
HighlightedDecl(nullptr),
HighlightedStmt(nullptr),
URLHover(false),
URLHovered(),
URLClick(false)
{}
/// \brief Construct and create.
///
ExplanationViewer(wxWindow *Parent,
OpenTrace &WithTrace,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID = wxID_ANY,
wxPoint const &Position = wxDefaultPosition,
wxSize const &Size = wxDefaultSize)
: ExplanationViewer()
{
Create(Parent, WithTrace, WithNotifier, WithRecording, WithReplay, ID,
Position, Size);
}
/// \brief Destructor.
///
virtual ~ExplanationViewer();
/// \brief Create the viewer.
///
bool Create(wxWindow *Parent,
OpenTrace &WithTrace,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID = wxID_ANY,
wxPoint const &Position = wxDefaultPosition,
wxSize const &Size = wxDefaultSize);
/// \name Mouse events.
/// @{
void OnMotion(wxMouseEvent &Event);
void OnEnterWindow(wxMouseEvent &Event);
void OnLeaveWindow(wxMouseEvent &Event);
void OnLeftDown(wxMouseEvent &Event);
void OnLeftUp(wxMouseEvent &Event);
/// @} (Mouse events)
/// \name Mutators.
/// @{
private:
/// \brief Show annotations for this state.
/// \return true iff ClangEPV explanation should be suppressed.
///
bool showAnnotations(seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread);
public:
void show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread);
/// \brief Attempt to show an explanation for the given Decl.
///
void showExplanation(::clang::Decl const *Decl);
/// \brief Attempt to show an explanation for the given Stmt.
///
/// pre: Caller must have locked access to the state containing InFunction.
///
void showExplanation(::clang::Stmt const *Statement,
::seec::cm::FunctionState const &InFunction);
/// \brief Clear the display.
///
void clearExplanation();
/// @} (Mutators)
};
#endif // SEEC_TRACE_VIEW_EXPLANATIONVIEWER_HPP
| 26.091667
| 80
| 0.648195
|
seec-team
|
aab965312397f90f3c18b850ecf341fe64ca32e9
| 2,825
|
cpp
|
C++
|
Tekken-7-Frames-To-Speech/audio.cpp
|
n-o-u/Tekken-7-Frames-To-Speech
|
b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d
|
[
"MIT"
] | 1
|
2021-01-28T22:12:28.000Z
|
2021-01-28T22:12:28.000Z
|
Tekken-7-Frames-To-Speech/audio.cpp
|
n-o-u/Tekken-7-Frames-To-Speech
|
b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d
|
[
"MIT"
] | null | null | null |
Tekken-7-Frames-To-Speech/audio.cpp
|
n-o-u/Tekken-7-Frames-To-Speech
|
b0c794464f34e0c0cdc3a848be3b51fc7e33ca1d
|
[
"MIT"
] | 1
|
2021-01-28T22:12:59.000Z
|
2021-01-28T22:12:59.000Z
|
#include "frames-to-speech.h"
#include "resource.h"
#include "audio.h"
void playFramesAudio(int frames) {
LPCWSTR path = getWavResourcePath(frames);
if (path != 0) {
PlaySound(path, GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
//PlaySound(path, GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC); //directly from a file
}
//PlaySound(path, GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//char* buffer = loadWavFile((char*)WAV_14_PATH);
//PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
}
LPCWSTR getWavResourcePath(int frames) {
LPCWSTR path = 0;
switch (frames) {
case 10:
path = MAKEINTRESOURCE(IDR_WAVE10);
break;
case 11:
path = MAKEINTRESOURCE(IDR_WAVE11);
break;
case 12:
path = MAKEINTRESOURCE(IDR_WAVE12);
break;
case 13:
path = MAKEINTRESOURCE(IDR_WAVE13);
break;
case 14:
path = MAKEINTRESOURCE(IDR_WAVE14);
break;
case 15:
path = MAKEINTRESOURCE(IDR_WAVE15);
break;
case 16:
path = MAKEINTRESOURCE(IDR_WAVE16);
break;
case 17:
path = MAKEINTRESOURCE(IDR_WAVE17);
break;
case 18:
path = MAKEINTRESOURCE(IDR_WAVE18);
break;
case 19:
path = MAKEINTRESOURCE(IDR_WAVE19);
break;
case 20:
path = MAKEINTRESOURCE(IDR_WAVE20);
break;
case 21:
path = MAKEINTRESOURCE(IDR_WAVE21);
break;
case 22:
path = MAKEINTRESOURCE(IDR_WAVE22);
break;
case 23:
path = MAKEINTRESOURCE(IDR_WAVE23);
break;
case 24:
path = MAKEINTRESOURCE(IDR_WAVE24);
break;
}
return path;
}
// not used
LPCWSTR getWavFilePath(int frames) {
LPCWSTR path = 0;
switch (frames) {
case 10:
path = WAV_10_PATH;
break;
case 11:
path = WAV_11_PATH;
break;
case 12:
path = WAV_12_PATH;
break;
case 13:
path = WAV_13_PATH;
break;
case 14:
path = WAV_14_PATH;
break;
case 15:
path = WAV_15_PATH;
break;
case 16:
path = WAV_16_PATH;
break;
case 17:
path = WAV_17_PATH;
break;
case 18:
path = WAV_18_PATH;
break;
case 19:
path = WAV_19_PATH;
break;
case 20:
path = WAV_20_PATH;
break;
case 21:
path = WAV_21_PATH;
break;
case 22:
path = WAV_22_PATH;
break;
case 23:
path = WAV_23_PATH;
break;
case 24:
path = WAV_24_PATH;
break;
}
return path;
}
// not used
WavFiles* loadWavFiles() {
WavFiles* result;
return result;
}
// not used
char* loadWavFile(char* path) {
char* result;
FILE* file;
unsigned long sizeFile, i;
char c;
errno_t errorCode;
if (0 != (errorCode = fopen_s(&file, path, "r"))) {
printf("Error, code: %d, loadWavFile(char*) failed to open file: %s\n", errorCode, path);
system("pause");
exit(0);
}
fseek(file, 0L, SEEK_END);
sizeFile = ftell(file);
rewind(file);
result = (char*) malloc((sizeFile + 1) * sizeof(char));
i = 0;
while ( (c = fgetc(file)) != EOF) {
result[i] = fgetc(file);
i++;
}
result[++i] = '\0';
return result;
}
| 17.993631
| 92
| 0.670088
|
n-o-u
|
aaba67aa05441d448ae0e0977586a10f1dc7c29d
| 64
|
cpp
|
C++
|
src/ui/src/comms/dfcomms.cpp
|
Terebinth/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 117
|
2015-01-13T14:48:49.000Z
|
2022-03-16T01:38:19.000Z
|
src/ui/src/comms/dfcomms.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 4
|
2015-05-01T13:09:53.000Z
|
2017-07-22T09:11:06.000Z
|
src/ui/src/comms/dfcomms.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 78
|
2015-01-13T09:27:47.000Z
|
2022-03-18T14:39:09.000Z
|
/*
UI Comms Driver stuff (ALL of it which is NOT part of VU)
*/
| 16
| 57
| 0.671875
|
Terebinth
|
aabca80b93a778881b4f513e64b9466519e11487
| 4,813
|
hpp
|
C++
|
src/sprite/llvm/type.hpp
|
andyjost/Sprite
|
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
|
[
"MIT"
] | 1
|
2022-03-16T16:37:11.000Z
|
2022-03-16T16:37:11.000Z
|
src/sprite/llvm/type.hpp
|
andyjost/Sprite
|
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
|
[
"MIT"
] | null | null | null |
src/sprite/llvm/type.hpp
|
andyjost/Sprite
|
7ecd6fc7d48d7f62da644e48c12c7b882e1a2929
|
[
"MIT"
] | null | null | null |
#pragma once
#include "sprite/llvm/config.hpp"
#include "sprite/llvm/fwd.hpp"
#include "sprite/llvm/llvmobj.hpp"
#include "sprite/llvm/array_ref.hpp"
#include "sprite/llvm/special_values.hpp"
#include "sprite/llvm/type_traits.hpp"
#include "llvm/IR/DerivedTypes.h"
#include <iostream>
#include <vector>
namespace sprite { namespace llvm
{
/**
* @brief Wrapper for @p Type objects.
*
* Elaborated types can be created by using the @p * operator (to create
* pointers), the @p [] operator (to create arrays), or the @p () operator
* (to create functions).
*
* Constant values can be created using the call operator, as in
* <tt>i32(42)</tt> to create a 32-bit integer constant with value @p 42
* (assuming @p i32 is a type wrapper for the 32-bit integer type).
*/
struct type : llvmobj<Type, custodian<Type, no_delete>>
{
// Inherit constructors.
using llvmobj_base_type::llvmobj;
/// Creates a pointer type.
type operator*() const;
/// Creates a vector type.
type operator*(size_t) const;
friend type operator*(size_t, type);
/// Creates an array type.
type operator[](size_t) const;
/// Creates a function type.
type make_function(
std::vector<Type*> const &, bool is_varargs = false
) const;
#ifdef TEMPORARILY_DISABLED
template<
typename... Args
, SPRITE_ENABLE_FOR_ALL_FUNCTION_PROTOTYPES(Args...)
>
type operator()(Args &&... argtypes) const;
/**
* @brief Creates a constant of the type represented by @p this, using @p
* arg as the initializer.
*
* Synonymous with @p get_constant. Implemented in get_constant.hpp.
*/
template<
typename Arg
, SPRITE_ENABLE_FOR_ALL_CONSTANT_INITIALIZERS(Arg)
>
constant operator()(Arg &&) const;
/**
* @brief Creates a constant of the (array) type represented by @p this,
* using @p arg as the initializer.
*
* Synonymous with @p get_constant. Implemented in get_constant.hpp. This
* needs to be mentioned explicitly so that @p std::initializer_list will
* be accepted.
*/
constant operator()(any_array_ref const &) const;
#endif
};
bool operator==(type const &, type const &);
bool operator!=(type const &, type const &);
}}
namespace sprite { namespace llvm { namespace types
{
/// Creates an integer type of the specified bit width.
type int_(size_t numBits);
/// Creates an integer type the width of a native int.
type int_();
/// Creates an integer type the width of a native long.
type long_();
/// Creates an integer type the width of a native long long.
type longlong();
/// Creates a char type.
type char_();
/// Creates a bool type.
type bool_();
/**
* @brief Creates a floating-point type (32-bit, by default).
*
* @p numBits should be 32, 64 or 128.
*/
type float_(size_t numBits);
/// Creates the 32-bit floating-point type.
type float_();
/// Creates the 64-bit floating-point type.
type double_();
/// Creates the 128-bit floating-point type.
type longdouble();
/// Creates the void type.
type void_();
#ifdef TEMPORARILY_DISABLED
/// Creates the label type (for holding a @p block_address).
type label();
#endif
/// Creates an anonymous struct (uniqued by structural equivalence).
type struct_(std::vector<type> const & elements);
/**
* @brief Gets a struct by name.
*
* If the struct has not been created, a new opaque struct will be created.
*/
type struct_(std::string const & name);
/**
* @brief Defines a struct.
*
* The struct must not already have a body (though, it may exist and be
* opaque).
*/
type struct_(
std::string const & name, std::vector<type> const & elements
);
}}}
namespace sprite { namespace llvm
{
/// Returns the array extents.
std::vector<size_t> array_extents(type const &);
/// Indicates whether the specified cast is permitted.
bool is_castable(type src, type dst);
/// Indicates whether the specified bitcast is permitted.
bool is_bitcastable(type src, type dst);
/**
* @brief Applies type transformations as when passing a value to a function.
*
* See std::type_traits::decay.
*/
type decay(type);
/**
* @brief Determines the common type of a group of types.
*
* See std::type_traits::common_type.
*/
type common_type(std::vector<type> const &);
/// Returns the size in bytes (with alignment padding).
size_t sizeof_(type const &);
/// Returns the size in bits (without padding).
size_t bitwidth(type const &);
/// Returns the name for struct types.
std::string struct_name(type const &);
/// Returns the subtypes, as defined by LLVM.
std::vector<type> subtypes(type const &);
}}
| 26.157609
| 79
| 0.658633
|
andyjost
|
aabcaa409c50b922c940044845f7282aba871d3f
| 11,251
|
cpp
|
C++
|
QtOpenGLDB/prism.cpp
|
as-i-see/OOPFundamentals2sem
|
a859001fba5e81446edf1e272909991fa2bfbd81
|
[
"MIT"
] | null | null | null |
QtOpenGLDB/prism.cpp
|
as-i-see/OOPFundamentals2sem
|
a859001fba5e81446edf1e272909991fa2bfbd81
|
[
"MIT"
] | null | null | null |
QtOpenGLDB/prism.cpp
|
as-i-see/OOPFundamentals2sem
|
a859001fba5e81446edf1e272909991fa2bfbd81
|
[
"MIT"
] | null | null | null |
#include "prism.h"
#include <QOpenGLFunctions>
void Prism::reconstruct() {
Vertex BA(this->dots[0].position());
Vertex BB(this->dots[1].position());
Vertex BC(this->dots[2].position());
Vertex BD(this->dots[3].position());
Vertex BE(this->dots[4].position());
Vertex BF(this->dots[5].position());
Vertex TA(this->dots[6].position());
QVector3D upVector = TA.position() - BA.position();
Vertex TB(BB.position() + upVector);
Vertex TC(BC.position() + upVector);
Vertex TD(BD.position() + upVector);
Vertex TE(BE.position() + upVector);
Vertex TF(BF.position() + upVector);
std::vector<Vertex> vertices = {// Bottom
BA, BF, BE, BD, BC, BB,
// Top
TA, TB, TC, TD, TE, TF,
// Face 1
BA, BB, TB, TA,
// Face 2
BB, BC, TC, TB,
// Face 3
BC, BD, TD, TC,
// Face 4
BD, BE, TE, TD,
// Face 5
BE, BF, TF, TE,
// Face 6
BF, BA, TA, TF};
this->dots = std::move(vertices);
}
void Prism::draw() {
if (this->isSelected()) {
glColor3f(153.0f / 255.0f, 51.0f / 255.0f, 255.0f / 255.0f);
} else {
glColor3f(this->color.x(), this->color.y(), this->color.z());
}
glPushMatrix();
glLoadMatrixf(this->transform.toMatrix().data());
for (int j = 0; j < 2; j++) {
glBegin(GL_POLYGON);
QVector3D normal = QVector3D::normal(this->dots[6 * j].position(),
this->dots[6 * j + 1].position(),
this->dots[6 * j + 2].position());
glNormal3f(normal.x(), normal.y(), normal.z());
glVertex3f(this->dots[6 * j].position().x(),
this->dots[6 * j].position().y(),
this->dots[6 * j].position().z());
glVertex3f(this->dots[6 * j + 1].position().x(),
this->dots[6 * j + 1].position().y(),
this->dots[6 * j + 1].position().z());
glVertex3f(this->dots[6 * j + 2].position().x(),
this->dots[6 * j + 2].position().y(),
this->dots[6 * j + 2].position().z());
glVertex3f(this->dots[6 * j + 3].position().x(),
this->dots[6 * j + 3].position().y(),
this->dots[6 * j + 3].position().z());
glVertex3f(this->dots[6 * j + 4].position().x(),
this->dots[6 * j + 4].position().y(),
this->dots[6 * j + 4].position().z());
glVertex3f(this->dots[6 * j + 5].position().x(),
this->dots[6 * j + 5].position().y(),
this->dots[6 * j + 5].position().z());
glEnd();
}
for (int j = 0; j < 6; j++) {
glBegin(GL_QUADS);
QVector3D normal = QVector3D::normal(this->dots[12 + 4 * j].position(),
this->dots[12 + 4 * j + 1].position(),
this->dots[12 + 4 * j + 2].position());
glNormal3f(normal.x(), normal.y(), normal.z());
glVertex3f(this->dots[12 + 4 * j].position().x(),
this->dots[12 + 4 * j].position().y(),
this->dots[12 + 4 * j].position().z());
glVertex3f(this->dots[12 + 4 * j + 1].position().x(),
this->dots[12 + 4 * j + 1].position().y(),
this->dots[12 + 4 * j + 1].position().z());
glVertex3f(this->dots[12 + 4 * j + 2].position().x(),
this->dots[12 + 4 * j + 2].position().y(),
this->dots[12 + 4 * j + 2].position().z());
glVertex3f(this->dots[12 + 4 * j + 3].position().x(),
this->dots[12 + 4 * j + 3].position().y(),
this->dots[12 + 4 * j + 3].position().z());
glEnd();
}
glPopMatrix();
}
void Prism::drawXYProjection() {
if (this->isSelected()) {
glColor3f(153.0f / 255.0f, 51.0f / 255.0f, 255.0f / 255.0f);
} else {
glColor3f(this->color.x(), this->color.y(), this->color.z());
}
glPushMatrix();
for (int j = 0; j < 2; j++) {
glBegin(GL_POLYGON);
glVertex3f((this->transform.toMatrix() * this->dots[6 * j].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j].position()).y(),
0);
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 1].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j + 1].position()).y(), 0);
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 2].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j + 2].position()).y(), 0);
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 3].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j + 3].position()).y(), 0);
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 4].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j + 4].position()).y(), 0);
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 5].position()).x(),
(this->transform.toMatrix() * this->dots[6 * j + 5].position()).y(), 0);
glEnd();
}
for (int j = 0; j < 6; j++) {
glBegin(GL_QUADS);
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j].position()).x(),
(this->transform.toMatrix() * this->dots[12 + 4 * j].position()).y(),
0);
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.x(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.y(),
0);
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.x(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.y(),
0);
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.x(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.y(),
0);
glEnd();
}
glPopMatrix();
}
void Prism::drawXZProjection() {
if (this->isSelected()) {
glColor3f(153.0f / 255.0f, 51.0f / 255.0f, 255.0f / 255.0f);
} else {
glColor3f(this->color.x(), this->color.y(), this->color.z());
}
glPushMatrix();
for (int j = 0; j < 2; j++) {
glBegin(GL_POLYGON);
glVertex3f((this->transform.toMatrix() * this->dots[6 * j].position()).x(),
0,
(this->transform.toMatrix() * this->dots[6 * j].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 1].position()).x(), 0,
(this->transform.toMatrix() * this->dots[6 * j + 1].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 2].position()).x(), 0,
(this->transform.toMatrix() * this->dots[6 * j + 2].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 3].position()).x(), 0,
(this->transform.toMatrix() * this->dots[6 * j + 3].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 4].position()).x(), 0,
(this->transform.toMatrix() * this->dots[6 * j + 4].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[6 * j + 5].position()).x(), 0,
(this->transform.toMatrix() * this->dots[6 * j + 5].position()).z());
glEnd();
}
for (int j = 0; j < 6; j++) {
glBegin(GL_QUADS);
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j].position()).x(), 0,
(this->transform.toMatrix() * this->dots[12 + 4 * j].position()).z());
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.x(),
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.z());
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.x(),
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.z());
glVertex3f(
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.x(),
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.z());
glEnd();
}
glPopMatrix();
}
void Prism::drawYZProjection() {
if (this->isSelected()) {
glColor3f(153.0f / 255.0f, 51.0f / 255.0f, 255.0f / 255.0f);
} else {
glColor3f(this->color.x(), this->color.y(), this->color.z());
}
glPushMatrix();
for (int j = 0; j < 2; j++) {
glBegin(GL_POLYGON);
glVertex3f(0,
(this->transform.toMatrix() * this->dots[6 * j].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j].position()).z());
glVertex3f(
0, (this->transform.toMatrix() * this->dots[6 * j + 1].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j + 1].position()).z());
glVertex3f(
0, (this->transform.toMatrix() * this->dots[6 * j + 2].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j + 2].position()).z());
glVertex3f(
0, (this->transform.toMatrix() * this->dots[6 * j + 3].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j + 3].position()).z());
glVertex3f(
0, (this->transform.toMatrix() * this->dots[6 * j + 4].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j + 4].position()).z());
glVertex3f(
0, (this->transform.toMatrix() * this->dots[6 * j + 5].position()).y(),
(this->transform.toMatrix() * this->dots[6 * j + 5].position()).z());
glEnd();
}
for (int j = 0; j < 6; j++) {
glBegin(GL_QUADS);
glVertex3f(
0, (this->transform.toMatrix() * this->dots[12 + 4 * j].position()).y(),
(this->transform.toMatrix() * this->dots[12 + 4 * j].position()).z());
glVertex3f(
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.y(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 1].position())
.z());
glVertex3f(
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.y(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 2].position())
.z());
glVertex3f(
0,
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.y(),
(this->transform.toMatrix() * this->dots[12 + 4 * j + 3].position())
.z());
glEnd();
}
glPopMatrix();
}
QVector3D Prism::centreOfMass() {
QVector3D bottomCenter;
for (int i = 0; i < 6; i++) {
bottomCenter += this->dots[i].position();
}
bottomCenter /= 6.0f;
QVector3D topCenter;
for (int i = 0; i < 6; i++) {
topCenter += this->dots[6 + i].position();
}
topCenter /= 6.0f;
QVector3D center;
center += bottomCenter;
center += topCenter;
center /= 2.0f;
return center;
}
| 39.616197
| 80
| 0.483513
|
as-i-see
|
aabe0f77f24de2d84727e21fdbde6daa6501ff11
| 4,052
|
hpp
|
C++
|
addons/briefing/CfgDiary.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
addons/briefing/CfgDiary.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
addons/briefing/CfgDiary.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
class CfgDiary {
class FixedPages {
class Diary {
text = "%TEXT";
};
class Tasks {
text = "%LINK_SET_CURRENT_TASK<br /><br />%TASK_DESCRIPTION";
};
};
};
class RscHTML;
class RscControlsGroup;
class RscDisplayMainMap {
class controls {
class CA_ContentBackgroundd: RscText {
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
h = "18 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CA_DiaryGroup: RscControlsGroup {
h = "safezoneH - 7 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
class controls {
class CA_Diary: RscHTML {
h = 100;
w = "20.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
};
};
};
};
};
class RscDisplayDiary {
class controls {
class CA_ContentBackgroundd: RscText {
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
h = "18 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CA_DiaryGroup: RscControlsGroup {
h = "safezoneH - 7 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
class controls {
class CA_Diary: RscHTML {
h = 100;
w = "20.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
};
};
};
};
};
class RscDisplayGetReady: RscDisplayMainMap {
class controls {
class CA_ContentBackgroundd: RscText {
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
h = "18 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CA_DiaryGroup: RscControlsGroup {
h = "safezoneH - 7 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
class controls {
class CA_Diary: RscHTML {
h = 100;
w = "20.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
};
};
};
};
};
class RscDisplayServerGetReady: RscDisplayGetReady {
class controls {
class CA_ContentBackgroundd: RscText {
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
h = "18 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CA_DiaryGroup: RscControlsGroup {
h = "safezoneH - 7 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
class controls {
class CA_Diary: RscHTML {
h = 100;
w = "20.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
};
};
};
};
};
class RscDisplayClientGetReady: RscDisplayGetReady {
class controls {
class CA_ContentBackgroundd: RscText {
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
h = "18 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CA_DiaryGroup: RscControlsGroup {
h = "safezoneH - 7 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
w = "21.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
class controls {
class CA_Diary: RscHTML {
h = 100;
w = "20.5 * (((safezoneW / safezoneH) min 1.2) / 40) * 1.25"; // *1.25 = 6SFG
};
};
};
};
};
| 37.518519
| 97
| 0.449161
|
YonVclaw
|
aac15adf50b4c9b80b307e9fbc15ee51f86bc62b
| 847
|
cpp
|
C++
|
problems21ruse/robot/1.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | null | null | null |
problems21ruse/robot/1.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | null | null | null |
problems21ruse/robot/1.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main () {
int K;
cin >> K;
string directions;
cin >> directions;
// well to work out the number of moves, let's just make the robot go backwards!
string reverse_directions(K, '-');
for (int i = 0; i < K; i++) {
if (directions[i] == 'E') reverse_directions[i] = 'W';
if (directions[i] == 'W') reverse_directions[i] = 'E';
if (directions[i] == 'N') reverse_directions[i] = 'S';
if (directions[i] == 'S') reverse_directions[i] = 'N';
}
reverse(reverse_directions.begin(), reverse_directions.end());
// cout << reverse_directions << endl;
// now we count up the number of moves
int num_moves = 0;
for (int i = 0; i < reverse_directions.size(); i++) {
num_moves += 1;
}
printf("%d\n", num_moves);
}
| 30.25
| 84
| 0.57379
|
Gomango999
|
aac258ecf21af6accf3dfd66fb591ef2fcd4856f
| 628
|
hpp
|
C++
|
Fusion/src/Fusion/Audio/Buffer.hpp
|
WhoseTheNerd/Fusion
|
35ab536388392b3ba2e14f288eecbc292abd7dea
|
[
"Apache-2.0"
] | 4
|
2018-11-12T18:43:02.000Z
|
2020-02-02T10:18:56.000Z
|
Fusion/src/Fusion/Audio/Buffer.hpp
|
WhoseTheNerd/Fusion
|
35ab536388392b3ba2e14f288eecbc292abd7dea
|
[
"Apache-2.0"
] | 2
|
2018-12-22T13:18:05.000Z
|
2019-07-24T20:15:45.000Z
|
Fusion/src/Fusion/Audio/Buffer.hpp
|
WhoseTheNerd/Fusion
|
35ab536388392b3ba2e14f288eecbc292abd7dea
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <cinttypes>
#include <vector>
#include "Common.hpp"
namespace Fusion { namespace Audio {
class Buffer
{
public:
Buffer();
Buffer(uint32_t id);
/* The class doesn't store buffer data and we can't query it from OpenAL so it cannot be copied. */
Buffer(const Buffer& other) = delete;
Buffer(Buffer&& other);
~Buffer();
void SetData(Format format, uint32_t sample_rate, const std::vector<uint8_t>& data);
operator uint32_t() const
{
return m_BufferID;
}
uint32_t GetBufferHandle() const { return m_BufferID; }
private:
uint32_t m_BufferID;
bool m_PlaceHolder;
};
} }
| 17.942857
| 101
| 0.69586
|
WhoseTheNerd
|
aac413e5574a6891287bff955bc123b8de305b5e
| 16,038
|
cpp
|
C++
|
rmf_traffic/src/rmf_traffic/blockade/Constraint.cpp
|
0to1/rmf_traffic
|
0e641f779e9c7e6d69c316e905df5a51a2c124e1
|
[
"Apache-2.0"
] | 10
|
2021-04-14T07:01:56.000Z
|
2022-02-21T02:26:58.000Z
|
rmf_traffic/src/rmf_traffic/blockade/Constraint.cpp
|
0to1/rmf_traffic
|
0e641f779e9c7e6d69c316e905df5a51a2c124e1
|
[
"Apache-2.0"
] | 63
|
2021-03-10T06:06:13.000Z
|
2022-03-25T08:47:07.000Z
|
rmf_traffic/src/rmf_traffic/blockade/Constraint.cpp
|
0to1/rmf_traffic
|
0e641f779e9c7e6d69c316e905df5a51a2c124e1
|
[
"Apache-2.0"
] | 10
|
2021-03-17T02:52:14.000Z
|
2022-02-21T02:27:02.000Z
|
/*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "Constraint.hpp"
#include <vector>
#include <cassert>
namespace rmf_traffic {
namespace blockade {
//==============================================================================
// To Uppercase Letter
std::string toul(const std::size_t input)
{
const std::size_t TotalLetters = 'Z'-'A'+1;
std::string output;
std::size_t value = input;
do
{
const std::size_t digit = value % TotalLetters;
char offset = output.empty() ? 'A' : 'A'-1;
output += static_cast<char>(digit + offset);
value /= TotalLetters;
} while (value > 0);
std::reverse(output.begin(), output.end());
return output;
}
//==============================================================================
class BlockageConstraint : public Constraint
{
public:
BlockageConstraint(
std::size_t blocked_by,
std::optional<std::size_t> blocker_hold_point,
std::optional<BlockageEndCondition> end_condition)
: _blocked_by(blocked_by),
_blocker_hold_point(blocker_hold_point),
_end_condition(end_condition)
{
_dependencies.insert(_blocked_by);
}
bool evaluate(const State& state) const final
{
const auto it = state.find(_blocked_by);
if (it == state.end())
{
std::string error = "Failed to evaluate BlockageConstraint ";
error += _description();
error += " for state: <";
for (const auto& s : state)
{
const auto p = std::to_string(s.first);
const auto begin = std::to_string(s.second.begin);
const auto end = std::to_string(s.second.end);
error += p + ":[" + begin + "," + end + "]";
}
error += ">";
throw std::runtime_error(error);
}
return _evaluate(it->second);
}
const std::unordered_set<std::size_t>& dependencies() const final
{
return _dependencies;
}
std::optional<bool> partial_evaluate(const State& state) const final
{
const auto it = state.find(_blocked_by);
if (it == state.end())
return std::nullopt;
return _evaluate(it->second);
}
std::string detail(const State& state) const final
{
const auto& range = state.at(_blocked_by);
std::stringstream str;
const bool two_parts =
_blocker_hold_point.has_value() && _end_condition.has_value();
const bool hold_failed = !_evaluate_can_hold(range);
const bool end_failed = !_evaluate_has_reached(range);
const bool whole_failed = hold_failed && end_failed;
if (two_parts)
{
if (whole_failed)
str << "{";
else
str << "[";
}
if (_blocker_hold_point.has_value())
{
if (hold_failed)
str << "{";
str << "h(" << toul(_blocked_by) << _blocker_hold_point.value() << ")";
if (hold_failed)
str << "}";
}
if (two_parts)
str << "|";
if (_end_condition.has_value())
{
if (end_failed)
str << "{";
if (_end_condition.value().condition == BlockageEndCondition::HasReached)
str << "r(";
else
str << "p(";
str << toul(_blocked_by) << _end_condition.value().index << ")";
if (end_failed)
str << "}";
}
if (two_parts)
{
if (whole_failed)
str << "}";
else
str << "]";
}
return str.str();
}
private:
bool _evaluate_can_hold(const ReservedRange& range) const
{
if (_blocker_hold_point)
{
if (range.end <= _blocker_hold_point)
return true;
}
return false;
}
bool _evaluate_has_reached(const ReservedRange& range) const
{
if (_end_condition)
{
const std::size_t has_reached = _end_condition->index;
if (range.begin < has_reached)
return false;
// Implicit: has_reached <= range.begin
if (has_reached < range.end)
return true;
if (_end_condition->condition == BlockageEndCondition::HasReached)
{
if (_end_condition->index == range.begin)
return true;
}
}
return false;
}
bool _evaluate(const ReservedRange& range) const
{
if (_evaluate_can_hold(range))
return true;
if (_evaluate_has_reached(range))
return true;
return false;
}
std::string _description() const
{
const auto h = _blocker_hold_point ?
std::to_string(*_blocker_hold_point) : std::string("null");
std::string desc = std::to_string(_blocked_by) + ":(" + h;
if (_end_condition)
{
desc += ", " + std::to_string(_end_condition->index);
if (_end_condition->condition == BlockageEndCondition::HasReached)
desc += ")";
else
desc += "]";
}
else
{
desc += ")";
}
return desc;
}
std::size_t _blocked_by;
std::optional<std::size_t> _blocker_hold_point;
std::optional<BlockageEndCondition> _end_condition;
std::unordered_set<std::size_t> _dependencies;
};
//==============================================================================
ConstConstraintPtr blockage(
std::size_t blocked_by,
std::optional<std::size_t> blocker_hold_point,
std::optional<BlockageEndCondition> end_condition)
{
return std::make_shared<BlockageConstraint>(
blocked_by, blocker_hold_point, end_condition);
}
//==============================================================================
class PassedConstraint : public Constraint
{
public:
PassedConstraint(
std::size_t participant,
std::size_t index)
: _participant(participant),
_index(index)
{
_dependencies.insert(_participant);
}
bool evaluate(const State& state) const final
{
const auto it = state.find(_participant);
if (it == state.end())
{
std::string error = "Failed to evaluate PassedConstraint because "
"participant " + std::to_string(_participant)
+ " is missing from the state.";
throw std::runtime_error(error);
}
return _evaluate(it->second);
}
const std::unordered_set<std::size_t>& dependencies() const final
{
return _dependencies;
}
std::optional<bool> partial_evaluate(const State& state) const final
{
const auto it = state.find(_participant);
if (it == state.end())
return std::nullopt;
return _evaluate(it->second);
}
std::string detail(const State& state) const final
{
std::stringstream str;
const auto& range = state.at(_participant);
const bool failed = !_evaluate(range);
if (failed)
str << "{";
str << "p(" << toul(_participant) << _index << ")";
if (failed)
str << "}";
return str.str();
}
private:
bool _evaluate(const ReservedRange& range) const
{
if (_index < range.begin)
return true;
if (range.begin < _index)
return false;
return _index < range.end;
}
std::size_t _participant;
std::size_t _index;
std::unordered_set<std::size_t> _dependencies;
};
//==============================================================================
ConstConstraintPtr passed(
std::size_t participant,
std::size_t index)
{
return std::make_shared<PassedConstraint>(participant, index);
}
//==============================================================================
class AlwaysValid : public Constraint
{
public:
bool evaluate(const State&) const final
{
return true;
}
const std::unordered_set<std::size_t>& dependencies() const final
{
static const std::unordered_set<std::size_t> empty_set;
return empty_set;
}
std::optional<bool> partial_evaluate(const State&) const final
{
return true;
}
std::string detail(const State&) const final
{
return "True";
}
};
//==============================================================================
AndConstraint::AndConstraint(const std::vector<ConstConstraintPtr>& constraints)
{
for (const auto& c : constraints)
add(c);
}
//==============================================================================
void AndConstraint::add(ConstConstraintPtr new_constraint)
{
for (const auto& dep : new_constraint->dependencies())
_dependencies.insert(dep);
_constraints.emplace(std::move(new_constraint));
}
//==============================================================================
bool AndConstraint::evaluate(const State& state) const
{
for (const auto& c : _constraints)
{
if (!c->evaluate(state))
return false;
}
return true;
}
//==============================================================================
const std::unordered_set<std::size_t>& AndConstraint::dependencies() const
{
return _dependencies;
}
//==============================================================================
std::optional<bool> AndConstraint::partial_evaluate(const State& state) const
{
for (const auto& c : _constraints)
{
if (const auto opt_value = c->partial_evaluate(state))
{
const auto value = *opt_value;
if (!value)
return false;
}
}
return std::nullopt;
}
//==============================================================================
std::string AndConstraint::detail(const State& state) const
{
if (_constraints.empty())
return "And-Empty-True";
if (_constraints.size() == 1)
{
return (*_constraints.begin())->detail(state);
}
std::stringstream str;
const bool failed = !evaluate(state);
if (failed)
str << "{ ";
else
str << "[ ";
bool first = true;
for (const auto& c : _constraints)
{
if (first)
first = false;
else
str << " & ";
str << c->detail(state);
}
if (failed)
str << " }";
else
str << " ]";
return str.str();
}
//==============================================================================
OrConstraint::OrConstraint(const std::vector<ConstConstraintPtr>& constraints)
{
for (const auto& c : constraints)
add(c);
}
//==============================================================================
void OrConstraint::add(ConstConstraintPtr new_constraint)
{
for (const auto& dep : new_constraint->dependencies())
_dependencies.insert(dep);
_constraints.emplace(std::move(new_constraint));
}
//==============================================================================
bool OrConstraint::evaluate(const State& state) const
{
for (const auto& c : _constraints)
{
if (c->evaluate(state))
return true;
}
if (_constraints.empty())
return true;
return false;
}
//==============================================================================
const std::unordered_set<std::size_t>& OrConstraint::dependencies() const
{
return _dependencies;
}
//==============================================================================
std::optional<bool> OrConstraint::partial_evaluate(const State& state) const
{
for (const auto& c : _constraints)
{
if (const auto opt_value = c->partial_evaluate(state))
{
const auto value = *opt_value;
if (value)
return true;
}
}
return std::nullopt;
}
//==============================================================================
std::string OrConstraint::detail(const State& state) const
{
if (_constraints.empty())
return "Or-Empty-True";
if (_constraints.size() == 1)
{
return (*_constraints.begin())->detail(state);
}
std::stringstream str;
const bool failed = !evaluate(state);
if (failed)
str << "{ ";
else
str << "[ ";
bool first = true;
for (const auto& c : _constraints)
{
if (first)
first = false;
else
str << " | ";
str << c->detail(state);
}
if (failed)
str << " }";
else
str << " ]";
return str.str();
}
namespace {
//==============================================================================
using Cache = std::unordered_map<std::size_t, std::unordered_set<std::size_t>>;
//==============================================================================
struct GridlockNode;
using GridlockNodePtr = std::shared_ptr<const GridlockNode>;
//==============================================================================
struct Blocker
{
std::size_t participant;
std::size_t index;
ConstConstraintPtr constraint;
bool operator==(const Blocker& other) const
{
return participant == other.participant && index == other.index;
}
bool operator!=(const Blocker& other) const
{
return !(*this == other);
}
};
//==============================================================================
struct GridlockNode
{
Blocker blocker;
GridlockNodePtr parent;
Cache visited;
};
} // anonymous namespace
//==============================================================================
ConstConstraintPtr compute_gridlock_constraint(GridlockNodePtr node)
{
auto or_constraint = std::make_shared<OrConstraint>();
const auto target_blocker = node->blocker;
do
{
or_constraint->add(node->blocker.constraint);
node = node->parent;
assert(node);
} while (target_blocker != node->blocker);
return or_constraint;
}
//==============================================================================
ConstConstraintPtr compute_gridlock_constraint(const Blockers& blockers)
{
std::vector<GridlockNodePtr> queue;
std::unordered_map<std::size_t, std::vector<Blocker>> dependents;
for (const auto& b : blockers)
{
const auto participant = b.first;
const auto& points = b.second;
for (const auto& p : points)
{
const auto index = p.first;
const auto constraint = p.second;
Blocker blocker{participant, index, constraint};
for (const std::size_t dependency : constraint->dependencies())
{
auto& v = dependents.insert({dependency, {}}).first->second;
v.push_back(blocker);
}
auto node = std::make_shared<GridlockNode>(
GridlockNode{blocker, nullptr, {}});
node->visited[participant].insert(index);
queue.push_back(std::move(node));
}
}
Cache expanded_nodes;
State test_state;
std::vector<ConstConstraintPtr> gridlock_constraints;
while (!queue.empty())
{
const auto top = queue.back();
queue.pop_back();
const bool is_new_node = expanded_nodes
.insert({top->blocker.participant, {}})
.first->second.insert(top->blocker.index).second;
if (!is_new_node)
continue;
const auto participant = top->blocker.participant;
const auto index = top->blocker.index;
const auto it = dependents.find(top->blocker.participant);
if (it == dependents.end())
continue;
test_state.clear();
test_state[participant] = ReservedRange{index, index};
for (const auto& dep : it->second)
{
std::optional<bool> opt_eval =
dep.constraint->partial_evaluate(test_state);
if (!opt_eval.has_value() || opt_eval.value())
continue;
// This constraint is blocked by holding here, so we'll add it to the
// chain
Cache new_visited = top->visited;
const bool loop_found = !new_visited[dep.participant]
.insert(dep.index).second;
auto next = std::make_shared<GridlockNode>(
GridlockNode{dep, top, std::move(new_visited)});
if (loop_found)
gridlock_constraints.push_back(compute_gridlock_constraint(next));
else
queue.push_back(next);
}
}
if (gridlock_constraints.empty())
return std::make_shared<AlwaysValid>();
return std::make_shared<AndConstraint>(gridlock_constraints);
}
} // namespace blockade
} // namespace rmf_traffic
| 23.76
| 80
| 0.563599
|
0to1
|
aac499dbfd84c5e8199bf8a5811a0056d1d7bdd4
| 3,161
|
cpp
|
C++
|
Hashing/Maths and hashing/Grid Illumination.cpp
|
cenation092/InterviewBit-Solutions
|
ac4510a10d965fb681f7b3c80990407e18bc2668
|
[
"MIT"
] | 7
|
2019-06-29T08:57:07.000Z
|
2021-02-13T06:43:40.000Z
|
Hashing/Maths and hashing/Grid Illumination.cpp
|
cenation092/InterviewBit-Solutions
|
ac4510a10d965fb681f7b3c80990407e18bc2668
|
[
"MIT"
] | null | null | null |
Hashing/Maths and hashing/Grid Illumination.cpp
|
cenation092/InterviewBit-Solutions
|
ac4510a10d965fb681f7b3c80990407e18bc2668
|
[
"MIT"
] | 3
|
2020-06-17T04:26:26.000Z
|
2021-02-12T04:51:40.000Z
|
int dx[] = {-1, -1, 1, 1, -1, 0, 0, 0, 1};
int dy[] = {-1, 1, -1, 1, 0, -1, 0, 1, 0};
struct line{
int x1,y1,x2,y2;
int ass(int a, int b, int c, int d ){
x1 = a;
y1 = b;
x2 = c;
y2 = d;
}
};
line left(int x, int y, int A){
int top_x, top_y;
int sub = min(x-1, y-1);
top_x = x-sub;
top_y = y-sub;
int add = min(A-x, A-y);
int bot_x, bot_y;
bot_x = x+add;
bot_y = y+add;
line L;
L.ass(top_x, top_y, bot_x, bot_y);
return L;
}
line right( int x, int y, int A){
int top_x, top_y;
int sub = min(x-1, A-y);
top_x = x-sub;
top_y = y+sub;
int bot_x, bot_y;
int add = min(A-x, y-1);
bot_x = x+add;
bot_y = y-add;
line L;
L.ass(top_x, top_y, bot_x, bot_y);
return L;
}
vector<int> Solution::solve(int A, vector<vector<int> > &B, vector<vector<int> > &C) {
map<pair<int,int>, int> fre;
map<pair<pair<int,int>, pair<int,int> >, int > s;
map<int, int> X, Y;
for( auto it : B ){
int x = it[0], y = it[1];
x++, y++;
if( fre[make_pair(x,y)] > 0 )continue;
fre[make_pair(x,y)]++;
X[x]++;
Y[y]++;
line a = left(x, y, A);
s[make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2))]++;
a = right(x, y, A);
s[make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2))]++;
}
vector<int> ans;
for( auto it : C ){
int x = it[0], y = it[1];
x++, y++;
pair<pair<int,int>, pair<int,int> > a1;
pair<pair<int,int>, pair<int,int> > a2;
line a = left(x, y, A);
a1 = (make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2)));
a = right(x, y, A);
a2 = (make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2)));
if( s.count(a1) ){
ans.push_back(1);
}
else if( s.count(a2) ){
ans.push_back(1);
}
else if( X.find(x) != X.end() ){
ans.push_back(1);
}
else if( Y.find(y) != Y.end()){
ans.push_back(1);
}
else{
ans.push_back(0);
}
for( int i = 0; i < 9; i++ ){
int xx = x + dx[i];
int yy = y + dy[i];
if( xx < 1 || yy < 1 || xx > A || yy > A )continue;
if( fre.count(make_pair(xx,yy)) > 0 ){
a = left(xx, yy, A);
a1 = (make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2)));
if( s.count(a1) ){
s[a1]--;
if( s[a1] == 0 )s.erase(a1);
}
a = right(xx, yy, A);
a1 = (make_pair(make_pair(a.x1, a.y1), make_pair(a.x2, a.y2)));
if( s.count(a1) ){
s[a1]--;
if( s[a1] == 0 )s.erase(a1);
}
X[xx]--;
Y[yy]--;
if( X[xx] == 0 )X.erase(xx);
if( Y[yy] == 0 )Y.erase(yy);
fre[make_pair(xx,yy)]--;
if( fre[make_pair(xx,yy)] == 0 )fre.erase(make_pair(xx,yy));
}
}
}
return ans;
}
| 28.223214
| 86
| 0.412528
|
cenation092
|
aac5f875f4abdf1245ad33f3d1c7dd52277d7295
| 18,950
|
cc
|
C++
|
src/neo.cc
|
Quicr/qmedia
|
96408d740bf35e6a845f61c40cc9f9ff859a9955
|
[
"BSD-2-Clause"
] | null | null | null |
src/neo.cc
|
Quicr/qmedia
|
96408d740bf35e6a845f61c40cc9f9ff859a9955
|
[
"BSD-2-Clause"
] | 1
|
2021-12-29T03:37:51.000Z
|
2022-03-16T05:59:11.000Z
|
src/neo.cc
|
Quicr/qmedia
|
96408d740bf35e6a845f61c40cc9f9ff859a9955
|
[
"BSD-2-Clause"
] | null | null | null |
#include <iostream>
#include "neo.hh"
#include "h264_encoder.hh"
namespace neo_media
{
Neo::Neo(const LoggerPointer &parent_logger) :
log(std::make_shared<Logger>("NEO", parent_logger)),
metrics(std::make_shared<Metrics>(MetricsConfig::URL,
MetricsConfig::ORG,
MetricsConfig::BUCKET,
MetricsConfig::AUTH_TOKEN))
{
}
void Neo::init(const std::string &remote_address,
const unsigned int remote_port,
unsigned int audio_sample_rate_,
unsigned int audio_channels_,
audio_sample_type audio_type,
unsigned int video_max_width_,
unsigned int video_max_height_,
unsigned int video_max_frame_rate_,
unsigned int video_max_bitrate_,
video_pixel_format video_encode_pixel_format_,
video_pixel_format video_decode_pixel_format_,
uint64_t clientID,
uint64_t conferenceID,
callbackSourceId callback,
NetTransport::Type xport_type,
bool echo)
{
myClientID = clientID;
myConferenceID = conferenceID;
audio_sample_rate = audio_sample_rate_;
audio_channels = audio_channels_;
type = audio_type;
video_max_width = video_max_width_;
video_max_height = video_max_height_;
video_max_frame_rate = video_max_frame_rate_;
video_max_bitrate = video_max_bitrate_;
video_encode_pixel_format = video_encode_pixel_format_;
video_decode_pixel_format = video_decode_pixel_format_;
newSources = callback;
transport_type = xport_type;
if (transport_type == NetTransport::Type::PICO_QUIC)
{
transport = std::make_unique<ClientTransportManager>(
NetTransport::Type::PICO_QUIC,
remote_address,
remote_port,
metrics,
log);
while (!transport->transport_ready())
{
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
else if (transport_type == NetTransport::Type::QUICR)
{
transport = std::make_unique<ClientTransportManager>(
NetTransport::Type::QUICR,
remote_address,
remote_port,
metrics,
log);
// setup sources
}
else
{
// UDP
transport = std::make_unique<ClientTransportManager>(
NetTransport::Type::UDP, remote_address, remote_port, metrics, log);
transport->start();
}
int64_t epoch_id = 1;
transport->setCryptoKey(epoch_id, bytes(8, uint8_t(epoch_id)));
// Construct and send a Join Packet
if (transport_type != NetTransport::Type::QUICR)
{
PacketPointer joinPacket = std::make_unique<Packet>();
assert(joinPacket);
joinPacket->packetType = neo_media::Packet::Type::Join;
joinPacket->clientID = myClientID;
joinPacket->conferenceID = myConferenceID;
joinPacket->echo = echo;
transport->send(std::move(joinPacket));
}
// TODO: add audio_encoder
workThread = std::thread(neoWorkThread, this);
// Init video pipeline unless disabled with zero width or height or bad
// format
if (!video_max_width || !video_max_height)
{
log->error << "video disabled" << std::flush;
return;
}
if (video_encode_pixel_format != video_pixel_format::NV12 &&
video_encode_pixel_format != video_pixel_format::I420)
{
std::cerr << "unsupported encode pixel format: "
<< int(video_encode_pixel_format) << std::endl;
return;
}
if (video_decode_pixel_format != video_pixel_format::NV12 &&
video_decode_pixel_format != video_pixel_format::I420)
{
std::cerr << "unsupported decode pixel format: "
<< int(video_decode_pixel_format) << std::endl;
return;
}
video_encoder = std::make_unique<H264Encoder>(
video_max_width,
video_max_height,
video_max_frame_rate,
video_max_bitrate,
(uint32_t) video_encode_pixel_format);
if (!video_encoder)
{
log->error << "AV1 video encoder init failed" << std::flush;
return;
}
}
void Neo::publish(std::uint64_t source_id,
Packet::MediaType media_type,
std::string url)
{
auto pkt_transport = transport->transport();
std::weak_ptr<NetTransportQUICR> tmp =
std::static_pointer_cast<NetTransportQUICR>(pkt_transport.lock());
auto quicr_transport = tmp.lock();
quicr_transport->publish(source_id, media_type, url);
}
void Neo::subscribe(Packet::MediaType mediaType, std::string url)
{
auto pkt_transport = transport->transport();
std::weak_ptr<NetTransportQUICR> tmp =
std::static_pointer_cast<NetTransportQUICR>(pkt_transport.lock());
auto quicr_transport = tmp.lock();
quicr_transport->subscribe(mediaType, url);
}
void Neo::start_transport(NetTransport::Type transport_type)
{
if (transport_type == NetTransport::Type::QUICR)
{
auto pkt_transport = transport->transport();
std::weak_ptr<NetTransportQUICR> tmp =
std::static_pointer_cast<NetTransportQUICR>(pkt_transport.lock());
auto quicr_transport = tmp.lock();
quicr_transport->start();
while (!transport->transport_ready())
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
/** Receive all packets in this thread, push to jitter buffer, and notify client
* if new stream via callback. */
void Neo::doWork()
{
// Wait on a condition variable
while (!shutdown)
{
transport->waitForPacket();
PacketPointer packet = transport->recv();
if (packet == nullptr)
{
continue;
}
if (Packet::Type::StreamContent == packet->packetType)
{
uint64_t clientID = packet->clientID;
uint64_t sourceID = packet->sourceID;
uint64_t sourceTS = packet->sourceRecordTime;
// TODO: This is pre-decode media type, which is
// not really right but close enough. Hold off changing a lot
// to get at that data before Geir's changes to Jitter/Playout.
Packet::MediaType sourceType = packet->mediaType;
bool new_stream;
auto jitter_instance = getJitter(clientID);
if (jitter_instance == nullptr)
{
jitter_instance = createJitter(clientID);
}
if (jitter_instance != nullptr)
{
new_stream = jitter_instance->push(std::move(packet));
// jitter assembles packets to frames, decodes, conceals
// and makes frames available to client
if (new_stream && newSources)
{
newSources(clientID, sourceID, sourceTS, sourceType);
}
}
}
else if (Packet::Type::IdrRequest == packet->packetType)
{
log->info << "Received IDR request" << std::flush;
reqKeyFrame = true;
}
}
}
void Neo::setMicrophoneMute(bool muted)
{
mutedAudioEmptyFrames = muted;
}
void Neo::sendAudio(const char *buffer,
unsigned int length,
uint64_t timestamp,
uint64_t sourceID)
{
std::shared_ptr<AudioEncoder> audio_encoder = getAudioEncoder(sourceID);
if (audio_encoder != nullptr)
{
audio_encoder->encodeFrame(
buffer, length, timestamp, mutedAudioEmptyFrames);
}
}
void Neo::sendVideoFrame(const char *buffer,
uint32_t length,
uint32_t width,
uint32_t height,
uint32_t stride_y,
uint32_t stride_uv,
uint32_t offset_u,
uint32_t offset_v,
uint32_t format,
uint64_t timestamp,
uint64_t sourceID)
{
// TODO:implement clone()
// TODO: remove assert
int sendRaw = 0; // 1 will send Raw YUV video instead of AV1
PacketPointer packet = std::make_unique<Packet>();
assert(packet);
packet->packetType = neo_media::Packet::Type::StreamContent;
packet->clientID = myClientID;
packet->conferenceID = myConferenceID;
packet->sourceID = sourceID;
packet->encodedSequenceNum = video_seq_no;
packet->sourceRecordTime = timestamp;
packet->mediaType = sendRaw ? Packet::MediaType::Raw :
Packet::MediaType::AV1;
// encode and packetize
encodeVideoFrame(buffer,
length,
width,
height,
stride_y,
stride_uv,
offset_u,
offset_v,
format,
timestamp,
packet.get());
if (packet->data.empty())
{
// encoder skipped this frame, nothing to send
return;
}
video_seq_no++;
if (loopbackMode == LoopbackMode::codec)
{
transport->loopback(std::move(packet));
return;
}
// create object for managing packetization
auto packets = std::make_shared<SimplePacketize>(std::move(packet),
1200 /* MTU */);
for (unsigned int i = 0; i < packets->GetPacketCount(); i++)
{
auto frame_packet = packets->GetPacket(i);
frame_packet->transportSequenceNumber = 0; // this will be set by
// the transport layer
// sending lots of Raw packets at the same time is unreliable.
if (frame_packet->mediaType == Packet::MediaType::Raw)
{
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
if (loopbackMode == LoopbackMode::full_media)
{
// don't transmit but return an recv from Net
transport->loopback(std::move(frame_packet));
}
else
{
// send over network
transport->send(std::move(frame_packet));
}
}
}
JitterInterface::JitterIntPtr Neo::getJitter(uint64_t clientID)
{
auto playout_key = clientID;
if (auto it{jitters.find(playout_key)}; it != std::end(jitters))
{
return it->second;
}
return nullptr;
}
JitterInterface::JitterIntPtr Neo::createJitter(uint64_t clientID)
{
Packet::MediaType packet_media_type = Packet::MediaType::Bad;
switch (type)
{
case audio_sample_type::Float32:
packet_media_type = Packet::MediaType::F32;
break;
case audio_sample_type::PCMint16:
packet_media_type = Packet::MediaType::L16;
break;
default:
assert(0);
}
if (jitters.size() < maxJitters)
{
if (loopbackMode == LoopbackMode::codec)
{
LoopbackJitter::LoopbackJitterPtr loopbackPtr =
std::make_shared<LoopbackJitter>(
audio_sample_rate,
audio_channels,
packet_media_type,
video_max_width,
video_max_height,
(uint32_t) video_decode_pixel_format,
log);
auto ret = jitters.emplace(
clientID,
JitterInterface::JitterIntPtr(
std::static_pointer_cast<JitterInterface>(loopbackPtr)));
return ret.first->second;
}
else
{
Jitter::JitterPtr jitterPtr = std::make_shared<Jitter>(
audio_sample_rate,
audio_channels,
packet_media_type,
video_max_width,
video_max_height,
(uint32_t) video_decode_pixel_format,
log,
metrics);
auto ret = jitters.emplace(
clientID,
JitterInterface::JitterIntPtr(
std::static_pointer_cast<JitterInterface>(jitterPtr)));
return ret.first->second;
}
}
return nullptr;
}
void Neo::encodeVideoFrame(const char *buffer,
uint32_t length,
uint32_t width,
uint32_t height,
uint32_t stride_y,
uint32_t stride_uv,
uint32_t offset_u,
uint32_t offset_v,
uint32_t format,
uint64_t timestamp,
Packet *packet)
{
switch (packet->mediaType)
{
case Packet::MediaType::AV1:
{
// TODO : add logic to determine to send keyframe or not
// TODO : encoder api needs to return frame type and its
// relationships
bool keyFrame = reqKeyFrame;
packet->videoFrameType = (Packet::VideoFrameType)
video_encoder->encode(buffer,
length,
width,
height,
stride_y,
stride_uv,
offset_u,
offset_v,
format,
timestamp,
packet->data,
keyFrame);
if (keyFrame &&
packet->videoFrameType == Packet::VideoFrameType::Idr)
{
log->info << "after encode, resetting keyFrame\n" << std::flush;
reqKeyFrame = false;
}
}
break;
case Packet::MediaType::Raw:
packet->data.resize(length);
memcpy(packet->data.data(), buffer, length);
break;
default:
log->error << "unknown video packet type: "
<< (int) packet->mediaType << std::flush;
assert(0); // TODO: handle more gracefully
}
}
int Neo::getAudio(uint64_t clientID,
uint64_t sourceID,
uint64_t ×tamp,
unsigned char **buffer,
unsigned int max_len,
Packet **packetToFree)
{
int recv_length = 0;
PacketPointer packet;
JitterInterface::JitterIntPtr jitter = getJitter(clientID);
if (jitter == nullptr) return 0;
packet = jitter->popAudio(sourceID, max_len);
if (packet != NULL)
{
timestamp = packet->sourceRecordTime;
*buffer = &packet->data[0];
recv_length = packet->data.size();
*packetToFree = packet.release();
}
return recv_length;
}
std::uint32_t Neo::getVideoFrame(uint64_t clientID,
uint64_t sourceID,
uint64_t ×tamp,
uint32_t &width,
uint32_t &height,
uint32_t &format,
unsigned char **buffer)
{
int recv_length = 0;
JitterInterface::JitterIntPtr jitter_instance = getJitter(clientID);
if (jitter_instance == nullptr) return 0;
Packet::IdrRequestData idr_data = {clientID, 0, 0};
recv_length = jitter_instance->popVideo(
sourceID, width, height, format, timestamp, buffer, idr_data);
if (idr_data.source_timestamp > 0)
{
log->debug << "jitter asked for keyFrame, sending IDR\n" << std::flush;
PacketPointer idr = std::make_unique<Packet>();
idr->packetType = Packet::Type::IdrRequest;
idr->transportSequenceNumber = 0;
idr->idrRequestData = std::move(idr_data);
transport->send(std::move(idr));
}
return recv_length;
}
void Neo::audioEncoderCallback(PacketPointer packet)
{
assert(packet);
// TODO: temporary copy until we decouple data from packet
packet->packetType = neo_media::Packet::Type::StreamContent;
packet->clientID = myClientID;
packet->conferenceID = myConferenceID;
packet->encodedSequenceNum = seq_no;
packet->transportSequenceNumber = 0; // this will be set by the
// transport layer
// This assumes that the callback is coming from an opus encoder
// Once we encode other media we need to change where this is set
packet->mediaType = Packet::MediaType::Opus;
// this seems to be incomplete, we need media timeline driven
// seq_no and may be also the media packet sequence number
seq_no++;
if (loopbackMode == LoopbackMode::full_media ||
loopbackMode == LoopbackMode::codec)
{
// don't transmit but return an recv from Net
transport->loopback(std::move(packet));
return;
}
// send it over the network
transport->send(std::move(packet));
}
std::shared_ptr<AudioEncoder> Neo::getAudioEncoder(uint64_t sourceID)
{
std::shared_ptr<AudioEncoder> audio_enc = nullptr;
if (auto it{audio_encoders.find(sourceID)}; it != std::end(audio_encoders))
{
audio_enc = it->second;
}
if (audio_enc == nullptr)
{
Packet::MediaType m_type;
switch (type)
{
case Neo::audio_sample_type::PCMint16:
m_type = Packet::MediaType::L16;
break;
case Neo::audio_sample_type::Float32:
m_type = Packet::MediaType::F32;
break;
default:
break;
}
auto callback = std::bind(
&Neo::audioEncoderCallback, this, std::placeholders::_1);
auto ret = audio_encoders.emplace(
sourceID,
std::make_shared<AudioEncoder>(audio_sample_rate,
audio_channels,
m_type,
callback,
sourceID,
log));
audio_enc = ret.first->second;
}
return audio_enc;
}
} // namespace neo_media
| 33.718861
| 80
| 0.539947
|
Quicr
|
aac7aa7ee563ffb6904482b84dc7ad5fc5cecc85
| 526
|
cpp
|
C++
|
11_10/11_10.cpp
|
wjingzhe/CPP_lab
|
081ba3612c2d96ffd074061ca1800b7f31486c37
|
[
"MIT"
] | null | null | null |
11_10/11_10.cpp
|
wjingzhe/CPP_lab
|
081ba3612c2d96ffd074061ca1800b7f31486c37
|
[
"MIT"
] | null | null | null |
11_10/11_10.cpp
|
wjingzhe/CPP_lab
|
081ba3612c2d96ffd074061ca1800b7f31486c37
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int value[]={ 3, 7, 0, 5, 4 };
ofstream os("intergers",ios_base::out|ios_base::binary);
os.write(reinterpret_cast<char*>(&value),sizeof(value));
os.close();
ifstream is("intergers",ios_base::in|ios_base::binary);
if(is)
{
is.seekg(3*sizeof(int));
int v;
is.read(reinterpret_cast<char*>(&v),sizeof(int));
cout<<"The 4th integer in the file 'intergers' is "<<v<<endl;
}
else
{
cout<<"ERROR:Cancot open the file."<<endl;
}
return 0;
}
| 21.04
| 63
| 0.659696
|
wjingzhe
|
aac7d13eded9ad84c4984a36a7e4f0a561e5c490
| 11,421
|
cpp
|
C++
|
DEM/Low/src/Animation/AnimationController.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 15
|
2019-05-07T11:26:13.000Z
|
2022-01-12T18:26:45.000Z
|
DEM/Low/src/Animation/AnimationController.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 16
|
2021-10-04T17:15:31.000Z
|
2022-03-20T09:34:29.000Z
|
DEM/Low/src/Animation/AnimationController.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 2
|
2019-04-28T23:27:48.000Z
|
2019-05-07T11:26:18.000Z
|
#include "AnimationController.h"
#include <Animation/Graph/AnimGraphNode.h>
#include <Animation/SkeletonInfo.h>
#include <Animation/Skeleton.h>
namespace DEM::Anim
{
CAnimationController::CAnimationController() = default;
CAnimationController::CAnimationController(CAnimationController&&) noexcept = default;
CAnimationController& CAnimationController::operator =(CAnimationController&&) noexcept = default;
CAnimationController::~CAnimationController() = default;
void CAnimationController::Init(PAnimGraphNode&& GraphRoot, Resources::CResourceManager& ResMgr,
CStrID LeftFootID, CStrID RightFootID,
std::map<CStrID, float>&& Floats,
std::map<CStrID, int>&& Ints,
std::map<CStrID, bool>&& Bools,
std::map<CStrID, CStrID>&& Strings,
const std::map<CStrID, CStrID>& AssetOverrides)
{
_Params.clear();
_FloatValues.reset();
_IntValues.reset();
_BoolValues.reset();
_StringValues.reset();
if (!Floats.empty())
{
UPTR CurrIdx = 0;
_FloatValues.reset(new float[Floats.size()]);
for (const auto [ID, DefaultValue] : Floats)
{
_Params.emplace(ID, std::pair{ EParamType::Float, CurrIdx });
_FloatValues[CurrIdx++] = DefaultValue;
// Duplicate IDs aren't allowed
Ints.erase(ID);
Bools.erase(ID);
Strings.erase(ID);
}
}
if (!Ints.empty())
{
UPTR CurrIdx = 0;
_IntValues.reset(new int[Ints.size()]);
for (const auto [ID, DefaultValue] : Ints)
{
_Params.emplace(ID, std::pair{ EParamType::Int, CurrIdx });
_IntValues[CurrIdx++] = DefaultValue;
// Duplicate IDs aren't allowed
Bools.erase(ID);
Strings.erase(ID);
}
}
if (!Bools.empty())
{
UPTR CurrIdx = 0;
_BoolValues.reset(new bool[Bools.size()]);
for (const auto [ID, DefaultValue] : Bools)
{
_Params.emplace(ID, std::pair{ EParamType::Bool, CurrIdx });
_BoolValues[CurrIdx++] = DefaultValue;
// Duplicate IDs aren't allowed
Strings.erase(ID);
}
}
if (!Strings.empty())
{
UPTR CurrIdx = 0;
_StringValues.reset(new CStrID[Strings.size()]);
for (const auto [ID, DefaultValue] : Strings)
{
_Params.emplace(ID, std::pair{ EParamType::String, CurrIdx });
_StringValues[CurrIdx++] = DefaultValue;
}
}
_GraphRoot = std::move(GraphRoot);
_SkeletonInfo = nullptr;
_UpdateCounter = 0;
if (_GraphRoot)
{
CAnimationInitContext Context{ *this, _SkeletonInfo, ResMgr, AssetOverrides };
_GraphRoot->Init(Context);
}
_PoseIndex = 2;
if (_SkeletonInfo)
{
_LastPoses[0].SetSize(_SkeletonInfo->GetNodeCount());
_LastPoses[1].SetSize(_SkeletonInfo->GetNodeCount());
_LeftFootBoneIndex = _SkeletonInfo->FindNodePort(LeftFootID);
_RightFootBoneIndex = _SkeletonInfo->FindNodePort(RightFootID);
}
else
{
// TODO: can issue a warning - no leaf animation data is provided or some assets are not resolved
_LeftFootBoneIndex = INVALID_BONE_INDEX;
_RightFootBoneIndex = INVALID_BONE_INDEX;
}
}
//---------------------------------------------------------------------
void CAnimationController::Update(const CSkeleton& Target, float dt)
{
// update conditions etc
// TODO:
// - selector (CStrID based?) with blend time for switching to actions like "open door". Finish vs cancel anim?
// - pose modifiers = skeletal controls, object space
// - inertialization
// - IK
if (_GraphRoot)
{
++_UpdateCounter;
CAnimationUpdateContext Context{ *this, Target };
_GraphRoot->Update(Context, dt);
// TODO: synchronize times by sync group?
}
_InertializationDt += dt; // Don't write to _InertializationElapsedTime, because dt may be discarded by teleportation
}
//---------------------------------------------------------------------
void CAnimationController::EvaluatePose(CSkeleton& Target)
{
Target.ToPoseBuffer(_CurrPose); // TODO: update only if changed externally?
if (_PoseIndex > 1)
{
// Init both poses from current. Should be used at the first frame and when teleported.
_PoseIndex = 0;
_LastPoses[0] = _CurrPose;
_LastPoses[1] = _CurrPose;
_LastPoseDt = 0.f;
}
else
{
// Swap current and previous pose buffers
_PoseIndex ^= 1;
_LastPoses[_PoseIndex] = _CurrPose;
_LastPoseDt = _InertializationDt;
}
if (_GraphRoot) _GraphRoot->EvaluatePose(_CurrPose);
//???else (if no _GraphRoot) leave as is or reset to refpose?
ProcessInertialization();
//!!!DBG TMP!
//pseudo root motion processing
//???diff from ref pose? can also be from the first frame of the animation, but that complicates things
//???precalculate something in tools to simplify processing here? is possible?
//Output.SetTranslation(0, vector3::Zero);
Target.FromPoseBuffer(_CurrPose);
}
//---------------------------------------------------------------------
bool CAnimationController::FindParam(CStrID ID, EParamType* pOutType, UPTR* pOutIndex) const
{
auto It = _Params.find(ID);
if (It == _Params.cend()) return false;
if (pOutType) *pOutType = It->second.first;
if (pOutIndex) *pOutIndex = It->second.second;
return true;
}
//---------------------------------------------------------------------
bool CAnimationController::SetFloat(CStrID ID, float Value)
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Float) return false;
_FloatValues[Index] = Value;
return true;
}
//---------------------------------------------------------------------
float CAnimationController::GetFloat(CStrID ID, float Default) const
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Float) return Default;
return _FloatValues[Index];
}
//---------------------------------------------------------------------
bool CAnimationController::SetInt(CStrID ID, int Value)
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Int) return false;
_IntValues[Index] = Value;
return true;
}
//---------------------------------------------------------------------
int CAnimationController::GetInt(CStrID ID, int Default) const
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Int) return Default;
return _IntValues[Index];
}
//---------------------------------------------------------------------
bool CAnimationController::SetBool(CStrID ID, bool Value)
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Bool) return false;
_BoolValues[Index] = Value;
return true;
}
//---------------------------------------------------------------------
bool CAnimationController::GetBool(CStrID ID, bool Default) const
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::Bool) return Default;
return _BoolValues[Index];
}
//---------------------------------------------------------------------
bool CAnimationController::SetString(CStrID ID, CStrID Value)
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::String) return false;
_StringValues[Index] = Value;
return true;
}
//---------------------------------------------------------------------
CStrID CAnimationController::GetString(CStrID ID, CStrID Default) const
{
EParamType Type;
UPTR Index;
if (!FindParam(ID, &Type, &Index) || Type != EParamType::String) return Default;
return _StringValues[Index];
}
//---------------------------------------------------------------------
float CAnimationController::GetLocomotionPhaseFromPose(const CSkeleton& Skeleton) const
{
if (_LeftFootBoneIndex == INVALID_BONE_INDEX || _RightFootBoneIndex == INVALID_BONE_INDEX) return -1.f;
const auto* pRootNode = Skeleton.GetNode(0);
const auto* pLeftFootNode = Skeleton.GetNode(_LeftFootBoneIndex);
const auto* pRightFootNode = Skeleton.GetNode(_RightFootBoneIndex);
if (!pRootNode || !pLeftFootNode || !pRightFootNode) return -1.f;
auto ForwardDir = pRootNode->GetWorldMatrix().AxisZ();
ForwardDir.norm();
auto SideDir = pRootNode->GetWorldMatrix().AxisX();
SideDir.norm();
// Project foot offset onto the locomotion plane (fwd, up) and normalize it to get phase direction
auto PhaseDir = pLeftFootNode->GetWorldMatrix().Translation() - pRightFootNode->GetWorldMatrix().Translation();
PhaseDir -= (SideDir * PhaseDir.Dot(SideDir));
PhaseDir.norm();
const float CosA = PhaseDir.Dot(ForwardDir);
const float SinA = (PhaseDir * ForwardDir).Dot(SideDir);
/* TODO: use ACL/RTM for poses
const auto Fwd = RootCoordSystem.GetColumn(2);
acl::Vector4_32 ForwardDir = { static_cast<float>(Fwd[0]), static_cast<float>(Fwd[1]), static_cast<float>(Fwd[2]), 0.0f };
ForwardDir = acl::vector_normalize3(ForwardDir);
const auto Side = RootCoordSystem.GetColumn(0);
acl::Vector4_32 SideDir = { static_cast<float>(Side[0]), static_cast<float>(Side[1]), static_cast<float>(Side[2]), 0.0f };
SideDir = acl::vector_normalize3(SideDir);
const auto Offset = acl::vector_sub(LeftFootPositions[i], RightFootPositions[i]);
const auto ProjectedOffset = acl::vector_sub(Offset, acl::vector_mul(SideDir, acl::vector_dot3(Offset, SideDir)));
const auto PhaseDir = acl::vector_normalize3(ProjectedOffset);
const float CosA = acl::vector_dot3(PhaseDir, ForwardDir);
const float SinA = acl::vector_dot3(acl::vector_cross3(PhaseDir, ForwardDir), SideDir);
*/
const float Angle = std::copysignf(std::acosf(CosA) * 180.f / PI, SinA); // Could also use Angle = RadToDeg(std::atan2f(SinA, CosA));
return 180.f - Angle; // map 180 -> -180 to 0 -> 360
}
//---------------------------------------------------------------------
void CAnimationController::RequestInertialization(float Duration)
{
if (_InertializationRequest < 0.f || _InertializationRequest > Duration)
_InertializationRequest = Duration;
}
//---------------------------------------------------------------------
// TODO: detect teleportation, reset pending request and _InertializationDt to mitigate abrupt velocity changes
// That must zero out _LastPoseDt, when it is not a last dt yet!
void CAnimationController::ProcessInertialization()
{
if (_PoseIndex > 1) return;
// Process new request
const bool RequestPending = (_InertializationRequest > 0.f);
if (RequestPending)
{
float NewDuration = _InertializationRequest;
_InertializationRequest = -1.f;
// When interrupt active inertialization, must reduce duration to avoid degenerate pose (see UE4)
if (_InertializationDuration > 0.f)
{
// TODO: learn why we check prevoius deficit to apply current
const bool HasDeficit = (_InertializationDeficit > 0.f);
_InertializationDeficit = _InertializationDuration - _InertializationElapsedTime;
if (HasDeficit) NewDuration = std::max(0.f, NewDuration - _InertializationDeficit);
}
_InertializationDuration = NewDuration;
_InertializationElapsedTime = 0.0f;
}
// Process active inertialization
if (_InertializationDuration > 0.f)
{
if (RequestPending)
_InertializationPoseDiff.Init(_CurrPose, _LastPoses[_PoseIndex], _LastPoses[_PoseIndex ^ 1], _LastPoseDt, _InertializationDuration);
_InertializationElapsedTime += _InertializationDt;
if (_InertializationElapsedTime >= _InertializationDuration)
{
_InertializationElapsedTime = 0.0f;
_InertializationDuration = 0.0f;
_InertializationDeficit = 0.0f;
}
else
{
_InertializationDeficit = std::max(0.f, _InertializationDeficit - _InertializationDt);
_InertializationPoseDiff.ApplyTo(_CurrPose, _InertializationElapsedTime);
}
}
_InertializationDt = 0.f;
}
//---------------------------------------------------------------------
}
| 31.902235
| 135
| 0.66404
|
niello
|
aacd3557b80b70df994458a9fd7e0f18c8833abf
| 682
|
cpp
|
C++
|
main.cpp
|
Zermil/mathEval
|
b49016bd21b787364c53b1fe6444d17366a838d7
|
[
"MIT"
] | null | null | null |
main.cpp
|
Zermil/mathEval
|
b49016bd21b787364c53b1fe6444d17366a838d7
|
[
"MIT"
] | null | null | null |
main.cpp
|
Zermil/mathEval
|
b49016bd21b787364c53b1fe6444d17366a838d7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "MathEval.hpp"
int main(int argc, char* argv[])
{
std::string EXPRESSIONS[] = {
" -123 + 12 * 3 \t",
"(2 * 3) + 1\n\r",
"(-1 + 2) * 3",
" 3 + 4 * 2/(1-5)^2^3",
"5 * 3 + (4 + 2 % 2 * 8)",
"-Pi + 3.2 - 4 + (-3 + 2)-E*3",
"2.398+14.23+3-e*3+(-3)",
"-123 + 4 - 16 +(-3-4)-6",
"-123,,+cos(-3)",
"-sin ( max ( 2, 3 ) / 3 * PI )",
"-sqrt(2)"
};
for (const std::string& exp : EXPRESSIONS) {
std::cout << "EXPRESSION: " << exp << std::endl;
std::cout << "= " << MathEval::evalExpression(exp) << '\n';
std::cout << "===================" << std::endl;
}
system("pause");
return 0;
}
| 24.357143
| 63
| 0.409091
|
Zermil
|
aace9f423d7a4dfaaf366da679a6d04e0150d58c
| 3,493
|
hpp
|
C++
|
src/Externals/spire/var-buffer/VarBuffer.hpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
src/Externals/spire/var-buffer/VarBuffer.hpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
src/Externals/spire/var-buffer/VarBuffer.hpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 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.
*/
#ifndef SPIRE_VARBUFFER_HPP
#define SPIRE_VARBUFFER_HPP
#include <es-log/trace-log.h>
#include <cstdint>
#include <memory>
#include <vector>
#include <bserialize/BSerialize.hpp>
#include <spire/scishare.h>
namespace spire {
/// This class is only for writing to a variable sized buffer. It is a thin
/// layer over the BSerialize code. To read data from a buffer, simply wrap
/// the buffer using BSerialize. There is no need to automatically extend
/// the buffer size when reading.
class SCISHARE VarBuffer final
{
public:
/// Initialize an empty buffer.
VarBuffer();
// Preallocate the variable buffer to the preset size.
explicit VarBuffer(size_t size);
// todo Add flag which will swap bytes when reading out of or into buffer.
// Writes numBytes of bytes.
void writeBytes(const char* bytes, size_t numBytes);
/// Writes a null terminated string.
void writeNullTermString(const char* str);
template <typename T>
void write(const T& val)
{
// Attempt to write the value to BSerialize. If a runtime exception is
// caught, then we need to resize the buffer.
while (mSerializer->write(val) == false)
{
resize();
}
}
template <typename T>
inline void writeUnsafe(const T& val)
{
mSerializer->writeUnsafe(val);
}
/// Clears all data currently written to the var buffer.
void clear();
/// Retrieves raw buffer contents.
char* getBuffer() {return mBuffer.empty() ? 0 : &mBuffer[0];}
/// Retrieves the current size of the buffer (size of all data currently
/// written to the buffer).
size_t getBufferSize() const {return mSerializer->getOffset();}
/// Retrieves currently allocated size of the buffer.
size_t getAllocatedSize() const {return mBufferSize;}
private:
void resize();
static bool serializeFloat(char* msg, int msgLen, int* offset_out, float in);
static bool serializeUInt16(char* msg, int msgLen, int* offset_out, uint16_t in);
static uint16_t deserializeUInt16(const char* msg, int msgLen, int* offset_out);
std::vector<char> mBuffer; ///< buffer
size_t mBufferSize; ///< Absolute size of mBuffer in bytes.
std::unique_ptr<spire::BSerialize> mSerializer;
};
} // namespace spire
#endif
| 31.468468
| 83
| 0.72631
|
Haydelj
|
aad0411c3c5470b87627b25488cd2b13710ec204
| 3,600
|
cpp
|
C++
|
test/StorageCacheNoneRuntimeTests.cpp
|
fsaporito/KVCache
|
4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2
|
[
"BSL-1.0"
] | null | null | null |
test/StorageCacheNoneRuntimeTests.cpp
|
fsaporito/KVCache
|
4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2
|
[
"BSL-1.0"
] | null | null | null |
test/StorageCacheNoneRuntimeTests.cpp
|
fsaporito/KVCache
|
4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2
|
[
"BSL-1.0"
] | null | null | null |
#include "KVCache/StorageCache/StorageCacheNone.h"
#include <catch2/catch.hpp>
TEST_CASE("Put 1 KV Pair into StorageCacheNone", "[runtime],[Put],[Singlepair],[StorageCacheNone][SingleThread]")
{
// Initialize StorageCache
auto storageType = KVCache::Interface::StorageCacheType::NONE;
auto storagePath = KVCache::Interface::StoragePath::defaultStoragePath;
auto storageCache = KVCache::Internal::StorageCache::AbstractStorageCache::createStorageCache(storagePath,
storageType);
// Put KV Pair
const std::string key = "TestKey";
const std::string value = "TestValue";
REQUIRE_NOTHROW(storageCache->put(key, value));
REQUIRE(storageCache->size() == 0);
}
TEST_CASE("Put 2 KV Pairs into StorageCacheNone", "[runtime],[Put],[Multipair],[StorageCacheNone][SingleThread]")
{
// Initialize StorageCache
auto storageType = KVCache::Interface::StorageCacheType::NONE;
auto storagePath = KVCache::Interface::StoragePath::defaultStoragePath;
auto storageCache = KVCache::Internal::StorageCache::AbstractStorageCache::createStorageCache(storagePath,
storageType);
// Put KV Pair
const std::string key1 = "TestKey";
const std::string value1 = "TestValue";
REQUIRE_NOTHROW(storageCache->put(key1, value1));
REQUIRE(storageCache->size() == 0);
// Put Second KV Pair
const std::string key2 = "TestKey2";
const std::string value2 = "TestValue2";
REQUIRE_NOTHROW(storageCache->put(key2, value2));
REQUIRE(storageCache->size() == 0);
}
TEST_CASE("Get Always return empty optional with StorageCacheNone", "[runtime],[Put],[Get],[Singlepair],[StorageCacheNone][SingleThread]")
{
// Initialize StorageCache
auto storageType = KVCache::Interface::StorageCacheType::NONE;
auto storagePath = KVCache::Interface::StoragePath::defaultStoragePath;
auto storageCache = KVCache::Internal::StorageCache::AbstractStorageCache::createStorageCache(storagePath,
storageType);
// Put KV Pair
const std::string key = "TestKey";
const std::string value = "TestValue";
REQUIRE_NOTHROW(storageCache->put(key, value));
REQUIRE(storageCache->size() == 0);
REQUIRE(storageCache->getByteSize() == 0);
// Get KV Pair
REQUIRE_NOTHROW(storageCache->get(key));
auto optionalPair = storageCache->get(key);
REQUIRE(!optionalPair);
}
TEST_CASE("Remove Doesn't Throw with StorageCacheNone Single Thread", "[runtime],[Put],[Remove],[Singlepair],[MemoryCacheMap][SingleThread]")
{
// Initialize StorageCache
auto storageType = KVCache::Interface::StorageCacheType::NONE;
auto storagePath = KVCache::Interface::StoragePath::defaultStoragePath;
auto storageCache = KVCache::Internal::StorageCache::AbstractStorageCache::createStorageCache(storagePath,
storageType);
// Put KV Pair
const std::string key = "TestKey";
const std::string value = "TestValue";
REQUIRE_NOTHROW(storageCache->put(key, value));
REQUIRE(storageCache->size() == 0);
REQUIRE(storageCache->getByteSize() == 0);
// Remove KV Pair
bool removeFlag = false;
REQUIRE_NOTHROW(removeFlag = storageCache->remove(key));
REQUIRE(!removeFlag);
REQUIRE(storageCache->size() == 0);
}
| 42.352941
| 141
| 0.640556
|
fsaporito
|
aad0dc0b0a6f3ecabd8fb02405516b86e6eda6e3
| 339
|
cpp
|
C++
|
00_cpp_beginners/04_pointers_memory/00_pointers/pointers.cpp
|
ganesh737/cfl-cpp
|
b1b9cff137897accca0f93a2d6f54129e5b9d19d
|
[
"MIT"
] | null | null | null |
00_cpp_beginners/04_pointers_memory/00_pointers/pointers.cpp
|
ganesh737/cfl-cpp
|
b1b9cff137897accca0f93a2d6f54129e5b9d19d
|
[
"MIT"
] | null | null | null |
00_cpp_beginners/04_pointers_memory/00_pointers/pointers.cpp
|
ganesh737/cfl-cpp
|
b1b9cff137897accca0f93a2d6f54129e5b9d19d
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int nVal = 10;
int* pVal = &nVal;
cout << "nVal=" << nVal << endl;
cout << "pVal=" << pVal << endl;
cout << "*pVal=" << *pVal << endl;
cout << "sizeof(pVal)=" << sizeof(pVal) << endl;
cout << "sizeof(*pVal)=" << sizeof(*pVal) << endl;
return 0;
}
| 22.6
| 54
| 0.501475
|
ganesh737
|
aad1719583164cf3767724b1362548d81cc3228a
| 1,218
|
cpp
|
C++
|
aws-cpp-sdk-chime/source/model/CreateSipMediaApplicationCallRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-chime/source/model/CreateSipMediaApplicationCallRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-chime/source/model/CreateSipMediaApplicationCallRequest.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/chime/model/CreateSipMediaApplicationCallRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Chime::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateSipMediaApplicationCallRequest::CreateSipMediaApplicationCallRequest() :
m_fromPhoneNumberHasBeenSet(false),
m_toPhoneNumberHasBeenSet(false),
m_sipMediaApplicationIdHasBeenSet(false),
m_sipHeadersHasBeenSet(false)
{
}
Aws::String CreateSipMediaApplicationCallRequest::SerializePayload() const
{
JsonValue payload;
if(m_fromPhoneNumberHasBeenSet)
{
payload.WithString("FromPhoneNumber", m_fromPhoneNumber);
}
if(m_toPhoneNumberHasBeenSet)
{
payload.WithString("ToPhoneNumber", m_toPhoneNumber);
}
if(m_sipHeadersHasBeenSet)
{
JsonValue sipHeadersJsonMap;
for(auto& sipHeadersItem : m_sipHeaders)
{
sipHeadersJsonMap.WithString(sipHeadersItem.first, sipHeadersItem.second);
}
payload.WithObject("SipHeaders", std::move(sipHeadersJsonMap));
}
return payload.View().WriteReadable();
}
| 21.75
| 79
| 0.761084
|
perfectrecall
|
aad1825460a7c417420398c215fefd9529353a97
| 1,214
|
cpp
|
C++
|
GuiLib/GuiButtonDoc.cpp
|
imxingquan/hotelMIS
|
f0da91dd5b4ffbe7d69a7038206a329e065d4c94
|
[
"MIT"
] | 9
|
2019-11-28T02:42:01.000Z
|
2021-12-25T08:32:02.000Z
|
GuiLib/GuiButtonDoc.cpp
|
imxingquan/hotelMIS
|
f0da91dd5b4ffbe7d69a7038206a329e065d4c94
|
[
"MIT"
] | null | null | null |
GuiLib/GuiButtonDoc.cpp
|
imxingquan/hotelMIS
|
f0da91dd5b4ffbe7d69a7038206a329e065d4c94
|
[
"MIT"
] | 2
|
2021-01-07T10:00:07.000Z
|
2021-11-01T11:18:37.000Z
|
// GuiButtonDoc.cpp : implementation file
//
#include "stdafx.h"
#include "GuiButtonDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGuiButtonDoc
CGuiButtonDoc::CGuiButtonDoc()
{
}
CGuiButtonDoc::~CGuiButtonDoc()
{
}
BEGIN_MESSAGE_MAP(CGuiButtonDoc, CWnd)
//{{AFX_MSG_MAP(CGuiButtonDoc)
ON_WM_CREATE()
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CGuiButtonDoc message handlers
BOOL CGuiButtonDoc::Create(DWORD dwStyle, CWnd* pParentWnd, UINT nID)
{
// TODO: Add your specialized code here and/or call the base class
return CWnd::Create(NULL, NULL, dwStyle, CRect(0,0,0,0), pParentWnd, nID, NULL);
}
int CGuiButtonDoc::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
return 0;
}
void CGuiButtonDoc::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CWnd::OnPaint() for painting messages
}
| 19.901639
| 81
| 0.636738
|
imxingquan
|
aad443b0febfc28694d99b2f0a2e2f887b32d0f3
| 2,768
|
cpp
|
C++
|
src/Test/TestMain.cpp
|
travelping/libamqp
|
afd15eec16bab7be4da9e4cc371392ea3f1a881e
|
[
"Apache-2.0"
] | 6
|
2015-11-05T10:28:59.000Z
|
2021-05-06T03:50:12.000Z
|
src/Test/TestMain.cpp
|
travelping/libamqp
|
afd15eec16bab7be4da9e4cc371392ea3f1a881e
|
[
"Apache-2.0"
] | 2
|
2015-04-21T09:57:43.000Z
|
2015-04-21T10:00:46.000Z
|
src/Test/TestMain.cpp
|
travelping/libamqp
|
afd15eec16bab7be4da9e4cc371392ea3f1a881e
|
[
"Apache-2.0"
] | 4
|
2016-09-14T08:01:24.000Z
|
2021-06-15T11:24:14.000Z
|
/*
Copyright 2011-2012 StormMQ Limited
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 <TestHarness.h>
#include <TestReporterStdout.h>
#include <XmlTestReporter.h>
#include <TraceReporter.h>
#include <iostream>
#include <fstream>
#include <SuiteFilter.h>
class ReporterMinder
{
public:
ReporterMinder(UnitTest::TestReporter *_reporter) : reporter(_reporter) {}
~ReporterMinder() { delete reporter; }
UnitTest::TestReporter& theReporter() const { return *reporter; }
private:
UnitTest::TestReporter *reporter;
};
class ArgumentProcessor
{
public:
ArgumentProcessor(SuiteFilter& filter) : _filter(filter), _reporter(0)
{
}
~ArgumentProcessor()
{
delete _reporter;
}
UnitTest::TestReporter& theReporter() const { return *_reporter; }
void scan(int argc, char const *argv[])
{
int i = 1;
while (i < argc && argv[i][0] == '-')
{
if (strcmp("--trace", argv[i]) == 0 && _reporter == 0)
{
_reporter = new TraceReporter();
}
else if (strcmp("--xml", argv[i]) == 0 && _reporter == 0)
{
_reporter = new UnitTest::XmlTestReporter(std::cout);
}
else if (strncmp("--xml=", argv[i], strlen("--xml=")) == 0 && _reporter == 0)
{
_resultFile.open(&argv[i][strlen("--xml=")]);
_reporter = new UnitTest::XmlTestReporter(_resultFile);
}
else if (strcmp("--exclude", argv[i]) == 0)
{
_filter.set_exclusion_mode();
}
i++;
}
while (i < argc)
{
_filter.add(argv[i++]);
}
if (_reporter == 0)
{
_reporter = new UnitTest::TestReporterStdout();
}
}
private:
std::ofstream _resultFile;
SuiteFilter& _filter;
UnitTest::TestReporter *_reporter;
};
int main(int argc, char const *argv[])
{
SuiteFilter filter;
ArgumentProcessor argumentProcessor(filter);
argumentProcessor.scan(argc, argv);
UnitTest::TestRunner runner(argumentProcessor.theReporter());
return runner.RunTestsIf(UnitTest::Test::GetTestList(), 0, filter, 0);
}
| 27.68
| 89
| 0.600434
|
travelping
|
aad457b42fbf4047458cbbacbfeadf42145e5c43
| 10,436
|
cpp
|
C++
|
src/gba/ppu/sprite.cpp
|
destoer/destoer-emu
|
2a7941b175126e998eed2df8df87ee382c43d0b1
|
[
"BSD-3-Clause"
] | 20
|
2020-01-19T21:54:23.000Z
|
2021-11-28T17:27:15.000Z
|
src/gba/ppu/sprite.cpp
|
destoer/destoer-emu
|
2a7941b175126e998eed2df8df87ee382c43d0b1
|
[
"BSD-3-Clause"
] | 3
|
2020-05-01T07:46:10.000Z
|
2021-09-18T13:50:18.000Z
|
src/gba/ppu/sprite.cpp
|
destoer/destoer-emu
|
2a7941b175126e998eed2df8df87ee382c43d0b1
|
[
"BSD-3-Clause"
] | null | null | null |
#include <gba/gba.h>
namespace gameboyadvance
{
void Display::render_sprites(int mode)
{
const TileData lose_bg(read_bg_palette(0,0),pixel_source::bd);
// make all of the line lose
// until something is rendred over it
std::fill(sprite_line.begin(),sprite_line.end(),lose_bg);
std::fill(sprite_semi_transparent.begin(),sprite_semi_transparent.end(),false);
std::fill(sprite_priority.begin(),sprite_priority.end(),5);
// objects aernt enabled do nothing more
if(!disp_io.disp_cnt.obj_enable)
{
return;
}
std::fill(oam_priority.begin(),oam_priority.end(),128+1);
const bool is_bitmap = mode >= 3;
// have to traverse it in forward order
// even though reverse is easier to handle most cases
for(uint32_t i = 0; i < 128; i++)
{
int obj_idx = i * 8;
const auto attr0 = handle_read<uint16_t>(mem.oam,obj_idx);
const auto attr1 = handle_read<uint16_t>(mem.oam,obj_idx+2);
const auto attr2 = handle_read<uint16_t>(mem.oam,obj_idx+4);
const bool affine = is_set(attr0,8);
// should check mosaic by here but we will just ignore it for now
// disable bit in regular mode
if(is_set(attr0,9) && !affine)
{
continue;
}
const int obj_mode = (attr0 >> 10) & 0x3;
// prohibited is this ignored on hardware
// or does it behave like another?
if(obj_mode == 3)
{
continue;
}
const int shape = (attr0 >> 14) & 0x3;
// prohibited is this ignored on hardware
// or does it behave like another?
if(shape == 3)
{
continue;
}
const int obj_size = (attr1 >> 14) & 0x3;
static constexpr int32_t x_size_lookup[3][4] =
{
{8,16,32,64},
{16,32,32,64},
{8,8,16,32}
};
static constexpr int32_t y_size_lookup[3][4] =
{
{8,16,32,64},
{8,8,16,32},
{16,32,32,64}
};
auto y_size = y_size_lookup[shape][obj_size];
auto x_size = x_size_lookup[shape][obj_size];
// original size of the sprite that is not affected by the double size flag
const auto x_sprite_size = x_size;
const auto y_sprite_size = y_size;
const bool double_size = is_set(attr0,9) && affine;
uint32_t y_cord = attr0 & 0xff;
// current x cords greater than screen width are handled in the decode loop
// by ignoring them until they are in range
uint32_t x_cord = attr1 & 511;
// bounding box even if double isnt going to draw outside
// because of how we operate on it
// how to get this working?
// on the top and left side its not going to extend
// only to the postive so we need to find a way to "centre" it
// see tonc graphical artifacts
if(double_size)
{
x_size *= 2;
y_size *= 2;
}
// if cordinate out of screen bounds and does not wrap around
// then we dont care
if(x_cord >= SCREEN_WIDTH && x_cord + x_size < 512)
{
continue;
}
// check we intersect with the current ly
bool line_overlap;
if(y_cord < SCREEN_HEIGHT)
{
line_overlap = y_cord + y_size > ly && y_cord <= ly;
}
// overflowed from 255
else
{
// by definiton it is allways greater than ly before it overflows
uint8_t y_end = (y_cord + y_size) & 0xff;
line_overlap = y_end >= ly && y_end < SCREEN_HEIGHT;
}
if(!line_overlap)
{
continue;
}
const bool color = is_set(attr0,13);
// assume palette
unsigned int tile_num = attr2 & 0x3ff;
// lower bit ignored in 2d mapping
if(color && !disp_io.disp_cnt.obj_vram_mapping)
{
tile_num &= ~1;
}
const unsigned int pal = (attr2 >> 12) & 0xf;
const unsigned int priority = (attr2 >> 10) & 3;
// bitmap modes starts at 0x14000 instead of 0x10000
// because of bg map tiles below this are simply ignored
if(is_bitmap && tile_num < 512)
{
continue;
}
// merge both into a single loop by here and dont worry about it being fast
// or this will fast become a painful mess to work with
// figure out how the affine transforms is actually calculated
const bool x_flip = is_set(attr1,12) && !affine;
const bool y_flip = is_set(attr1,13) && !affine;
const uint32_t aff_param = (attr1 >> 9) & 31;
// rotation centre
const int32_t x0 = x_sprite_size / 2;
const int32_t y0 = y_sprite_size / 2;
const int32_t y_max = y_size - 1;
const int32_t y1 = y_flip? y_max - ((ly-y_cord) & y_max) : ((ly-y_cord) & y_max);
for(int32_t x1 = 0; x1 < x_size; x1++)
{
const uint32_t x_offset = (x_cord + x1) & 511;
// probably a nicer way to do this but this is fine for now
if(x_offset >= SCREEN_WIDTH)
{
continue;
}
int32_t y2 = y1;
int32_t x2 = x1;
if(affine)
{
const auto base = aff_param*0x20;
// 8.8 fixed point
const int16_t pa = handle_read<uint16_t>(mem.oam,base+0x6);
const int16_t pb = handle_read<uint16_t>(mem.oam,base+0xe);
const int16_t pc = handle_read<uint16_t>(mem.oam,base+0x16);
const int16_t pd = handle_read<uint16_t>(mem.oam,base+0x1e);
const int32_t x_param = x1 - (x_size / 2);
const int32_t y_param = y1 - (y_size / 2);
// perform the affine transform (8.8 fixed point)
x2 = ((pa*x_param + pb*y_param) >> 8) + x0;
y2 = ((pc*x_param + pd*y_param) >> 8) + y0;
// out of range transform pixel is transparent
if(x2 >= x_sprite_size || y2 >= y_sprite_size || x2 < 0 || y2 < 0)
{
continue;
}
}
else if(x_flip)
{
x2 = x_size - x2 - 1;
}
uint32_t tile_offset;
// 1d object mapping
if(disp_io.disp_cnt.obj_vram_mapping)
{
tile_offset = ((y2 / 8) * (x_sprite_size / 8)) + (x2 / 8);
}
// 2d object mapping
// in 4bpp 1024 tiles split into 32 by 32
// or 16 by 32 in 8bpp mode
else
{
tile_offset = ((y2 / 8) * (32 >> color)) + (x2 / 8);
}
const auto &disp_cnt = disp_io.disp_cnt;
// 4bpp
if(!color)
{
// base + tile_base * tile_size
const uint32_t addr = 0x10000 + ((tile_offset + tile_num) * 8 * 4);
const uint32_t data_offset = ((x2 % 8) / 2) + ((y2 % 8) * 4);
const auto tile_data = mem.vram[addr+data_offset];
// lower x cord stored in lower nibble
const uint32_t idx = ((x2 & 1)? (tile_data >> 4) : tile_data) & 0xf;
// object window obj not displayed any non zero pixels are
// the object window
if(idx != 0 && obj_mode == 2 && disp_cnt.obj_window_enable)
{
// window 0 and 1 have higher priority
if(window[x_offset] == window_source::out)
{
window[x_offset] = window_source::obj;
}
}
else
{
if(i < oam_priority[x_offset])
{
if(idx != 0)
{
const auto color = read_obj_palette(pal,idx);
sprite_line[x_offset].color = color;
sprite_line[x_offset].source = pixel_source::obj;
oam_priority[x_offset] = i;
}
// hardware bug priority is updated even if transparent
sprite_priority[x_offset] = priority;
}
}
}
else
{
// base + tile_base * tile_size
// tile size is still 32 bytes for the tile num in 256 for some reason (thanks fleroviux)
// even though the bg uses the logical 64...
// the actual offset into it because of the cords is still 64
const uint32_t addr = 0x10000 + (tile_num * 8 * 4) + (tile_offset * 8 * 8);
const uint32_t data_offset = (x2 % 8) + ((y2 % 8) * 8);
const auto tile_data = mem.vram[addr+data_offset];
// object window obj not displayed any non zero pixels are
// the object window
if(tile_data != 0 && obj_mode == 2 && disp_cnt.obj_window_enable)
{
// window 0 and 1 have higher priority
if(window[x_offset] == window_source::out)
{
window[x_offset] = window_source::obj;
}
}
else
{
if(i < oam_priority[x_offset])
{
if(tile_data != 0)
{
const auto color = read_obj_palette(0,tile_data);
sprite_line[x_offset].color = color;
sprite_line[x_offset].source = pixel_source::obj;
oam_priority[x_offset] = i;
}
// hardware bug priority is updated even if transparent
sprite_priority[x_offset] = priority;
}
}
}
if(obj_mode == 1)
{
sprite_semi_transparent[x_offset] = true;
}
}
}
}
}
| 30.425656
| 105
| 0.489651
|
destoer
|
aad5874acdd66e9037de46edf6f39957d593bd74
| 4,776
|
cpp
|
C++
|
src/system_model/system_model.cpp
|
ibrahimkakbar/ros-system_model
|
0bf91e6bf2f6208d260319543b6407be3a48c217
|
[
"MIT"
] | null | null | null |
src/system_model/system_model.cpp
|
ibrahimkakbar/ros-system_model
|
0bf91e6bf2f6208d260319543b6407be3a48c217
|
[
"MIT"
] | null | null | null |
src/system_model/system_model.cpp
|
ibrahimkakbar/ros-system_model
|
0bf91e6bf2f6208d260319543b6407be3a48c217
|
[
"MIT"
] | null | null | null |
#include "system_model/system_model.hpp"
#include <system_model_msgs/variable.h>
#include <ros/console.h>
#include <ros/names.h>
#include <dlfcn.h>
using namespace system_model;
// CONSTRUCTORS
system_model_t::system_model_t(uint32_t n_variables, uint32_t n_observers)
: ukf_t(n_variables, n_observers)
{
// Initialize ROS node handle.
system_model_t::m_node = std::make_unique<ros::NodeHandle>();
// Read parameters.
ros::NodeHandle private_node("~");
// Set up default variable names.
system_model_t::m_variable_names.reserve(n_variables);
for(uint32_t i = 0; i < n_variables; ++i)
{
system_model_t::m_variable_names.push_back(std::to_string(i));
}
// Reserve space for state publishers.
system_model_t::m_state_publishers.reserve(n_variables);
// Set initial delta time.
system_model_t::m_dt = 0;
}
std::shared_ptr<system_model_t> system_model_t::load_plugin(const std::string& plugin_path)
{
// Check that path was provided (dl gets handle to program if empty)
if(plugin_path.empty())
{
ROS_ERROR("attempted to load plugin with empty path");
return nullptr;
}
// Open plugin shared object library.
void* so_handle = dlopen(plugin_path.c_str(), RTLD_NOW);
if(!so_handle)
{
ROS_ERROR_STREAM("failed to load model plugin (" << dlerror() << ")");
return nullptr;
}
// Get a reference to the instantiate symbol.
typedef system_model_t* (*instantiate_t)();
instantiate_t instantiate = reinterpret_cast<instantiate_t>(dlsym(so_handle, "instantiate"));
if(!instantiate)
{
ROS_ERROR_STREAM("failed to load model plugin (" << dlerror() << ")");
dlclose(so_handle);
return nullptr;
}
// Try to instantiate the plugin.
system_model_t* plugin = nullptr;
try
{
plugin = instantiate();
}
catch(const std::exception& error)
{
ROS_ERROR_STREAM("failed to instantiate model plugin (" << error.what() << ")");
dlclose(so_handle);
return nullptr;
}
// Return the plugin as a shared ptr with a custom deleter.
return std::shared_ptr<system_model_t>(plugin,
[so_handle](system_model_t* plugin){delete plugin; dlclose(so_handle);});
}
// METHODS
void system_model_t::set_variable_name(uint32_t index, const std::string& name)
{
// Check if index is valid.
if(!(index < system_model_t::m_variable_names.size()))
{
ROS_ERROR_STREAM("failed to set variable name (variable index " << index << " does not exist)");
return;
}
// Check if name is valid as a ROS graph resource name.
std::string error;
if(!ros::names::validate(name, error))
{
ROS_ERROR_STREAM("failed to set variable name (variable name is invalid: " << error << ")");
return;
}
// Update variable name.
system_model_t::m_variable_names.at(index) = name;
}
void system_model_t::run()
{
// Bring up state publishers.
ros::NodeHandle private_node("~");
for(uint32_t i = 0; i < system_model_t::n_variables(); ++i)
{
// Set up topic name.
std::string topic_name = ros::names::remap(ros::names::append("state", system_model_t::m_variable_names.at(i)));
// Publish topic.
system_model_t::m_state_publishers.push_back(private_node.advertise<system_model_msgs::variable>(topic_name, 10));
}
// Set up the loop rate timer.
double_t p_loop_rate = private_node.param<double_t>("loop_rate", 100);
ros::Rate loop(p_loop_rate);
// Initialize dt calculation.
ros::Time update_timestamp = ros::Time::now();
ros::Time current_timestamp;
// Loop while ROS ok.
while(ros::ok())
{
// Get current time and dt.
current_timestamp = ros::Time::now();
system_model_t::m_dt = (current_timestamp - update_timestamp).toSec();
update_timestamp = current_timestamp;
// Run callbacks to process observations.
ros::spinOnce();
// Run iteration.
system_model_t::iterate();
// Publish current state.
auto& state = system_model_t::state();
auto& covariance = system_model_t::covariance();
for(uint32_t i = 0; i < state.size(); ++i)
{
system_model_msgs::variable message;
message.value = state(i);
message.variance = covariance(i,i);
system_model_t::m_state_publishers.at(i).publish(message);
}
// Sleep for remaining loop time.
loop.sleep();
}
// Shutdown publishers.
system_model_t::m_state_publishers.clear();
}
double_t system_model_t::dt() const
{
return system_model_t::m_dt;
}
| 30.420382
| 122
| 0.639866
|
ibrahimkakbar
|
aad807720f53c483f3f535c63dab83810cdc2e2c
| 644
|
cpp
|
C++
|
API/source/src/WektorC.cpp
|
HPytkiewicz/DronPodwodny
|
b63feaca2abb268ef0ab6e831bed663608fadcbb
|
[
"MIT"
] | null | null | null |
API/source/src/WektorC.cpp
|
HPytkiewicz/DronPodwodny
|
b63feaca2abb268ef0ab6e831bed663608fadcbb
|
[
"MIT"
] | null | null | null |
API/source/src/WektorC.cpp
|
HPytkiewicz/DronPodwodny
|
b63feaca2abb268ef0ab6e831bed663608fadcbb
|
[
"MIT"
] | null | null | null |
#include "Wektor.cpp"
#include <iostream>
#include <iomanip>
template class Wektor<double, 2>;
template Wektor<double,2> operator *(double a, const Wektor<double,2> &Wektor2);
template std::ostream & operator <<(std::ostream &Strm, const Wektor<double, 2> &wektor);
template std::istream & operator >>(std::istream &Strm, Wektor<double, 2> &wektor);
template class Wektor<double, 3>;
template Wektor<double,3> operator *(double a, const Wektor<double,3> &Wektor2);
template std::ostream & operator <<(std::ostream &Strm, const Wektor<double, 3> &wektor);
template std::istream & operator >>(std::istream &Strm, Wektor<double, 3> &wektor);
| 37.882353
| 89
| 0.72205
|
HPytkiewicz
|
aadbe9c297dcf14b54d8ec30efc511e5f34e7c1c
| 3,097
|
cpp
|
C++
|
TestConditionCode.cpp
|
andkrau/nuance
|
32b9d6b9257c6c51944727456fce2e7caf074182
|
[
"W3C"
] | null | null | null |
TestConditionCode.cpp
|
andkrau/nuance
|
32b9d6b9257c6c51944727456fce2e7caf074182
|
[
"W3C"
] | null | null | null |
TestConditionCode.cpp
|
andkrau/nuance
|
32b9d6b9257c6c51944727456fce2e7caf074182
|
[
"W3C"
] | null | null | null |
#include "mpe.h"
bool MPE::TestConditionCode(const uint32 whichCondition) const
{
//This sequencing is correct for 32/64 bit ECU instructions. The decode
//handler for 16/48 bit ECU instructions converts the extracted condition
//to this sequence. VMLabs must die. Mission accomplished!
switch(whichCondition & 0x1FUL)
{
case 0:
//ne
return (tempCC & CC_ALU_ZERO) == 0;
case 1:
//c0z
return (tempCC & CC_COUNTER0_ZERO);
case 2:
//c1z
return (tempCC & CC_COUNTER1_ZERO);
case 3:
//cc
return (tempCC & CC_ALU_CARRY) == 0;
case 4:
//eq
return (tempCC & CC_ALU_ZERO);
case 5:
//cs
return (tempCC & CC_ALU_CARRY);
case 6:
//vc
return (tempCC & CC_ALU_OVERFLOW) == 0;
case 7:
//vs
return (tempCC & CC_ALU_OVERFLOW);
case 8:
//lt
return ((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == CC_ALU_NEGATIVE) ||
((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == CC_ALU_OVERFLOW);
case 9:
//mvc
return (tempCC & CC_MUL_OVERFLOW) == 0;
case 10:
//mvs
return (tempCC & CC_MUL_OVERFLOW);
case 11:
//hi
return (tempCC & (CC_ALU_CARRY | CC_ALU_ZERO)) == 0;
case 12:
//le
return (tempCC & CC_ALU_ZERO) || ((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == CC_ALU_NEGATIVE) ||
((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == CC_ALU_OVERFLOW);
case 13:
//ls
return (tempCC & (CC_ALU_CARRY | CC_ALU_ZERO));
case 14:
//pl
return (tempCC & CC_ALU_NEGATIVE) == 0;
case 15:
//mi
return (tempCC & CC_ALU_NEGATIVE);
case 16:
//gt
return ((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW | CC_ALU_ZERO)) == (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) ||
((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW | CC_ALU_ZERO)) == 0);
case 17:
//always
return true;
case 18:
//modmi
return (tempCC & CC_MODMI);
case 19:
//modpl
return (tempCC & CC_MODMI) == 0;
case 20:
//ge
return ((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) ||
((tempCC & (CC_ALU_NEGATIVE | CC_ALU_OVERFLOW)) == 0);
case 21:
//modge
return (tempCC & CC_MODGE);
case 22:
//modlt
return (tempCC & CC_MODGE) == 0;
case 23:
//never
return false;
case 24:
//c0ne
return (tempCC & CC_COUNTER0_ZERO) == 0;
case 25:
//never
return false;
case 26:
//never
return false;
case 27:
//cf0lo
return (tempCC & CC_COPROCESSOR0) == 0;
case 28:
//c1ne
return (tempCC & CC_COUNTER1_ZERO) == 0;
case 29:
//cf0hi
return (tempCC & CC_COPROCESSOR0);
case 30:
//cf1lo
return (tempCC & CC_COPROCESSOR1) == 0;
case 31:
//cf1hi
return (tempCC & CC_COPROCESSOR1);
}
return false;
}
| 26.930435
| 118
| 0.55247
|
andkrau
|
aadf7e152155b081274583b31025f99ca823fb6e
| 5,510
|
cpp
|
C++
|
src/UI/SettingsDlg.cpp
|
ShiraNai7/rstpad
|
754e6b34229585946c9238350ca1d94f17ea2678
|
[
"MIT"
] | 44
|
2017-02-13T18:56:55.000Z
|
2021-12-28T09:45:09.000Z
|
src/UI/SettingsDlg.cpp
|
ShiraNai7/rstpad
|
754e6b34229585946c9238350ca1d94f17ea2678
|
[
"MIT"
] | 2
|
2017-08-01T22:56:58.000Z
|
2019-07-15T21:28:29.000Z
|
src/UI/SettingsDlg.cpp
|
ShiraNai7/rstpad
|
754e6b34229585946c9238350ca1d94f17ea2678
|
[
"MIT"
] | 8
|
2017-10-31T15:08:01.000Z
|
2022-02-24T05:05:19.000Z
|
#include "SettingsDlg.h"
#include "ui_SettingsDlg.h"
#include "../App.h"
#include <Qt>
#include <QLineEdit>
#include <QTextOption>
#include <QCheckBox>
#include <QComboBox>
namespace RstPad {
SettingsDlg::SettingsDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::SettingsDlg)
{
ui->setupUi(this);
setWindowFlags((windowFlags() & ~Qt::WindowContextHelpButtonHint) | Qt::MSWindowsFixedSizeDialogHint);
setFixedSize(size());
ui->Orientation->addItem(tr("Horizontal"), static_cast<int>(EditorOrientation::Horizontal));
ui->Orientation->addItem(tr("Vertical"), static_cast<int>(EditorOrientation::Vertical));
ui->AutoscrollMode->addItem(tr("First visible line"), static_cast<int>(AutoscrollMode::FirstLine));
ui->AutoscrollMode->addItem(tr("Current line (cursor)"), static_cast<int>(AutoscrollMode::CurrentLine));
ui->AutoscrollMode->addItem(tr("Disabled"), static_cast<int>(AutoscrollMode::Disabled));
ui->WordWrapMode->addItem(tr("No wrap"), static_cast<int>(QTextOption::NoWrap));
ui->WordWrapMode->addItem(tr("Word wrap"), static_cast<int>(QTextOption::WordWrap));
ui->WordWrapMode->addItem(tr("Wrap anywhere"), static_cast<int>(QTextOption::WrapAnywhere));
ui->WordWrapMode->addItem(tr("Wrap anywhere but prefer word boundary"), static_cast<int>(QTextOption::WrapAtWordBoundaryOrAnywhere));
ui->Headings->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
ui->Headings->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
}
SettingsDlg::~SettingsDlg()
{
delete ui;
}
void SettingsDlg::showEvent(QShowEvent * e)
{
QDialog::showEvent(e);
updateWidgets(APP->config()->all());
}
void SettingsDlg::updateWidgets(const QVariantMap &config)
{
ui->Orientation->setCurrentIndex(ui->Orientation->findData(config["orientation"]));
ui->AutoscrollMode->setCurrentIndex(ui->AutoscrollMode->findData(config["autoscrollMode"]));
ui->AutoscrollWaitDelay->setValue(config["autoscrollWaitDelay"].toInt());
ui->RstRendererDelay->setValue(config["rstRendererDelay"].toInt());
ui->PreviewZoomFactor->setValue(config["previewZoomFactor"].toDouble());
ui->WordWrapMode->setCurrentIndex(ui->WordWrapMode->findData(config["wordWrapMode"]));
ui->FontSize->setValue(config["fontSize"].toInt());
ui->SearchWrapAround->setChecked(config["searchWrapAround"].toBool());
ui->IndentSize->setValue(config["indentSize"].toInt());
ui->EnsureSingleEmptyLineAtEndOnSave->setChecked(config["ensureSingleEmptyLineAtEndOnSave"].toBool());
ui->TrimTrailingWhitespaceOnSave->setChecked(config["trimTrailingWhitespaceOnSave"].toBool());
ui->HrSymbol->setText(config["hrSymbol"].toString());
ui->HrWidth->setValue(config["hrWidth"].toInt());
for (int i = 1; i <= 6; ++i) {
auto row = i - 1;
auto symbolWidget = new QLineEdit();
symbolWidget->setMaxLength(1);
symbolWidget->setText(config.value(QString("headingSymbol%1").arg(i)).toString());
auto overlineWidget = new QCheckBox();
overlineWidget->setChecked(config.value(QString("headingOverline%1").arg(i)).toBool());
ui->Headings->setCellWidget(row, 0, symbolWidget);
ui->Headings->setCellWidget(row, 1, overlineWidget);
}
}
void SettingsDlg::updateConfig(Config &config)
{
QVariantMap values;
values.insert("orientation", ui->Orientation->currentData());
values.insert("autoscrollMode", ui->AutoscrollMode->currentData());
values.insert("autoscrollWaitDelay", ui->AutoscrollWaitDelay->value());
values.insert("rstRendererDelay", ui->RstRendererDelay->value());
values.insert("previewZoomFactor", ui->PreviewZoomFactor->value());
values.insert("wordWrapMode", ui->WordWrapMode->currentData());
values.insert("fontSize", ui->FontSize->value());
values.insert("searchWrapAround", ui->SearchWrapAround->isChecked());
values.insert("indentSize", ui->IndentSize->value());
values.insert("ensureSingleEmptyLineAtEndOnSave", ui->EnsureSingleEmptyLineAtEndOnSave->isChecked());
values.insert("trimTrailingWhitespaceOnSave", ui->TrimTrailingWhitespaceOnSave->isChecked());
values.insert("hrSymbol", ui->HrSymbol->text());
values.insert("hrWidth", ui->HrWidth->text());
for (int i = 1; i <= 6; ++i) {
auto row = i - 1;
values.insert(QString("headingSymbol%1").arg(i), static_cast<QLineEdit*>(ui->Headings->cellWidget(row, 0))->text());
values.insert(QString("headingOverline%1").arg(i), static_cast<QCheckBox*>(ui->Headings->cellWidget(row, 1))->isChecked());
}
config.set(values);
}
}
void RstPad::SettingsDlg::on_ButtonBox_clicked(QAbstractButton *button)
{
auto buttonGroup = qobject_cast<QDialogButtonBox*>(sender());
switch (buttonGroup->standardButton(button)) {
case QDialogButtonBox::RestoreDefaults:
updateWidgets(APP->config()->defaultValues());
break;
case QDialogButtonBox::Save:
updateConfig(*APP->config());
break;
default:
break;
}
}
| 43.730159
| 142
| 0.647731
|
ShiraNai7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.