hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e3c240f69dbf0efe4f5387bed47dcfb9dff54ab | 6,606 | cc | C++ | src/native/tchmain/TchMainExportWin.cc | dudes-come/tchapp | 24844869813edafff277e8c0ca6126d195423134 | [
"MIT"
] | 8 | 2016-11-08T08:56:58.000Z | 2017-03-30T02:34:00.000Z | src/native/tchmain/TchMainExportWin.cc | dudes-come/tchapp | 24844869813edafff277e8c0ca6126d195423134 | [
"MIT"
] | 32 | 2016-11-08T10:22:08.000Z | 2016-12-19T07:51:55.000Z | src/native/tchmain/TchMainExportWin.cc | dudes-come/tchapp | 24844869813edafff277e8c0ca6126d195423134 | [
"MIT"
] | 5 | 2016-11-08T08:57:02.000Z | 2022-01-29T09:22:46.000Z | #include "TchMainExport.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <locale>
#include <cstring>
#include <experimental/filesystem>
#include "../tch_include/TchVersion.h"
#include <io.h>
namespace gnu_fs = std::experimental::filesystem;
mbstate_t in_cvt_state;
mbstate_t out_cvt_state;
std::wstring s2ws(const std::string& s)
{
std::locale sys_loc("");
const char* src_str = s.c_str();
const size_t BUFFER_SIZE = s.size() + 1;
wchar_t* intern_buffer = new wchar_t[BUFFER_SIZE];
std::wmemset(intern_buffer, 0, BUFFER_SIZE);
const char* extern_from = src_str;
const char* extern_from_end = extern_from + s.size();
const char* extern_from_next = 0;
wchar_t* intern_to = intern_buffer;
wchar_t* intern_to_end = intern_to + BUFFER_SIZE;
wchar_t* intern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
const std::codecvt<wchar_t,char,mbstate_t>& ct=std::use_facet<CodecvtFacet>(sys_loc);
auto cvt_rst=ct.in(
in_cvt_state,
extern_from, extern_from_end, extern_from_next,
intern_to, intern_to_end, intern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch (cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check in_cvt_state."
<< std::endl;
}
std::wstring result = intern_buffer;
delete[]intern_buffer;
return result;
}
std::string ws2s(const std::wstring& ws)
{
std::locale sys_loc("");
const wchar_t* src_wstr = ws.c_str();
const size_t MAX_UNICODE_BYTES = 4;
const size_t BUFFER_SIZE =
ws.size() * MAX_UNICODE_BYTES + 1;
char* extern_buffer = new char[BUFFER_SIZE];
std::memset(extern_buffer, 0, BUFFER_SIZE);
const wchar_t* intern_from = src_wstr;
const wchar_t* intern_from_end = intern_from + ws.size();
const wchar_t* intern_from_next = 0;
char* extern_to = extern_buffer;
char* extern_to_end = extern_to + BUFFER_SIZE;
char* extern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
const std::codecvt<wchar_t, char, mbstate_t>& ct = std::use_facet<CodecvtFacet>(sys_loc);
auto cvt_rst =ct.out(
out_cvt_state,
intern_from, intern_from_end, intern_from_next,
extern_to, extern_to_end, extern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch (cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check out_cvt_state."
<< std::endl;
}
std::string result = extern_buffer;
delete[]extern_buffer;
return result;
}
void AddFilesFromDirectoryToTpaList(std::wstring directory, std::wstring& tpa_list_out) {
for (auto& dirent : gnu_fs::directory_iterator(directory)) {
std::wstring path = s2ws(dirent.path().string());
if (!path.compare(path.length() - 4, 4, L".dll")) {
tpa_list_out.append(path + L";");
}
}
tpa_list_out.erase(tpa_list_out.size() - 1, 1);
}
int TchMain(int argc,char* argv[]){
wchar_t exe_path[MAX_PATH];
GetModuleFileName(GetModuleHandle(0), exe_path, MAX_PATH);
std::wstring cmd_line_str(exe_path);
int scan_i = cmd_line_str.rfind('\\');
std::wstring app_name = cmd_line_str.substr(scan_i + 1, cmd_line_str.size() - scan_i);
std::wstring app_path(exe_path);
std::wstring app_dir = app_path.substr(0, app_path.length() - app_name.length() - 1);
std::wstring cli_entry_path = app_path.substr(0, app_path.size() - 4).append(L".dll");
std::wstring clr_dir;
std::wstring clr_path;
std::string clr_path_c(ws2s(app_dir));
clr_path_c.append("\\clr\\coreclr.dll");
bool is_use_local_clr = access(clr_path_c.c_str(), 0)==0;//检查是否存在本地clr
if (!is_use_local_clr) {
auto clr_path_var = ::getenv("ProgramFiles");
clr_dir = s2ws(clr_path_var).append(L"\\dotnet").append(L"\\shared\\Microsoft.NETCore.App\\").append(DOTNETCORE_VERSION);
}
else {
clr_dir=app_dir;
clr_dir.append(L"\\clr");
}
clr_path = clr_dir;
clr_path.append(L"\\coreclr.dll");
std::wstring tpa_list;
AddFilesFromDirectoryToTpaList(clr_dir, tpa_list);
std::wstring nativeDllSearchDirs(app_dir);
nativeDllSearchDirs.append(L";").append(clr_dir);
const char* serverGcVar = "CORECLR_SERVER_GC";
const char* useServerGc = std::getenv(serverGcVar);
if (useServerGc == nullptr)
{
useServerGc = "0";
}
useServerGc = std::strcmp(useServerGc, "1") == 0 ? "true" : "false";
const char *propertyKeys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"System.GC.Server",
};
std::string tpa_list_c = ws2s(tpa_list);
std::string app_dir_c = ws2s(app_dir);
std::string nativeDllSearchDirs_c = ws2s(nativeDllSearchDirs);
const char *propertyValues[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpa_list_c.c_str(),
// APP_PATHS
app_dir_c.c_str(),
// APP_NI_PATHS
app_dir_c.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
nativeDllSearchDirs_c.c_str(),
// System.GC.Server
useServerGc,
};
auto coreclr_hmodule = ::LoadLibrary(clr_path.c_str());
auto coreclr_initialize = (coreclr_initialize_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_initialize");
auto coreclr_shutdown = (coreclr_shutdown_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_shutdown");
//auto coreclr_create_delegate = (coreclr_create_delegate_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_create_delegate");
auto coreclr_execute_assembly = (coreclr_execute_assembly_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_execute_assembly");
void* hostHandle;
unsigned int domainId;
int status = 0;
status = coreclr_initialize(ws2s(app_path).c_str(), "TchApp", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, &hostHandle, &domainId);
LPWSTR str_status;
printf("coreclr_initialize status:%x\r\n", status);
unsigned int exit_code = 0;
std::string cli_entry_path_c = ws2s(cli_entry_path);
const char** argv_c = const_cast<const char**>(argv);
status = coreclr_execute_assembly(hostHandle, domainId, argc, argv_c, cli_entry_path_c.c_str(), &exit_code);
printf("coreclr_execute_assembly status:%x\r\n", status);
//Run run = 0;
//status = coreclr_create_delegate(hostHandle, domainId, "TchApp.CLIEntrance", "TchApp.CLIEntrance.Program", "EnterCLI", reinterpret_cast<void**>(&run));
//printf("coreclr_create_delegate status:%x\r\n", status);
coreclr_shutdown(hostHandle, domainId);
return exit_code;
} | 30.725581 | 165 | 0.725401 | dudes-come |
6e3e9583df39fc0cae7f47d412ce2a06cbc3621f | 2,468 | cpp | C++ | utils/L1/examples/tag_select_processing/tb.cpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-06-14T17:02:06.000Z | 2021-06-14T17:02:06.000Z | utils/L1/examples/tag_select_processing/tb.cpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | null | null | null | utils/L1/examples/tag_select_processing/tb.cpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <vector>
#include <iostream>
#include <stdlib.h>
#include "code.hpp"
int test() {
hls::stream<ap_uint<W_STRM> > istrm;
hls::stream<bool> e_istrm;
hls::stream<ap_uint<W_TAG> > tg_strms[2];
hls::stream<bool> e_tg_strms[2];
hls::stream<ap_uint<W_STRM> > ostrm;
hls::stream<bool> e_ostrm;
std::cout << std::dec << "W_STRM = " << W_STRM << std::endl;
std::cout << std::dec << "W_TAG = " << W_TAG << std::endl;
std::cout << std::dec << "NTAG = " << NTAG << std::endl;
std::cout << std::dec << "NS = " << NS << std::endl;
for (int d = 0; d < NS; ++d) {
istrm.write(d);
e_istrm.write(false);
ap_uint<W_TAG> tg = NTAG - d % NTAG;
tg_strms[0].write(d);
tg_strms[1].write(d);
e_tg_strms[0].write(false);
e_tg_strms[1].write(false);
}
e_istrm.write(true);
e_tg_strms[0].write(true);
e_tg_strms[1].write(true);
// process
test_core(istrm, e_istrm, tg_strms, e_tg_strms, ostrm, e_ostrm);
// fetch back and check
int nerror = 0;
int count = 0;
while (!e_ostrm.read()) {
ap_uint<W_STRM> d = ostrm.read();
ap_uint<W_STRM> gld = count + 1;
if (count <= NS && d != gld) {
nerror = 1;
std::cout << "erro: "
<< "c=" << count << ", gld=" << gld << ", "
<< " data=" << d << std::endl;
}
count++;
} // while
std::cout << "\n total read: " << count << std::endl;
if (count != NS) {
nerror = 1;
std::cout << "\n error: total read = " << count << ", NS = " << NS << std::endl;
}
if (nerror) {
std::cout << "\nFAIL: " << nerror << "the order is wrong.\n";
} else {
std::cout << "\nPASS: no error found.\n";
}
return nerror;
}
int main() {
return test();
}
| 30.469136 | 89 | 0.549838 | vmayoral |
6e44146463e32b7e0207db0fc807c245742eedf4 | 865 | cpp | C++ | Source/Shared/UI/WidgetGameButton.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | 5 | 2022-02-09T21:19:03.000Z | 2022-03-03T01:53:03.000Z | Source/Shared/UI/WidgetGameButton.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | Source/Shared/UI/WidgetGameButton.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | #include "Shared/UI/WidgetGameButton.h"
#include "Components/Button.h"
#include "Components/TextBlock.h"
#include "Kismet/GameplayStatics.h"
void UWidgetGameButton::NativeConstruct()
{
Super::NativeConstruct();
if (IsValid(this->Button))
{
this->Button->OnClicked.AddUniqueDynamic(this, &ThisClass::OnClicked);
}
}
void UWidgetGameButton::NativeDestruct()
{
Super::NativeDestruct();
if (IsValid(this->Button))
{
this->Button->OnClicked.RemoveAll(this);
}
}
void UWidgetGameButton::NativeOnListItemObjectSet(UObject* ListItemObject)
{
this->GameInfo = Cast<UWidgetGameInfo>(ListItemObject);
if (IsValid(this->GameInfo) && IsValid(this->Text))
{
this->Text->SetText(this->GameInfo->GameName);
}
}
void UWidgetGameButton::OnClicked()
{
if (IsValid(this->GameInfo))
{
UGameplayStatics::OpenLevel(GetWorld(), this->GameInfo->MapName);
}
}
| 19.659091 | 74 | 0.734104 | PsichiX |
6e4589cabeade3926d44ee96da95ded4970060a0 | 16,224 | cpp | C++ | tests/utilities/20.meta.rel.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 53 | 2015-01-13T05:46:43.000Z | 2022-02-24T23:46:04.000Z | tests/utilities/20.meta.rel.cpp | mann-patel/stdcxx | a22c5192f4b2a8b0b27d3588ea8f6d1faf8b037a | [
"Apache-2.0"
] | 1 | 2021-11-04T12:35:39.000Z | 2021-11-04T12:35:39.000Z | tests/utilities/20.meta.rel.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 33 | 2015-07-09T13:31:00.000Z | 2021-11-04T12:12:20.000Z | // -*- C++ -*-
/***************************************************************************
*
* 20.meta.rel.cpp - test exercising meta.rel
*
* $Id$
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1999-2008 Rogue Wave Software, Inc.
*
**************************************************************************/
#include <type_traits>
#include <rw_driver.h>
#include <rw/_defs.h>
// compile out all test code if extensions disabled
#ifndef _RWSTD_NO_EXT_CXX_0X
/**************************************************************************/
enum enum_A { E_a = 0 };
enum enum_B { E_b = 0 };
struct struct_A {
int i_; float f_;
};
struct struct_AA {
int i_; float f_;
};
class class_B {
int i_; float f_;
};
class class_BB {
int i_; float f_;
};
struct convertible_to_A
{
operator struct_A ();
};
struct constructible_from_B
{
constructible_from_B (class_B);
};
template <class T>
struct derived_t : T
{
};
template <class T>
struct derived_private_t : private T
{
};
template <class T>
struct derived_protected_t : protected T
{
};
template <class T>
struct derived_with_conversion_t : T
{
derived_with_conversion_t (const T&);
};
class incomplete_t;
union union_C {
int i_; float f_;
};
union union_CC {
int i_; float f_;
};
/**************************************************************************/
void test_trait (int line, bool value, bool expect,
const char* trait, const char* typeT, const char* typeU)
{
rw_assert (value == expect, 0, line,
"%s<%s, %s>::type is%{?}n't%{;} %b as expected",
trait, typeT, typeU, value != expect, expect);
}
#define TEST(Trait,TypeT,TypeU,Expect) \
{ const bool value = Trait< TypeT, TypeU >::value; \
test_trait (__LINE__, value, Expect, #Trait, #TypeT, #TypeU); \
} typedef void __dummy
static void test_is_same ()
{
TEST (std::is_same, bool, bool, true);
TEST (std::is_same, char, char, true);
TEST (std::is_same, short, short, true);
TEST (std::is_same, int, int, true);
TEST (std::is_same, long, long, true);
TEST (std::is_same, float, float, true);
TEST (std::is_same, double, double, true);
TEST (std::is_same, enum_A, enum_A, true);
TEST (std::is_same, enum_B, enum_B, true);
TEST (std::is_same, struct_A, struct_A, true);
typedef derived_t<struct_A> derived_A;
TEST (std::is_same, derived_A, derived_A, true);
TEST (std::is_same, class_B, class_B, true);
typedef derived_t<class_B> derived_B;
TEST (std::is_same, derived_B, derived_B, true);
// other combinations should fail
TEST (std::is_same, signed char, char, false);
TEST (std::is_same, char, signed char, false);
TEST (std::is_same, unsigned char, char, false);
TEST (std::is_same, char, unsigned char, false);
TEST (std::is_same, signed char, unsigned char, false);
TEST (std::is_same, unsigned char, signed char, false);
TEST (std::is_same, signed short, unsigned short, false);
TEST (std::is_same, unsigned short, signed short, false);
TEST (std::is_same, signed int, unsigned int, false);
TEST (std::is_same, unsigned int, signed int, false);
TEST (std::is_same, signed long, unsigned long, false);
TEST (std::is_same, unsigned long, signed long, false);
TEST (std::is_same, long, const long, false);
TEST (std::is_same, const long, long, false);
TEST (std::is_same, long, volatile long, false);
TEST (std::is_same, volatile long, long, false);
TEST (std::is_same, long, const volatile long, false);
TEST (std::is_same, const volatile long, long, false);
TEST (std::is_same, enum_A, char, false);
TEST (std::is_same, enum_A, short, false);
TEST (std::is_same, enum_A, int, false);
TEST (std::is_same, enum_A, long, false);
TEST (std::is_same, enum_A, unsigned char, false);
TEST (std::is_same, enum_A, unsigned short, false);
TEST (std::is_same, enum_A, unsigned int, false);
TEST (std::is_same, enum_A, unsigned long, false);
TEST (std::is_same, struct_A, derived_t<struct_A>, false);
TEST (std::is_same, class_B, derived_t<class_B>, false);
TEST (std::is_same, int[], int*, false);
TEST (std::is_same, int*, int[], false);
}
#define TEST(Trait,TypeT,TypeU,Expect) \
{ const bool value = Trait< TypeT, TypeU >::value; \
test_trait (__LINE__, value, Expect, #Trait, #TypeT, #TypeU); \
} typedef void __dummy
static void test_is_base_of ()
{
TEST (std::is_base_of, bool, bool, false);
TEST (std::is_base_of, char, char, false);
TEST (std::is_base_of, short, short, false);
TEST (std::is_base_of, int, int, false);
TEST (std::is_base_of, long, long, false);
TEST (std::is_base_of, float, float, false);
TEST (std::is_base_of, double, double, false);
TEST (std::is_base_of, enum_A, enum_A, false);
TEST (std::is_base_of, enum_B, enum_B, false);
TEST (std::is_base_of, struct_A, struct_A, true);
TEST (std::is_base_of, derived_t<struct_A>,
derived_t<struct_A>, true);
TEST (std::is_base_of, class_B, class_B, true);
TEST (std::is_base_of, derived_t<class_B>,
derived_t<class_B>, true);
#if defined (_RWSTD_TT_IS_BASE_OF) \
|| defined (_RWSTD_TT_IS_CLASS) \
|| defined (_RWSTD_TT_IS_UNION)
// without one of the above, we can't reliably implement
// this trait for union type
TEST (std::is_base_of, union_C, union_C, false);
#else
rw_warn (0, 0, __LINE__,
"portions of test_is_base_of() have been disabled due "
"to lack of compiler support.");
#endif
// public inheritance
TEST (std::is_base_of, struct_A, derived_t<struct_A>, true);
TEST (std::is_base_of, class_B, derived_t<class_B>, true);
#if defined (__SUNPRO_CC) && (__SUNPRO_CC <= 0x590)
// for some reason the trick used to detect private and protected
// inheritance doesn't work on sunpro-5.9
rw_warn (0, 0, __LINE__,
"unable to detect private or protected base classes.");
#else
// protected inheritance
TEST (std::is_base_of, struct_A, derived_protected_t<struct_A>, true);
// private inheritance
TEST (std::is_base_of, struct_A, derived_private_t<struct_A>, true);
#endif
// cv-qualified
TEST (std::is_base_of, const struct_A, struct_A, true);
TEST (std::is_base_of, struct_A, const struct_A, true);
TEST (std::is_base_of, volatile struct_A, struct_A, true);
TEST (std::is_base_of, struct_A, volatile struct_A, true);
TEST (std::is_base_of, const volatile struct_A, struct_A, true);
TEST (std::is_base_of, struct_A, const volatile struct_A, true);
TEST (std::is_base_of, const struct_A, derived_t<struct_A>, true);
TEST (std::is_base_of, struct_A, const derived_t<struct_A>, true);
TEST (std::is_base_of, volatile struct_A, derived_t<struct_A>, true);
TEST (std::is_base_of, struct_A, volatile derived_t<struct_A>, true);
TEST (std::is_base_of, const volatile struct_A, derived_t<struct_A>, true);
TEST (std::is_base_of, struct_A, const volatile derived_t<struct_A>, true);
// other combinations should fail
TEST (std::is_base_of, signed char, char, false);
TEST (std::is_base_of, char, signed char, false);
TEST (std::is_base_of, unsigned char, char, false);
TEST (std::is_base_of, char, unsigned char, false);
TEST (std::is_base_of, signed char, unsigned char, false);
TEST (std::is_base_of, unsigned char, signed char, false);
TEST (std::is_base_of, signed short, unsigned short, false);
TEST (std::is_base_of, unsigned short, signed short, false);
TEST (std::is_base_of, signed int, unsigned int, false);
TEST (std::is_base_of, unsigned int, signed int, false);
TEST (std::is_base_of, signed long, unsigned long, false);
TEST (std::is_base_of, unsigned long, signed long, false);
TEST (std::is_base_of, enum_A, char, false);
TEST (std::is_base_of, enum_A, short, false);
TEST (std::is_base_of, enum_A, int, false);
TEST (std::is_base_of, enum_A, long, false);
TEST (std::is_base_of, enum_A, unsigned char, false);
TEST (std::is_base_of, enum_A, unsigned short, false);
TEST (std::is_base_of, enum_A, unsigned int, false);
TEST (std::is_base_of, enum_A, unsigned long, false);
TEST (std::is_base_of, int[], int*, false);
TEST (std::is_base_of, int*, int[], false);
TEST (std::is_base_of, struct_A, class_B, false);
TEST (std::is_base_of, class_B, struct_A, false);
TEST (std::is_base_of, derived_t<struct_A>, struct_A, false);
TEST (std::is_base_of, derived_t<class_B>, class_B, false);
}
static void test_is_convertible ()
{
TEST (std::is_convertible, derived_t<struct_A> , struct_A , true); // slice
TEST (std::is_convertible, derived_t<struct_A>*, struct_A*, true);
TEST (std::is_convertible, derived_t<struct_A>&, struct_A&, true);
TEST (std::is_convertible, derived_t<class_B> , class_B , true); // slice
TEST (std::is_convertible, derived_t<class_B>*, class_B*, true);
TEST (std::is_convertible, derived_t<class_B>&, class_B&, true);
TEST (std::is_convertible, convertible_to_A, struct_A, true);
TEST (std::is_convertible, struct_A, convertible_to_A, false);
TEST (std::is_convertible, convertible_to_A*, struct_A*, false);
TEST (std::is_convertible, convertible_to_A&, struct_A&, false);
TEST (std::is_convertible, constructible_from_B, class_B, false);
TEST (std::is_convertible, class_B, constructible_from_B, true);
TEST (std::is_convertible, class_B*, constructible_from_B*, false);
TEST (std::is_convertible, class_B&, constructible_from_B&, false);
//
// pointer to pointer conversions
//
TEST (std::is_convertible, int*, int*, true);
TEST (std::is_convertible, const int*, const int*, true);
TEST (std::is_convertible, volatile int*, volatile int*, true);
TEST (std::is_convertible, const volatile int*, const volatile int*, true);
// add cv-qualifiers
TEST (std::is_convertible, int*, const int*, true);
TEST (std::is_convertible, int*, volatile int*, true);
TEST (std::is_convertible, int*, const volatile int*, true);
// strip cv-qualifiers
TEST (std::is_convertible, const int*, int*, false);
TEST (std::is_convertible, volatile int*, int*, false);
TEST (std::is_convertible, const volatile int*, int*, false);
//
// special case void conversions
//
TEST (std::is_convertible, void, void, true);
TEST (std::is_convertible, void, long, false);
TEST (std::is_convertible, long, void, false);
//
// array to pointer conversions
//
TEST (std::is_convertible, int[], int*, true);
TEST (std::is_convertible, const int[], const int*, true);
TEST (std::is_convertible, volatile int[], volatile int*, true);
TEST (std::is_convertible, const volatile int[], const volatile int*, true);
// add cv-qualifiers
TEST (std::is_convertible, int[], const int*, true);
TEST (std::is_convertible, int[], volatile int*, true);
TEST (std::is_convertible, int[], const volatile int*, true);
// strip cv-qualifiers
TEST (std::is_convertible, const int[], int*, false);
TEST (std::is_convertible, volatile int[], int*, false);
TEST (std::is_convertible, const volatile int[], int*, false);
//
// pointer to array conversions should all fail
//
TEST (std::is_convertible, int*, int[], false);
TEST (std::is_convertible, const int*, const int[], false);
TEST (std::is_convertible, volatile int*, volatile int[], false);
TEST (std::is_convertible, const volatile int*, const volatile int[], false);
// add cv-qualifiers
TEST (std::is_convertible, int*, const int[], false);
TEST (std::is_convertible, int*, volatile int[], false);
TEST (std::is_convertible, int*, const volatile int[], false);
// strip cv-qualifiers
TEST (std::is_convertible, const int*, int[], false);
TEST (std::is_convertible, volatile int*, int[], false);
TEST (std::is_convertible, const volatile int*, int[], false);
//// from an abstract type is allowed
//TEST (std::is_convertible, abstract_, int, false);
//TEST (std::is_convertible, derived_t<abstract_>, abstract_, false);
TEST (std::is_convertible, long*, void*, true);
TEST (std::is_convertible, void*, long*, false);
// function to function conversions fail
TEST (std::is_convertible, int (), int (), false);
TEST (std::is_convertible, int (), int (char, long), false);
// function to function pointer
TEST (std::is_convertible, int (), int (*)(), true);
TEST (std::is_convertible, int (char, long), int (*)(char, long), true);
TEST (std::is_convertible, int (), int (*)(char), false);
// function to function reference
TEST (std::is_convertible, int (), int (&)(), true);
TEST (std::is_convertible, int (char, long), int (&)(char, long), true);
TEST (std::is_convertible, int (), int (&)(char), false);
TEST (std::is_convertible, int*, void*, true);
#if defined (_MSC_VER) || defined (__IBMCPP__)
// microsoft language extension allows this conversion, and that
// extension is enabled by default.
TEST (std::is_convertible, int (*)(), void*, true);
#else
TEST (std::is_convertible, int (*)(), void*, false);
#endif
TEST (std::is_convertible,
int (*)(derived_t<struct_A>*),
int (*)(struct_A*), false);
TEST (std::is_convertible,
int (*)(struct_A*),
int (*)(derived_t<struct_A>*), false);
// pointer to derived member convertible to
// pointer to base member
TEST (std::is_convertible,
int derived_t<struct_A>::*,
int struct_A::*, false);
// pointer to base member convertible to
// pointer to derived member
TEST (std::is_convertible,
int struct_A::*,
int derived_t<struct_A>::*, true);
TEST (std::is_convertible, int, double, true);
TEST (std::is_convertible, const int, double, true);
}
/**************************************************************************/
static int run_test (int, char*[])
{
test_is_same ();
test_is_base_of ();
test_is_convertible ();
return 0;
}
/**************************************************************************/
#else // _RWSTD_NO_EXT_CXX_0X
/**************************************************************************/
static int run_test (int, char*[])
{
rw_warn (0, 0, __LINE__,
"test disabled because _RWSTD_NO_EXT_CXX_0X is defined");
return 0;
}
#endif // !_RWSTD_NO_EXT_CXX_0X
/**************************************************************************/
int main (int argc, char *argv[])
{
return rw_test (argc, argv, __FILE__,
"meta.rel",
0 /* no comment */,
run_test,
0);
}
| 35.116883 | 81 | 0.612857 | isabella232 |
6e45f2a66417dc67c04cfc99f03269b9a4486a3f | 599 | cpp | C++ | src/Context.cpp | desktopgame/ofxLua | 098cc40277dd00d42aaf191bbf0cc43d3b2349fd | [
"BSL-1.0",
"MIT"
] | 1 | 2020-01-28T05:10:19.000Z | 2020-01-28T05:10:19.000Z | src/Context.cpp | desktopgame/ofxLua | 098cc40277dd00d42aaf191bbf0cc43d3b2349fd | [
"BSL-1.0",
"MIT"
] | null | null | null | src/Context.cpp | desktopgame/ofxLua | 098cc40277dd00d42aaf191bbf0cc43d3b2349fd | [
"BSL-1.0",
"MIT"
] | null | null | null | #include "Context.h"
#include <stdexcept>
namespace ofxLua {
std::stack<Context::Instance> Context::stack;
Context::Instance Context::push() {
Instance inst = std::shared_ptr<Context>(new Context());
stack.push(inst);
return inst;
}
Context::Instance Context::top() {
if (stack.empty()) {
throw std::logic_error("stack is empty");
}
return stack.top();
}
void Context::pop() {
if (stack.empty()) {
throw std::logic_error("stack is empty");
}
stack.pop();
}
bool Context::contains(const std::string & name) const {
return map.count(name);
}
// private
Context::Context() : map() {
}
} | 19.966667 | 57 | 0.672788 | desktopgame |
6e4b9ab17d46534a56a7934aab995fb8b4c08fcd | 414 | cpp | C++ | Sources/C++/TypeSupport/is_member_pointer.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 27 | 2017-12-19T09:15:36.000Z | 2021-07-30T13:02:00.000Z | Sources/C++/TypeSupport/is_member_pointer.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | null | null | null | Sources/C++/TypeSupport/is_member_pointer.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 29 | 2018-04-10T13:25:54.000Z | 2021-12-24T01:51:03.000Z | #include <iostream>
#include <type_traits>
int main() {
class cls {};
std::cout << (std::is_member_pointer<int(cls::*)>::value
? "T is member pointer"
: "T is not a member pointer") << '\n';
std::cout << (std::is_member_pointer<int>::value
? "T is member pointer"
: "T is not a member pointer") << '\n';
} | 34.5 | 61 | 0.471014 | wurui1994 |
6e4cb71385fec4a18bfc6f76cfff779e1e0b2c14 | 989 | cpp | C++ | SLogLib/AddToCallStack.cpp | saurabhg17/SLogLib | bb5bbc1ae4f83f01947d2b1232ad7b7e4b7d4aee | [
"MIT"
] | 9 | 2015-05-16T05:59:14.000Z | 2019-10-30T00:49:20.000Z | SLogLib/AddToCallStack.cpp | saurabhg17/SLogLib | bb5bbc1ae4f83f01947d2b1232ad7b7e4b7d4aee | [
"MIT"
] | null | null | null | SLogLib/AddToCallStack.cpp | saurabhg17/SLogLib | bb5bbc1ae4f83f01947d2b1232ad7b7e4b7d4aee | [
"MIT"
] | 2 | 2017-10-15T13:29:35.000Z | 2019-09-09T08:08:59.000Z | //
// This file is part of SLogLib; you can redistribute it and/or
// modify it under the terms of the MIT License.
// Author: Saurabh Garg (saurabhgarg@mysoc.net)
//
#include "AddToCallStack.h"
#include "LoggingManager.h"
namespace SLogLib {
;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
AddToCallStack::AddToCallStack(const std::string& fileName,
const std::string& funcName,
unsigned int lineNumber)
{
if(LoggingManager::Instance())
{
LoggingManager::Instance()->PushFunction(fileName, funcName, lineNumber);
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
AddToCallStack::~AddToCallStack()
{
if(LoggingManager::Instance())
{
LoggingManager::Instance()->PopFunction();
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
}; // End namespace SLogLib.
| 26.72973 | 80 | 0.466127 | saurabhg17 |
6e5192c204f0327c507d2eb370e626d5e9d3cda0 | 67 | hpp | C++ | tests/src/utils/generate_unique_mock_id.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 4 | 2019-11-14T10:41:34.000Z | 2021-12-09T23:54:52.000Z | tests/src/utils/generate_unique_mock_id.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 2 | 2021-10-04T20:12:53.000Z | 2021-12-14T18:13:03.000Z | tests/src/utils/generate_unique_mock_id.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 2 | 2021-08-05T11:17:03.000Z | 2021-12-13T15:22:48.000Z | #pragma once
#include <cstdint>
uint64_t generateUniqueMockId();
| 11.166667 | 32 | 0.776119 | aahmed-2 |
6e5296191454b28306a2722dc1d12cfda2fef7b7 | 1,302 | cpp | C++ | Enviados/Brinde_Face_2015.cpp | VictorCurti/URI | abc344597682a3099e8b1899c78584f9b762a494 | [
"MIT"
] | null | null | null | Enviados/Brinde_Face_2015.cpp | VictorCurti/URI | abc344597682a3099e8b1899c78584f9b762a494 | [
"MIT"
] | null | null | null | Enviados/Brinde_Face_2015.cpp | VictorCurti/URI | abc344597682a3099e8b1899c78584f9b762a494 | [
"MIT"
] | null | null | null | /* Brinde Face 2015
Data: 25/03/2019 Autor: Victor Curti
ex:
4
0 1 2 3 4
(F A C E - E C F A - A C F E - A C E F - F E C A)
F A C E E C F A A C F E A C E F F E C A
F A C E E C F A A C F E
A C E F - F E C A
Stack A:
F
E
C
A
*/
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
string Dado ("FACE");
int num,Ganhadores=0;
cin >> num;
cin.get();
while(num--){
string Leirura;
getline(cin,Leirura);
for (char c: Leirura)
if(c != ' ' && c!= '\n')
Dado += c;
stack <char> StackA;
bool Test = true;
for(int i=0 ; i<=4 ; i++){
StackA.push(Dado[Dado.size()-i]);
}
//Apaga ultimas 4 letras ja lidas
for(int i=4 ; i<=7 && Test; i++){
if(StackA.top()!= Dado[(Dado.size()-1)-i])
Test = false;
StackA.pop();
}
//Caso Ganhador Tirar as 4 anterios tambem
if(Test){
Dado.erase(Dado.size()-8,8);
Ganhadores++;
}
if(Dado.empty())
Dado += "FACE";
}
cout << Ganhadores;
return 0;
} | 21 | 54 | 0.417819 | VictorCurti |
6e58d6692a7aaca7a90bb12f68d407cb7ef56f34 | 1,549 | cpp | C++ | utiles/source/Stemming.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | utiles/source/Stemming.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | utiles/source/Stemming.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | #include <utiles/include/Stemming.h>
// stl
#include <locale>
#include <codecvt>
using namespace herramientas::utiles;
stemming::spanish_stem<> Stemming::stem_spanish;
Stemming::Stemming()
{
}
Stemming::~Stemming()
{
}
void Stemming::stemUTF8(std::string & string_a_hashear)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
std::wstring word = conv.from_bytes(string_a_hashear.c_str());
stem_spanish(word);
string_a_hashear = conv.to_bytes(word);
}
void Stemming::stemUTF8(std::vector<std::string> & vector_de_string_a_stemmear)
{
for (std::vector<std::string>::iterator it = vector_de_string_a_stemmear.begin(); it != vector_de_string_a_stemmear.end(); it++)
{
stemUTF8(*it);
}
}
void Stemming::stem(std::string & string_a_hashear)
{
wchar_t * unicode_text_buffer = new wchar_t[string_a_hashear.length() + 1];
std::wmemset(unicode_text_buffer, 0, string_a_hashear.length() + 1);
std::mbstowcs(unicode_text_buffer, string_a_hashear.c_str(), string_a_hashear.length());
std::wstring word = unicode_text_buffer;
stem_spanish(word);
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
string_a_hashear = conv.to_bytes(word);
delete[] unicode_text_buffer;
}
void Stemming::stem(std::vector<std::string> & vector_de_string_a_stemmear)
{
for (std::vector<std::string>::iterator it = vector_de_string_a_stemmear.begin(); it != vector_de_string_a_stemmear.end(); it++)
{
stem(*it);
}
}
| 26.254237 | 133 | 0.684958 | miglesias91 |
6e59e9c273bfd71e626210828711b2681f7ecb8e | 1,062 | cpp | C++ | Gems/GraphModel/Code/Source/Integration/GraphCanvasMetadata.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/GraphModel/Code/Source/Integration/GraphCanvasMetadata.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/GraphModel/Code/Source/Integration/GraphCanvasMetadata.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// AZ
#include <AzCore/Serialization/SerializeContext.h>
// Graph Canvas
#include <GraphCanvas/Types/EntitySaveData.h>
// Graph Model
#include <GraphModel/Integration/GraphCanvasMetadata.h>
namespace GraphModelIntegration
{
void GraphCanvasMetadata::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<GraphCanvasMetadata>()
->Version(0)
->Field("m_sceneMetadata", &GraphCanvasMetadata::m_sceneMetadata)
->Field("m_nodeMetadata", &GraphCanvasMetadata::m_nodeMetadata)
->Field("m_otherMetadata", &GraphCanvasMetadata::m_otherMetadata)
;
}
}
} // namespace ShaderCanvas
| 32.181818 | 158 | 0.684557 | aaarsene |
6e5b52dd869faa243903a19d3e2f3ae1221c8412 | 619 | cpp | C++ | AllCombinationsOfString/combinations.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 6 | 2019-08-29T23:31:17.000Z | 2021-11-14T20:35:47.000Z | AllCombinationsOfString/combinations.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | null | null | null | AllCombinationsOfString/combinations.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 1 | 2019-09-01T12:22:58.000Z | 2019-09-01T12:22:58.000Z | #include <iostream>
#include <string>
void find_permutations( std::string first, std::string others )
{
if( others.size() <= 0 ) {
std::cout << first << "\n";
return;
}
int len = others.size();
for( int i = 0; i < len; ++i ) {
std::string sub = others;
std::string first_tmp = first;
first_tmp += sub[ i ];
sub.erase( sub.begin() + i );
find_permutations( first_tmp, sub );
}
}
int main()
{
std::string s = "chirag";
int len = s.size();
for( int i = 0; i < len; ++i ) {
std::string sub = s;
sub.erase( sub.begin() + i );
find_permutations( std::string( 1, s[ i ] ), sub );
}
return 0;
}
| 19.967742 | 63 | 0.573506 | Electrux |
6e5bca89d247516231fb68cf075693d455fd0450 | 422 | hpp | C++ | src/tree/base/import.hpp | Azer0s/littl | 3d2bfd979bdeee74cded9f31b62640b45b86a155 | [
"MIT"
] | 4 | 2018-12-30T13:15:55.000Z | 2019-05-12T17:39:38.000Z | src/tree/base/import.hpp | Azer0s/littl | 3d2bfd979bdeee74cded9f31b62640b45b86a155 | [
"MIT"
] | null | null | null | src/tree/base/import.hpp | Azer0s/littl | 3d2bfd979bdeee74cded9f31b62640b45b86a155 | [
"MIT"
] | 1 | 2018-12-29T19:12:07.000Z | 2018-12-29T19:12:07.000Z | #pragma once
#include "../syntaxtree.hpp"
namespace littl {
class Import : public SyntaxTree{
public:
Import(SyntaxTree* name){
this->name = name;
}
virtual ~Import(){
delete name;
};
virtual std::string toCode() const{
return "";
}
private:
SyntaxTree* name;
};
} | 21.1 | 47 | 0.440758 | Azer0s |
6e5d5f620d9a2aeb6eb2c8f7d3ed7e8e2902cedf | 2,181 | cpp | C++ | src/HumanPlayer.cpp | ColinVDH/checkers | bbcdac94a9d9f4c61625780902b891b12311d62d | [
"MIT"
] | null | null | null | src/HumanPlayer.cpp | ColinVDH/checkers | bbcdac94a9d9f4c61625780902b891b12311d62d | [
"MIT"
] | null | null | null | src/HumanPlayer.cpp | ColinVDH/checkers | bbcdac94a9d9f4c61625780902b891b12311d62d | [
"MIT"
] | null | null | null | //
// Created by colin on 11/10/16.
//
#include "HumanPlayer.h"
#include <sstream>
using namespace std;
//constructor
HumanPlayer::HumanPlayer(Color color): input(""), Player(color){}
//return the current input
string HumanPlayer::getInput() {
return input;
}
//set the current input by getting it from the user
void HumanPlayer::setInput(){
string i;
getline(cin, i);
input=i;
}
//checks if the user has valid input (of the form "a1 b2" etc...)
bool HumanPlayer::hasValidInput(){
if (input.length()==0) return false; //no input
if (input=="q") return true; //quit character
vector<string> split_input = split(input,' '); //split input by whitespace into a vector of strings.
if (split_input.size()<2) return false;
for (auto const& item : split_input) {
if (!((item.length()==2)
&& 0<=(tolower(item[0])-'a') && (tolower(item[0])-'a')<=7
&& 0<=(item[1]-'1') && (item[1]-'1')<=7)){ //checks if the first part of each word is a letter from a to h and the second part is a number from 1 to 8
return false;
}
}
return true;
}
//returns the human players move
Move HumanPlayer::getMove() {
vector<array<int,2>> sequence;
if (!hasValidInput()) return Move(); //returns an empty move if there is no valid input
else{
vector<string> split_input = split(input,' '); //split input by whitespace into a vector of strings.
for (auto const& item : split_input){
int x=tolower(item[0])-'a'; //convert the labels to actual x coordinates
int y=item[1]-'1'; //convert the label to actual y coordinate
sequence.push_back({x,y}); //add to the move sequence
}
}
return Move(sequence); //return the move
}
//helper method to split a string into a vector of strings, given a delimiter
vector<string> HumanPlayer::split(string s, char delim) {
stringstream ss; //string stream
vector<string> elements={};
ss.str(s);
string item;
while (getline(ss, item, delim)){
elements.push_back(item);
}
return elements;
}
//checks if human
bool HumanPlayer::isHuman(){
return true;
}
| 29.08 | 164 | 0.630445 | ColinVDH |
6e5e03b24741ecdc6c83cae97aedd0b7b61eff5e | 1,328 | cpp | C++ | Code/C++/selection_sort.cpp | parthmshah1302/Algo-Tree | 451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc | [
"MIT"
] | 356 | 2021-01-24T11:34:15.000Z | 2022-03-16T08:39:02.000Z | Code/C++/selection_sort.cpp | parthmshah1302/Algo-Tree | 451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc | [
"MIT"
] | 1,778 | 2021-01-24T10:52:44.000Z | 2022-01-30T12:34:05.000Z | Code/C++/selection_sort.cpp | parthmshah1302/Algo-Tree | 451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc | [
"MIT"
] | 782 | 2021-01-24T10:54:10.000Z | 2022-03-23T10:16:04.000Z | /*
Selection sort is an algorithm that selects the smallest element from an unsorted list in each iteration
and places that element at the beginning of the unsorted list.
* Strategy:
find the smallest number in the array and exchange it with the value in first position of array.
Now, find the second smallest element in the remainder of array and exchange it with a value in the second position,
carry on till you have reached the end of array. Now all the elements have been sorted in ascending order.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,k;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
// move boundary of unsorted subarray one by one
for(i=0;i<n-1;i++){
// Find the minimum element in unsorted array
for(j=k=i;j<n;j++){
if(a[j]<a[k])
k=j;
}
// Swap the minimum element with the ith element of array
swap(a[i],a[k]);
}
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
/*
Test case 1:
Input : 7
3 5 4 1 2 7 6
Output :
1 2 3 4 5 6 7
Test case 2:
Input : 5
50 20 40 10 30
Output:
10 20 30 40 50
Time Complexity: O(n^2)
Space Complexity: O(1)
*/
| 16.395062 | 124 | 0.576054 | parthmshah1302 |
6e61a110389e77a76be83f94d795d9465eb0c47f | 2,646 | hpp | C++ | include/stl2/detail/algorithm/swap_ranges.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | include/stl2/detail/algorithm/swap_ranges.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | include/stl2/detail/algorithm/swap_ranges.hpp | marehr/cmcstl2 | 7a7cae1e23beacb18fd786240baef4ae121d813f | [
"MIT"
] | null | null | null | // cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 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_ALGORITHM_SWAP_RANGES_HPP
#define STL2_DETAIL_ALGORITHM_SWAP_RANGES_HPP
#include <stl2/iterator.hpp>
#include <stl2/utility.hpp>
#include <stl2/detail/algorithm/tagspec.hpp>
///////////////////////////////////////////////////////////////////////////
// swap_ranges [alg.swap]
//
STL2_OPEN_NAMESPACE {
namespace __swap_ranges {
template<ForwardIterator I1, Sentinel<I1> S1, ForwardIterator I2>
requires
IndirectlySwappable<I1, I2>
constexpr tagged_pair<tag::in1(I1), tag::in2(I2)>
impl(I1 first1, S1 last1, I2 first2)
{
for (; first1 != last1; ++first1, void(++first2)) {
__stl2::iter_swap(first1, first2);
}
return {std::move(first1), std::move(first2)};
}
}
template<ForwardIterator I1, Sentinel<I1> S1, class I2>
[[deprecated]] tagged_pair<tag::in1(I1), tag::in2(std::decay_t<I2>)>
swap_ranges(I1 first1, S1 last1, I2&& first2_)
requires ForwardIterator<std::decay_t<I2>> && !Range<I2> &&
IndirectlySwappable<I1, std::decay_t<I2>>
{
return __swap_ranges::impl(
std::move(first1), std::move(last1), std::forward<I2>(first2_));
}
template<ForwardRange Rng, class I>
[[deprecated]] tagged_pair<tag::in1(safe_iterator_t<Rng>), tag::in2(std::decay_t<I>)>
swap_ranges(Rng&& rng1, I&& first2_)
requires ForwardIterator<std::decay_t<I>> && !Range<I> &&
IndirectlySwappable<iterator_t<Rng>, std::decay_t<I>>
{
auto first2 = std::forward<I>(first2_);
return __swap_ranges::impl(__stl2::begin(rng1), __stl2::end(rng1), std::move(first2));
}
template<ForwardIterator I1, Sentinel<I1> S1,
ForwardIterator I2, Sentinel<I2> S2>
requires
IndirectlySwappable<I1, I2>
tagged_pair<tag::in1(I1), tag::in2(I2)>
swap_ranges(I1 first1, S1 last1, I2 first2, S2 last2)
{
for (; first1 != last1 && first2 != last2; ++first1, void(++first2)) {
__stl2::iter_swap(first1, first2);
}
return {std::move(first1), std::move(first2)};
}
template<ForwardRange Rng1, ForwardRange Rng2>
requires
IndirectlySwappable<iterator_t<Rng1>, iterator_t<Rng2>>
tagged_pair<tag::in1(safe_iterator_t<Rng1>),
tag::in2(safe_iterator_t<Rng2>)>
swap_ranges(Rng1&& rng1, Rng2&& rng2)
{
return __stl2::swap_ranges(
__stl2::begin(rng1), __stl2::end(rng1),
__stl2::begin(rng2), __stl2::end(rng2));
}
} STL2_CLOSE_NAMESPACE
#endif
| 31.5 | 88 | 0.688209 | marehr |
6e6281a18b516b647e016e47df7b5113b35c998e | 23,820 | cc | C++ | third_party/blink/renderer/platform/loader/fetch/resource_response.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/platform/loader/fetch/resource_response.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/platform/loader/fetch/resource_response.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
namespace {
template <typename Interface>
Vector<Interface> IsolatedCopy(const Vector<Interface>& src) {
Vector<Interface> result;
result.ReserveCapacity(src.size());
for (const auto& timestamp : src) {
result.push_back(timestamp.IsolatedCopy());
}
return result;
}
static const char kCacheControlHeader[] = "cache-control";
static const char kPragmaHeader[] = "pragma";
} // namespace
ResourceResponse::SignedCertificateTimestamp::SignedCertificateTimestamp(
const blink::WebURLResponse::SignedCertificateTimestamp& sct)
: status_(sct.status),
origin_(sct.origin),
log_description_(sct.log_description),
log_id_(sct.log_id),
timestamp_(sct.timestamp),
hash_algorithm_(sct.hash_algorithm),
signature_algorithm_(sct.signature_algorithm),
signature_data_(sct.signature_data) {}
ResourceResponse::SignedCertificateTimestamp
ResourceResponse::SignedCertificateTimestamp::IsolatedCopy() const {
return SignedCertificateTimestamp(
status_.IsolatedCopy(), origin_.IsolatedCopy(),
log_description_.IsolatedCopy(), log_id_.IsolatedCopy(), timestamp_,
hash_algorithm_.IsolatedCopy(), signature_algorithm_.IsolatedCopy(),
signature_data_.IsolatedCopy());
}
ResourceResponse::ResourceResponse()
: expected_content_length_(0), is_null_(true) {}
ResourceResponse::ResourceResponse(const KURL& url,
const AtomicString& mime_type,
long long expected_length,
const AtomicString& text_encoding_name)
: url_(url),
mime_type_(mime_type),
expected_content_length_(expected_length),
text_encoding_name_(text_encoding_name),
is_null_(false) {}
ResourceResponse::ResourceResponse(CrossThreadResourceResponseData* data)
: ResourceResponse() {
SetURL(data->url_);
SetMimeType(AtomicString(data->mime_type_));
SetExpectedContentLength(data->expected_content_length_);
SetTextEncodingName(AtomicString(data->text_encoding_name_));
SetHTTPStatusCode(data->http_status_code_);
SetHTTPStatusText(AtomicString(data->http_status_text_));
http_header_fields_.Adopt(std::move(data->http_headers_));
SetResourceLoadTiming(std::move(data->resource_load_timing_));
remote_ip_address_ = AtomicString(data->remote_ip_address_);
remote_port_ = data->remote_port_;
has_major_certificate_errors_ = data->has_major_certificate_errors_;
ct_policy_compliance_ = data->ct_policy_compliance_;
is_legacy_symantec_cert_ = data->is_legacy_symantec_cert_;
cert_validity_start_ = data->cert_validity_start_;
was_fetched_via_spdy_ = data->was_fetched_via_spdy_;
was_fetched_via_proxy_ = data->was_fetched_via_proxy_;
was_fetched_via_service_worker_ = data->was_fetched_via_service_worker_;
was_fallback_required_by_service_worker_ =
data->was_fallback_required_by_service_worker_;
did_service_worker_navigation_preload_ =
data->did_service_worker_navigation_preload_;
response_type_via_service_worker_ = data->response_type_via_service_worker_;
security_style_ = data->security_style_;
security_details_.protocol = data->security_details_.protocol;
security_details_.cipher = data->security_details_.cipher;
security_details_.key_exchange = data->security_details_.key_exchange;
security_details_.key_exchange_group =
data->security_details_.key_exchange_group;
security_details_.mac = data->security_details_.mac;
security_details_.subject_name = data->security_details_.subject_name;
security_details_.san_list = data->security_details_.san_list;
security_details_.issuer = data->security_details_.issuer;
security_details_.valid_from = data->security_details_.valid_from;
security_details_.valid_to = data->security_details_.valid_to;
for (auto& cert : data->certificate_)
security_details_.certificate.push_back(AtomicString(cert));
security_details_.sct_list = data->security_details_.sct_list;
http_version_ = data->http_version_;
app_cache_id_ = data->app_cache_id_;
app_cache_manifest_url_ = data->app_cache_manifest_url_.Copy();
multipart_boundary_ = data->multipart_boundary_;
url_list_via_service_worker_ = data->url_list_via_service_worker_;
cache_storage_cache_name_ = data->cache_storage_cache_name_;
response_time_ = data->response_time_;
encoded_data_length_ = data->encoded_data_length_;
encoded_body_length_ = data->encoded_body_length_;
decoded_body_length_ = data->decoded_body_length_;
downloaded_file_path_ = data->downloaded_file_path_;
downloaded_file_handle_ = data->downloaded_file_handle_;
// Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
// whatever values may be present in the opaque m_extraData structure.
}
ResourceResponse::ResourceResponse(const ResourceResponse&) = default;
ResourceResponse& ResourceResponse::operator=(const ResourceResponse&) =
default;
std::unique_ptr<CrossThreadResourceResponseData> ResourceResponse::CopyData()
const {
std::unique_ptr<CrossThreadResourceResponseData> data =
std::make_unique<CrossThreadResourceResponseData>();
data->url_ = Url().Copy();
data->mime_type_ = MimeType().GetString().IsolatedCopy();
data->expected_content_length_ = ExpectedContentLength();
data->text_encoding_name_ = TextEncodingName().GetString().IsolatedCopy();
data->http_status_code_ = HttpStatusCode();
data->http_status_text_ = HttpStatusText().GetString().IsolatedCopy();
data->http_headers_ = HttpHeaderFields().CopyData();
if (resource_load_timing_)
data->resource_load_timing_ = resource_load_timing_->DeepCopy();
data->remote_ip_address_ = remote_ip_address_.GetString().IsolatedCopy();
data->remote_port_ = remote_port_;
data->has_major_certificate_errors_ = has_major_certificate_errors_;
data->ct_policy_compliance_ = ct_policy_compliance_;
data->is_legacy_symantec_cert_ = is_legacy_symantec_cert_;
data->cert_validity_start_ = cert_validity_start_;
data->was_fetched_via_spdy_ = was_fetched_via_spdy_;
data->was_fetched_via_proxy_ = was_fetched_via_proxy_;
data->was_fetched_via_service_worker_ = was_fetched_via_service_worker_;
data->was_fallback_required_by_service_worker_ =
was_fallback_required_by_service_worker_;
data->did_service_worker_navigation_preload_ =
did_service_worker_navigation_preload_;
data->response_type_via_service_worker_ = response_type_via_service_worker_;
data->security_style_ = security_style_;
data->security_details_.protocol = security_details_.protocol.IsolatedCopy();
data->security_details_.cipher = security_details_.cipher.IsolatedCopy();
data->security_details_.key_exchange =
security_details_.key_exchange.IsolatedCopy();
data->security_details_.key_exchange_group =
security_details_.key_exchange_group.IsolatedCopy();
data->security_details_.mac = security_details_.mac.IsolatedCopy();
data->security_details_.subject_name =
security_details_.subject_name.IsolatedCopy();
data->security_details_.san_list = IsolatedCopy(security_details_.san_list);
data->security_details_.issuer = security_details_.issuer.IsolatedCopy();
data->security_details_.valid_from = security_details_.valid_from;
data->security_details_.valid_to = security_details_.valid_to;
for (auto& cert : security_details_.certificate)
data->certificate_.push_back(cert.GetString().IsolatedCopy());
data->security_details_.sct_list = IsolatedCopy(security_details_.sct_list);
data->http_version_ = http_version_;
data->app_cache_id_ = app_cache_id_;
data->app_cache_manifest_url_ = app_cache_manifest_url_.Copy();
data->multipart_boundary_ = multipart_boundary_;
data->url_list_via_service_worker_.resize(
url_list_via_service_worker_.size());
std::transform(url_list_via_service_worker_.begin(),
url_list_via_service_worker_.end(),
data->url_list_via_service_worker_.begin(),
[](const KURL& url) { return url.Copy(); });
data->cache_storage_cache_name_ = CacheStorageCacheName().IsolatedCopy();
data->response_time_ = response_time_;
data->encoded_data_length_ = encoded_data_length_;
data->encoded_body_length_ = encoded_body_length_;
data->decoded_body_length_ = decoded_body_length_;
data->downloaded_file_path_ = downloaded_file_path_.IsolatedCopy();
data->downloaded_file_handle_ = downloaded_file_handle_;
// Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
// whatever values may be present in the opaque m_extraData structure.
return data;
}
bool ResourceResponse::IsHTTP() const {
return url_.ProtocolIsInHTTPFamily();
}
const KURL& ResourceResponse::Url() const {
return url_;
}
void ResourceResponse::SetURL(const KURL& url) {
is_null_ = false;
url_ = url;
}
const AtomicString& ResourceResponse::MimeType() const {
return mime_type_;
}
void ResourceResponse::SetMimeType(const AtomicString& mime_type) {
is_null_ = false;
// FIXME: MIME type is determined by HTTP Content-Type header. We should
// update the header, so that it doesn't disagree with m_mimeType.
mime_type_ = mime_type;
}
long long ResourceResponse::ExpectedContentLength() const {
return expected_content_length_;
}
void ResourceResponse::SetExpectedContentLength(
long long expected_content_length) {
is_null_ = false;
// FIXME: Content length is determined by HTTP Content-Length header. We
// should update the header, so that it doesn't disagree with
// m_expectedContentLength.
expected_content_length_ = expected_content_length;
}
const AtomicString& ResourceResponse::TextEncodingName() const {
return text_encoding_name_;
}
void ResourceResponse::SetTextEncodingName(const AtomicString& encoding_name) {
is_null_ = false;
// FIXME: Text encoding is determined by HTTP Content-Type header. We should
// update the header, so that it doesn't disagree with m_textEncodingName.
text_encoding_name_ = encoding_name;
}
int ResourceResponse::HttpStatusCode() const {
return http_status_code_;
}
void ResourceResponse::SetHTTPStatusCode(int status_code) {
http_status_code_ = status_code;
}
const AtomicString& ResourceResponse::HttpStatusText() const {
return http_status_text_;
}
void ResourceResponse::SetHTTPStatusText(const AtomicString& status_text) {
http_status_text_ = status_text;
}
const AtomicString& ResourceResponse::HttpHeaderField(
const AtomicString& name) const {
return http_header_fields_.Get(name);
}
void ResourceResponse::UpdateHeaderParsedState(const AtomicString& name) {
static const char kAgeHeader[] = "age";
static const char kDateHeader[] = "date";
static const char kExpiresHeader[] = "expires";
static const char kLastModifiedHeader[] = "last-modified";
if (DeprecatedEqualIgnoringCase(name, kAgeHeader))
have_parsed_age_header_ = false;
else if (DeprecatedEqualIgnoringCase(name, kCacheControlHeader) ||
DeprecatedEqualIgnoringCase(name, kPragmaHeader))
cache_control_header_ = CacheControlHeader();
else if (DeprecatedEqualIgnoringCase(name, kDateHeader))
have_parsed_date_header_ = false;
else if (DeprecatedEqualIgnoringCase(name, kExpiresHeader))
have_parsed_expires_header_ = false;
else if (DeprecatedEqualIgnoringCase(name, kLastModifiedHeader))
have_parsed_last_modified_header_ = false;
}
void ResourceResponse::SetSecurityDetails(
const String& protocol,
const String& key_exchange,
const String& key_exchange_group,
const String& cipher,
const String& mac,
const String& subject_name,
const Vector<String>& san_list,
const String& issuer,
time_t valid_from,
time_t valid_to,
const Vector<AtomicString>& certificate,
const SignedCertificateTimestampList& sct_list) {
security_details_.protocol = protocol;
security_details_.key_exchange = key_exchange;
security_details_.key_exchange_group = key_exchange_group;
security_details_.cipher = cipher;
security_details_.mac = mac;
security_details_.subject_name = subject_name;
security_details_.san_list = san_list;
security_details_.issuer = issuer;
security_details_.valid_from = valid_from;
security_details_.valid_to = valid_to;
security_details_.certificate = certificate;
security_details_.sct_list = sct_list;
}
void ResourceResponse::SetHTTPHeaderField(const AtomicString& name,
const AtomicString& value) {
UpdateHeaderParsedState(name);
http_header_fields_.Set(name, value);
}
void ResourceResponse::AddHTTPHeaderField(const AtomicString& name,
const AtomicString& value) {
UpdateHeaderParsedState(name);
HTTPHeaderMap::AddResult result = http_header_fields_.Add(name, value);
if (!result.is_new_entry)
result.stored_value->value = result.stored_value->value + ", " + value;
}
void ResourceResponse::ClearHTTPHeaderField(const AtomicString& name) {
http_header_fields_.Remove(name);
}
const HTTPHeaderMap& ResourceResponse::HttpHeaderFields() const {
return http_header_fields_;
}
bool ResourceResponse::CacheControlContainsNoCache() const {
if (!cache_control_header_.parsed) {
cache_control_header_ = ParseCacheControlDirectives(
http_header_fields_.Get(kCacheControlHeader),
http_header_fields_.Get(kPragmaHeader));
}
return cache_control_header_.contains_no_cache;
}
bool ResourceResponse::CacheControlContainsNoStore() const {
if (!cache_control_header_.parsed) {
cache_control_header_ = ParseCacheControlDirectives(
http_header_fields_.Get(kCacheControlHeader),
http_header_fields_.Get(kPragmaHeader));
}
return cache_control_header_.contains_no_store;
}
bool ResourceResponse::CacheControlContainsMustRevalidate() const {
if (!cache_control_header_.parsed) {
cache_control_header_ = ParseCacheControlDirectives(
http_header_fields_.Get(kCacheControlHeader),
http_header_fields_.Get(kPragmaHeader));
}
return cache_control_header_.contains_must_revalidate;
}
bool ResourceResponse::HasCacheValidatorFields() const {
static const char kLastModifiedHeader[] = "last-modified";
static const char kETagHeader[] = "etag";
return !http_header_fields_.Get(kLastModifiedHeader).IsEmpty() ||
!http_header_fields_.Get(kETagHeader).IsEmpty();
}
double ResourceResponse::CacheControlMaxAge() const {
if (!cache_control_header_.parsed) {
cache_control_header_ = ParseCacheControlDirectives(
http_header_fields_.Get(kCacheControlHeader),
http_header_fields_.Get(kPragmaHeader));
}
return cache_control_header_.max_age;
}
static double ParseDateValueInHeader(const HTTPHeaderMap& headers,
const AtomicString& header_name) {
const AtomicString& header_value = headers.Get(header_name);
if (header_value.IsEmpty())
return std::numeric_limits<double>::quiet_NaN();
// This handles all date formats required by RFC2616:
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
// Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
double date_in_milliseconds = ParseDate(header_value);
if (!std::isfinite(date_in_milliseconds))
return std::numeric_limits<double>::quiet_NaN();
return date_in_milliseconds / 1000;
}
double ResourceResponse::Date() const {
if (!have_parsed_date_header_) {
static const char kHeaderName[] = "date";
date_ = ParseDateValueInHeader(http_header_fields_, kHeaderName);
have_parsed_date_header_ = true;
}
return date_;
}
double ResourceResponse::Age() const {
if (!have_parsed_age_header_) {
static const char kHeaderName[] = "age";
const AtomicString& header_value = http_header_fields_.Get(kHeaderName);
bool ok;
age_ = header_value.ToDouble(&ok);
if (!ok)
age_ = std::numeric_limits<double>::quiet_NaN();
have_parsed_age_header_ = true;
}
return age_;
}
double ResourceResponse::Expires() const {
if (!have_parsed_expires_header_) {
static const char kHeaderName[] = "expires";
expires_ = ParseDateValueInHeader(http_header_fields_, kHeaderName);
have_parsed_expires_header_ = true;
}
return expires_;
}
double ResourceResponse::LastModified() const {
if (!have_parsed_last_modified_header_) {
static const char kHeaderName[] = "last-modified";
last_modified_ = ParseDateValueInHeader(http_header_fields_, kHeaderName);
have_parsed_last_modified_header_ = true;
}
return last_modified_;
}
bool ResourceResponse::IsAttachment() const {
static const char kAttachmentString[] = "attachment";
String value = http_header_fields_.Get(HTTPNames::Content_Disposition);
size_t loc = value.find(';');
if (loc != kNotFound)
value = value.Left(loc);
value = value.StripWhiteSpace();
return DeprecatedEqualIgnoringCase(value, kAttachmentString);
}
AtomicString ResourceResponse::HttpContentType() const {
return ExtractMIMETypeFromMediaType(
HttpHeaderField(HTTPNames::Content_Type).DeprecatedLower());
}
bool ResourceResponse::WasCached() const {
return was_cached_;
}
void ResourceResponse::SetWasCached(bool value) {
was_cached_ = value;
}
bool ResourceResponse::ConnectionReused() const {
return connection_reused_;
}
void ResourceResponse::SetConnectionReused(bool connection_reused) {
connection_reused_ = connection_reused;
}
unsigned ResourceResponse::ConnectionID() const {
return connection_id_;
}
void ResourceResponse::SetConnectionID(unsigned connection_id) {
connection_id_ = connection_id;
}
ResourceLoadTiming* ResourceResponse::GetResourceLoadTiming() const {
return resource_load_timing_.get();
}
void ResourceResponse::SetResourceLoadTiming(
scoped_refptr<ResourceLoadTiming> resource_load_timing) {
resource_load_timing_ = std::move(resource_load_timing);
}
scoped_refptr<ResourceLoadInfo> ResourceResponse::GetResourceLoadInfo() const {
return resource_load_info_.get();
}
void ResourceResponse::SetResourceLoadInfo(
scoped_refptr<ResourceLoadInfo> load_info) {
resource_load_info_ = std::move(load_info);
}
void ResourceResponse::SetCTPolicyCompliance(CTPolicyCompliance compliance) {
ct_policy_compliance_ = compliance;
}
bool ResourceResponse::IsOpaqueResponseFromServiceWorker() const {
switch (response_type_via_service_worker_) {
case network::mojom::FetchResponseType::kBasic:
case network::mojom::FetchResponseType::kCORS:
case network::mojom::FetchResponseType::kDefault:
case network::mojom::FetchResponseType::kError:
return false;
case network::mojom::FetchResponseType::kOpaque:
case network::mojom::FetchResponseType::kOpaqueRedirect:
return true;
}
NOTREACHED();
return false;
}
KURL ResourceResponse::OriginalURLViaServiceWorker() const {
if (url_list_via_service_worker_.IsEmpty())
return KURL();
return url_list_via_service_worker_.back();
}
AtomicString ResourceResponse::ConnectionInfoString() const {
std::string connection_info_string =
net::HttpResponseInfo::ConnectionInfoToString(connection_info_);
return AtomicString(
reinterpret_cast<const LChar*>(connection_info_string.data()),
connection_info_string.length());
}
void ResourceResponse::SetEncodedDataLength(long long value) {
encoded_data_length_ = value;
}
void ResourceResponse::SetEncodedBodyLength(long long value) {
encoded_body_length_ = value;
}
void ResourceResponse::SetDecodedBodyLength(long long value) {
decoded_body_length_ = value;
}
void ResourceResponse::SetDownloadedFilePath(
const String& downloaded_file_path) {
downloaded_file_path_ = downloaded_file_path;
if (downloaded_file_path_.IsEmpty()) {
downloaded_file_handle_ = nullptr;
return;
}
// TODO(dmurph): Investigate whether we need the mimeType on this blob.
std::unique_ptr<BlobData> blob_data =
BlobData::CreateForFileWithUnknownSize(downloaded_file_path_);
blob_data->DetachFromCurrentThread();
downloaded_file_handle_ = BlobDataHandle::Create(std::move(blob_data), -1);
}
void ResourceResponse::AppendRedirectResponse(
const ResourceResponse& response) {
redirect_responses_.push_back(response);
}
bool ResourceResponse::Compare(const ResourceResponse& a,
const ResourceResponse& b) {
if (a.IsNull() != b.IsNull())
return false;
if (a.Url() != b.Url())
return false;
if (a.MimeType() != b.MimeType())
return false;
if (a.ExpectedContentLength() != b.ExpectedContentLength())
return false;
if (a.TextEncodingName() != b.TextEncodingName())
return false;
if (a.HttpStatusCode() != b.HttpStatusCode())
return false;
if (a.HttpStatusText() != b.HttpStatusText())
return false;
if (a.HttpHeaderFields() != b.HttpHeaderFields())
return false;
if (a.GetResourceLoadTiming() && b.GetResourceLoadTiming() &&
*a.GetResourceLoadTiming() == *b.GetResourceLoadTiming())
return true;
if (a.GetResourceLoadTiming() != b.GetResourceLoadTiming())
return false;
if (a.EncodedBodyLength() != b.EncodedBodyLength())
return false;
if (a.DecodedBodyLength() != b.DecodedBodyLength())
return false;
return true;
}
STATIC_ASSERT_ENUM(WebURLResponse::kHTTPVersionUnknown,
ResourceResponse::kHTTPVersionUnknown);
STATIC_ASSERT_ENUM(WebURLResponse::kHTTPVersion_0_9,
ResourceResponse::kHTTPVersion_0_9);
STATIC_ASSERT_ENUM(WebURLResponse::kHTTPVersion_1_0,
ResourceResponse::kHTTPVersion_1_0);
STATIC_ASSERT_ENUM(WebURLResponse::kHTTPVersion_1_1,
ResourceResponse::kHTTPVersion_1_1);
STATIC_ASSERT_ENUM(WebURLResponse::kHTTPVersion_2_0,
ResourceResponse::kHTTPVersion_2_0);
} // namespace blink
| 38.051118 | 79 | 0.767045 | zipated |
6e637694e3e4aff5c1efb30f44f91330b7b5d80e | 1,287 | hpp | C++ | bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | null | null | null | bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 10 | 2018-02-06T14:46:36.000Z | 2018-03-20T13:37:20.000Z | bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 1 | 2021-11-26T10:59:09.000Z | 2021-11-26T10:59:09.000Z | #pragma once
#include <bunsan/error.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>
namespace bunsan::interprocess {
struct file_guard_error : virtual bunsan::error {
using lock_path =
boost::error_info<struct tag_lock_path, boost::filesystem::path>;
};
struct file_guard_create_error : virtual file_guard_error {};
struct file_guard_locked_error : virtual file_guard_create_error {};
struct file_guard_remove_error : virtual file_guard_error {};
class file_guard {
public:
/// Unlocked guard.
file_guard() = default;
/*!
* \brief Create file at specified path.
*
* \throw file_guard_locked_error if file exists (type of file does not
*matter)
*/
explicit file_guard(const boost::filesystem::path &path);
// move semantics
file_guard(file_guard &&) noexcept;
file_guard &operator=(file_guard &&) noexcept;
// no copying
file_guard(const file_guard &) = delete;
file_guard &operator=(const file_guard &) = delete;
explicit operator bool() const noexcept;
void swap(file_guard &guard) noexcept;
void remove();
~file_guard();
private:
boost::optional<boost::filesystem::path> m_path;
};
inline void swap(file_guard &a, file_guard &b) noexcept { a.swap(b); }
} // namespace bunsan::interprocess
| 23.4 | 73 | 0.724165 | bacsorg |
6e66f1f9b926dc031a644f8d3c082542629decc0 | 792 | cc | C++ | C++/Bit Magic/closest_int_same_weight.cc | aditya30394/Interview-Questions | 2e114e30a17b4e99ecf7d8416781374a4dc475e2 | [
"MIT"
] | 2 | 2019-05-15T04:37:13.000Z | 2022-01-28T08:01:51.000Z | C++/Bit Magic/closest_int_same_weight.cc | aditya30394/Interview-Questions | 2e114e30a17b4e99ecf7d8416781374a4dc475e2 | [
"MIT"
] | null | null | null | C++/Bit Magic/closest_int_same_weight.cc | aditya30394/Interview-Questions | 2e114e30a17b4e99ecf7d8416781374a4dc475e2 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include "../../test_framework/generic_test.h"
using std::invalid_argument;
unsigned long long ClosestIntSameBitCount(unsigned long long x) {
const int bitSize = 64;
for(int i=0;i<bitSize-1;++i)
{
if(( (x>>i)&1) != ((x>>(i+1))&1))
{
x = x ^ ((1UL<<i) | (1UL << (i+1)));
return x;
}
}
// Throw error if all bits of x are 0 or 1.
throw invalid_argument("All bits are 0 or 1");
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"x"};
return GenericTestMain(args, "closest_int_same_weight.cc",
"closest_int_same_weight.tsv", &ClosestIntSameBitCount,
DefaultComparator{}, param_names);
}
| 28.285714 | 80 | 0.590909 | aditya30394 |
6e67824c151ab4c88abb82b79f8cae650ddf9a22 | 4,406 | cpp | C++ | src/compiler/lowering/DistributeComputationsPass.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 10 | 2022-03-31T21:49:35.000Z | 2022-03-31T23:37:06.000Z | src/compiler/lowering/DistributeComputationsPass.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | 3 | 2022-03-31T22:10:10.000Z | 2022-03-31T22:46:30.000Z | src/compiler/lowering/DistributeComputationsPass.cpp | daphne-eu/daphne | 64d4040132cf4059efaf184c4e363dbb921c87d6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 The DAPHNE Consortium
*
* 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 "ir/daphneir/Daphne.h"
#include "ir/daphneir/Passes.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include <mlir/Dialect/LLVMIR/LLVMDialect.h>
#include "mlir/Transforms/DialectConversion.h"
#include <memory>
#include <utility>
using namespace mlir;
namespace
{
struct Distribute : public OpInterfaceConversionPattern<daphne::Distributable>
{
using OpInterfaceConversionPattern::OpInterfaceConversionPattern;
LogicalResult
matchAndRewrite(daphne::Distributable op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override
{
std::vector<Value> distributedInputs;
for (auto zipIt : llvm::zip(operands, op.getOperandDistrPrimitives())) {
Value operand = std::get<0>(zipIt);
bool isBroadcast = std::get<1>(zipIt);
if (operand.getType().isa<daphne::HandleType>())
// The operand is already distributed/broadcasted, we can
// directly use it.
// TODO Check if it is distributed the way we need it here
// (distributed/broadcasted), but so far, this is not tracked
// at compile-time.
distributedInputs.push_back(operand);
else if (auto co = dyn_cast_or_null<daphne::DistributedCollectOp>(operand.getDefiningOp()))
// The operand has just been collected from a distributed data
// object, so we should reuse the original distributed data
// object.
distributedInputs.push_back(co.arg());
else {
// The operands need to be distributed/broadcasted first.
Type t = daphne::HandleType::get(getContext(), operand.getType());
if(isBroadcast)
distributedInputs.push_back(rewriter.create<daphne::BroadcastOp>(op->getLoc(), t, operand));
else
distributedInputs.push_back(rewriter.create<daphne::DistributeOp>(op->getLoc(), t, operand));
}
}
auto results = op.createEquivalentDistributedDAG(rewriter, distributedInputs);
rewriter.replaceOp(op, results);
return success();
}
};
struct DistributeComputationsPass
: public PassWrapper<DistributeComputationsPass, OperationPass<ModuleOp>>
{
void runOnOperation() final;
};
}
bool onlyMatrixOperands(Operation * op) {
return llvm::all_of(op->getOperandTypes(), [](Type t) {
return t.isa<daphne::MatrixType>();
});
}
void DistributeComputationsPass::runOnOperation()
{
auto module = getOperation();
OwningRewritePatternList patterns(&getContext());
// convert other operations
ConversionTarget target(getContext());
target.addLegalDialect<StandardOpsDialect, LLVM::LLVMDialect, scf::SCFDialect>();
target.addLegalOp<ModuleOp, FuncOp>();
target.addDynamicallyLegalDialect<daphne::DaphneDialect>([](Operation *op)
{
// An operation is legal (does not need to be replaced), if ...
return
// ... it is not distributable
!llvm::isa<daphne::Distributable>(op) ||
// ... it is inside some distributed computation already
op->getParentOfType<daphne::DistributedComputeOp>() ||
// ... not all of its operands are matrices
// TODO Support distributing frames and scalars.
!onlyMatrixOperands(op);
});
patterns.insert<Distribute>(&getContext());
if (failed(applyFullConversion(module, target, std::move(patterns))))
signalPassFailure();
}
std::unique_ptr<Pass> daphne::createDistributeComputationsPass()
{
return std::make_unique<DistributeComputationsPass>();
}
| 37.338983 | 113 | 0.655697 | daphne-eu |
6e6a804df0c9963523df7aef487638803473235b | 7,687 | cpp | C++ | Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp | jswigart/UE4-EditorScriptingToolsPlugin | 5fa4012bf10c1fc918d2c6ddeab0d1c6bbac85ca | [
"MIT"
] | 77 | 2020-12-04T21:10:16.000Z | 2021-09-20T03:47:47.000Z | Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp | ProjectBorealis/UE4-EditorScriptingToolsPlugin | 251b9b4f64bb465e74514fac2cec82a824ea2200 | [
"MIT"
] | 11 | 2021-03-03T19:00:05.000Z | 2021-06-19T18:11:42.000Z | Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp | ProjectBorealis/UE4-EditorScriptingToolsPlugin | 251b9b4f64bb465e74514fac2cec82a824ea2200 | [
"MIT"
] | 12 | 2020-12-09T04:47:41.000Z | 2021-09-11T12:19:34.000Z | //==========================================================================//
// Copyright Elhoussine Mehnik (ue4resources@gmail.com). All Rights Reserved.
//================== http://unrealengineresources.com/ =====================//
#include "EditorScriptingAssetTypeActions_Base.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Misc/PackageName.h"
#include "Misc/MessageDialog.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "BlueprintEditorModule.h"
#include "IContentBrowserSingleton.h"
#include "ContentBrowserModule.h"
#include "Widgets/Layout/SBorder.h"
#include "Widgets/Images/SThrobber.h"
#include "EditorScriptingToolsModule.h"
#include "EditorScriptingToolsSubsystem.h"
#include "BluEdMode.h"
#include "EditorModeToolInstance.h"
#include "EditorTypesWrapperTypes.h"
#include "EditorScriptingToolsStyle.h"
#include "EditorFontGlyphs.h"
#include "IEditorScriptingUtilityAssetInterface.h"
#include "EditorScriptingUtilityBlueprint.h"
#include "Widgets/Images/SImage.h"
#define LOCTEXT_NAMESPACE "AssetTypeActions"
uint32 FEditorScriptingAssetTypeActions_Base::GetCategories()
{
if (IEditorScriptingToolsModule* EditorScriptingToolsModulePtr = IEditorScriptingToolsModule::GetPtr())
{
return EditorScriptingToolsModulePtr->GetEditorScriptingAssetCategory();
}
return EAssetTypeCategories::Blueprint;
}
bool FEditorScriptingAssetTypeActions_Base::CanLocalize() const
{
return false;
}
bool FEditorScriptingAssetTypeActions_Base::HasActions(const TArray<UObject*>& InObjects) const
{
return InObjects.Num() > 0;
}
TSharedPtr<class SWidget> FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlay(const FAssetData& AssetData) const
{
TWeakObjectPtr<UObject> ObjectWeakPtr = AssetData.GetAsset();
return SNew(SImage)
.Visibility(this, &FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlayVisibility, ObjectWeakPtr)
.ColorAndOpacity(FLinearColor(1.0f, 1.0f, 1.0f, .1f));
}
void FEditorScriptingAssetTypeActions_Base::GetActions(const TArray<UObject*>& InObjects, FMenuBuilder& MenuBuilder)
{
if (InObjects.Num() == 1)
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
TWeakObjectPtr<UObject> ObjectWeakPtr = InObjects[0];
IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get());
check(ScriptingUtilityAsset != nullptr);
MenuBuilder.AddMenuEntry(
ScriptingToolsModule->GetRegisterScriptingUtilityText(ScriptingUtilityAsset),
ScriptingToolsModule->GetRegisterScriptingUtilityToolTipText(ScriptingUtilityAsset),
FSlateIcon(FEditorScriptingToolsStyle::Get()->GetStyleSetName(), TEXT("EditorScriptingUtility.Register")),
FUIAction(
FExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::RegisterUtility, ObjectWeakPtr),
FCanExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanRegisterUtility, ObjectWeakPtr),
FIsActionChecked(),
FIsActionButtonVisible::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanRegisterUtility, ObjectWeakPtr)
)
);
MenuBuilder.AddMenuEntry(
ScriptingToolsModule->GetUnregisterScriptingUtilityText(ScriptingUtilityAsset),
ScriptingToolsModule->GetUnregisterScriptingUtilityToolTipText(ScriptingUtilityAsset),
FSlateIcon(FEditorScriptingToolsStyle::Get()->GetStyleSetName(), TEXT("EditorScriptingUtility.Unregister")),
FUIAction(
FExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::UnregisterUtility, ObjectWeakPtr),
FCanExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility, ObjectWeakPtr),
FIsActionChecked(),
FIsActionButtonVisible::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility, ObjectWeakPtr)
)
);
GetAdditionalActions(ObjectWeakPtr, MenuBuilder);
}
else
{
MenuBuilder.AddWidget
(
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
.AutoWidth()
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor(0.65f, 0.4f, 0.15f, 1.0f))
.TextStyle(FEditorStyle::Get(), "ContentBrowser.TopBar.Font")
.Font(FEditorStyle::Get().GetFontStyle("FontAwesome.11"))
.Text(FEditorFontGlyphs::Exclamation_Triangle)
]
+SHorizontalBox::Slot()
.Padding(8.f, 0.f)
.AutoWidth()
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor(0.65f, 0.4f, 0.15f, 1.0f))
.Text(LOCTEXT("WarningMsg", "Select a single asset to see utility actions"))
],
FText::GetEmpty()
);
}
}
void FEditorScriptingAssetTypeActions_Base::OpenAssetEditor(const TArray<UObject*>& InObjects, TSharedPtr<class IToolkitHost> EditWithinLevelEditor)
{
EToolkitMode::Type Mode = EditWithinLevelEditor.IsValid() ? EToolkitMode::WorldCentric : EToolkitMode::Standalone;
for (auto ObjIt = InObjects.CreateConstIterator(); ObjIt; ++ObjIt)
{
if (UEditorScriptingUtilityBlueprint* ScriptingUtilityBlueprint = Cast<UEditorScriptingUtilityBlueprint>(*ObjIt))
{
FBlueprintEditorModule& BlueprintEditorModule = FModuleManager::LoadModuleChecked<FBlueprintEditorModule>("Kismet");
TSharedRef<IBlueprintEditor> NewBlueprintEditor = BlueprintEditorModule.CreateBlueprintEditor(Mode, EditWithinLevelEditor, ScriptingUtilityBlueprint, false);
}
}
}
void FEditorScriptingAssetTypeActions_Base::RegisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
ScriptingToolsModule->RegisterEditorScriptingUtility(ScriptingUtilityAsset);
}
}
bool FEditorScriptingAssetTypeActions_Base::CanRegisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
return ScriptingToolsModule->CanRegisterEditorScriptingUtility(ScriptingUtilityAsset);
}
return false;
}
void FEditorScriptingAssetTypeActions_Base::UnregisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
ScriptingToolsModule->UnregisterEditorScriptingUtility(ScriptingUtilityAsset);
}
}
bool FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
return ScriptingToolsModule->IsEditorScriptingUtilityRegistered(ScriptingUtilityAsset);
}
return false;
}
EVisibility FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlayVisibility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (UEditorScriptingToolsSubsystem::GetSubsystem()->bEnableThumbnailOverlayOnRegisteredUtilities)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
if (ScriptingToolsModule->IsEditorScriptingUtilityRegistered(ScriptingUtilityAsset))
{
return EVisibility::Visible;
}
}
}
return EVisibility::Collapsed;
}
#undef LOCTEXT_NAMESPACE
| 38.435 | 160 | 0.802133 | jswigart |
6e6af7e66d17cac6043592b01643c412a5d6ba4d | 6,374 | cpp | C++ | lib/Dialect/TPU/Analysis/GenFakeWeightNpz.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | 3 | 2022-03-14T11:47:20.000Z | 2022-03-16T01:45:37.000Z | lib/Dialect/TPU/Analysis/GenFakeWeightNpz.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | null | null | null | lib/Dialect/TPU/Analysis/GenFakeWeightNpz.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | null | null | null | //===- TpuOpPrint.cpp - Implementation of TPU Op Print ---------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
//
// This file implements the TPU dialect OP pass.
//
//===----------------------------------------------------------------------===//
#include <cmath>
#include <random>
#include <sstream>
#include "tpuc/Dialect/TPU/TPUDialect.h"
#include "tpuc/TPUTensorSupport.h"
#include "tpuc/TPUOperationSupport.h"
#include "tpuc/Passes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/FileUtilities.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ToolOutputFile.h"
using namespace mlir;
namespace {
static llvm::cl::opt<std::string> clPseudoCaliTableFilename(
"pseudo-calibration-table",
llvm::cl::desc("save pseudo calibration table file"),
llvm::cl::init("-"));
class GenPseudoWeightNpzPass : public mlir::PassWrapper<GenPseudoWeightNpzPass, FunctionPass> {
public:
explicit GenPseudoWeightNpzPass() {}
void runOnFunction() override {
auto fn = getFunction();
auto *context = &getContext();
Builder builder(context);
cnpy::npz_t npz;
cnpy::npz_t input_npz;
std::random_device rd{};
std::mt19937 gen{rd()};
StringRef npzFileName;
std::unique_ptr<llvm::ToolOutputFile> caliTableFile = nullptr;
if (clPseudoCaliTableFilename != "-") {
std::string errorMessage;
caliTableFile = openOutputFile(clPseudoCaliTableFilename, &errorMessage);
if (!caliTableFile) {
llvm::errs() << errorMessage << "\n";
exit(1);
}
}
fn.walk([&](Operation *op) {
if (auto tpuOp = llvm::dyn_cast<tpu::TpuOpCommonInterface>(op)) {
if (caliTableFile) {
auto name = tpuOp.getOpName();
std::normal_distribution<float> d{0.01, 12.0};
float rand = d(gen);
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << std::fabs(rand);
auto &os = caliTableFile->os();
os << name << " " << ss.str() << "\n";
}
}
if (auto castOp = llvm::dyn_cast<tpu::WeightFileOp>(op)) {
npzFileName = castOp.filename();
} else if (auto castOp = llvm::dyn_cast<tpu::InputOp>(op)) {
std::string op_name = castOp.name().str();
auto resultShape = getTensorShape(castOp.getResult());
std::vector<size_t> shape;
for (int i = 0; i < (int)resultShape.size(); ++i) {
shape.push_back(resultShape[i]);
}
auto count = std::accumulate(resultShape.begin(), resultShape.end(), 1,
std::multiplies<int>());
std::vector<float> data(count);
std::normal_distribution<float> d{0, 0.88};
for (int i = 0; i < (int)count; i++) {
float rand = d(gen);
rand = rand < -2 ? -2 : rand;
rand = rand > 2 ? 2 : rand;
data[i] = rand;
}
cnpy::npz_add_array<float>(input_npz, op_name, (float *)data.data(), shape);
} else if (auto castOp = llvm::dyn_cast<tpu::LoadWeightOp>(op)) {
std::string op_name = castOp.name().str();
llvm::errs() << op_name << "\n";
auto resultShape = getTensorShape(castOp.getResult());
std::vector<size_t> shape;
for (int i = 0; i < (int)resultShape.size(); ++i) {
shape.push_back(resultShape[i]);
}
auto count = std::accumulate(resultShape.begin(), resultShape.end(), 1,
std::multiplies<int>());
auto elementType =
op->getResult(0).getType().template cast<TensorType>().getElementType();
if (elementType.isF32()) {
std::vector<float> data(count);
std::normal_distribution<float> d{0, 0.2};
for (int i = 0; i < (int)count; i++) {
float rand = d(gen);
rand = rand < -1 ? -1 : rand;
rand = rand > 1 ? 1 : rand;
data[i] = rand;
}
if (count == 1) {
data[0] = 1;
}
cnpy::npz_add_array<float>(npz, op_name, (float *)data.data(), shape);
} else if (elementType.isBF16()) {
std::vector<uint16_t> data(count);
std::normal_distribution<float> d{0, 0.2};
for (int i = 0; i < (int)count; i++) {
float rand = d(gen);
rand = rand < -1 ? -1 : rand;
rand = rand > 1 ? 1 : rand;
uint32_t* u32_val = reinterpret_cast<uint32_t*>(&rand);
uint32_t input = *u32_val;
uint32_t lsb = (input >> 16) & 1;
uint32_t rounding_bias = 0x7fff + lsb;
input += rounding_bias;
uint16_t bf_val = (uint16_t)(input >> 16);
data[i] = bf_val;
}
cnpy::npz_add_array<uint16_t>(npz, op_name, (uint16_t *)data.data(), shape);
} else if (elementType.isInteger(8)) {
std::vector<float> data(count);
std::normal_distribution<float> d{50, 50};
for (int i = 0; i < (int)count; i++) {
float rand = std::round(d(gen));
rand = rand < 0 ? 0 : rand;
rand = rand > 127 ? 127 : rand;
data[i] = (float)rand;
}
cnpy::npz_add_array<float>(npz, op_name, (float *)data.data(), shape);
} else {
llvm_unreachable("unsupported data type");
}
}
});
cnpy::npz_save_all(npzFileName.str(), npz);
cnpy::npz_save_all("input.npz", input_npz);
if (caliTableFile) {
caliTableFile->keep();
}
}
};
} // namespace
std::unique_ptr<mlir::Pass> mlir::createGenPseudoWeightNpzPass() {
return std::make_unique<GenPseudoWeightNpzPass>();
}
| 37.05814 | 95 | 0.566677 | sophgo |
6e6b8012cee881f82a10cc8c3fbec6bc0897f308 | 22,364 | cpp | C++ | phe/seal/SEAL/decryptor.cpp | BNext-IQT/GEMstone | 3fba78440bf1cbedc21dd7d96566696227f0b6a2 | [
"Apache-2.0"
] | 6 | 2017-08-24T17:49:18.000Z | 2021-10-16T06:17:46.000Z | phe/seal/SEAL/decryptor.cpp | BNext-IQT/GEMstone | 3fba78440bf1cbedc21dd7d96566696227f0b6a2 | [
"Apache-2.0"
] | 6 | 2017-10-31T11:28:18.000Z | 2017-10-31T11:28:43.000Z | phe/seal/SEAL/decryptor.cpp | BNext-IQT/GEMstone | 3fba78440bf1cbedc21dd7d96566696227f0b6a2 | [
"Apache-2.0"
] | 3 | 2017-12-20T20:00:35.000Z | 2019-06-14T10:36:37.000Z | #include <algorithm>
#include <stdexcept>
#include "decryptor.h"
#include "util/common.h"
#include "util/uintcore.h"
#include "util/uintarith.h"
#include "util/polycore.h"
#include "util/polyarith.h"
#include "util/polyarithmod.h"
#include "util/polyfftmultmod.h"
#include "bigpoly.h"
#include "util/uintarithmod.h"
#include "util/polyextras.h"
using namespace std;
using namespace seal::util;
namespace seal
{
namespace
{
bool are_poly_coefficients_less_than(const BigPoly &poly, const BigUInt &max_coeff)
{
return util::are_poly_coefficients_less_than(poly.pointer(), poly.coeff_count(), poly.coeff_uint64_count(), max_coeff.pointer(), max_coeff.uint64_count());
}
}
Decryptor::Decryptor(const EncryptionParameters &parms, const BigPoly &secret_key, const MemoryPoolHandle &pool) :
pool_(pool), poly_modulus_(parms.poly_modulus()), coeff_modulus_(parms.coeff_modulus()), plain_modulus_(parms.plain_modulus()),
secret_key_(secret_key), orig_plain_modulus_bit_count_(parms.plain_modulus().significant_bit_count()), ntt_tables_(pool_),
qualifiers_(parms.get_qualifiers())
{
// Verify parameters
if (!qualifiers_.parameters_set)
{
throw invalid_argument("encryption parameters are not set correctly");
}
// Resize encryption parameters to consistent size.
int coeff_count = poly_modulus_.significant_coeff_count();
int coeff_bit_count = coeff_modulus_.significant_bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
if (poly_modulus_.coeff_count() != coeff_count || poly_modulus_.coeff_bit_count() != coeff_bit_count)
{
poly_modulus_.resize(coeff_count, coeff_bit_count);
}
if (coeff_modulus_.bit_count() != coeff_bit_count)
{
coeff_modulus_.resize(coeff_bit_count);
}
if (plain_modulus_.bit_count() != coeff_bit_count)
{
plain_modulus_.resize(coeff_bit_count);
}
// Secret key has to have right size.
if (secret_key_.coeff_count() != coeff_count || secret_key_.coeff_bit_count() != coeff_bit_count ||
secret_key_.significant_coeff_count() == coeff_count || !are_poly_coefficients_less_than(secret_key_, coeff_modulus_))
{
throw invalid_argument("secret_key is not valid for encryption parameters");
}
// Set the secret_key_array to have size 1 (first power of secret)
secret_key_array_.resize(1, coeff_count, coeff_bit_count);
set_poly_poly(secret_key_.pointer(), coeff_count, coeff_uint64_count, secret_key_array_.pointer(0));
// Calculate coeff_modulus / plain_modulus.
coeff_div_plain_modulus_.resize(coeff_bit_count);
Pointer temp(allocate_uint(coeff_uint64_count, pool_));
divide_uint_uint(coeff_modulus_.pointer(), plain_modulus_.pointer(), coeff_uint64_count, coeff_div_plain_modulus_.pointer(), temp.get(), pool_);
// Calculate upper_half_increment.
upper_half_increment_.resize(coeff_bit_count);
set_uint_uint(temp.get(), coeff_uint64_count, upper_half_increment_.pointer());
// Calculate coeff_modulus / plain_modulus / 2.
coeff_div_plain_modulus_div_two_.resize(coeff_bit_count);
right_shift_uint(coeff_div_plain_modulus_.pointer(), 1, coeff_uint64_count, coeff_div_plain_modulus_div_two_.pointer());
// Calculate coeff_modulus / 2.
upper_half_threshold_.resize(coeff_bit_count);
half_round_up_uint(coeff_modulus_.pointer(), coeff_uint64_count, upper_half_threshold_.pointer());
// Initialize moduli.
polymod_ = PolyModulus(poly_modulus_.pointer(), coeff_count, coeff_uint64_count);
mod_ = Modulus(coeff_modulus_.pointer(), coeff_uint64_count, pool_);
if (qualifiers_.enable_ntt)
{
// Copy over NTT tables (switching to local pool)
ntt_tables_ = parms.ntt_tables_;
}
}
Decryptor::Decryptor(const Decryptor ©) : pool_(copy.pool_), poly_modulus_(copy.poly_modulus_), coeff_modulus_(copy.coeff_modulus_),
plain_modulus_(copy.plain_modulus_), upper_half_threshold_(copy.upper_half_threshold_), upper_half_increment_(copy.upper_half_increment_),
coeff_div_plain_modulus_(copy.coeff_div_plain_modulus_), coeff_div_plain_modulus_div_two_(copy.coeff_div_plain_modulus_div_two_),
secret_key_(copy.secret_key_), orig_plain_modulus_bit_count_(copy.orig_plain_modulus_bit_count_), ntt_tables_(copy.ntt_tables_),
secret_key_array_(copy.secret_key_array_), qualifiers_(copy.qualifiers_)
{
int coeff_count = poly_modulus_.significant_coeff_count();
int coeff_bit_count = coeff_modulus_.significant_bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
// Initialize moduli.
polymod_ = PolyModulus(poly_modulus_.pointer(), coeff_count, coeff_uint64_count);
mod_ = Modulus(coeff_modulus_.pointer(), coeff_uint64_count, pool_);
}
void Decryptor::decrypt(const BigPolyArray &encrypted, BigPoly &destination)
{
// Extract encryption parameters.
// Remark: poly_modulus_ has enlarged coefficient size set in constructor
int coeff_count = poly_modulus_.coeff_count();
int coeff_bit_count = poly_modulus_.coeff_bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
int array_poly_uint64_count = coeff_count * coeff_uint64_count;
// Verify parameters.
if (encrypted.size() < 2 || encrypted.coeff_count() != coeff_count || encrypted.coeff_bit_count() != coeff_bit_count)
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
#ifdef _DEBUG
for (int i = 0; i < encrypted.size(); ++i)
{
if (encrypted[i].significant_coeff_count() == coeff_count || !are_poly_coefficients_less_than(encrypted[i], coeff_modulus_))
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
}
#endif
// Make sure destination is of right size to perform all computations. At the end we will
// resize the coefficients to be the size of plain_modulus.
// Remark: plain_modulus_ has enlarged coefficient size set in constructor
if (destination.coeff_count() != coeff_count || destination.coeff_bit_count() != coeff_bit_count)
{
destination.resize(coeff_count, coeff_bit_count);
}
// Make sure we have enough secret keys computed
compute_secret_key_array(encrypted.size() - 1);
/*
Firstly find c_0 + c_1 *s + ... + c_{count-1} * s^{count-1} mod q
This is equal to Delta m + v where ||v|| < Delta/2.
So, add Delta / 2 and now we have something which is Delta * (m + epsilon) where epsilon < 1
Therefore, we can (integer) divide by Delta and the answer will round down to m.
*/
// put < (c_1 , c_2, ... , c_{count-1}) , (s,s^2,...,s^{count-1}) > mod q in destination
if (qualifiers_.enable_ntt)
{
// Make a copy of the encrypted BigPolyArray for NTT (except the first polynomial is not needed)
Pointer encrypted_copy(allocate_poly((encrypted.size() - 1) * coeff_count, coeff_uint64_count, pool_));
set_poly_poly(encrypted.pointer(1), (encrypted.size() - 1) * coeff_count, coeff_uint64_count, encrypted_copy.get());
// Now do the dot product of encrypted_copy and the secret key array using NTT. The secret key powers are already NTT transformed.
ntt_dot_product_bigpolyarray_nttbigpolyarray(encrypted_copy.get(), secret_key_array_.pointer(0), encrypted.size() - 1, array_poly_uint64_count, ntt_tables_, destination.pointer(), pool_);
}
else if(!qualifiers_.enable_ntt && qualifiers_.enable_nussbaumer)
{
nussbaumer_dot_product_bigpolyarray_coeffmod(encrypted.pointer(1), secret_key_array_.pointer(0), encrypted.size() - 1, polymod_, mod_, destination.pointer(), pool_);
}
else
{
// This branch should never be reached
throw logic_error("invalid encryption parameters");
}
// add c_0 into destination
add_poly_poly_coeffmod(destination.pointer(), encrypted[0].pointer(), coeff_count, coeff_modulus_.pointer(), coeff_uint64_count, destination.pointer());
// For each coefficient, reposition and divide by coeff_div_plain_modulus.
uint64_t *dest_coeff = destination.pointer();
Pointer quotient(allocate_uint(coeff_uint64_count, pool_));
Pointer big_alloc(allocate_uint(2 * coeff_uint64_count, pool_));
for (int i = 0; i < coeff_count; i++)
{
// Round to closest level by adding coeff_div_plain_modulus_div_two (mod coeff_modulus).
// This is necessary, as a small negative noise coefficient and message zero can take the coefficient to close to coeff_modulus.
// Adding coeff_div_plain_modulus_div_two at this fixes the problem.
add_uint_uint_mod(dest_coeff, coeff_div_plain_modulus_div_two_.pointer(), coeff_modulus_.pointer(), coeff_uint64_count, dest_coeff);
// Reposition if it is in upper-half of coeff_modulus.
bool is_upper_half = is_greater_than_or_equal_uint_uint(dest_coeff, upper_half_threshold_.pointer(), coeff_uint64_count);
if (is_upper_half)
{
sub_uint_uint(dest_coeff, upper_half_increment_.pointer(), coeff_uint64_count, dest_coeff);
}
// Find closest level.
divide_uint_uint_inplace(dest_coeff, coeff_div_plain_modulus_.pointer(), coeff_uint64_count, quotient.get(), pool_, big_alloc.get());
set_uint_uint(quotient.get(), coeff_uint64_count, dest_coeff);
dest_coeff += coeff_uint64_count;
}
// Resize the coefficient to the original plain_modulus size
destination.resize(coeff_count, orig_plain_modulus_bit_count_);
}
void Decryptor::compute_secret_key_array(int max_power)
{
//// This check is not needed. The function will never be called with max_power < 1.
//if (max_power < 1)
//{
// throw invalid_argument("max_power cannot be less than 1");
//}
int old_count = secret_key_array_.size();
int new_count = max(max_power, secret_key_array_.size());
if (old_count == new_count)
{
return;
}
int coeff_count = poly_modulus_.coeff_count();
int coeff_bit_count = coeff_modulus_.bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
// Compute powers of secret key until max_power
secret_key_array_.resize(new_count, coeff_count, coeff_bit_count);
int poly_ptr_increment = coeff_count * coeff_uint64_count;
uint64_t *prev_poly_ptr = secret_key_array_.pointer(old_count - 1);
uint64_t *next_poly_ptr = prev_poly_ptr + poly_ptr_increment;
if (qualifiers_.enable_ntt)
{
// Since all of the key powers in secret_key_array_ are already NTT transformed, to get the next one
// we simply need to compute a dyadic product of the last one with the first one [which is equal to NTT(secret_key_)].
for (int i = old_count; i < new_count; i++)
{
dyadic_product_coeffmod(prev_poly_ptr, secret_key_array_.pointer(0), coeff_count, mod_, next_poly_ptr, pool_);
prev_poly_ptr = next_poly_ptr;
next_poly_ptr += poly_ptr_increment;
}
}
else if(!qualifiers_.enable_ntt && qualifiers_.enable_nussbaumer)
{
// Non-NTT path involves computing powers of the secret key.
for (int i = old_count; i < new_count; i++)
{
nussbaumer_multiply_poly_poly_coeffmod(prev_poly_ptr, secret_key_.pointer(), polymod_.coeff_count_power_of_two(), mod_, next_poly_ptr, pool_);
prev_poly_ptr = next_poly_ptr;
next_poly_ptr += poly_ptr_increment;
}
}
else
{
// This branch should never be reached
throw logic_error("invalid encryption parameters");
}
}
void Decryptor::inherent_noise(const BigPolyArray &encrypted, BigUInt &destination)
{
// Extract encryption parameters.
// Remark: poly_modulus_ has enlarged coefficient size set in constructor
int coeff_count = poly_modulus_.coeff_count();
int coeff_bit_count = poly_modulus_.coeff_bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
int array_poly_uint64_count = coeff_count * coeff_uint64_count;
// Verify parameters.
if (encrypted.size() < 2 || encrypted.coeff_count() != coeff_count || encrypted.coeff_bit_count() != coeff_bit_count)
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
#ifdef _DEBUG
for (int i = 0; i < encrypted.size(); ++i)
{
if (encrypted[i].significant_coeff_count() == coeff_count || !are_poly_coefficients_less_than(encrypted[i], coeff_modulus_))
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
}
#endif
// Make sure destination is of right size.
if (destination.bit_count() != coeff_bit_count)
{
destination.resize(coeff_bit_count);
}
// Now need to compute c(s) - Delta*m (mod q)
// Make sure we have enough secret keys computed
compute_secret_key_array(encrypted.size() - 1);
Pointer noise_poly(allocate_poly(coeff_count, coeff_uint64_count, pool_));
Pointer plain_poly(allocate_poly(coeff_count, coeff_uint64_count, pool_));
/*
Firstly find c_0 + c_1 *s + ... + c_{count-1} * s^{count-1} mod q
This is equal to Delta m + v where ||v|| < Delta/2.
*/
// put < (c_1 , c_2, ... , c_{count-1}) , (s,s^2,...,s^{count-1}) > mod q in destination_poly
if (qualifiers_.enable_ntt)
{
// Make a copy of the encrypted BigPolyArray for NTT (except the first polynomial is not needed)
Pointer encrypted_copy(allocate_poly((encrypted.size() - 1) * coeff_count, coeff_uint64_count, pool_));
set_poly_poly(encrypted.pointer(1), (encrypted.size() - 1) * coeff_count, coeff_uint64_count, encrypted_copy.get());
// Now do the dot product of encrypted_copy and the secret key array using NTT. The secret key powers are already NTT transformed.
ntt_dot_product_bigpolyarray_nttbigpolyarray(encrypted_copy.get(), secret_key_array_.pointer(0), encrypted.size() - 1, array_poly_uint64_count, ntt_tables_, noise_poly.get(), pool_);
}
else if(!qualifiers_.enable_ntt && qualifiers_.enable_nussbaumer)
{
nussbaumer_dot_product_bigpolyarray_coeffmod(encrypted.pointer(1), secret_key_array_.pointer(0), encrypted.size() - 1, polymod_, mod_, noise_poly.get(), pool_);
}
else
{
// This branch should never be reached
throw logic_error("invalid encryption parameters");
}
// add c_0 into noise_poly
add_poly_poly_coeffmod(noise_poly.get(), encrypted[0].pointer(), coeff_count, coeff_modulus_.pointer(), coeff_uint64_count, noise_poly.get());
// Copy noise_poly to plain_poly
set_poly_poly(noise_poly.get(), coeff_count, coeff_uint64_count, plain_poly.get());
// We need to find the plaintext first, so finish decryption (see Decryptor::decrypt).
// For each coefficient, reposition and divide by coeff_div_plain_modulus.
uint64_t *plain_coeff = plain_poly.get();
Pointer quotient(allocate_uint(coeff_uint64_count, pool_));
Pointer big_alloc(allocate_uint(2 * coeff_uint64_count, pool_));
for (int i = 0; i < coeff_count; i++)
{
// Round to closest level by adding coeff_div_plain_modulus_div_two (mod coeff_modulus).
add_uint_uint_mod(plain_coeff, coeff_div_plain_modulus_div_two_.pointer(), coeff_modulus_.pointer(), coeff_uint64_count, plain_coeff);
// Reposition if it is in upper-half of coeff_modulus.
bool is_upper_half = is_greater_than_or_equal_uint_uint(plain_coeff, upper_half_threshold_.pointer(), coeff_uint64_count);
if (is_upper_half)
{
sub_uint_uint(plain_coeff, upper_half_increment_.pointer(), coeff_uint64_count, plain_coeff);
}
// Find closest level.
divide_uint_uint_inplace(plain_coeff, coeff_div_plain_modulus_.pointer(), coeff_uint64_count, quotient.get(), pool_, big_alloc.get());
// Now perform preencrypt correction.
multiply_truncate_uint_uint(quotient.get(), coeff_div_plain_modulus_.pointer(), coeff_uint64_count, plain_coeff);
if (is_upper_half)
{
add_uint_uint(plain_coeff, upper_half_increment_.pointer(), coeff_uint64_count, plain_coeff);
}
plain_coeff += coeff_uint64_count;
}
// Next subtract from current noise_poly the plain_poly. Inherent noise (poly) is this difference mod coeff_modulus.
sub_poly_poly_coeffmod(noise_poly.get(), plain_poly.get(), coeff_count, mod_.get(), coeff_uint64_count, noise_poly.get());
// Return the infinity norm of noise_poly
poly_infty_norm_coeffmod(noise_poly.get(), coeff_count, coeff_uint64_count, mod_, destination.pointer(), pool_);
}
int Decryptor::invariant_noise_budget(const BigPolyArray &encrypted)
{
// Extract encryption parameters.
// Remark: poly_modulus_ has enlarged coefficient size set in constructor
int coeff_count = poly_modulus_.coeff_count();
int coeff_bit_count = poly_modulus_.coeff_bit_count();
int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);
int array_poly_uint64_count = coeff_count * coeff_uint64_count;
// Verify parameters.
if (encrypted.size() < 2 || encrypted.coeff_count() != coeff_count || encrypted.coeff_bit_count() != coeff_bit_count)
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
#ifdef _DEBUG
for (int i = 0; i < encrypted.size(); ++i)
{
if (encrypted[i].significant_coeff_count() == coeff_count || !are_poly_coefficients_less_than(encrypted[i], coeff_modulus_))
{
throw invalid_argument("encrypted is not valid for encryption parameters");
}
}
#endif
// Make sure destination is of right size.
BigUInt destination;
destination.resize(coeff_bit_count);
// Now need to compute c(s) - Delta*m (mod q)
// Make sure we have enough secret keys computed
compute_secret_key_array(encrypted.size() - 1);
Pointer noise_poly(allocate_poly(coeff_count, coeff_uint64_count, pool_));
Pointer plain_poly(allocate_poly(coeff_count, coeff_uint64_count, pool_));
Pointer plain_poly_copy(allocate_poly(coeff_count, coeff_uint64_count, pool_));
Pointer result_poly(allocate_poly(coeff_count, coeff_uint64_count, pool_));
/*
Firstly find c_0 + c_1 *s + ... + c_{count-1} * s^{count-1} mod q
This is equal to Delta m + v where ||v|| < Delta/2.
*/
// put < (c_1 , c_2, ... , c_{count-1}) , (s,s^2,...,s^{count-1}) > mod q in destination_poly
if (qualifiers_.enable_ntt)
{
// Make a copy of the encrypted BigPolyArray for NTT (except the first polynomial is not needed)
Pointer encrypted_copy(allocate_poly((encrypted.size() - 1) * coeff_count, coeff_uint64_count, pool_));
set_poly_poly(encrypted.pointer(1), (encrypted.size() - 1) * coeff_count, coeff_uint64_count, encrypted_copy.get());
// Now do the dot product of encrypted_copy and the secret key array using NTT. The secret key powers are already NTT transformed.
ntt_dot_product_bigpolyarray_nttbigpolyarray(encrypted_copy.get(), secret_key_array_.pointer(0), encrypted.size() - 1, array_poly_uint64_count, ntt_tables_, noise_poly.get(), pool_);
}
else if (!qualifiers_.enable_ntt && qualifiers_.enable_nussbaumer)
{
nussbaumer_dot_product_bigpolyarray_coeffmod(encrypted.pointer(1), secret_key_array_.pointer(0), encrypted.size() - 1, polymod_, mod_, noise_poly.get(), pool_);
}
else
{
// This branch should never be reached
throw logic_error("invalid encryption parameters");
}
// add c_0 into noise_poly
add_poly_poly_coeffmod(noise_poly.get(), encrypted[0].pointer(), coeff_count, coeff_modulus_.pointer(), coeff_uint64_count, noise_poly.get());
// Multiply by plain_modulus_ and reduce mod coeff_modulus_ to get coeff_modulus_*noise
multiply_poly_scalar_coeffmod(noise_poly.get(), coeff_count, plain_modulus_.pointer(), mod_, noise_poly.get(), pool_);
// Next we compute the infinity norm mod coeff_modulus_
poly_infty_norm_coeffmod(noise_poly.get(), coeff_count, coeff_uint64_count, mod_, destination.pointer(), pool_);
// The -1 accounts for scaling the invariant noise by 2
return max(0, mod_.significant_bit_count() - destination.significant_bit_count() - 1);
}
}
| 51.648961 | 200 | 0.661062 | BNext-IQT |
6e6c5ded5de564bb58c9911c3dbdb1d927458c82 | 12,194 | cpp | C++ | process_data.cpp | skpang/Teensy32_can_fd_to_usb_converter | 8717188d059dbfe67185815e7dc223b60355c511 | [
"MIT"
] | 1 | 2020-01-13T23:50:15.000Z | 2020-01-13T23:50:15.000Z | process_data.cpp | skpang/Teensy32_can_fd_to_usb_converter | 8717188d059dbfe67185815e7dc223b60355c511 | [
"MIT"
] | 1 | 2018-10-20T21:58:40.000Z | 2018-10-20T21:58:40.000Z | process_data.cpp | skpang/Teensy32_can_fd_to_usb_converter | 8717188d059dbfe67185815e7dc223b60355c511 | [
"MIT"
] | null | null | null | #include "process_data.h"
#include "drv_canfdspi_defines.h"
#include "drv_canfdspi_api.h"
unsigned char timestamping = 0;
CAN_BITTIME_SETUP bt;
extern CAN_TX_MSGOBJ txObj;
extern CAN_RX_MSGOBJ rxObj;
extern uint8_t txd[MAX_DATA_BYTES];
extern uint8_t rxd[MAX_DATA_BYTES];
extern uint8_t prompt;
extern volatile uint8_t state;
#define DRV_CANFDSPI_INDEX_0 0
unsigned char parseHex(char * line, unsigned char len, unsigned long * value)
{
*value = 0;
while (len--) {
if (*line == 0) return 0;
*value <<= 4;
if ((*line >= '0') && (*line <= '9')) {
*value += *line - '0';
} else if ((*line >= 'A') && (*line <= 'F')) {
*value += *line - 'A' + 10;
} else if ((*line >= 'a') && (*line <= 'f')) {
*value += *line - 'a' + 10;
} else return 0;
line++;
}
return 1;
}
void sendByteHex(unsigned char value)
{
unsigned char ch = value >> 4;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
Serial.print(ch,BYTE);
ch = value & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
Serial.print(ch,BYTE);
}
unsigned char transmitStd(char *line)
{
uint32_t temp;
unsigned char idlen;
unsigned char i;
unsigned char length;
switch(line[0])
{
case 'D':
case 'd':
txObj.bF.ctrl.BRS = 1;
txObj.bF.ctrl.FDF = 1;
break;
case 'B':
case 'b':
txObj.bF.ctrl.BRS = 0;
txObj.bF.ctrl.FDF = 1;
break;
default:
txObj.bF.ctrl.BRS = 0;
txObj.bF.ctrl.FDF = 0;
break;
}
if (line[0] < 'Z') {
txObj.bF.ctrl.IDE = 1;
idlen = 8;
} else {
txObj.bF.ctrl.IDE = 0;
idlen = 3;
}
if (!parseHex(&line[1], idlen, &temp)) return 0;
if (line[0] < 'Z') {
txObj.bF.id.SID = (uint32_t)(0xffff0000 & temp) >> 18;
txObj.bF.id.EID = 0x0000ffff & temp;
} else {
txObj.bF.id.SID = temp;
}
if (!parseHex(&line[1 + idlen], 1, &temp)) return 0;
txObj.bF.ctrl.DLC = temp;
length = temp;
if(txObj.bF.ctrl.FDF == 0)
{
// Classic CAN
if (length > 8) length = 8;
for (i = 0; i < length; i++) {
if (!parseHex(&line[idlen + 2 + i*2], 2, &temp)) return 0;
txd[i] = temp;
}
}else
{
// CAN FD
length = DRV_CANFDSPI_DlcToDataBytes((CAN_DLC) txObj.bF.ctrl.DLC);
if (length > 64) length = 64;
for (i = 0; i < length; i++) {
if (!parseHex(&line[idlen + 2 + i*2], 2, &temp)) return 0;
txd[i] = temp;
}
}
APP_TransmitMessageQueue();
return 1;
}
void parseLine(char * line)
{
unsigned char result = BELL;
switch (line[0]) {
case 'S': // Setup with standard CAN bitrates
if (state == STATE_CONFIG)
{
switch (line[1]) {
// case '0': ; result = CR; break;
// case '1': ; result = CR; break;
// case '2': ; result = CR; break;
// case '3': ; result = CR; break;
case '4': APP_CANFDSPI_Init(CAN_125K_500K); result = CR; break;
case '5': APP_CANFDSPI_Init(CAN_250K_500K); result = CR; break;
case '6': APP_CANFDSPI_Init(CAN_500K_1M); result = CR; break;
// case '7': ; result = CR; break;
case '8': APP_CANFDSPI_Init(CAN_1000K_4M); result = CR; break;
case '9': APP_CANFDSPI_Init(CAN_500K_1M); result = CR; break;
case 'A': APP_CANFDSPI_Init(CAN_500K_2M); result = CR; break;
case 'B': APP_CANFDSPI_Init(CAN_500K_3M); result = CR; break;
case 'C': APP_CANFDSPI_Init(CAN_500K_4M); result = CR; break;
case 'D': APP_CANFDSPI_Init(CAN_500K_5M); result = CR; break;
case 'E': APP_CANFDSPI_Init(CAN_500K_8M); result = CR; break;
case 'F': APP_CANFDSPI_Init(CAN_500K_10M); result = CR; break;
case 'G': APP_CANFDSPI_Init(CAN_250K_500K); result = CR; break;
case 'H': APP_CANFDSPI_Init(CAN_250K_1M); result = CR; break;
case 'I': APP_CANFDSPI_Init(CAN_250K_2M); result = CR; break;
case 'J': APP_CANFDSPI_Init(CAN_250K_3M); result = CR; break;
case 'K': APP_CANFDSPI_Init(CAN_250K_4M); result = CR; break;
case 'L': APP_CANFDSPI_Init(CAN_1000K_4M); result = CR; break;
case 'M': APP_CANFDSPI_Init(CAN_1000K_8M); result = CR; break;
case 'N': APP_CANFDSPI_Init(CAN_125K_500K); result = CR; break;
}
}
break;
case 's':
if (state == STATE_CONFIG)
{
unsigned long cnf1, cnf2, cnf3;
if (parseHex(&line[1], 2, &cnf1) && parseHex(&line[3], 2, &cnf2) && parseHex(&line[5], 2, &cnf3)) {
result = CR;
}
}
break;
case 'G':
{
unsigned long address;
if (parseHex(&line[1], 2, &address)) {
//
// sendByteHex(value);
result = CR;
}
}
break;
case 'W':
{
unsigned long address, data;
if (parseHex(&line[1], 2, &address) && parseHex(&line[3], 2, &data)) {
result = CR;
}
}
break;
case 'V': // Get hardware version
{
Serial.print('V');
sendByteHex(VERSION_HARDWARE_MAJOR);
sendByteHex(VERSION_HARDWARE_MINOR);
result = CR;
}
break;
case 'v': // Get firmware version
{
Serial.print('v');;
sendByteHex(VERSION_FIRMWARE_MAJOR);
sendByteHex(VERSION_FIRMWARE_MINOR);
result = CR;
}
break;
case 'N': // Get serial number
{
result = CR;
}
break;
case 'O': // Open CAN channel
if (state == STATE_CONFIG)
{
DRV_CANFDSPI_OperationModeSelect(DRV_CANFDSPI_INDEX_0, CAN_NORMAL_MODE);
state = STATE_OPEN;
result = CR;
}
break;
case 'l': // Loop-back mode
if (state == STATE_CONFIG)
{
state = STATE_OPEN;
result = CR;
}
break;
case 'L': // Open CAN channel in listen-only mode
if (state == STATE_CONFIG)
{
state = STATE_LISTEN;
result = CR;
}
break;
case 'C': // Close CAN channel
if (state != STATE_CONFIG)
{
DRV_CANFDSPI_OperationModeSelect(0, CAN_CONFIGURATION_MODE);
state = STATE_CONFIG;
result = CR;
}
break;
case 'r': // Transmit standard RTR (11 bit) frame
case 'R': // Transmit extended RTR (29 bit) frame
case 't': // Transmit standard (11 bit) frame
case 'T': // Transmit extended (29 bit) frame
case 'd': // Transmit FD standard (11 bit) frame with BRS
case 'D': // Transmit FD extended (29 bit) frame with BRS
case 'B': // Transmit FD standard (11 bit) frame no BRS
case 'b': // Transmit FD extended (29 bit) frame no BRS
if (state == STATE_OPEN)
{
if (transmitStd(line)) {
Serial.print('z');
result = CR;
}
}
break;
case 'F': // Read status flags
{
unsigned char status = 0;
sendByteHex(status);
result = CR;
}
break;
case 'Z': // Set time stamping
{
unsigned long stamping;
if (parseHex(&line[1], 1, &stamping)) {
timestamping = (stamping != 0);
result = CR;
}
}
break;
case 'm': // Set accpetance filter mask
if (state == STATE_CONFIG)
{
unsigned long am0, am1, am2, am3;
result = CR;
}
break;
case 'M': // Set accpetance filter code
if (state == STATE_CONFIG)
{
unsigned long ac0, ac1, ac2, ac3;
result = CR;
}
break;
}
Serial.print(result,BYTE);
}
unsigned char canmsg2ascii_getNextChar(uint32_t id, unsigned char dlc, unsigned char * step) {
char ch = BELL;
char newstep = *step;
if (*step == RX_STEP_TYPE) {
// type 1st char
if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 1) && (rxObj.bF.ctrl.BRS == 1))
{
newstep = RX_STEP_ID_EXT;
ch = 'D';
} else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 1))
{
newstep = RX_STEP_ID_STD;
ch = 'd';
} else if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 0))
{
newstep = RX_STEP_ID_EXT;
ch = 'T';
}else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 0))
{
newstep = RX_STEP_ID_STD;
ch = 't';
}else if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 0))
{
newstep = RX_STEP_ID_EXT;
ch = 'B';
}else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 0))
{
newstep = RX_STEP_ID_STD;
ch = 'b';
}
} else if (*step < RX_STEP_DLC) {
unsigned char i = *step - 1;
unsigned char * id_bp = (unsigned char*)&id; // rxObj.bF.id.SID;
ch = id_bp[3 - (i / 2)];
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
} else if (*step < RX_STEP_DATA) {
ch = rxObj.bF.ctrl.DLC;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
if (dlc ==0) newstep = RX_STEP_TIMESTAMP;
else newstep++;
} else if (*step < RX_STEP_TIMESTAMP) {
unsigned char i = *step - RX_STEP_DATA;
ch = rxd[i/2];
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
if (newstep - RX_STEP_DATA ==dlc*2) newstep = RX_STEP_TIMESTAMP;
} else if (timestamping && (*step < RX_STEP_CR)) {
unsigned char i = *step - RX_STEP_TIMESTAMP;
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
} else {
ch = CR;
newstep = RX_STEP_FINISHED;
}
*step = newstep;
return ch;
}
void out_usb(void)
{
uint8_t dlc,i,rxstep;
uint8_t out_buff[200];
uint8_t outdata = 0;
uint32_t id = 0;
i =0;
rxstep = 0;
dlc = DRV_CANFDSPI_DlcToDataBytes((CAN_DLC)rxObj.bF.ctrl.DLC);
if(rxObj.bF.ctrl.IDE == 1)
{
id = (((uint32_t)rxObj.bF.id.SID) <<18) |rxObj.bF.id.EID;
}else
{
id = rxObj.bF.id.SID;
}
while( rxstep != RX_STEP_FINISHED)
{
outdata = canmsg2ascii_getNextChar(id, dlc, &rxstep);
out_buff[i++] =outdata;
}
out_buff[i] = 0; //Add null
Serial.print((char *)out_buff);
}
| 27.525959 | 115 | 0.454568 | skpang |
6e6d46d3f098ac9491d606ac53421d7ae2c024ce | 13,964 | cpp | C++ | Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | 3 | 2015-11-08T07:17:46.000Z | 2019-04-05T17:08:05.000Z | Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | null | null | null | Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp | jpoirier/x-gauges | 8261b19a9678ad27db44eb8c354f5e66bd061693 | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* *
* Copyright (C) 2008 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* Licence: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
#include <QDebug>
#include <QDate>
#include <fstream>
#include "BestFit/AbstractBestFitLinear.h"
#include "GeoMag/GeoMagModel.h"
#include "JulianDay.h"
#include "MagSphereCalibration.h"
#define MIN_MAGU_RAW_DISTANCE 30
namespace can {
// ------------------------------------------------------------------------
MagSphereCalibration::MagSphereCalibration()
{
m_vS.SetAllTo(1.0f);
}
// ------------------------------------------------------------------------
int MagSphereCalibration::CreateRecord()
{
int id = m_conRecord.count();
m_conRecord.push_back(Record());
qDebug() << "Magu record" << id << "was created.";
return id;
}
// ------------------------------------------------------------------------
void MagSphereCalibration::UndoRecord()
{
if(!m_conRecord.isEmpty())
m_conRecord.pop_back();
}
// ------------------------------------------------------------------------
bool MagSphereCalibration::AddItem(int iRec, const V3f& v)
{
Q_ASSERT(iRec >= 0 && iRec < m_conRecord.count());
// Check all items in the record.
// This prevents forming groups on one spot.
bool bReject = false;
for(int i=0; i<m_conRecord[iRec].count(); i++) {
V3f x(v);
x.Subtract(m_conRecord[iRec][i]);
// Check if the new item is far enough from all other items in the record.
if(x.GetNorm() < MIN_MAGU_RAW_DISTANCE) {
bReject = true;
break;
}
}
if(bReject)
return false;
// Ok, we can accept new item.
m_conRecord[iRec].push_back(v);
// qDebug() << "vM =" << v[0] << v[1] << v[2];
return true;
}
// ------------------------------------------------------------------------
bool MagSphereCalibration::AddItem(const V3f& v)
{
return AddItem(m_conRecord.count()-1, v);
}
// ------------------------------------------------------------------------
using namespace bestfit;
class MagLinFit3D : public AbstractBestFitLinear
{
public:
MagLinFit3D() : AbstractBestFitLinear(6,3) {};
double CalcFunction(const Vec& vC, const common::VectorD& vD) const
{
smx::Vector<double, 6> vX;
CalcX(vD, vX);
return vC.Multiply(vX);
}
protected:
//! Calculate the "Xi" vector for best fit function for given vD data point.
virtual void CalcX(const common::VectorD& vM, smx::VectorBase<double>& vX) const
{
ASSERT(vX.GetSize() == m_vC.GetSize());
vX[0] = vM[1]*vM[1]; // my2 * A
vX[1] = vM[2]*vM[2]; // mz2 * B
vX[2] = vM[0]; // mx * C
vX[3] = vM[1]; // my * D
vX[4] = vM[2]; // my * E
vX[5] = 1.0; // 1 * F
}
//! The yi value out of the data.
double CalcY(const common::VectorD& vM) const
{ return -vM[0]*vM[0]; }
};
// ------------------------------------------------------------------------
class MagLinFit2D : public AbstractBestFitLinear
{
public:
MagLinFit2D() : AbstractBestFitLinear(4,2) {};
double CalcFunction(const Vec& vC, const common::VectorD& vD) const
{
smx::Vector<double, 4> vX;
CalcX(vD, vX);
return vC.Multiply(vX);
}
protected:
//! Calculate the "Xi" vector for best fit function for given vD data point.
virtual void CalcX(const common::VectorD& vM, smx::VectorBase<double>& vX) const
{
ASSERT(vX.GetSize() == m_vC.GetSize());
vX[0] = vM[1]*vM[1]; // my2 * A
vX[1] = vM[0]; // mx * B
vX[2] = vM[1]; // my * C
vX[3] = 1.0; // 1 * D
}
//! The yi value out of the data.
double CalcY(const common::VectorD& vM) const
{ return -vM[0]*vM[0]; }
};
// ------------------------------------------------------------------------
/*
using namespace numeric;
class MagNonFit3D : public BestFit
{
public:
//! Fit Compass constructor
MagNonFit3D(double dR) : BestFit(6) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
return -m_dR*m_dR + pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2);
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
vd.Resize(m_uiUnknowns);
vd[0] = 2*(bx-mx)/(sx*sx);
vd[1] = 2*(by-my)/(sy*sy);
vd[2] = 2*(bz-mz)/(sz*sz);
vd[3] = (-2*pow(bx-mx,2))/pow(sx,3);
vd[4] = (-2*pow(by-my,2))/pow(sy,3);
vd[5] = (-2*pow(bz-mz,2))/pow(sz,3);
}
protected:
//! Radius
double m_dR;
};
// ------------------------------------------------------------------------
class MagNonFit2D : public BestFit
{
public:
//! Fit Compass constructor
MagNonFit2D(double dR) : BestFit(4) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& bx = vX[0];
const double& by = vX[1];
const double& sx = vX[2];
const double& sy = vX[3];
return -m_dR*m_dR + pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2);
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& bx = vX[0];
const double& by = vX[1];
const double& sx = vX[2];
const double& sy = vX[3];
vd.Resize(m_uiUnknowns);
vd[0] = 2*(bx-mx)/(sx*sx);
vd[1] = 2*(by-my)/(sy*sy);
vd[2] = (-2*pow(bx-mx,2))/pow(sx,3);
vd[3] = (-2*pow(by-my,2))/pow(sy,3);
}
protected:
//! Radius
double m_dR;
};
// ------------------------------------------------------------------------
class MagNonFitSqrt : public BestFit
{
public:
//! Fit Compass constructor
MagNonFitSqrt(double dR) : BestFit(6) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
return -m_dR + sqrt(pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2));
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
vd.Resize(m_uiUnknowns);
double A = sqrt(pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2));
vd[0] = 2*(bx-mx)/(sx*sx*A);
vd[1] = 2*(by-my)/(sy*sy*A);
vd[2] = 2*(bz-mz)/(sz*sz*A);
vd[3] = (-2*pow(bx-mx,2))/(A*pow(sx,3));
vd[4] = (-2*pow(by-my,2))/(A*pow(sy,3));
vd[5] = (-2*pow(bz-mz,2))/(A*pow(sz,3));
}
protected:
//! Radius
double m_dR;
};
*/
// ------------------------------------------------------------------------
bool MagSphereCalibration::Solve(float fLon, float fLat, float fAlt_km)
{
using namespace common;
// We need the geomag model for today and given geographic position.
GeoMagModel gmm;
JulianDay jd(QDate::currentDate().toJulianDay());
gmm.SetDate(jd.GetDateAsDecimalYear());
gmm.Evaluate(fLat, fLon, fAlt_km);
// We need total radius and xy-plane radius.
float fRxy = sqrt(pow(gmm.GetX(),2) + pow(gmm.GetY(),2));
float fR, fI, fD;
gmm.CalcIDH(fI, fD, fR);
// Show some results
qDebug() << "Total Earth magnetic field strenth" << fR;
qDebug() << "XY plane Earth magnetic field strenth" << fRxy;
qDebug() << "Inclination =" << Deg(fI) << ", declination =" << Deg(fD);
VectorD vX(3);
MagLinFit3D mlf3D;
MagLinFit2D mlf2D;
// MagNonFit2D mnf2D(fRxy);
// Merge the data and output the mathematica version
std::ofstream out("MagSphereData.txt");
for(int r=0; r<m_conRecord.count(); r++) {
out << "\nPts" << r+1 << " = {\n";
for(int i=0; i<m_conRecord[r].count(); i++) {
mlf3D.AddData(m_conRecord[r][i]);
// The first data record MUST be the xy plane. We take x and y only.
if(r==0) {
mlf2D.AddData(
m_conRecord[r][i][0], // x
m_conRecord[r][i][1] // y
);
/* mnf2D.AddData(
m_conRecord[r][i][0], // x
m_conRecord[r][i][1] // y
);*/
}
out << "{"
<< m_conRecord[r][i][0] << ","
<< m_conRecord[r][i][1] << ","
<< m_conRecord[r][i][2];
if(i==m_conRecord[r].count()-1)
out << "}";
else
out << "},";
}
out << "};\n";
}
out.close();
// The linear LSM
bool bSuccess3D = mlf3D.Solve();
// Convert resulting LMS parameters into meaningful 3D results.
const smx::VectorBase<double>& vC = mlf3D.GetParameters();
double fBx3, fBy3, fBz3, fSx3, fSy3, fSz3;
fBx3 = -vC[2]/2;
fBy3 = -vC[3]/(2*vC[0]);
fBz3 = -vC[4]/(2*vC[1]);
fSx3 = (fBx3*fBx3 + vC[0]*fBy3*fBy3 + vC[1]*fBz3*fBz3 - vC[5])/(fR*fR);
fSy3 = fSx3/vC[0];
fSz3 = fSx3/vC[1];
fSx3 = sqrt(fSx3);
fSy3 = sqrt(fSy3);
fSz3 = sqrt(fSz3);
// Now, get the 2D linear LSM solution.
bool bSuccess2D = mlf2D.Solve();
// Convert resulting parameters into 2D results.
const smx::VectorBase<double>& vE = mlf2D.GetParameters();
double fBx2, fBy2, fSx2, fSy2;
fBx2 = -vE[1]/2;
fBy2 = -vE[2]/(2*vE[0]);
fSx2 = (fBx2*fBx2 + vE[0]*fBy2*fBy2 - vE[3])/(fRxy*fRxy);
fSy2 = fSx2/vE[0];
fSx2 = sqrt(fSx2);
fSy2 = sqrt(fSy2);
// Store results in a bit unusual way.
// x and y values are taken from 2D solution, while the z values are
// taken from 3D solution.
m_vB[0] = fBx2;
m_vB[1] = fBy2;
m_vB[2] = fBz3;
m_vS[0] = fSx2;
m_vS[1] = fSy2;
m_vS[2] = fSz3;
qDebug() << "Linear 3D solution:"
<< fBx3 << fBy3 << fBz3 << fSx3 << fSy3 << fSz3;
qDebug() << "Linear 2D solution:"
<< fBx2 << fBy2 << fSx2 << fSy2;
// Nonliear 2D solution
/* BestFit::Vec vY2(4);
vY2[0] = fBx3;
vY2[1] = fBy3;
vY2[2] = fSx3;
vY2[3] = fSy3;
FitSolverLevenbergMarquard fslm2;
FitSolverLevenbergMarquard::StoppingCriterion sc;
sc = fslm2.Solve(mnf2D, vY2);
qDebug() << "Nonlinear 2D solution:"
<< vY2[0] << vY2[1] << vY2[2] << vY2[3];
m_vB[0] = vY2[0];
m_vB[1] = vY2[1];
m_vS[0] = vY2[2];
m_vS[1] = vY2[3];
// Nonlinear solutions
MagNonFit3D mnf(fR);
// Kontrola
const AbstractBestFit::Data& mD = mlf3D.GetData();
for(unsigned int i=0; i<mD.size(); i++) {
float fmx = mD[i][0];
float fmy = mD[i][1];
float fmz = mD[i][2];
fmx = (fmx - fBx3)/fSx3;
fmy = (fmy - fBy3)/fSy3;
fmz = (fmz - fBz3)/fSz3;
float fRC = sqrt(fmx*fmx + fmy*fmy + fmz*fmz);
mnf.AddData(mD[i]);
}
qDebug() << "Second stage" << mnf.GetData().size() << "items";
BestFit::Vec vY(6);
vY[0] = fBx3;
vY[1] = fBy3;
vY[2] = fBz3;
vY[3] = fSx3;
vY[4] = fSy3;
vY[5] = fSz3;
FitSolverLevenbergMarquard fslm;
//FitSolverLevenbergMarquard::StoppingCriterion sc;
sc = fslm.Solve(mnf, vY);
qDebug() << "Nonlinear 3D solution:"
<< vY[0] << vY[1] << vY[2] << vY[3] << vY[4] << vY[5];*/
/* m_vB[0] = vY[0];
m_vB[1] = vY[1];
m_vB[2] = vY[2];
m_vS[0] = vY[3];
m_vS[1] = vY[4];
m_vS[2] = vY[5];*/
// Kontrola
/* const BestFit::Data& mD2 = mnf.GetData();
for(unsigned int i=0; i<mD2.size(); i++) {
float fmx = mD2[i][0];
float fmy = mD2[i][1];
float fmz = mD2[i][2];
fmx = (fmx - fBx3)/fSx3;
fmy = (fmy - fBy3)/fSy3;
fmz = (fmz - fBz3)/fSz3;
float fRC = sqrt(fmx*fmx + fmy*fmy + fmz*fmz);
// qDebug() << i << ":" << fmx << fmy << fmz << fRC << fabs(fR-fRC);
}*/
/* qDebug() << "Final solution:"
<< m_vB[0] << m_vB[1] << m_vB[2]
<< m_vS[0] << m_vS[1] << m_vS[2];*/
return bSuccess3D && bSuccess2D;
}
// ------------------------------------------------------------------------
void MagSphereCalibration::VerifyItem(
const V3f& v, //!< Raw magnetic field sensor reading.
float fRoll, //!< Roll angle
float fPitch //!< Pitch angle
)
{
// Get "true" magnetic vector.
V3f m = v;
m.Subtract(m_vB);
for(int i=0; i<3; i++)
m[i]/=m_vS[i];
// Calculate heading - use pitch and roll correction.
// Convert magnetic sensor values into xy plane first.
float fSinR, fCosR; // Roll
float fSinP, fCosP; // Pitch
// XXX:
// sincosf(fRoll, &fSinR, &fCosR);
// sincosf(fPitch, &fSinP, &fCosP);
// We will uses sensor values ...
float fXh = m[0]*fCosP + m[1]*fSinR*fSinP + m[2]*fCosR*fSinP;
float fYh = m[1]*fCosR - m[2]*fSinR;
qDebug("Xh = %f, Yh = %f", fXh, fYh);
// Now, calculate heading ...
float fYaw = -common::ATan2Safe(m[1],m[0]);
if(fYaw < 0)
fYaw += M_PI*2;
qDebug("Yaw = %f", common::Deg(fYaw));
}
// ------------------------------------------------------------------------
} // namespace
| 27.488189 | 84 | 0.533228 | jpoirier |
6e6e458bc3694dd2c6548bebe2889912422c33d2 | 143 | cpp | C++ | examples/polar_plots/ezpolar/ezpolar_1.cpp | solosuper/matplotplusplus | 87ff5728b14ad904bc6acaa2bf010c1a03c6cb4a | [
"MIT"
] | 2,709 | 2020-08-29T01:25:40.000Z | 2022-03-31T18:35:25.000Z | examples/polar_plots/ezpolar/ezpolar_1.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 124 | 2020-08-29T04:48:17.000Z | 2022-03-25T15:45:59.000Z | examples/polar_plots/ezpolar/ezpolar_1.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 203 | 2020-08-29T04:16:22.000Z | 2022-03-30T02:08:36.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
ezpolar("1+cos(t)");
show();
return 0;
} | 13 | 28 | 0.594406 | solosuper |
6e753663e1cde35adcad68f05d4318cc1c092f18 | 1,410 | inl | C++ | Win32.FlexiSpy/Symbian/Trunk/CodeBase/inc/Global.inl | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 2 | 2021-02-04T06:47:45.000Z | 2021-07-28T10:02:10.000Z | Win32.FlexiSpy/Symbian/Trunk/CodeBase/inc/Global.inl | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Win32.FlexiSpy/Symbian/Trunk/CodeBase/inc/Global.inl | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | #include "Global.h"
inline CCoeEnv& Global::CoeEnv()
{
return AppUi().CoeEnv();
}
inline CFxsAppUi& Global::AppUi()
{
return *STATIC_CAST(CFxsAppUi*, CEikonEnv::Static()->AppUi());
}
inline CFxsAppUi* Global::AppUiPtr()
{
return STATIC_CAST(CFxsAppUi*, CEikonEnv::Static()->AppUi());
}
inline CFxsSettings& Global::Settings()
{
return AppUi().SettingsInfo();
}
inline CFxsDatabase& Global::Database()
{
return AppUi().Database();
}
inline MFxPositionMethod* Global::FxPositionMethod()
{
return AppUi().FxPositionMethod();
}
inline MFxNetworkInfo* Global::FxNetworkInfo()
{
return AppUi().FxNetworkInfo();
}
inline RFs& Global::FsSession()
{
return AppUi().FsSession();
}
inline RWsSession& Global::WsSession()
{
return AppUi().WsSession();
}
inline RWindowGroup& Global::RootWin()
{
return AppUi().RootWin();
}
inline void Global::GetAppPath(TFileName& aPath)
{
AppUi().GetAppPath(aPath);
}
inline void Global::SendToBackground()
{
AppUi().SendToBackground();
}
inline void Global::BringToForeground()
{
AppUi().BringToForeground();
}
inline TBool Global::ProductActivated()
{
return AppUi().ProductActivated();
}
inline CLicenceManager& Global::LicenceManager()
{
return AppUi().LicenceManager();
}
inline CTerminator* Global::TheTerminator()
{
return AppUi().TheTerminator();
}
inline void Global::ExitApp()
{
AppUi().ExitApp();
}
| 16.206897 | 63 | 0.692908 | 010001111 |
6e7672a2b632a5a3c092e701bccec80007eaa4b7 | 16,329 | cpp | C++ | vision/blackItem/image_converter.cpp | Eithwa/kymavoid | 2cd099021f111aa342c3f655c0eee06f9e2e3f2a | [
"Apache-2.0"
] | null | null | null | vision/blackItem/image_converter.cpp | Eithwa/kymavoid | 2cd099021f111aa342c3f655c0eee06f9e2e3f2a | [
"Apache-2.0"
] | null | null | null | vision/blackItem/image_converter.cpp | Eithwa/kymavoid | 2cd099021f111aa342c3f655c0eee06f9e2e3f2a | [
"Apache-2.0"
] | 1 | 2020-08-10T03:19:27.000Z | 2020-08-10T03:19:27.000Z | #include "image_converter.hpp"
#include "math.h"
#include "omp.h"
using namespace std;
using namespace cv;
const double ALPHA = 0.5;
ImageConverter::ImageConverter():
it_(nh),
FrameRate(0.0),
obj_filter_size(500)
{
get_Camera();
get_center();
get_distance();
get_whitedata();
image_sub_ = it_.subscribe("/camera/image_raw", 1, &ImageConverter::imageCb, this);
black_pub = nh.advertise<std_msgs::Int32MultiArray>("/vision/BlackRealDis", 1);
red_pub = nh.advertise<std_msgs::Int32MultiArray>("/vision/redRealDis", 1);
mpicture = nh.advertise<vision::visionlook>("/vision/picture_m", 1);
double ang_PI;
for (int ang = 0; ang < 360; ang++)
{
ang_PI = ang * M_PI / 180;
Angle_sin.push_back(sin(ang_PI));
Angle_cos.push_back(cos(ang_PI));
}
}
ImageConverter::~ImageConverter()
{
}
int Frame_area(int num, int range)
{
if (num < 0)
num = 0;
else if (num >= range)
num = range - 1;
return num;
}
void ImageConverter::imageCb(const sensor_msgs::ImageConstPtr &msg)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8);
cv::flip(cv_ptr->image, Main_frame, 1);
Black_Mask = Main_frame.clone();
Red_Mask = Main_frame.clone();
static double StartTime = ros::Time::now().toSec();
double EndTime = ros::Time::now().toSec();
if(EndTime-StartTime>2){
get_Camera();
get_center();
get_distance();
get_whitedata();
StartTime = EndTime;
}
#pragma omp parallel sections
{
#pragma omp section
{
//================Black obstacle detection========
black_binarization();
black_filter();
black_item();
}
#pragma omp section
{
//================Red line detection==============
red_binarization();
red_line();
}
}
cv::imshow("black_item", Black_Mask);
cv::imshow("red_line", Red_Mask);
cv::waitKey(1);
//=======================FPS======================
FrameRate = Rate();
//================================================
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
}
double ImageConverter::Rate()
{
double ALPHA = 0.5;
double dt;
static int frame_counter = 0;
static double frame_rate = 0.0;
static double StartTime = ros::Time::now().toNSec();
double EndTime;
frame_counter++;
if (frame_counter == 10)
{
EndTime = ros::Time::now().toNSec();
dt = (EndTime - StartTime) / frame_counter;
StartTime = EndTime;
if (dt != 0)
{
frame_rate = (1000000000.0 / dt) * ALPHA + frame_rate * (1.0 - ALPHA);
//cout << "FPS: " << frame_rate << endl;
}
frame_counter = 0;
}
return frame_rate;
}
void ImageConverter::black_binarization()
{
int gray_count = 0;
gray_ave = 0;
for (int i = 0; i < Main_frame.rows; i++)
{
for (int j = 0; j < Main_frame.cols; j++)
{
unsigned char gray = (Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 0]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 1]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 2]) / 3;
if (gray < black_gray)
{
gray_ave += gray;
gray_count++;
}
}
}
gray_count = (gray_count == 0) ? 0.00001 : gray_count;
gray_ave = gray_ave / gray_count;
for (int i = 0; i < Main_frame.rows; i++)
{
for (int j = 0; j < Main_frame.cols; j++)
{
unsigned char gray = (Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 0]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 1]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 2]) / 3;
if (gray < black_gray - (setgray - gray_ave))
{
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 0] = 0;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 1] = 0;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 2] = 0;
}
else
{
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 0] = 255;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 1] = 255;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 2] = 255;
}
}
}
}
class Coord
{
public:
Coord(int x_, int y_) : x(x_), y(y_) {}
Coord operator+(const Coord &addon) const { return Coord(x + addon.x, y + addon.y); }
int get_x() const { return x; }
int get_y() const { return y; }
private:
int x, y;
};
Coord directions[8] = {
Coord(0, 1),
Coord(0, -1),
Coord(-1, 0),
Coord(1, 0),
Coord(-1, 1),
Coord(1, 1),
Coord(-1, -1),
Coord(1, -1)};
bool is_black(Mat &img, const Coord &c)
{
if(img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 0] == 0
&&img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 1] == 0
&&img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 2] == 0)
{
return true;
}else{
return false;
}
}
void is_checked(Mat &img, const Coord &c){
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 0] = 255;
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 1] = 255;
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 2] = 255;
}
Mat convertTo3Channels(const Mat &binImg)
{
Mat three_channel = Mat::zeros(binImg.rows, binImg.cols, CV_8UC3);
vector<Mat> channels;
for (int i = 0; i < 3; i++)
{
channels.push_back(binImg);
}
merge(channels, three_channel);
return three_channel;
}
void ImageConverter::black_filter()
{
int inner = center_inner, outer = center_outer, centerx = center_x, centery = center_y;
int detection_range = (inner+outer)/2;
int width = Black_Mask.cols-1, length = Black_Mask.rows-1;
int obj_size = obj_filter_size;
vector<vector<Coord> > obj; //物件列表
Mat check_map = Mat(Size(Black_Mask.cols, Black_Mask.rows), CV_8UC3, Scalar(0, 0, 0));//確認搜尋過的pix
//inner中心塗白 outer切斷與外面相連黑色物體
circle(Black_Mask, Point(centerx, centery), inner, Scalar(255, 255, 255), -1);
circle(Black_Mask, Point(centerx, centery), outer, Scalar(255, 0, 0), 2);
//搜尋範圍顯示
circle(Black_Mask, Point(centerx, centery), detection_range, Scalar(255, 0, 0), 1);
//rectangle(Black_Mask, Point(centerx - detection_range, centery - detection_range), Point(centerx + detection_range, centery + detection_range), Scalar(255, 0, 0), 1);
//選取的範圍做搜尋
//0為黑
for (int i = centerx - detection_range; i < centerx + detection_range; i++)
{
for (int j = centery - detection_range; j < centery + detection_range; j++)
{
//std::cout << i << " " << j << std::endl;
if(hypot(centerx-i,centery-j)>detection_range) continue;
if (is_black(check_map,Coord(i, j)))
{
is_checked(check_map,Coord(i, j));
if (is_black(Black_Mask, Coord(i, j)))
{
queue<Coord> bfs_list;
bfs_list.push(Coord(i, j));
vector<Coord> dot;
dot.push_back(Coord(i, j));
//放入佇列
while (!bfs_list.empty())
{
Coord ori = bfs_list.front();
bfs_list.pop();
//搜尋八方向
for (int k = 0; k < 8; k++)
{
Coord dst = ori + directions[k];
//處理邊界
if ((dst.get_x() < 0) || (dst.get_x() >= width) || (dst.get_y() < 0) || (dst.get_y() >= length)) continue;
if(hypot(centerx-dst.get_x(),centery-dst.get_y())>outer) continue;
if (!is_black(check_map,Coord(dst.get_x(), dst.get_y()))) continue;
if (is_black(Black_Mask, dst))
{
bfs_list.push(dst);
dot.push_back(dst);
}
is_checked(check_map,Coord(dst.get_x(), dst.get_y()));
}
}
obj.push_back(dot);
}
}
}
}
//上色
for (int i = 0; i < obj.size(); i++)
{
//需要塗色的物體大小
if (obj[i].size() > obj_size) continue;
for (int j = 0; j < obj[i].size(); j++)
{
Coord point = obj[i][j];
line(Black_Mask, Point(point.get_x(), point.get_y()), Point(point.get_x(), point.get_y()), Scalar(255, 0, 255), 1);
}
}
//cv::imshow("black filter", Black_Mask);
//cv::waitKey(1);
}
void ImageConverter::black_item()
{
int object_dis;
blackItem_pixel.clear();
BlackRealDis.data.clear();
Mat binarization_map = Black_Mask.clone();
for (int angle = 0; angle < 360; angle = angle + black_angle)
{
int angle_be = angle + center_front;
if (angle_be >= 360)
angle_be -= 360;
double x_ = Angle_cos[angle_be];
double y_ = Angle_sin[angle_be];
for (int r = center_inner - 1; r <= center_outer; r++)
{
int dis_x = x_ * r;
int dis_y = y_ * r;
int image_x = Frame_area(center_x + dis_x, binarization_map.cols);
int image_y = Frame_area(center_y - dis_y, binarization_map.rows);
if (binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 0] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 1] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 2] == 0)
{
blackItem_pixel.push_back(hypot(dis_x, dis_y));
break;
}
else
{
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 0] = 0;
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 1] = 0;
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 2] = 255;
}
if (r == center_outer)
{
blackItem_pixel.push_back(hypot(dis_x, dis_y));
}
}
}
//ROS_INFO("%d , blackangle=%d",blackItem_pixel.size(),black_angle);
for (int j = 0; j < blackItem_pixel.size(); j++)
{
object_dis = Omni_distance(blackItem_pixel[j]);
BlackRealDis.data.push_back(object_dis);
}
black_pub.publish(BlackRealDis);
//cv::imshow("black_item", Black_Mask);
//cv::waitKey(1);
}
void ImageConverter::red_binarization()
{
Mat inputMat = Red_Mask.clone();
Mat hsv(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(0, 0, 0));
Mat mask(inputMat.rows, inputMat.cols, CV_8UC1, Scalar(0, 0, 0));
Mat mask2(inputMat.rows, inputMat.cols, CV_8UC1, Scalar(0, 0, 0));
Mat dst(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(0, 0, 0));
Mat white(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(255, 255, 255));
int hmin, hmax, smin, smax, vmin, vmax;
cvtColor(inputMat, hsv, CV_BGR2HSV);
hmax = double(red[0]*0.5);
hmin = double(red[1]*0.5);
smax = red[2];
smin = red[3];
vmax = red[4];
vmin = red[5];
if (red[0] >= red[1])
{
inRange(hsv, Scalar(hmin, smin, vmin), Scalar(hmax, smax, vmax), mask);
}
else
{
inRange(hsv, Scalar(hmin, smin, vmin), Scalar(255, smax, vmax), mask);
inRange(hsv, Scalar(0, smin, vmin), Scalar(hmax, smax, vmax), mask2);
mask = mask + mask2;
}
convertTo3Channels(mask);
//開操作 (去除一些噪點)
Mat element = getStructuringElement(MORPH_RECT, Size(2, 2));
morphologyEx(mask, mask, MORPH_OPEN, element);
white.copyTo(dst, (cv::Mat::ones(mask.size(), mask.type()) * 255 - mask));
Red_Mask = dst;
///////////////////Show view/////////////////
//cv::imshow("dst", dst);
//cv::imshow("Red_Mask", Red_Mask);
//cv::waitKey(1);
/////////////////////////////////////////////
}
void ImageConverter::red_line()
{
int object_dis;
redItem_pixel.clear();
redRealDis.data.clear();
Mat binarization_map = Red_Mask.clone();
for (int angle = 0; angle < 360; angle = angle + black_angle)
{
int angle_be = angle + center_front;
if (angle_be >= 360)
angle_be -= 360;
double x_ = Angle_cos[angle_be];
double y_ = Angle_sin[angle_be];
for (int r = center_inner; r <= center_outer; r++)
{
int dis_x = x_ * r;
int dis_y = y_ * r;
int image_x = Frame_area(center_x + dis_x, binarization_map.cols);
int image_y = Frame_area(center_y - dis_y, binarization_map.rows);
if (binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 0] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 1] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 2] == 0)
{
redItem_pixel.push_back(hypot(dis_x, dis_y));
break;
}
else
{
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 0] = 0;
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 1] = 0;
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 2] = 255;
}
if (r == center_outer)
{
redItem_pixel.push_back(hypot(dis_x, dis_y));
}
}
}
for (int j = 0; j < redItem_pixel.size(); j++)
{
object_dis = Omni_distance(redItem_pixel[j]);
redRealDis.data.push_back(object_dis);
}
red_pub.publish(redRealDis);
to_strategy.mpicture++;
to_strategy.gray_ave = gray_ave;
mpicture.publish(to_strategy);
///////////////////Show view/////////////////
//cv::imshow("red_line", Red_Mask);
//cv::waitKey(1);
/////////////////////////////////////////////
}
double ImageConverter::Omni_distance(double dis_pixel)
{
double Z = -1 * Camera_H;
double c = 83.125;
double b = c * 0.8722;
double f = Camera_f;
double dis;
//double pixel_dis = sqrt(pow(object_x,2)+pow(object_y,2));
double pixel_dis = dis_pixel;
double r = atan2(f, pixel_dis * 0.0099);
dis = Z * (pow(b, 2) - pow(c, 2)) * cos(r) / ((pow(b, 2) + pow(c, 2)) * sin(r) - 2 * b * c);
if (dis / 10 < 0 || dis / 10 > 999)
{
dis = 9990;
}
return dis / 10;
}
void ImageConverter::get_center()
{
nh.setParam("/FIRA/gray_ave", gray_ave);
nh.getParam("/AvoidChallenge/GraySet", setgray);
nh.getParam("/FIRA/Center/X", center_x);
nh.getParam("/FIRA/Center/Y", center_y);
nh.getParam("/FIRA/Center/Inner", center_inner);
nh.getParam("/FIRA/Center/Outer", center_outer);
nh.getParam("/FIRA/Center/Front", center_front);
}
void ImageConverter::get_distance()
{
nh.getParam("/FIRA/Distance/Gap", dis_gap);
nh.getParam("/FIRA/Distance/Space", dis_space);
nh.getParam("/FIRA/Distance/Pixel", dis_pixel);
}
void ImageConverter::get_Camera()
{
nh.getParam("/FIRA/Camera/High", Camera_H);
nh.getParam("/FIRA/Camera/Focal", Camera_f);
}
void ImageConverter::get_whitedata()
{
red.clear();
if (nh.hasParam("/FIRA/blackItem/obj_filter_size"))
{
nh.getParam("/FIRA/blackItem/obj_filter_size", obj_filter_size);
}
nh.getParam("/FIRA/blackItem/gray", black_gray);
nh.getParam("/FIRA/blackItem/angle", black_angle);
nh.getParam("/FIRA/HSV/Redrange", red);
//std::cout<<red[0]<<" "<<red[1]<<" "<<red[2]<<" "<<red[3]<<" "<<red[4]<<" "<<red[5]<<std::endl;
}
| 32.334653 | 172 | 0.519873 | Eithwa |
6e797c232267aa24a883602c87355ef60000f3c7 | 5,818 | cc | C++ | src/d3d11/d3d11_main.cc | R2Northstar/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | 3 | 2022-02-17T03:11:52.000Z | 2022-02-20T21:20:16.000Z | src/d3d11/d3d11_main.cc | pg9182/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | null | null | null | src/d3d11/d3d11_main.cc | pg9182/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | 2 | 2022-02-17T14:04:09.000Z | 2022-02-20T17:52:55.000Z | #include "d3d11_device.h"
#include "dxgi_factory.h"
#include "d3d11_include.h"
extern "C" {
using namespace dxvk;
DLLEXPORT HRESULT __stdcall D3D11CoreCreateDevice(
IDXGIFactory* pFactory,
IDXGIAdapter* pAdapter,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
ID3D11Device** ppDevice) {
InitReturnPtr(ppDevice);
D3D_FEATURE_LEVEL defaultFeatureLevels[] = {
D3D_FEATURE_LEVEL_11_0,
};
if (pFeatureLevels == nullptr || FeatureLevels == 0) {
pFeatureLevels = defaultFeatureLevels,
FeatureLevels = sizeof(defaultFeatureLevels) / sizeof(*defaultFeatureLevels);
}
UINT flId;
for (flId = 0 ; flId < FeatureLevels; flId++) {
if (pFeatureLevels[flId] == D3D_FEATURE_LEVEL_11_1 || pFeatureLevels[flId] == D3D_FEATURE_LEVEL_11_0)
break;
}
if (flId == FeatureLevels) {
DXVK_LOG_FUNC("err", "Requested feature level not supported");
return E_INVALIDARG;
}
// Try to create the device with the given parameters.
const D3D_FEATURE_LEVEL fl = pFeatureLevels[flId];
Com<D3D11DXGIDevice> device = new D3D11DXGIDevice(pAdapter, fl, Flags);
return device->QueryInterface(__uuidof(ID3D11Device), reinterpret_cast<void**>(ppDevice));
}
static HRESULT D3D11InternalCreateDeviceAndSwapChain(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc,
IDXGISwapChain** ppSwapChain,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
InitReturnPtr(ppDevice);
InitReturnPtr(ppSwapChain);
InitReturnPtr(ppImmediateContext);
if (pFeatureLevel)
*pFeatureLevel = D3D_FEATURE_LEVEL(0);
HRESULT hr;
Com<IDXGIFactory> dxgiFactory = nullptr;
Com<IDXGIAdapter> dxgiAdapter = pAdapter;
Com<ID3D11Device> device = nullptr;
if (ppSwapChain && !pSwapChainDesc)
return E_INVALIDARG;
if (!pAdapter) {
hr = (new DxgiFactory(0))->QueryInterface(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory));
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "Failed to create a DXGI factory");
return hr;
}
hr = dxgiFactory->EnumAdapters(0, &dxgiAdapter);
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "No default adapter available");
return hr;
}
} else {
if (FAILED(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory)))) {
DXVK_LOG_FUNC("err", "Failed to query DXGI factory from DXGI adapter");
return E_INVALIDARG;
}
if (DriverType != D3D_DRIVER_TYPE_UNKNOWN || Software)
return E_INVALIDARG;
}
hr = D3D11CoreCreateDevice(
dxgiFactory.ptr(), dxgiAdapter.ptr(),
Flags, pFeatureLevels, FeatureLevels,
&device);
if (FAILED(hr))
return hr;
// Create the swap chain, if requested
if (ppSwapChain) {
DXGI_SWAP_CHAIN_DESC desc = *pSwapChainDesc;
hr = dxgiFactory->CreateSwapChain(device.ptr(), &desc, ppSwapChain);
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "Failed to create swap chain");
return hr;
}
}
// Write back whatever info the application requested
if (pFeatureLevel)
*pFeatureLevel = device->GetFeatureLevel();
if (ppDevice)
*ppDevice = device.ref();
if (ppImmediateContext)
device->GetImmediateContext(ppImmediateContext);
// If we were unable to write back the device and the
// swap chain, the application has no way of working
// with the device so we should report S_FALSE here.
if (!ppDevice && !ppImmediateContext && !ppSwapChain)
return S_FALSE;
return S_OK;
}
DLLEXPORT HRESULT __stdcall D3D11CreateDevice(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
DXVK_LOG("D3D11CreateDevice", "initializing d3d11 stub for northstar (github.com/R2Northstar/NorthstarStubs)");
return D3D11InternalCreateDeviceAndSwapChain(
pAdapter, DriverType, Software, Flags,
pFeatureLevels, FeatureLevels, SDKVersion,
nullptr, nullptr,
ppDevice, pFeatureLevel, ppImmediateContext);
}
DLLEXPORT HRESULT __stdcall D3D11CreateDeviceAndSwapChain(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc,
IDXGISwapChain** ppSwapChain,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
return D3D11InternalCreateDeviceAndSwapChain(
pAdapter, DriverType, Software, Flags,
pFeatureLevels, FeatureLevels, SDKVersion,
pSwapChainDesc, ppSwapChain,
ppDevice, pFeatureLevel, ppImmediateContext);
}
} | 32.502793 | 115 | 0.630113 | R2Northstar |
6e7acaaeb160f14ee94a4b522c3d80999863bbcf | 2,197 | cpp | C++ | test/unittests/test_parser.cpp | SmaranTum/syrec | 7fd0eece4c3376e52c1f5f17add71a49e5826dac | [
"MIT"
] | 1 | 2022-03-19T21:51:58.000Z | 2022-03-19T21:51:58.000Z | test/unittests/test_parser.cpp | SmaranTum/syrec | 7fd0eece4c3376e52c1f5f17add71a49e5826dac | [
"MIT"
] | 9 | 2022-02-28T17:03:50.000Z | 2022-03-25T16:02:39.000Z | test/unittests/test_parser.cpp | cda-tum/syrec | 43dcdd997edd02c80304f53f66118f9dd0fc5f68 | [
"MIT"
] | 2 | 2022-02-02T10:35:09.000Z | 2022-02-02T15:52:24.000Z | #include "core/syrec/program.hpp"
#include "gtest/gtest.h"
using namespace syrec;
class SyrecParserTest: public testing::TestWithParam<std::string> {
protected:
std::string test_circuits_dir = "./circuits/";
std::string file_name;
void SetUp() override {
file_name = test_circuits_dir + GetParam() + ".src";
}
};
INSTANTIATE_TEST_SUITE_P(SyrecParserTest, SyrecParserTest,
testing::Values(
"alu_2",
"binary_numeric",
"bitwise_and_2",
"bitwise_or_2",
"bn_2",
"call_8",
"divide_2",
"for_4",
"for_32",
"gray_binary_conversion_16",
"input_repeated_2",
"input_repeated_4",
"logical_and_1",
"logical_or_1",
"modulo_2",
"multiply_2",
"negate_8",
"numeric_2",
"operators_repeated_4",
"parity_4",
"parity_check_16",
"shift_4",
"simple_add_2",
"single_longstatement_4",
"skip",
"swap_2"),
[](const testing::TestParamInfo<SyrecParserTest::ParamType>& info) {
auto s = info.param;
std::replace( s.begin(), s.end(), '-', '_');
return s; });
TEST_P(SyrecParserTest, GenericParserTest) {
program prog;
read_program_settings settings;
std::string error_string;
error_string = prog.read(file_name, settings);
EXPECT_TRUE(error_string.empty());
}
| 38.54386 | 93 | 0.383705 | SmaranTum |
6e7b2e21e7f082665dd3ed0d7e291a0edf4bfa1d | 518 | cpp | C++ | mcc/mcc/MccIdentifierConflictError.cpp | Goclis/mcc | 475ff1a1e92db749bc935f979d79296ca466470d | [
"MIT"
] | null | null | null | mcc/mcc/MccIdentifierConflictError.cpp | Goclis/mcc | 475ff1a1e92db749bc935f979d79296ca466470d | [
"MIT"
] | null | null | null | mcc/mcc/MccIdentifierConflictError.cpp | Goclis/mcc | 475ff1a1e92db749bc935f979d79296ca466470d | [
"MIT"
] | null | null | null | #include "MccIdentifierConflictError.h"
#include <iostream>
using std::cout;
MccIdentifierConflictError::MccIdentifierConflictError(const string &name)
{
m_id_name = name;
m_line_no_cause_conflict = 0;
m_line_no_having_conflict = 0;
}
MccIdentifierConflictError::~MccIdentifierConflictError(void)
{
}
void MccIdentifierConflictError::report() const
{
cout << "Identifier `" << m_id_name << "` conflict: "
<< "line " << m_line_no_cause_conflict << " and "
<< "line " << m_line_no_having_conflict << "\n";
} | 22.521739 | 74 | 0.735521 | Goclis |
6e7e54b9a9a38df535c5340485638e5c4fe83116 | 1,820 | hpp | C++ | include/header.hpp | Skvortsovvv/lab-05-stack-Skvortsovvv | e658a314c8a729dc024daba28dbd585c21987526 | [
"MIT"
] | null | null | null | include/header.hpp | Skvortsovvv/lab-05-stack-Skvortsovvv | e658a314c8a729dc024daba28dbd585c21987526 | [
"MIT"
] | null | null | null | include/header.hpp | Skvortsovvv/lab-05-stack-Skvortsovvv | e658a314c8a729dc024daba28dbd585c21987526 | [
"MIT"
] | null | null | null | // Copyright 2020 Your Name <your_email>
#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_
#include <memory>
#include <atomic>
#include <type_traits>
#include <utility>
#include <iostream>
#include <stdexcept>
template<typename T>
class Stack
{
private:
Stack(Stack&) = delete;
Stack& operator=(Stack&) = delete;
static_assert(std::is_move_assignable<T>::value,
"Error: this type is not moveable");
static_assert(!std::is_copy_assignable<T>::value,
"Error: type cant be copyable");
static_assert(!std::is_copy_constructible<T>::value,
"Error: type cant be copy construtible");
struct node
{
node* next;
//std::shared_ptr<T> data;
T data;
explicit node(T& d, node* n = nullptr):
next(n), data(std::move(d)) {}
};
node* Head = nullptr;
public:
Stack(){}
~Stack() {
while (Head) {
node* temp = Head;
Head = Head->next;
delete temp;
}
}
template <typename ... Args>
void push_emplace(Args&&... value) {
T temp(std::forward<Args>(value)...);
node* new_node = new node(temp, Head);
Head = new_node;
}
void push(T&& value) {
T temp(std::move(value));
node* new_node = new node(
temp, Head);
Head = new_node;
}
const T& head() const {
return Head->data;
/*return *(Head->data);*/
}
T pop() {
T Data = std::move(Head->data);
node* to_be_delted = Head;
Head = Head->next;
delete to_be_delted;
return Data;
/*T Data = std::move(*(Head->data));
node* to_be_deleted = Head;
Head = Head->next;
delete to_be_deleted;
return Data;*/
}
};
#endif // INCLUDE_HEADER_HPP_
| 23.947368 | 56 | 0.558242 | Skvortsovvv |
6e7e621088102c1f3a2229315eb53a33bd6452c0 | 4,501 | hpp | C++ | include/mserialize/make_template_tag.hpp | linhanwang/binlog | b4da55f2ae9b61c31c34bf307c0937ec515293df | [
"Apache-2.0"
] | 248 | 2019-12-05T20:59:51.000Z | 2021-01-19T15:56:12.000Z | include/mserialize/make_template_tag.hpp | Galaxy2416/binlog | 14bf705b51602d43403733670d6110f8742b0409 | [
"Apache-2.0"
] | 57 | 2019-12-18T07:00:46.000Z | 2021-01-04T14:04:16.000Z | include/mserialize/make_template_tag.hpp | Galaxy2416/binlog | 14bf705b51602d43403733670d6110f8742b0409 | [
"Apache-2.0"
] | 22 | 2021-03-27T20:43:40.000Z | 2022-03-31T10:01:38.000Z | #ifndef MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
#define MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
#include <mserialize/cx_string.hpp>
#include <mserialize/detail/foreach.hpp>
#include <mserialize/detail/preprocessor.hpp>
#include <mserialize/make_struct_tag.hpp>
/**
* MSERIALIZE_MAKE_TEMPLATE_TAG(TemplateArgs, TypenameWithTemplateArgs, members...)
*
* Define a CustomTag specialization for the given
* struct or class template, allowing serialized objects
* of it to be visited using mserialize::visit.
*
* The first argument of the macro must be the arguments
* of the template, with the necessary typename prefix,
* where needed, as they appear after the template keyword
* in the definition, wrapped by parentheses.
* (The parentheses are required to avoid the preprocessor
* splitting the arguments at the commas)
*
* The second argument is the template name with
* the template arguments, as it should appear in a specialization,
* wrapped by parentheses.
*
* Following the second argument come the members,
* which are either accessible fields or getters.
*
* Example:
*
* template <typename A, typename B>
* struct Pair {
* A a;
* B b;
* };
* MSERIALIZE_MAKE_TEMPLATE_TAG((typename A, typename B), (Pair<A,B>), a, b)
*
* The macro has to be called in global scope
* (outside of any namespace).
*
* The member list can be empty.
* The member list does not have to enumerate every member
* of the given type, but it must be sync with
* the specialization of CustomSerializer,
* if visitation of objects serialized that way
* is desired.
*
* The maximum number of members and template arguments
* is limited by mserialize/detail/foreach.hpp, currently 100.
*
* Limitation: it is not possible to generate
* a tag for a recursive types with this macro.
* CustomTag for recursive types need to be manually
* specialized.
*
* If some of the members are private, the following friend
* declaration can be added to the type declaration:
*
* template <typename, typename>
* friend struct mserialize::CustomTag;
*/
//
// The macros below deserve a bit of an explanation.
//
// Given the following example call:
//
// MSERIALIZE_MAKE_TEMPLATE_TAG((typename A, typename B, typename C), (Tuple<A,B,C>), a, b, c)
//
// Then the below macros expand to:
//
// TemplateArgs = (typename A, typename B, typename C)
// __VA_ARGS__ = (Tuple<A,B,C>), a, b, c
// ^-- this is here to avoid empty pack if there are no members,
// as until C++20 the pack cannot be empty
//
// MSERIALIZE_FIRST(__VA_ARGS__) = (Tuple<A,B,C>)
// MSERIALIZE_UNTUPLE((Tuple<A,B,C>)) = Tuple<A,B,C>
// MSERIALIZE_STRINGIZE_LIST(Tuple<A,B,C>) ~= "Tuple<A,B,C>"
//
#define MSERIALIZE_MAKE_TEMPLATE_TAG(TemplateArgs, ...) \
namespace mserialize { \
template <MSERIALIZE_UNTUPLE(TemplateArgs)> \
struct CustomTag<MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__)), void> \
{ \
using T = MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__)); \
static constexpr auto tag_string() \
{ \
return cx_strcat( \
make_cx_string( \
"{" MSERIALIZE_STRINGIZE_LIST(MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__))) \
), \
MSERIALIZE_FOREACH( \
MSERIALIZE_STRUCT_MEMBER_TAG, _, __VA_ARGS__ \
) \
make_cx_string("}") \
); \
} \
}; \
} /* namespace mserialize */ \
/**/
/** MSERIALIZE_STRINGIZE_LIST(a,b,c) -> "a" "," "b" "," "c" */
#define MSERIALIZE_STRINGIZE_LIST(...) \
MSERIALIZE_STRINGIZE(MSERIALIZE_FIRST(__VA_ARGS__)) \
MSERIALIZE_FOREACH(MSERIALIZE_STRINGIZE_LIST_I, _, __VA_ARGS__) \
/**/
#define MSERIALIZE_STRINGIZE_LIST_I(_, a) "," #a
#endif // MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
| 40.1875 | 94 | 0.582537 | linhanwang |
6e8026c4eacc4dc6bff492879ed3821c9a2ad587 | 4,897 | cpp | C++ | Framework/DrawPass/ShadowMapPass.cpp | kiorisyshen/newbieGameEngine | d1e68fbd75884fdf0f171212396d8bc5fec8ad9e | [
"MIT"
] | 3 | 2019-06-07T15:29:45.000Z | 2019-11-11T01:26:12.000Z | Framework/DrawPass/ShadowMapPass.cpp | kiorisyshen/newbieGameEngine | d1e68fbd75884fdf0f171212396d8bc5fec8ad9e | [
"MIT"
] | null | null | null | Framework/DrawPass/ShadowMapPass.cpp | kiorisyshen/newbieGameEngine | d1e68fbd75884fdf0f171212396d8bc5fec8ad9e | [
"MIT"
] | null | null | null | #include "ShadowMapPass.hpp"
#include "GraphicsManager.hpp"
using namespace std;
using namespace newbieGE;
void ShadowMapPass::Draw(Frame &frame) {
if (frame.frameContext.shadowMapLight.size() > 0 ||
frame.frameContext.cubeShadowMapLight.size() > 0 ||
frame.frameContext.globalShadowMapLight.size() > 0) {
g_pGraphicsManager->DestroyShadowMaps();
frame.frameContext.shadowMapLight.clear();
frame.frameContext.cubeShadowMapLight.clear();
frame.frameContext.globalShadowMapLight.clear();
frame.frameContext.shadowMap = -1;
frame.frameContext.cubeShadowMap = -1;
frame.frameContext.globalShadowMap = -1;
}
// count shadow map
vector<Light *> lights_cast_shadow;
for (int32_t i = 0; i < frame.frameContext.numLights; i++) {
auto &light = frame.lightInfo.lights[i];
light.lightShadowMapIndex = -1;
if (light.lightCastShadow) {
switch (light.lightType) {
case LightType::Omni:
light.lightShadowMapIndex = frame.frameContext.cubeShadowMapLight.size();
frame.frameContext.cubeShadowMapLight.push_back(&light);
break;
case LightType::Spot:
light.lightShadowMapIndex = frame.frameContext.shadowMapLight.size();
frame.frameContext.shadowMapLight.push_back(&light);
break;
case LightType::Area:
light.lightShadowMapIndex = frame.frameContext.shadowMapLight.size();
frame.frameContext.shadowMapLight.push_back(&light);
break;
case LightType::Infinity:
light.lightShadowMapIndex = frame.frameContext.globalShadowMapLight.size();
frame.frameContext.globalShadowMapLight.push_back(&light);
break;
default:
assert(0);
}
}
}
if (frame.frameContext.shadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kNormalShadowMap.type,
m_kNormalShadowMap.width, m_kNormalShadowMap.height,
frame.frameContext.shadowMapLight.size());
frame.frameContext.shadowMap = shadowmapID;
}
if (frame.frameContext.cubeShadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kCubeShadowMap.type,
m_kCubeShadowMap.width, m_kCubeShadowMap.height,
frame.frameContext.cubeShadowMapLight.size());
frame.frameContext.cubeShadowMap = shadowmapID;
}
if (frame.frameContext.globalShadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kGlobalShadowMap.type,
m_kGlobalShadowMap.width, m_kGlobalShadowMap.height,
frame.frameContext.globalShadowMapLight.size());
frame.frameContext.globalShadowMap = shadowmapID;
}
for (auto it : frame.frameContext.shadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.shadowMap, it->lightShadowMapIndex);
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMap2DShader);
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::NormalShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.shadowMap, it->lightShadowMapIndex);
}
for (auto it : frame.frameContext.cubeShadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.cubeShadowMap, it->lightShadowMapIndex);
#ifdef USE_METALCUBEDEPTH
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMapCubeShader);
#endif
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::CubeShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.cubeShadowMap, it->lightShadowMapIndex);
}
for (auto it : frame.frameContext.globalShadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.globalShadowMap, it->lightShadowMapIndex);
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMap2DShader);
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::GlobalShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.globalShadowMap, it->lightShadowMapIndex);
}
}
| 51.547368 | 125 | 0.627731 | kiorisyshen |
6e819d93aa468191533a76b7b5862970a87b8cb9 | 2,524 | cpp | C++ | Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp | kevinjpetersen/Shrek2ModdingSDK | 1d517fccc4d83b24342e62f80951318fd4f7c707 | [
"MIT"
] | 1 | 2022-03-24T21:43:49.000Z | 2022-03-24T21:43:49.000Z | Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp | kevinjpetersen/Shrek2ModdingSDK | 1d517fccc4d83b24342e62f80951318fd4f7c707 | [
"MIT"
] | null | null | null | Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp | kevinjpetersen/Shrek2ModdingSDK | 1d517fccc4d83b24342e62f80951318fd4f7c707 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Kevin J. Petersen https://github.com/kevinjpetersen/
*/
#include "Shrek2ModdingSDK.h"
void Shrek2Timer::Start()
{
try {
if (IsRunning) return;
IsRunning = true;
timer.start();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Start", ex.what());
}
}
void Shrek2Timer::Stop()
{
try {
if (!IsRunning) return;
IsRunning = false;
timer.stop();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Stop", ex.what());
}
}
void Shrek2Timer::Reset()
{
try {
IsRunning = false;
timer.reset();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Reset", ex.what());
}
}
bool Shrek2Timer::IsTimerRunning()
{
return IsRunning;
}
std::string Shrek2Timer::GetTimeString()
{
try {
int mils = CurrentMilliseconds();
int secs = CurrentSeconds();
int mins = CurrentMinutes();
std::string milliseconds = (mils <= 9 ? "00" : (mils <= 99 ? "0" : "")) + std::to_string(mils);
std::string seconds = (secs <= 9 ? "0" : "") + std::to_string(secs);
std::string minutes = (mins <= 9 ? "0" : "") + std::to_string(mins);
return minutes + ":" + seconds + "." + milliseconds;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::GetTimeString", ex.what());
return "";
}
}
int Shrek2Timer::TotalMilliseconds()
{
try {
return timer.count<std::chrono::milliseconds>();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalMilliseconds", ex.what());
return 0;
}
}
int Shrek2Timer::TotalSeconds()
{
try {
return TotalMilliseconds() / 1000.0;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalSeconds", ex.what());
return 0;
}
}
int Shrek2Timer::TotalMinutes()
{
try {
return TotalSeconds() / 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalMinutes", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentMilliseconds()
{
try {
return (int)TotalMilliseconds() % 1000;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentMilliseconds", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentSeconds()
{
try {
return (int)TotalSeconds() % 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentSeconds", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentMinutes()
{
try {
return (int)TotalMinutes() % 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentMinutes", ex.what());
return 0;
}
} | 18.028571 | 97 | 0.650951 | kevinjpetersen |
6e822a4c8963a206f5724481f638fbf508424e85 | 1,107 | hh | C++ | exp.hh | aicodix/dsp | c83add357c695482590825ddd2713dc29fd903d2 | [
"0BSD"
] | 16 | 2019-01-25T02:02:21.000Z | 2022-02-11T04:05:54.000Z | exp.hh | aicodix/dsp | c83add357c695482590825ddd2713dc29fd903d2 | [
"0BSD"
] | 2 | 2020-12-10T05:46:36.000Z | 2020-12-15T00:16:25.000Z | exp.hh | aicodix/dsp | c83add357c695482590825ddd2713dc29fd903d2 | [
"0BSD"
] | 4 | 2019-01-25T02:02:15.000Z | 2021-10-06T13:50:59.000Z | /*
Exponentiation approximations
Constants below lifted from the Cephes Mathematical Library:
https://www.netlib.org/cephes/cmath.tgz
Copyright 2018 Ahmet Inan <inan@aicodix.de>
*/
#pragma once
namespace DSP {
template <typename TYPE>
TYPE ldexp(TYPE x, int n)
{
int a = n < 0 ? -n : n;
int a8 = a / 8;
int ar = a - a8 * 8;
TYPE t = 1 << a8;
t *= t;
t *= t;
t *= t;
t *= 1 << ar;
return n < 0 ? x / t : x * t;
}
template <typename TYPE>
TYPE exp10(TYPE x)
{
static constexpr TYPE
LOG210 = 3.32192809488736234787e0,
LG102A = 3.01025390625000000000E-1,
LG102B = 4.60503898119521373889E-6,
P0 = 4.09962519798587023075E-2,
P1 = 1.17452732554344059015E1,
P2 = 4.06717289936872725516E2,
P3 = 2.39423741207388267439E3,
Q0 = 8.50936160849306532625E1,
Q1 = 1.27209271178345121210E3,
Q2 = 2.07960819286001865907E3;
TYPE i = nearbyint(x * LOG210);
x -= i * LG102A;
x -= i * LG102B;
TYPE xx = x * x;
TYPE py = x * (xx * (xx * (xx * P0 + P1) + P2) + P3);
TYPE qy = xx * (xx * (xx + Q0) + Q1) + Q2;
TYPE pq = TYPE(1) + TYPE(2) * py / (qy - py);
return ldexp(pq, (int)i);
}
}
| 20.5 | 60 | 0.630533 | aicodix |
6e87cd251d1062079c2f6635787a5405e720e4d7 | 143 | cpp | C++ | compiler/useful_visitors.cpp | Bhare8972/Cyth | 334194be4b00456ed3fbf279f18bb22458d4ca81 | [
"Apache-2.0"
] | null | null | null | compiler/useful_visitors.cpp | Bhare8972/Cyth | 334194be4b00456ed3fbf279f18bb22458d4ca81 | [
"Apache-2.0"
] | 1 | 2016-01-09T19:00:14.000Z | 2016-01-09T19:00:14.000Z | compiler/useful_visitors.cpp | Bhare8972/Cyth | 334194be4b00456ed3fbf279f18bb22458d4ca81 | [
"Apache-2.0"
] | null | null | null |
#include "AST_visitor.hpp"
#include "useful_visitors.hpp"
#include <string>
#include <sstream>
using namespace csu;
using namespace std;
| 11 | 30 | 0.748252 | Bhare8972 |
6e8a30e159ef58180085f2e1d99af91a543eca85 | 571 | hpp | C++ | data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp | vlad-iancu/alg-lib | 706b30253018a8a6f16d353396c8a9ddf2d0b51e | [
"MIT"
] | null | null | null | data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp | vlad-iancu/alg-lib | 706b30253018a8a6f16d353396c8a9ddf2d0b51e | [
"MIT"
] | 11 | 2021-09-04T19:12:23.000Z | 2021-09-25T21:13:06.000Z | data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp | vlad-iancu/libalg | 706b30253018a8a6f16d353396c8a9ddf2d0b51e | [
"MIT"
] | null | null | null | #ifndef ALG_LIB_DATA_STRUCTURE_EDGE_EDGE_LIST_READER_H_
#define ALG_LIB_DATA_STRUCTURE_EDGE_EDGE_LIST_READER_H_
#include <graph/EdgeList.hpp>
#include <graph/types.hpp>
#include <edge/readers/EdgeReader.hpp>
namespace graph
{
class EdgeListEdgeReader : public EdgeReader
{
private:
const EdgeList &graph;
bool _can_read;
SizeE index;
public:
EdgeListEdgeReader(const EdgeList &graph);
bool increment();
EdgePtr current_edge() const;
bool can_read() const;
};
} // namespace graph
#endif | 19.033333 | 55 | 0.69352 | vlad-iancu |
6e8a540e10842778612cec396c18b7549b904169 | 9,551 | cpp | C++ | Flw_Piano.cpp | jpcima/Flw_Piano | 115ca63d8068c9bedbe40bc5ea8aeec5f1363855 | [
"BSL-1.0"
] | 1 | 2019-08-15T13:57:23.000Z | 2019-08-15T13:57:23.000Z | Flw_Piano.cpp | jpcima/Flw_Piano | 115ca63d8068c9bedbe40bc5ea8aeec5f1363855 | [
"BSL-1.0"
] | null | null | null | Flw_Piano.cpp | jpcima/Flw_Piano | 115ca63d8068c9bedbe40bc5ea8aeec5f1363855 | [
"BSL-1.0"
] | null | null | null | // Copyright Jean Pierre Cimalando 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "Flw_Piano.h"
#include <FL/Fl_Button.H>
#include <FL/Fl.H>
#include <vector>
#include <math.h>
enum Key_Color { Key_White, Key_Black };
enum { white_keywidth = 24, black_keywidth = 14 };
struct Flw_Piano::Impl {
explicit Impl(Flw_Piano *q);
Flw_Piano *const Q;
Fl_Boxtype box_[2];
Fl_Color bg_[2];
class Key_Button : public Fl_Button {
public:
Key_Button(int x, int y, int w, int h, unsigned key)
: Fl_Button(x, y, w, h), key_(key) {}
unsigned piano_key() const
{ return key_; }
int handle(int event) override;
private:
unsigned key_;
};
std::vector<Key_Button *> keys_;
unsigned pushed_key_;
static int handle_key(Key_Button *btn, int event);
void create_keys(unsigned nkeys);
void delete_keys();
Key_Button *key_at(int x, int y);
static const int *keypos_;
static void make_positions(int *pos);
static Key_Color key_color(unsigned key);
static unsigned next_white_key(unsigned key);
static int key_position(unsigned key);
static int key_width(unsigned key);
static Piano_Event event_type_;
static unsigned event_key_;
void do_piano_callback(Piano_Event type, unsigned key);
};
Flw_Piano::Flw_Piano(int x, int y, int w, int h)
: Fl_Group(x, y, w, h),
P(new Impl(this))
{
if (!Impl::keypos_) {
static int table[12];
Impl::make_positions(table);
Impl::keypos_ = table;
}
key_count(48);
}
Flw_Piano::~Flw_Piano()
{
}
const Fl_Color *Flw_Piano::key_color() const
{
return P->bg_;
}
void Flw_Piano::key_color(Fl_Color wh, Fl_Color bl)
{
P->bg_[0] = wh;
P->bg_[1] = bl;
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
Fl_Color bg = (keyc == Key_White) ? wh : bl;
keys[key]->color(bg, bg);
}
}
const Fl_Boxtype *Flw_Piano::key_box() const
{
return P->box_;
}
void Flw_Piano::key_box(Fl_Boxtype wh, Fl_Boxtype bl)
{
P->box_[0] = wh;
P->box_[1] = bl;
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = Impl::key_color(key);
keys[key]->box((keyc == Key_White) ? wh : bl);
}
}
unsigned Flw_Piano::key_count() const
{
return P->keys_.size();
}
void Flw_Piano::key_count(unsigned nkeys)
{
P->create_keys(nkeys);
}
int Flw_Piano::key_value(unsigned key) const
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return 0;
return keys[key]->value();
}
void Flw_Piano::key_value(unsigned key, int value)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return;
keys[key]->value(value);
}
bool Flw_Piano::press_key(unsigned key)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return false;
Impl::Key_Button *btn = keys[key];
if (btn->value())
return false;
btn->value(1);
P->do_piano_callback(PIANO_PRESS, key);
return true;
}
bool Flw_Piano::release_key(unsigned key)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return false;
Impl::Key_Button *btn = keys[key];
if (!btn->value())
return false;
btn->value(0);
P->do_piano_callback(PIANO_RELEASE, key);
return true;
}
void Flw_Piano::draw()
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
if (keyc == Key_White)
draw_child(*keys[key]);
}
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
if (keyc == Key_Black)
draw_child(*keys[key]);
}
}
Flw_Piano::Impl::Impl(Flw_Piano *q)
: Q(q),
pushed_key_((unsigned)-1)
{
box_[0] = FL_UP_BOX;
box_[1] = FL_UP_BOX;
bg_[0] = fl_rgb_color(0xee, 0xee, 0xec);
bg_[1] = fl_rgb_color(0x88, 0x8a, 0x85);
}
int Flw_Piano::Impl::Key_Button::handle(int event)
{
if (static_cast<Flw_Piano::Impl *>(user_data())->handle_key(this, event))
return 1;
return Fl_Button::handle(event);
}
int Flw_Piano::Impl::handle_key(Key_Button *btn, int event)
{
Impl *self = static_cast<Impl *>(btn->user_data());
Flw_Piano *Q = self->Q;
Key_Button **keys = self->keys_.data();
switch (event) {
case FL_PUSH:
case FL_DRAG: {
int x = Fl::event_x();
int y = Fl::event_y();
Key_Button *btn = self->key_at(x, y);
if (btn) {
unsigned key = btn->piano_key();
unsigned oldkey = self->pushed_key_;
if (key != oldkey) {
Q->release_key(oldkey);
Q->press_key(key);
self->pushed_key_ = key;
}
}
return 1;
}
case FL_RELEASE: {
unsigned key = self->pushed_key_;
Q->release_key(key);
self->pushed_key_ = (unsigned)-1;
return 1;
}
}
return 0;
}
void Flw_Piano::Impl::create_keys(unsigned nkeys)
{
delete_keys();
if (nkeys == 0)
return;
const Fl_Boxtype *box = box_;
Fl_Color bg_white = bg_[0];
Fl_Color bg_black = bg_[1];
int x = Q->x();
int y = Q->y();
int w = Q->w();
int h = Q->h();
int fullw = key_position(nkeys - 1) + key_width(nkeys - 1);
double wr = (double)w / (double)fullw;
keys_.resize(nkeys);
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = key_color(key);
if (keyc == Key_White) {
int keyx = x + lround(wr * key_position(key));
unsigned nextkey = next_white_key(key);
int nextx = x + lround(wr * (keypos_[nextkey % 12] + (int)(nextkey / 12) * 7 * keypos_[2]));
int keyw = nextx - keyx;
int keyh = h;
Key_Button *btn = new Key_Button(keyx, y, keyw, keyh, key);
btn->user_data(this);
btn->visible_focus(0);
btn->color(bg_white, bg_white);
btn->box(box[0]);
keys_[key] = btn;
}
}
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = key_color(key);
if (keyc == Key_Black) {
int keyx = x + lround(wr * key_position(key));
int keyw = lround(wr * black_keywidth);
int keyh = h / 2;
Key_Button *btn = new Key_Button(keyx, y, keyw, keyh, key);
btn->user_data(this);
btn->visible_focus(0);
btn->color(bg_black, bg_black);
btn->box(box[1]);
keys_[key] = btn;
}
}
}
void Flw_Piano::Impl::delete_keys()
{
while (!keys_.empty()) {
delete keys_.back();
keys_.pop_back();
}
}
Flw_Piano::Impl::Key_Button *Flw_Piano::Impl::key_at(int x, int y)
{
Key_Button **keys = keys_.data();
unsigned nkeys = keys_.size();
for (unsigned i = 0; i < nkeys; ++i) {
if (key_color(i) == Key_Black) {
Key_Button *btn = keys[i];
bool inside = x >= btn->x() && x < btn->x() + btn->w() &&
y >= btn->y() && y < btn->y() + btn->h();
if (inside)
return btn;
}
}
for (unsigned i = 0; i < nkeys; ++i) {
if (key_color(i) == Key_White) {
Key_Button *btn = keys[i];
bool inside = x >= btn->x() && x < btn->x() + btn->w() &&
y >= btn->y() && y < btn->y() + btn->h();
if (inside)
return btn;
}
}
return NULL;
}
Key_Color Flw_Piano::Impl::key_color(unsigned key)
{
unsigned n = key % 12;
n = (n < 5) ? n : (n - 1);
return (n & 1) ? Key_Black : Key_White;
}
unsigned Flw_Piano::Impl::next_white_key(unsigned key)
{
unsigned nextkey = key + 1;
while (key_color(nextkey) != Key_White)
++nextkey;
return nextkey;
}
int Flw_Piano::Impl::key_position(unsigned key)
{
return keypos_[key % 12] + (int)(key / 12) * 7 * keypos_[2];
}
int Flw_Piano::Impl::key_width(unsigned key)
{
if (key_color(key) == Key_White)
return key_position(next_white_key(key)) - key_position(key);
else
return black_keywidth;
}
const int *Flw_Piano::Impl::keypos_ = NULL;
void Flw_Piano::Impl::make_positions(int *pos)
{
unsigned nth = 0;
for (int i = 0; i < 7; ++i) {
int index = i * 2;
index -= (index > 4) ? 1 : 0;
pos[index] = i * white_keywidth;
}
for (int i = 0; i < 2; ++i)
pos[1 + 2 * i] = 15 + 2 * i * black_keywidth;
for (int i = 0; i < 3; ++i)
pos[6 + 2 * i] = pos[5] + 13 + 2 * i * black_keywidth;
}
Piano_Event Flw_Piano::Impl::event_type_;
unsigned Flw_Piano::Impl::event_key_;
void Flw_Piano::Impl::do_piano_callback(Piano_Event type, unsigned key)
{
event_type_ = type;
event_key_ = key;
Q->do_callback();
}
Piano_Event Piano::event()
{
return Flw_Piano::Impl::event_type_;
}
unsigned Piano::key()
{
return Flw_Piano::Impl::event_key_;
}
| 24.872396 | 104 | 0.564548 | jpcima |
6e8fd61636a4415133c16e1c79dc719373bfd776 | 1,299 | cpp | C++ | UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp | luiscbr92/algorithmic-challenges | bc35729e54e4284e9ade1aa61b51a1c2d72aa62c | [
"MIT"
] | 3 | 2015-10-21T18:56:43.000Z | 2017-06-06T10:44:22.000Z | UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp | luiscbr92/algorithmic-challenges | bc35729e54e4284e9ade1aa61b51a1c2d72aa62c | [
"MIT"
] | null | null | null | UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp | luiscbr92/algorithmic-challenges | bc35729e54e4284e9ade1aa61b51a1c2d72aa62c | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
ios_base::sync_with_stdio (false);
int game = 1;
char field[100][100];
int rows, columns, i, j, count, ii, jj;
string line;
cin >> rows >> columns;
cin.ignore();
while(rows > 0 && columns > 0){
for(i = 0; i < rows; i++){
getline(cin, line);
for(j = 0; j < columns; j++) field[i][j] = line[j];
}
if(game > 1) cout << endl;
cout << "Field #" << game << ":" << endl;
for(i = 0; i < rows; i++){
for(j = 0; j < columns; j++){
if(field[i][j] == '*') cout << '*';
else{
count = 0;
for(ii = i-1; ii <= i+1; ii++){
if(ii < 0 || ii >= rows) continue;
for(jj = j-1; jj <= j+1; jj++){
if(jj < 0 || jj >= columns) continue;
if(ii == i && jj == j) continue;
if(field[ii][jj] == '*') count +=1;
}
}
cout << count;
}
}
cout << endl;
}
cin >> rows >> columns;
cin.ignore();
game +=1;
}
return 0;
}
| 25.470588 | 65 | 0.345651 | luiscbr92 |
6e96f5995213da096cfa6fade9cccfd43d3c8f5f | 3,558 | cpp | C++ | src/data/resources.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | src/data/resources.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | src/data/resources.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | #include <string>
#include <algorithm>
#include "resources/VarCopy.txt"
#include "resources/anaquin.txt"
#include "resources/VarFlip.txt"
#include "resources/VarTrim.txt"
#include "resources/VarAlign.txt"
#include "resources/VarKmer.txt"
#include "resources/VarGermline.txt"
#include "resources/VarSomatic.txt"
#include "resources/VarConjoint.txt"
#include "resources/VarStructure.txt"
#include "resources/VarCalibrate.txt"
#include "resources/RnaAlign.txt"
#include "resources/RnaReport.txt"
#include "resources/RnaAssembly.txt"
#include "resources/RnaSubsample.txt"
#include "resources/RnaExpression.txt"
#include "resources/RnaFoldChange.txt"
#include "resources/MetaAssembly.txt"
#include "resources/MetaCoverage.txt"
#include "resources/MetaSubsample.txt"
#include "resources/plotCNV.R"
#include "resources/plotFold.R"
#include "resources/plotTROC.R"
#include "resources/plotVGROC.R"
#include "resources/plotVCROC.R"
#include "resources/plotTLODR.R"
#include "resources/plotAllele.R"
#include "resources/plotLinear.R"
#include "resources/plotKAllele.R"
#include "resources/plotConjoint.R"
#include "resources/plotLogistic.R"
#include "resources/report.py"
typedef std::string Scripts;
#define ToString(x) std::string(reinterpret_cast<char*>(x))
Scripts Manual()
{
return ToString(data_manuals_anaquin_txt);
}
Scripts PlotFold() { return ToString(src_r_plotFold_R); }
Scripts PlotCNV() { return ToString(src_r_plotCNV_R); }
Scripts PlotLinear() { return ToString(src_r_plotLinear_R); }
Scripts PlotConjoint() { return ToString(src_r_plotConjoint_R); }
Scripts PlotAllele() { return ToString(src_r_plotAllele_R); }
Scripts PlotKAllele() { return ToString(src_r_plotKAllele_R); }
Scripts PlotLogistic() { return ToString(src_r_plotLogistic_R); }
Scripts RnaAlign() { return ToString(data_manuals_RnaAlign_txt); }
Scripts RnaReport() { return ToString(data_manuals_RnaReport_txt); }
Scripts RnaSubsample() { return ToString(data_manuals_RnaSubsample_txt); }
Scripts RnaAssembly() { return ToString(data_manuals_RnaAssembly_txt); }
Scripts RnaExpression() { return ToString(data_manuals_RnaExpression_txt); }
Scripts RnaFoldChange() { return ToString(data_manuals_RnaFoldChange_txt); }
Scripts VarTrim() { return ToString(data_manuals_VarTrim_txt); }
Scripts VarFlip() { return ToString(data_manuals_VarFlip_txt); }
Scripts VarCopy() { return ToString(data_manuals_VarCopy_txt); }
Scripts VarAlign() { return ToString(data_manuals_VarAlign_txt); }
Scripts VarKmer() { return ToString(data_manuals_VarKmer_txt); }
Scripts VarCalibrate() { return ToString(data_manuals_VarCalibrate_txt); }
Scripts VarGermline() { return ToString(data_manuals_VarGermline_txt); }
Scripts VarSomatic() { return ToString(data_manuals_VarSomatic_txt); }
Scripts VarConjoint() { return ToString(data_manuals_VarConjoint_txt); }
Scripts VarStructure() { return ToString(data_manuals_VarStructure_txt); }
Scripts MetaCoverage() { return ToString(data_manuals_MetaCoverage_txt); }
Scripts MetaSubsample() { return ToString(data_manuals_MetaSubsample_txt); }
Scripts MetaAssembly() { return ToString(data_manuals_MetaAssembly_txt); }
Scripts PlotTROC() { return ToString(src_r_plotTROC_R); }
Scripts PlotTLODR() { return ToString(src_r_plotTLODR_R); }
Scripts PlotVGROC() { return ToString(src_r_plotVGROC_R); }
Scripts PlotVCROC() { return ToString(src_r_plotVCROC_R); }
Scripts PythonReport() { return ToString(scripts_report_py); }
| 40.896552 | 79 | 0.769252 | danielnavarrogomez |
6e96facabae3ab4a3127b68592fbc7300e284c49 | 2,610 | cpp | C++ | src/lib/netlist/devices/nld_7493.cpp | mamedev/netedit | 815723fc4772ee7f47558d1a63abc189a65e01b6 | [
"BSD-3-Clause"
] | 3 | 2017-04-12T16:13:34.000Z | 2021-02-24T03:42:19.000Z | src/lib/netlist/devices/nld_7493.cpp | mamedev/netedit | 815723fc4772ee7f47558d1a63abc189a65e01b6 | [
"BSD-3-Clause"
] | null | null | null | src/lib/netlist/devices/nld_7493.cpp | mamedev/netedit | 815723fc4772ee7f47558d1a63abc189a65e01b6 | [
"BSD-3-Clause"
] | 7 | 2017-01-24T23:07:50.000Z | 2021-01-28T04:10:59.000Z | // license:GPL-2.0+
// copyright-holders:Couriersud
/*
* nld_7493.c
*
*/
#include "nld_7493.h"
#include "nl_setup.h"
namespace netlist
{
namespace devices
{
NETLIB_OBJECT(7493ff)
{
NETLIB_CONSTRUCTOR(7493ff)
, m_I(*this, "CLK")
, m_Q(*this, "Q")
, m_reset(*this, "m_reset", 0)
, m_state(*this, "m_state", 0)
{
}
NETLIB_RESETI();
NETLIB_UPDATEI();
public:
logic_input_t m_I;
logic_output_t m_Q;
state_var_u8 m_reset;
state_var_u8 m_state;
};
NETLIB_OBJECT(7493)
{
NETLIB_CONSTRUCTOR(7493)
, m_R1(*this, "R1")
, m_R2(*this, "R2")
, A(*this, "A")
, B(*this, "B")
, C(*this, "C")
, D(*this, "D")
{
register_subalias("CLKA", A.m_I);
register_subalias("CLKB", B.m_I);
register_subalias("QA", A.m_Q);
register_subalias("QB", B.m_Q);
register_subalias("QC", C.m_Q);
register_subalias("QD", D.m_Q);
connect_late(C.m_I, B.m_Q);
connect_late(D.m_I, C.m_Q);
}
NETLIB_RESETI() { }
NETLIB_UPDATEI();
logic_input_t m_R1;
logic_input_t m_R2;
NETLIB_SUB(7493ff) A;
NETLIB_SUB(7493ff) B;
NETLIB_SUB(7493ff) C;
NETLIB_SUB(7493ff) D;
};
NETLIB_OBJECT_DERIVED(7493_dip, 7493)
{
NETLIB_CONSTRUCTOR_DERIVED(7493_dip, 7493)
{
register_subalias("1", B.m_I);
register_subalias("2", m_R1);
register_subalias("3", m_R2);
// register_subalias("4", ); --> NC
// register_subalias("5", ); --> VCC
// register_subalias("6", ); --> NC
// register_subalias("7", ); --> NC
register_subalias("8", C.m_Q);
register_subalias("9", B.m_Q);
// register_subalias("10", ); -. GND
register_subalias("11", D.m_Q);
register_subalias("12", A.m_Q);
// register_subalias("13", ); -. NC
register_subalias("14", A.m_I);
}
};
NETLIB_RESET(7493ff)
{
m_reset = 1;
m_state = 0;
m_I.set_state(logic_t::STATE_INP_HL);
}
NETLIB_UPDATE(7493ff)
{
constexpr netlist_time out_delay = NLTIME_FROM_NS(18);
if (m_reset)
{
m_state ^= 1;
m_Q.push(m_state, out_delay);
}
}
NETLIB_UPDATE(7493)
{
const netlist_sig_t r = m_R1() & m_R2();
if (r)
{
A.m_I.inactivate();
B.m_I.inactivate();
A.m_Q.push(0, NLTIME_FROM_NS(40));
B.m_Q.push(0, NLTIME_FROM_NS(40));
C.m_Q.push(0, NLTIME_FROM_NS(40));
D.m_Q.push(0, NLTIME_FROM_NS(40));
A.m_reset = B.m_reset = C.m_reset = D.m_reset = 0;
A.m_state = B.m_state = C.m_state = D.m_state = 0;
}
else
{
A.m_I.activate_hl();
B.m_I.activate_hl();
A.m_reset = B.m_reset = C.m_reset = D.m_reset = 1;
}
}
NETLIB_DEVICE_IMPL(7493)
NETLIB_DEVICE_IMPL(7493_dip)
} //namespace devices
} // namespace netlist
| 18.913043 | 56 | 0.628352 | mamedev |
6e99926adbca19f6123b18b537f0df682fbdc9c6 | 1,031 | cpp | C++ | compiler-rt/test/tsan/custom_mutex3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | compiler-rt/test/tsan/custom_mutex3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | compiler-rt/test/tsan/custom_mutex3.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clangxx_tsan -O1 --std=c++11 %s -o %t
// RUN: %env_tsan_opts=report_destroy_locked=0 %run %t 2>&1 | FileCheck %s
#include "custom_mutex.h"
// Regression test for a bug.
// Thr1 destroys a locked mutex, previously such mutex was not removed from
// sync map and as the result subsequent uses of a mutex located at the same
// address caused false race reports.
Mutex mu(false, __tsan_mutex_write_reentrant);
long data;
void *thr1(void *arg) {
mu.Lock();
mu.~Mutex();
new(&mu) Mutex(true, __tsan_mutex_write_reentrant);
return 0;
}
void *thr2(void *arg) {
barrier_wait(&barrier);
mu.Lock();
data++;
mu.Unlock();
return 0;
}
int main() {
barrier_init(&barrier, 2);
pthread_t th;
pthread_create(&th, 0, thr1, 0);
pthread_join(th, 0);
barrier_init(&barrier, 2);
pthread_create(&th, 0, thr2, 0);
mu.Lock();
data++;
mu.Unlock();
barrier_wait(&barrier);
pthread_join(th, 0);
fprintf(stderr, "DONE\n");
return 0;
}
// CHECK-NOT: WARNING: ThreadSanitizer: data race
// CHECK: DONE
| 21.93617 | 76 | 0.673133 | medismailben |
6e9a8efb9828b129ea420d8fbc55b1e351bdceb9 | 6,287 | cpp | C++ | hpritl/bicgstab.cpp | stillwater-sc/hpr-itl | b9cb650054be432189257e51af943138f3970eee | [
"MIT"
] | null | null | null | hpritl/bicgstab.cpp | stillwater-sc/hpr-itl | b9cb650054be432189257e51af943138f3970eee | [
"MIT"
] | null | null | null | hpritl/bicgstab.cpp | stillwater-sc/hpr-itl | b9cb650054be432189257e51af943138f3970eee | [
"MIT"
] | 1 | 2019-10-25T07:09:36.000Z | 2019-10-25T07:09:36.000Z | // hpr-itl bicgstab.cpp: HPR Bi-Conjugate Gradient Stabilized algorithm
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "common.hpp"
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <posit>
// MTL
#define MTL_VERBOSE_ITERATION
#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>
// defines all Krylov solvers
// CG, CGS, BiCG, BiCGStab, BiCGStab2, BiCGStab_ell, FSM, IDRs, GMRES TFQMR, QMR, PC
namespace hpr {
template<typename Vector, size_t nbits, size_t es, size_t capacity = 10>
sw::unum::posit<nbits, es> fused_dot(const Vector& x, const Vector& y) {
sw::unum::quire<nbits, es, capacity> q = 0;
size_t ix, iy, n = size(x);
for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + 1, iy = iy + 1) {
q += sw::unum::quire_mul(x[ix], y[iy]);
}
sw::unum::posit<nbits, es> sum;
convert(q.to_value(), sum); // one and only rounding step of the fused-dot product
return sum;
}
/// Bi-Conjugate Gradient Stabilized
template < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB,
class Preconditioner, class Iteration >
int bicgstab(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b,
const Preconditioner& M, Iteration& iter)
{
typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;
typedef HilbertSpaceX Vector;
mtl::vampir_trace<7004> tracer;
constexpr size_t nbits = Scalar::nbits;
constexpr size_t es = Scalar::es;
Scalar rho_1(0), rho_2(0), alpha(0), beta(0), gamma, omega(0);
Vector p(resource(x)), phat(resource(x)), s(resource(x)), shat(resource(x)),
t(resource(x)), v(resource(x)), r(resource(x)), rtilde(resource(x));
r = b - A * x;
rtilde = r;
while (!iter.finished(r)) {
++iter;
rho_1 = fused_dot<Vector, nbits, es>(rtilde, r);
MTL_THROW_IF(rho_1 == 0.0, itl::unexpected_orthogonality());
if (iter.first())
p = r;
else {
MTL_THROW_IF(omega == 0.0, itl::unexpected_orthogonality());
beta = (rho_1 / rho_2) * (alpha / omega);
p = r + beta * (p - omega * v);
}
phat = solve(M, p);
v = A * phat;
gamma = fused_dot<Vector, nbits, es>(rtilde, v);
MTL_THROW_IF(gamma == 0.0, itl::unexpected_orthogonality());
alpha = rho_1 / gamma;
s = r - alpha * v;
if (iter.finished(s)) {
x += alpha * phat;
break;
}
shat = solve(M, s);
t = A * shat;
omega = fused_dot<Vector, nbits, es>(t, s) / fused_dot<Vector, nbits, es>(t, t);
x += omega * shat + alpha * phat;
r = s - omega * t;
rho_2 = rho_1;
}
return iter;
}
} // namespace hpr
template<typename Scalar>
void regular_BiCGStab() {
using namespace std;
const size_t size = 40, N = size * size;
using Matrix = mtl::mat::compressed2D< Scalar >;
using Vector = mtl::vec::dense_vector< Scalar >;
// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil
Matrix A(N, N);
mtl::mat::laplacian_setup(A, size, size);
// Create an ILU(0) preconditioner
itl::pc::ilu_0< Matrix > P(A);
// Set b such that x == 1 is solution; start with x == 0
mtl::vec::dense_vector<Scalar> x(N, 1.0), b(N);
b = A * x; x = 0;
// Termination criterion: r < 1e-6 * b or N iterations
itl::noisy_iteration< Scalar > iter(b, 5, (Scalar)1.e-6);
// Solve Ax == b with left preconditioner P
itl::bicgstab(A, x, b, P, iter);
}
template<typename Scalar>
void fdp_BiCGStab() {
using namespace std;
const size_t size = 40, N = size * size;
using Matrix = mtl::mat::compressed2D< Scalar >;
using Vector = mtl::vec::dense_vector< Scalar >;
// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil
Matrix A(N, N);
mtl::mat::laplacian_setup(A, size, size);
// Create an ILU(0) preconditioner
itl::pc::ilu_0< Matrix > P(A);
// Set b such that x == 1 is solution; start with x == 0
mtl::vec::dense_vector<Scalar> x(N, 1.0), b(N);
b = A * x; x = 0;
// Termination criterion: r < 1e-6 * b or N iterations
itl::noisy_iteration< Scalar > iter(b, 5, 1.e-6);
// Solve Ax == b with left preconditioner P
hpr::bicgstab(A, x, b, P, iter);
}
int main(int, char**)
{
using namespace std;
using namespace mtl;
constexpr size_t nbits = 32;
constexpr size_t es = 2;
using Scalar = sw::unum::posit<nbits, es>;
regular_BiCGStab<float>();
fdp_BiCGStab< sw::unum::posit<32, 2> >();
fdp_BiCGStab< sw::unum::posit<24, 3> >();
return 0;
}
void debugging() {
using namespace std;
using namespace mtl;
constexpr size_t nbits = 32;
constexpr size_t es = 2;
using Scalar = sw::unum::posit<nbits, es>;
{
size_t nrElements = 4;
std::vector<double> data = { -0.25, -0.25, 0.25, 0.25 };
//std::vector<double> data = { 1, -1, 1, -1 };
vec::dense_vector< double> dv(nrElements);
vec::dense_vector< Scalar > pv(nrElements);
{
double n2 = 0;
Scalar p2 = 0;
int i = 0;
for (auto v : data) {
dv(i) = v;
pv(i) = v;
++i;
n2 += v*v;
cout << pretty_print(Scalar(v)*Scalar(v)) << endl;
p2 += Scalar(v)*Scalar(v);
}
cout << "n2 = " << n2 << " sqrt(n2) = " << sqrt(n2) << endl;
cout << "p2 = " << p2 << " sqrt(p2) = " << sqrt(p2) << endl;
}
cout << setprecision(10);
cout << "data elements = " << dv << endl;
cout << "||vector<double>|| = " << two_norm(dv) << endl;
cout << "||vector<posit>|| = " << two_norm(pv) << endl;
//Scalar r = two_norm(pv);
Scalar x = -0.25;
Scalar a;
a = abs(x);
cout << "abs(-0.25) " << a << endl;
}
{
std::vector<double> data = { -0.174422, +0.104777, +0.0490646, +0.0335677, -0.033611, +0.104777, +0.393583, +0.339555, +0.347771, +0.0403458, +0.0490646, +0.339555, +0.305213, +0.354414, +0.0556945, +0.0335677, +0.347771, +0.354414, +0.426084, +0.132617, -0.033611, +0.0403458, +0.0556945, +0.132617, -0.174422 };
vec::dense_vector< double> dv(25);
vec::dense_vector< Scalar > pv(25);
// || r || = +44.4951
{
int i = 0;
for (auto v : data) {
dv(i) = v;
pv(i) = v;
++i;
}
}
cout << "||vector<double>|| = " << two_norm(dv) << endl;
cout << "||vector<posit>|| = " << two_norm(pv) << endl;
Scalar r = two_norm(pv);
}
} | 27.818584 | 315 | 0.610943 | stillwater-sc |
6e9ea6e4b61a6d3da6cf48e4f2cf9a035fa43ea1 | 6,118 | hpp | C++ | cvlib/include/cvlib.hpp | Pol22/cvclasses18 | 94c3b398349c739dcbce5e02b0e9a277456cd85b | [
"MIT"
] | null | null | null | cvlib/include/cvlib.hpp | Pol22/cvclasses18 | 94c3b398349c739dcbce5e02b0e9a277456cd85b | [
"MIT"
] | null | null | null | cvlib/include/cvlib.hpp | Pol22/cvclasses18 | 94c3b398349c739dcbce5e02b0e9a277456cd85b | [
"MIT"
] | 1 | 2019-12-22T12:51:06.000Z | 2019-12-22T12:51:06.000Z | /* Computer Vision Functions.
* @file
* @date 2018-09-05
* @author Anonymous
*/
#ifndef __CVLIB_HPP__
#define __CVLIB_HPP__
#include <opencv2/opencv.hpp>
namespace cvlib
{
/// \brief Split and merge algorithm for image segmentation
/// \param image, in - input image
/// \param stddev, in - threshold to treat regions as homogeneous
/// \return segmented image
cv::Mat split_and_merge(const cv::Mat& image, double stddev);
cv::Mat only_split(const cv::Mat& image, double stddev);
/// \brief Segment texuture on passed image according to sample in ROI
/// \param image, in - input image
/// \param roi, in - region with sample texture on passed image
/// \param eps, in - threshold parameter for texture's descriptor distance
/// \return binary mask with selected texture
cv::Mat select_texture(const cv::Mat& image, const cv::Rect& roi, double eps, void* data);
struct GMM
{
float weight = 0.0;
float mean[3] = { 0.0, 0.0, 0.0 }; // mean RGB
float variance = 0.0;
float significants = 0.0; // weight / variance = which Gaussians shoud be part of bg
};
/// \brief Motion Segmentation algorithm
class motion_segmentation : public cv::BackgroundSubtractor
{
public:
/// \brief ctor
motion_segmentation() {}
~motion_segmentation()
{
if (modes != nullptr)
delete[] modes;
}
void reinit();
void setVarThreshold(int threshold);
/// \see cv::BackgroundSubtractor::apply
void apply(cv::InputArray image, cv::OutputArray fgmask, double learningRate = -1) override;
/// \see cv::BackgroundSubtractor::BackgroundSubtractor
void getBackgroundImage(cv::OutputArray backgroundImage) const override
{
//backgroundImage.assign(bg_model_);
}
private:
void createModel(cv::Size size);
int substractPixel(long posPixel, const cv::Scalar pixelRGB, uchar& numModes);
float bg_threshold;
float m_variance;
GMM* modes; // gaussian mixture model
cv::Mat modes_per_pixel;
cv::Mat bg_model;
float alpha = 1.0 / 50;
unsigned number_of_frames = 2;
const int max_modes = 3;
static const int BACKGROUND = 0;
static const int FOREGROUND = 255;
};
/// \brief FAST corner detection algorithm
class corner_detector_fast : public cv::Feature2D
{
public:
corner_detector_fast();
/// \brief Fabrique method for creating FAST detector
static cv::Ptr<corner_detector_fast> create();
/// \see Feature2d::detect
virtual void detect(cv::InputArray image, CV_OUT std::vector<cv::KeyPoint>& keypoints, cv::InputArray mask = cv::noArray()) override;
/// \see Feature2d::compute
virtual void compute(cv::InputArray image, std::vector<cv::KeyPoint>& keypoints, cv::OutputArray descriptors) override;
/// \see Feature2d::detectAndCompute
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask, std::vector<cv::KeyPoint>& keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) override;
/// \see Feature2d::getDefaultName
virtual cv::String getDefaultName() const override
{
return "FAST_Binary";
}
private:
int getShift(const int& index) const;
char checkDarkerOrBrighter(const uchar* pixel, const uchar* neighbour) const;
bool highSpeedTest(const uchar* pixel) const;
bool pointOnImage(const cv::Mat& image, const cv::Point2f& point);
int twoPointsTest(const cv::Mat& image, const cv::Point2f& point1, const cv::Point2f& point2, const int& num);
void binaryTest(const cv::Mat& image, const cv::Point2f& keypoint, int* descriptor);
// detector
static const int number_of_circle_pixels = 16;
static const int number_non_similar_pixels = 12;
static const uchar threshold = 30;
static const int roi_mask_size = 7;
char circle_pixels[number_of_circle_pixels + 1];
char int_circle_pixels[number_of_circle_pixels + number_non_similar_pixels + 1];
int width = 0;
int end_j;
int end_i;
// extractor
static const int S = 15;
static const int desc_length = 8; // 32 * 8 = 256
static const int all_length = desc_length * 32; // 256
cv::Point2f test_points1[all_length];
cv::Point2f test_points2[all_length];
cv::RNG rng;
};
/// \brief Descriptor matched based on ratio of SSD
class descriptor_matcher : public cv::DescriptorMatcher
{
public:
/// \brief ctor
descriptor_matcher(float ratio = 1.5) : ratio_(ratio) {}
/// \brief setup ratio threshold for SSD filtering
void set_ratio(float r)
{
ratio_ = r;
}
protected:
/// \see cv::DescriptorMatcher::knnMatchImpl
void knnMatchImpl(cv::InputArray queryDescriptors, std::vector<std::vector<cv::DMatch>>& matches, int k,
cv::InputArrayOfArrays masks = cv::noArray(), bool compactResult = false) override;
/// \see cv::DescriptorMatcher::radiusMatchImpl
void radiusMatchImpl(cv::InputArray queryDescriptors, std::vector<std::vector<cv::DMatch>>& matches, float maxDistance,
cv::InputArrayOfArrays masks = cv::noArray(), bool compactResult = false) override;
/// \see cv::DescriptorMatcher::isMaskSupported
bool isMaskSupported() const override
{
return false;
}
/// \see cv::DescriptorMatcher::isMaskSupported
cv::Ptr<cv::DescriptorMatcher> clone(bool emptyTrainData = false) const override
{
cv::Ptr<cv::DescriptorMatcher> copy = new descriptor_matcher(*this);
if (emptyTrainData)
{
copy->clear();
}
return copy;
}
private:
int hamming_distance(int* x1, int* x2);
float ratio_;
int desc_length = 0;
};
/// \brief Stitcher for merging images into big one
class Stitcher
{
public:
Stitcher() = default;
~Stitcher() { detector.release(); }
void setReference(cv::Mat& img);
cv::Mat stitch(cv::Mat& img);
private:
cv::Ptr<cvlib::corner_detector_fast> detector = cvlib::corner_detector_fast::create();
cvlib::descriptor_matcher matcher;
cv::Mat ref_img;
std::vector<cv::KeyPoint> ref_keypoints;
cv::Mat ref_descriptors;
static constexpr float max_distance = 100.0f;
};
} // namespace cvlib
#endif // __CVLIB_HPP__
| 31.374359 | 143 | 0.695652 | Pol22 |
6ea09188ed70c796d8f58ef20a5909ecc3062b2b | 351 | cpp | C++ | src/musl/poll.cpp | paulyc/IncludeOS | 5c82bad4a22838bc2219fbadef57d94f006b4760 | [
"Apache-2.0"
] | 5 | 2016-10-01T11:50:51.000Z | 2019-10-24T12:54:36.000Z | src/musl/poll.cpp | paulyc/IncludeOS | 5c82bad4a22838bc2219fbadef57d94f006b4760 | [
"Apache-2.0"
] | 1 | 2016-11-25T22:37:41.000Z | 2016-11-25T22:37:41.000Z | src/musl/poll.cpp | paulyc/IncludeOS | 5c82bad4a22838bc2219fbadef57d94f006b4760 | [
"Apache-2.0"
] | 3 | 2016-09-28T18:15:50.000Z | 2017-07-18T17:02:25.000Z | #include "stub.hpp"
#include <poll.h>
static long sys_poll(struct pollfd *fds, nfds_t nfds, int /*timeout*/)
{
for (nfds_t i = 0; i < nfds; i++)
{
fds[i].revents = fds[i].events;
}
return nfds;
}
extern "C"
long syscall_SYS_poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
return stubtrace(sys_poll, "poll", fds, nfds, timeout);
}
| 19.5 | 70 | 0.655271 | paulyc |
6ea1b3c0fb1d8209dbb6367eb49c38c79242a5ff | 2,842 | cpp | C++ | source/playlunky/mod/fix_mod_structure.cpp | C-ffeeStain/Playlunky | c0df8a993712192fb44048c8542776ead110441d | [
"MIT"
] | null | null | null | source/playlunky/mod/fix_mod_structure.cpp | C-ffeeStain/Playlunky | c0df8a993712192fb44048c8542776ead110441d | [
"MIT"
] | null | null | null | source/playlunky/mod/fix_mod_structure.cpp | C-ffeeStain/Playlunky | c0df8a993712192fb44048c8542776ead110441d | [
"MIT"
] | null | null | null | #include "unzip_mod.h"
#include "log.h"
#include "util/algorithms.h"
#include "util/regex.h"
static constexpr ctll::fixed_string s_FontRule{ ".*\\.fnb" };
static constexpr std::string_view s_FontTargetPath{ "Data/Fonts" };
static constexpr ctll::fixed_string s_ArenaLevelRule{ "dm.*\\.lvl" };
static constexpr ctll::fixed_string s_ArenaLevelTokRule{ ".*\\.tok" };
static constexpr std::string_view s_ArenaLevelTargetPath{ "Data/Levels/Arena" };
static constexpr ctll::fixed_string s_LevelRule{ ".*\\.lvl" };
static constexpr std::string_view s_LevelTargetPath{ "Data/Levels" };
static constexpr ctll::fixed_string s_OldTextureRule{ "ai\\.(DDS|png)" };
static constexpr std::string_view s_OldTextureTargetPath{ "Data/Textures/OldTextures" };
static constexpr ctll::fixed_string s_FullTextureRule{ ".*_full\\.(DDS|png)" };
static constexpr std::string_view s_FullTextureTargetPath{ "Data/Textures/Merged" };
static constexpr ctll::fixed_string s_TextureRule{ ".*\\.(DDS|png)" };
static constexpr std::string_view s_TextureTargetPath{ "Data/Textures" };
void FixModFolderStructure(const std::filesystem::path& mod_folder) {
namespace fs = std::filesystem;
struct PathMapping {
fs::path CurrentPath;
fs::path TargetPath;
};
std::vector<PathMapping> path_mappings;
const auto db_folder = mod_folder / ".db";
for (const auto& path : fs::recursive_directory_iterator(mod_folder)) {
if (fs::is_regular_file(path) && !algo::is_sub_path(path, db_folder)) {
const auto file_name = path.path().filename().string();
if (ctre::match<s_FontRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_FontTargetPath / file_name });
}
else if (ctre::match<s_ArenaLevelRule>(file_name) || ctre::match<s_ArenaLevelTokRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_ArenaLevelTargetPath / file_name });
}
else if (ctre::match<s_LevelRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_LevelTargetPath / file_name });
}
else if (ctre::match<s_OldTextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_OldTextureTargetPath / file_name });
}
else if (ctre::match<s_FullTextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_FullTextureTargetPath / file_name });
}
else if (ctre::match<s_TextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_TextureTargetPath / file_name });
}
else {
path_mappings.push_back({ path, mod_folder / file_name });
}
}
}
for (auto& [current_path, target_path] : path_mappings) {
if (current_path != target_path) {
{
const auto target_parent_path = target_path.parent_path();
if (!fs::exists(target_parent_path)) {
fs::create_directories(target_parent_path);
}
}
fs::rename(current_path, target_path);
}
}
} | 37.893333 | 102 | 0.724138 | C-ffeeStain |
6ea3c7dba877c577794b2a764d864917f79e3026 | 631 | cpp | C++ | Sculptor2_0/putbox.cpp | igorsergioJS/sculptor-2.0 | c4224d8485dfb0305bb5ebc8c816c527c8c6f698 | [
"MIT"
] | null | null | null | Sculptor2_0/putbox.cpp | igorsergioJS/sculptor-2.0 | c4224d8485dfb0305bb5ebc8c816c527c8c6f698 | [
"MIT"
] | null | null | null | Sculptor2_0/putbox.cpp | igorsergioJS/sculptor-2.0 | c4224d8485dfb0305bb5ebc8c816c527c8c6f698 | [
"MIT"
] | null | null | null | #include "putbox.h"
PutBox::PutBox(int x0, int x1, int y0, int y1, int z0, int z1, float r, float g, float b, float a)
{
this->x0 = x0;
this->x1 = x1;
this->y0 = y0;
this->y1 = y1;
this->z0 = z0;
this->z1 = z1;
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
PutBox::~PutBox()
{
}
void PutBox::draw(Sculptor &t)
{
for(int i=x0;i<x1;i++)
{
for(int j=y0;j<y1;j++)
{
for(int k=z0;k<z1;k++)
{
t.setColor(r,g,b,a);
t.putVoxel(i,j,k);
}
}
}
}
| 17.527778 | 98 | 0.397781 | igorsergioJS |
6ea4430ee8412eaa0f0e3d093e9038a3ec51d343 | 1,118 | cpp | C++ | src/ServiceDescription.cpp | ruurdadema/dnssd | 5c444ed901d177e57dd7f9338cf9466fa12f7794 | [
"MIT"
] | null | null | null | src/ServiceDescription.cpp | ruurdadema/dnssd | 5c444ed901d177e57dd7f9338cf9466fa12f7794 | [
"MIT"
] | 1 | 2022-02-25T19:03:49.000Z | 2022-02-25T19:03:49.000Z | src/ServiceDescription.cpp | ruurdadema/dnssd | 5c444ed901d177e57dd7f9338cf9466fa12f7794 | [
"MIT"
] | null | null | null | #include <dnssd/ServiceDescription.h>
#include <sstream>
using namespace dnssd;
std::string ServiceDescription::description() const noexcept
{
std::string txtRecordDescription;
for (auto& kv : txtRecord)
{
txtRecordDescription += kv.first;
txtRecordDescription += "=";
txtRecordDescription += kv.second;
txtRecordDescription += ", ";
}
std::string addressesDescription;
for (auto& interface : interfaces)
{
addressesDescription += "interface ";
addressesDescription += std::to_string(interface.first);
addressesDescription += ": ";
for (auto& addr : interface.second)
{
addressesDescription += addr;
addressesDescription += ", ";
}
}
std::stringstream output;
output
<< "fullname: " << fullname
<< ", name: " << name
<< ", type: " << type
<< ", domain: " << domain
<< ", hostTarget: " << hostTarget
<< ", port: " << port
<< ", txtRecord: " << txtRecordDescription
<< "addresses: " << addressesDescription;
return output.str();
}
| 23.787234 | 64 | 0.580501 | ruurdadema |
6ea4728f3dd90a5457945af3a0aec7c0fe3ebe7d | 601 | cpp | C++ | cpp/codefestival_2016_qualB_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/codefestival_2016_qualB_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/codefestival_2016_qualB_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int N, A, B;
cin >> N >> A >> B;
string S;
cin >> S;
int total_pass = 0;
int b_rank = 0;
for(int i = 0; i < S.size(); i++) {
if(S[i] == 'b') {
b_rank += 1;
}
if(S[i] == 'a' && total_pass < (A+B)) {
total_pass += 1;
cout << "Yes" << endl;
} else if(S[i] == 'b' && total_pass < (A+B) && b_rank <= B) {
total_pass += 1;
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
| 19.387097 | 69 | 0.371048 | kokosabu |
6ea61efaeacce9a946491e7f090cb47b8d85d3f0 | 3,576 | hpp | C++ | src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp | AlexWayfer/RankCheck | cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014 | [
"Unlicense",
"MIT"
] | 10 | 2018-02-12T16:14:07.000Z | 2022-03-19T15:08:29.000Z | src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp | AlexWayfer/RankCheck | cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014 | [
"Unlicense",
"MIT"
] | 11 | 2018-02-08T16:46:49.000Z | 2022-02-03T20:48:12.000Z | src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp | AlexWayfer/RankCheck | cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014 | [
"Unlicense",
"MIT"
] | 3 | 2018-02-12T22:08:55.000Z | 2021-06-24T16:29:17.000Z | #ifndef SRC_CLIENT_GUI3_WIDGETS_ABSTRACTPANEL_HPP_
#define SRC_CLIENT_GUI3_WIDGETS_ABSTRACTPANEL_HPP_
#include <Client/GUI3/Container.hpp>
#include <Client/GUI3/Events/Callback.hpp>
#include <Client/GUI3/Events/StateEvent.hpp>
#include <Client/GUI3/Types.hpp>
#include <SFML/System/Vector2.hpp>
#include <algorithm>
#include <memory>
#include <vector>
namespace gui3
{
struct EmptyPanelData
{
};
/**
* Simple container without automatic layout management.
*/
template<typename ExtraData = EmptyPanelData>
class AbstractPanel : public Container
{
public:
AbstractPanel() :
myWidgetScale(1, 1)
{
}
virtual ~AbstractPanel()
{
while (!myOwnedWidgets.empty())
{
dropOwnership(myOwnedWidgets.end() - 1);
}
}
protected:
/**
* Adds the widget to the container, leaving lifetime management up to the caller.
*
* Call this function inside the "add" function of subclasses.
*/
bool own(Ptr<Widget> widget)
{
if (takeOwnership(widget))
{
return addWidget(*widget);
}
else
{
return false;
}
}
/**
* Removes the widget from the container.
*
* If the widget is owned by this container, it is automatically deallocated.
*
* Call this function inside the "remove" function of subclasses.
*/
bool disown(Widget& widget)
{
if (removeWidget(widget))
{
return dropOwnership(widget);
}
else
{
return false;
}
}
/**
* Returns a pointer to a custom data structure holding information for a specific widget in the panel.
*/
ExtraData * getWidgetData(Widget & widget) const
{
auto it = findWidget(widget);
if (it == myOwnedWidgets.end() || it->widget.get() != &widget)
{
return nullptr;
}
return it->data.get();
}
private:
struct OwnedWidget
{
Ptr<Widget> widget;
std::unique_ptr<ExtraData> data;
CallbackHandle<StateEvent> callback;
};
bool takeOwnership(Ptr<Widget> widget)
{
if (widget == nullptr)
{
return false;
}
auto it = findWidget(*widget);
Widget* widgetPointer = widget.get();
if (it != myOwnedWidgets.end() && it->widget.get() == widgetPointer)
{
return false;
}
auto func = [this, widgetPointer](StateEvent event)
{
if (widgetPointer->getParent() != this)
{
dropOwnership(*widgetPointer);
}
};
OwnedWidget info;
info.widget = widget;
info.data = makeUnique<ExtraData>();
info.callback = widget->addStateCallback(std::move(func), StateEvent::ParentChanged, 0);
myOwnedWidgets.insert(it, std::move(info));
return true;
}
bool dropOwnership(Widget& widget)
{
auto it = findWidget(widget);
if (it == myOwnedWidgets.end() || it->widget.get() != &widget)
{
return false;
}
dropOwnership(it);
return true;
}
void dropOwnership(typename std::vector<OwnedWidget>::iterator it)
{
myDisownedWidgets.push_back(std::move(*it));
myOwnedWidgets.erase(it);
invokeLater([=]
{
myDisownedWidgets.clear();
});
}
typename std::vector<OwnedWidget>::iterator findWidget(Widget & widget)
{
return std::lower_bound(myOwnedWidgets.begin(), myOwnedWidgets.end(), &widget,
[](const OwnedWidget& left, Widget* right)
{
return left.widget.get() < right;
});
}
typename std::vector<OwnedWidget>::const_iterator findWidget(Widget & widget) const
{
return std::lower_bound(myOwnedWidgets.begin(), myOwnedWidgets.end(), &widget,
[](const OwnedWidget& left, Widget* right)
{
return left.widget.get() < right;
});
}
std::vector<OwnedWidget> myOwnedWidgets;
std::vector<OwnedWidget> myDisownedWidgets;
sf::Vector2f myWidgetScale;
};
}
#endif
| 19.021277 | 104 | 0.682606 | AlexWayfer |
6ea7a381371e7b64f10f2b39a65c8c700401b0b4 | 13,376 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qitemmodel/modelstotest.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qitemmodel/modelstotest.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qitemmodel/modelstotest.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <QtSql/QtSql>
#include <QtWidgets/QtWidgets>
#include <QtCore/QSortFilterProxyModel>
/*
To add a model to be tested add the header file to the includes
and impliment what is needed in the four functions below.
You can add more then one model, several Qt models and included as examples.
In tst_qitemmodel.cpp a new ModelsToTest object is created for each test.
When you have errors fix the first ones first. Later tests depend upon them working
*/
class ModelsToTest {
public:
ModelsToTest();
QAbstractItemModel *createModel(const QString &modelType);
QModelIndex populateTestArea(QAbstractItemModel *model);
void cleanupTestArea(QAbstractItemModel *model);
enum Read {
ReadOnly, // won't perform remove(), insert(), and setData()
ReadWrite
};
enum Contains {
Empty, // Confirm that rowCount() == 0 etc throughout the test
HasData // Confirm that rowCount() != 0 etc throughout the test
};
struct test {
test(QString m, Read r, Contains c) : modelType(m), read(r), contains(c){};
QString modelType;
Read read;
Contains contains;
};
QList<test> tests;
static void setupDatabase();
private:
QScopedPointer<QTemporaryDir> m_dirModelTempDir;
};
/*!
Add new tests, they can be the same model, but in a different state.
The name of the model is passed to createModel
If readOnly is true the remove tests will be skipped. Example: QDirModel is disabled.
If createModel returns an empty model. Example: QDirModel does not
*/
ModelsToTest::ModelsToTest()
{
setupDatabase();
tests.append(test("QDirModel", ReadOnly, HasData));
tests.append(test("QStringListModel", ReadWrite, HasData));
tests.append(test("QStringListModelEmpty", ReadWrite, Empty));
tests.append(test("QStandardItemModel", ReadWrite, HasData));
tests.append(test("QStandardItemModelEmpty", ReadWrite, Empty));
// QSortFilterProxyModel test uses QStandardItemModel so test it first
tests.append(test("QSortFilterProxyModel", ReadWrite, HasData));
tests.append(test("QSortFilterProxyModelEmpty", ReadWrite, Empty));
tests.append(test("QSortFilterProxyModelRegExp", ReadWrite, HasData));
tests.append(test("QListModel", ReadWrite, HasData));
tests.append(test("QListModelEmpty", ReadWrite, Empty));
tests.append(test("QTableModel", ReadWrite, HasData));
tests.append(test("QTableModelEmpty", ReadWrite, Empty));
tests.append(test("QTreeModel", ReadWrite, HasData));
tests.append(test("QTreeModelEmpty", ReadWrite, Empty));
tests.append(test("QSqlQueryModel", ReadOnly, HasData));
tests.append(test("QSqlQueryModelEmpty", ReadOnly, Empty));
// Fails on remove
tests.append(test("QSqlTableModel", ReadOnly, HasData));
}
/*!
Return a new modelType.
*/
QAbstractItemModel *ModelsToTest::createModel(const QString &modelType)
{
if (modelType == "QStringListModelEmpty")
return new QStringListModel();
if (modelType == "QStringListModel") {
QStringListModel *model = new QStringListModel();
populateTestArea(model);
return model;
}
if (modelType == "QStandardItemModelEmpty") {
return new QStandardItemModel();
}
if (modelType == "QStandardItemModel") {
QStandardItemModel *model = new QStandardItemModel();
populateTestArea(model);
return model;
}
if (modelType == "QSortFilterProxyModelEmpty") {
QSortFilterProxyModel *model = new QSortFilterProxyModel;
QStandardItemModel *standardItemModel = new QStandardItemModel;
model->setSourceModel(standardItemModel);
return model;
}
if (modelType == "QSortFilterProxyModelRegExp") {
QSortFilterProxyModel *model = new QSortFilterProxyModel;
QStandardItemModel *standardItemModel = new QStandardItemModel;
model->setSourceModel(standardItemModel);
populateTestArea(model);
model->setFilterRegExp(QRegExp("(^$|I.*)"));
return model;
}
if (modelType == "QSortFilterProxyModel") {
QSortFilterProxyModel *model = new QSortFilterProxyModel;
QStandardItemModel *standardItemModel = new QStandardItemModel;
model->setSourceModel(standardItemModel);
populateTestArea(model);
return model;
}
if (modelType == "QDirModel") {
QDirModel *model = new QDirModel();
model->setReadOnly(false);
return model;
}
if (modelType == "QSqlQueryModel") {
QSqlQueryModel *model = new QSqlQueryModel();
populateTestArea(model);
return model;
}
if (modelType == "QSqlQueryModelEmpty") {
QSqlQueryModel *model = new QSqlQueryModel();
return model;
}
if (modelType == "QSqlTableModel") {
QSqlTableModel *model = new QSqlTableModel();
populateTestArea(model);
return model;
}
if (modelType == "QListModelEmpty")
return (new QListWidget)->model();
if (modelType == "QListModel") {
QListWidget *widget = new QListWidget;
populateTestArea(widget->model());
return widget->model();
}
if (modelType == "QTableModelEmpty")
return (new QTableWidget)->model();
if (modelType == "QTableModel") {
QTableWidget *widget = new QTableWidget;
populateTestArea(widget->model());
return widget->model();
}
if (modelType == "QTreeModelEmpty") {
QTreeWidget *widget = new QTreeWidget;
return widget->model();
}
if (modelType == "QTreeModel") {
QTreeWidget *widget = new QTreeWidget;
populateTestArea(widget->model());
return widget->model();
}
return 0;
}
/*!
Fills model with some test data at least twenty rows and if possible twenty or more columns.
Return the parent of a row/column that can be tested.
NOTE: If readOnly is true tests will try to remove and add rows and columns.
If you have a tree model returning not the root index will help catch more errors.
*/
QModelIndex ModelsToTest::populateTestArea(QAbstractItemModel *model)
{
if (QStringListModel *stringListModel = qobject_cast<QStringListModel *>(model)) {
QString alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
stringListModel->setStringList( alphabet.split(QLatin1Char(',')) );
return QModelIndex();
}
if (qobject_cast<QStandardItemModel *>(model)) {
// Basic tree StandardItemModel
QModelIndex parent;
QVariant blue = QVariant(QColor(Qt::blue));
for (int i = 0; i < 4; ++i) {
parent = model->index(0, 0, parent);
model->insertRows(0, 26 + i, parent);
model->insertColumns(0, 4 + i, parent);
// Fill in some values to make it easier to debug
/*
for (int x = 0; x < 26 + i; ++x) {
QString xval = QString::number(x);
for (int y = 0; y < 26 + i; ++y) {
QString val = xval + QString::number(y) + QString::number(i);
QModelIndex index = model->index(x, y, parent);
model->setData(index, val);
model->setData(index, blue, Qt::TextColorRole);
}
}
*/
}
return model->index(0,0);
}
if (qobject_cast<QSortFilterProxyModel *>(model)) {
QAbstractItemModel *realModel = (qobject_cast<QSortFilterProxyModel *>(model))->sourceModel();
// Basic tree StandardItemModel
QModelIndex parent;
QVariant blue = QVariant(QColor(Qt::blue));
for (int i = 0; i < 4; ++i) {
parent = realModel->index(0, 0, parent);
realModel->insertRows(0, 26+i, parent);
realModel->insertColumns(0, 4, parent);
// Fill in some values to make it easier to debug
/*
for (int x = 0; x < 26+i; ++x) {
QString xval = QString::number(x);
for (int y = 0; y < 26 + i; ++y) {
QString val = xval + QString::number(y) + QString::number(i);
QModelIndex index = realModel->index(x, y, parent);
realModel->setData(index, val);
realModel->setData(index, blue, Qt::TextColorRole);
}
}
*/
}
QModelIndex returnIndex = model->index(0,0);
if (!returnIndex.isValid())
qFatal("%s: model index to be returned is invalid", Q_FUNC_INFO);
return returnIndex;
}
if (QDirModel *dirModel = qobject_cast<QDirModel *>(model)) {
m_dirModelTempDir.reset(new QTemporaryDir);
if (!m_dirModelTempDir->isValid())
qFatal("Cannot create temporary directory \"%s\": %s",
qPrintable(QDir::toNativeSeparators(m_dirModelTempDir->path())),
qPrintable(m_dirModelTempDir->errorString()));
QDir tempDir(m_dirModelTempDir->path());
for (int i = 0; i < 26; ++i) {
const QString subdir = QLatin1String("foo_") + QString::number(i);
if (!tempDir.mkdir(subdir))
qFatal("Cannot create directory %s",
qPrintable(QDir::toNativeSeparators(tempDir.path() + QLatin1Char('/') +subdir)));
}
return dirModel->index(tempDir.path());
}
if (QSqlQueryModel *queryModel = qobject_cast<QSqlQueryModel *>(model)) {
QSqlQuery q;
q.exec("CREATE TABLE test(id int primary key, name varchar(30))");
q.prepare("INSERT INTO test(id, name) values (?, ?)");
for (int i = 0; i < 1024; ++i) {
q.addBindValue(i);
q.addBindValue("Mr. Smith" + QString::number(i));
q.exec();
}
if (QSqlTableModel *tableModel = qobject_cast<QSqlTableModel *>(model)) {
tableModel->setTable("test");
tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
tableModel->select();
} else {
queryModel->setQuery("select * from test");
}
return QModelIndex();
}
if (QListWidget *listWidget = qobject_cast<QListWidget *>(model->parent())) {
int items = 50;
while (items--)
listWidget->addItem(QLatin1String("item ") + QString::number(items));
return QModelIndex();
}
if (QTableWidget *tableWidget = qobject_cast<QTableWidget *>(model->parent())) {
tableWidget->setColumnCount(20);
tableWidget->setRowCount(20);
return QModelIndex();
}
if (QTreeWidget *treeWidget = qobject_cast<QTreeWidget *>(model->parent())) {
int topItems = 20;
treeWidget->setColumnCount(1);
QTreeWidgetItem *parent;
while (topItems--){
const QString tS = QString::number(topItems);
parent = new QTreeWidgetItem(treeWidget, QStringList(QLatin1String("top ") + tS));
for (int i = 0; i < 20; ++i)
new QTreeWidgetItem(parent, QStringList(QLatin1String("child ") + tS));
}
return QModelIndex();
}
qFatal("%s: unknown type of model", Q_FUNC_INFO);
return QModelIndex();
}
/*!
If you need to cleanup from populateTest() do it here.
Note that this is called after every test even if populateTestArea isn't called.
*/
void ModelsToTest::cleanupTestArea(QAbstractItemModel *model)
{
if (qobject_cast<QDirModel *>(model)) {
m_dirModelTempDir.reset();
} else if (qobject_cast<QSqlQueryModel *>(model)) {
QSqlQuery q("DROP TABLE test");
}
}
void ModelsToTest::setupDatabase()
{
if (!QSqlDatabase::database().isValid()) {
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
qWarning() << "Unable to open database" << db.lastError();
return;
}
}
}
| 35.107612 | 104 | 0.619767 | GrinCash |
6eaf4b56574eea425bc9c9e89831da13e21e93f2 | 62,518 | cpp | C++ | src/Prey/prey_baseweapons.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | 2 | 2018-08-30T23:48:22.000Z | 2021-04-07T19:16:18.000Z | src/Prey/prey_baseweapons.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | src/Prey/prey_baseweapons.cpp | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | #include "../idlib/precompiled.h"
#pragma hdrstop
#include "prey_local.h"
#define WEAPON_DEBUG if(g_debugWeapon.GetBool()) gameLocal.Warning
/***********************************************************************
hhWeapon
***********************************************************************/
const idEventDef EV_PlayAnimWhenReady( "playAnimWhenReady", "s" );
const idEventDef EV_Weapon_Aside( "<weaponAside>" );
const idEventDef EV_Weapon_EjectAltBrass( "ejectAltBrass" );
const idEventDef EV_Weapon_HasAmmo( "hasAmmo", "", 'd' );
const idEventDef EV_Weapon_HasAltAmmo( "hasAltAmmo", "", 'd' );
const idEventDef EV_Weapon_GetFireDelay( "getFireDelay", "", 'f' );
const idEventDef EV_Weapon_GetAltFireDelay( "getAltFireDelay", "", 'f' );
const idEventDef EV_Weapon_GetSpread( "getSpread", "", 'f' );
const idEventDef EV_Weapon_GetAltSpread( "getAltSpread", "", 'f' );
const idEventDef EV_Weapon_GetString( "getString", "s", 's' );
const idEventDef EV_Weapon_GetAltString( "getAltString", "s", 's' );
const idEventDef EV_Weapon_AddToAltClip( "addToAltClip", "f" );
const idEventDef EV_Weapon_AltAmmoInClip( "altAmmoInClip", "", 'f' );
const idEventDef EV_Weapon_AltAmmoAvailable( "altAmmoAvailable", "", 'f' );
const idEventDef EV_Weapon_AltClipSize( "altClipSize", "", 'f' );
const idEventDef EV_Weapon_FireAltProjectiles( "fireAltProjectiles" );
const idEventDef EV_Weapon_FireProjectiles( "fireProjectiles" );
const idEventDef EV_Weapon_WeaponAside( "weaponAside" ); // nla
const idEventDef EV_Weapon_WeaponPuttingAside( "weaponPuttingAside" ); // nla
const idEventDef EV_Weapon_WeaponUprighting( "weaponUprighting" ); // nla
const idEventDef EV_Weapon_IsAnimPlaying( "isAnimPlaying", "s", 'd' );
const idEventDef EV_Weapon_Raise( "<raise>" ); // nla - For the hands to post an event to raise the weapons
const idEventDef EV_Weapon_SetViewAnglesSensitivity( "setViewAnglesSensitivity", "f" );
const idEventDef EV_Weapon_UseAltAmmo( "useAltAmmo", "d" );
const idEventDef EV_Weapon_Hide( "hideWeapon" );
const idEventDef EV_Weapon_Show( "showWeapon" );
CLASS_DECLARATION( hhAnimatedEntity, hhWeapon )
EVENT( EV_Weapon_FireAltProjectiles, hhWeapon::Event_FireAltProjectiles )
EVENT( EV_Weapon_FireProjectiles, hhWeapon::Event_FireProjectiles )
EVENT( EV_PlayAnimWhenReady, hhWeapon::Event_PlayAnimWhenReady )
EVENT( EV_SpawnFxAlongBone, hhWeapon::Event_SpawnFXAlongBone )
EVENT( EV_Weapon_EjectAltBrass, hhWeapon::Event_EjectAltBrass )
EVENT( EV_Weapon_HasAmmo, hhWeapon::Event_HasAmmo )
EVENT( EV_Weapon_HasAltAmmo, hhWeapon::Event_HasAltAmmo )
EVENT( EV_Weapon_AddToAltClip, hhWeapon::Event_AddToAltClip )
EVENT( EV_Weapon_AltAmmoInClip, hhWeapon::Event_AltAmmoInClip )
EVENT( EV_Weapon_AltAmmoAvailable, hhWeapon::Event_AltAmmoAvailable )
EVENT( EV_Weapon_AltClipSize, hhWeapon::Event_AltClipSize )
EVENT( EV_Weapon_GetFireDelay, hhWeapon::Event_GetFireDelay )
EVENT( EV_Weapon_GetAltFireDelay, hhWeapon::Event_GetAltFireDelay )
EVENT( EV_Weapon_GetString, hhWeapon::Event_GetString )
EVENT( EV_Weapon_GetAltString, hhWeapon::Event_GetAltString )
EVENT( EV_Weapon_Raise, hhWeapon::Event_Raise )
EVENT( EV_Weapon_WeaponAside, hhWeapon::Event_Weapon_Aside )
EVENT( EV_Weapon_WeaponPuttingAside, hhWeapon::Event_Weapon_PuttingAside )
EVENT( EV_Weapon_WeaponUprighting, hhWeapon::Event_Weapon_Uprighting )
EVENT( EV_Weapon_IsAnimPlaying, hhWeapon::Event_IsAnimPlaying )
EVENT( EV_Weapon_SetViewAnglesSensitivity, hhWeapon::Event_SetViewAnglesSensitivity )
EVENT( EV_Weapon_Hide, hhWeapon::Event_HideWeapon )
EVENT( EV_Weapon_Show, hhWeapon::Event_ShowWeapon )
//idWeapon
EVENT( EV_Weapon_State, hhWeapon::Event_WeaponState )
EVENT( EV_Weapon_WeaponReady, hhWeapon::Event_WeaponReady )
EVENT( EV_Weapon_WeaponOutOfAmmo, hhWeapon::Event_WeaponOutOfAmmo )
EVENT( EV_Weapon_WeaponReloading, hhWeapon::Event_WeaponReloading )
EVENT( EV_Weapon_WeaponHolstered, hhWeapon::Event_WeaponHolstered )
EVENT( EV_Weapon_WeaponRising, hhWeapon::Event_WeaponRising )
EVENT( EV_Weapon_WeaponLowering, hhWeapon::Event_WeaponLowering )
EVENT( EV_Weapon_AddToClip, hhWeapon::Event_AddToClip )
EVENT( EV_Weapon_AmmoInClip, hhWeapon::Event_AmmoInClip )
EVENT( EV_Weapon_AmmoAvailable, hhWeapon::Event_AmmoAvailable )
EVENT( EV_Weapon_ClipSize, hhWeapon::Event_ClipSize )
EVENT( AI_PlayAnim, hhWeapon::Event_PlayAnim )
EVENT( AI_PlayCycle, hhWeapon::Event_PlayCycle )
EVENT( AI_AnimDone, hhWeapon::Event_AnimDone )
EVENT( EV_Weapon_Next, hhWeapon::Event_Next )
EVENT( EV_Weapon_Flashlight, hhWeapon::Event_Flashlight )
EVENT( EV_Weapon_EjectBrass, hhWeapon::Event_EjectBrass )
EVENT( EV_Weapon_GetOwner, hhWeapon::Event_GetOwner )
EVENT( EV_Weapon_UseAmmo, hhWeapon::Event_UseAmmo )
EVENT( EV_Weapon_UseAltAmmo, hhWeapon::Event_UseAltAmmo )
END_CLASS
/*
================
hhWeapon::hhWeapon
================
*/
hhWeapon::hhWeapon() {
owner = NULL;
worldModel = NULL;
thread = NULL;
//HUMANHEAD: aob
fireController = NULL;
altFireController = NULL;
fl.networkSync = true;
cameraShakeOffset.Zero(); //rww - had to move here to avoid den/nan/blah in spawn
//HUMANHEAD END
Clear();
}
/*
================
hhWeapon::Spawn
================
*/
void hhWeapon::Spawn() {
//idWeapon
if ( !gameLocal.isClient )
{
worldModel = static_cast< hhAnimatedEntity * >( gameLocal.SpawnEntityType( hhAnimatedEntity::Type, NULL ) );
worldModel.GetEntity()->fl.networkSync = true;
}
thread = new idThread();
thread->ManualDelete();
thread->ManualControl();
//idWeapon End
physicsObj.SetSelf( this );
physicsObj.SetClipModel( NULL, 1.0f );
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
SetPhysics( &physicsObj );
fl.solidForTeam = true;
// HUMANHEAD: aob
memset( &eyeTraceInfo, 0, sizeof(trace_t) );
eyeTraceInfo.fraction = 1.0f;
BecomeActive( TH_TICKER );
handedness = hhMath::hhMax<int>( 1, spawnArgs.GetInt("handedness", "1") );
fl.neverDormant = true;
// HUMANHEAD END
}
/*
================
hhWeapon::~hhWeapon()
================
*/
hhWeapon::~hhWeapon() {
SAFE_REMOVE( worldModel );
SAFE_REMOVE( thread );
SAFE_DELETE_PTR( fireController );
SAFE_DELETE_PTR( altFireController );
if ( nozzleFx && nozzleGlowHandle != -1 ) {
gameRenderWorld->FreeLightDef( nozzleGlowHandle );
}
}
/*
================
hhWeapon::SetOwner
================
*/
void hhWeapon::SetOwner( idPlayer *_owner ) {
if( !_owner || !_owner->IsType(hhPlayer::Type) ) {
owner = NULL;
return;
}
owner = static_cast<hhPlayer*>( _owner );
if( GetPhysics() && GetPhysics()->IsType(hhPhysics_StaticWeapon::Type) ) {
static_cast<hhPhysics_StaticWeapon*>(GetPhysics())->SetSelfOwner( owner.GetEntity() );
}
}
/*
================
hhWeapon::Save
================
*/
void hhWeapon::Save( idSaveGame *savefile ) const {
savefile->WriteInt( status );
savefile->WriteObject( thread );
savefile->WriteString( state );
savefile->WriteString( idealState );
savefile->WriteInt( animBlendFrames );
savefile->WriteInt( animDoneTime );
owner.Save( savefile );
worldModel.Save( savefile );
savefile->WriteStaticObject( physicsObj );
savefile->WriteObject( fireController );
savefile->WriteObject( altFireController );
savefile->WriteTrace( eyeTraceInfo );
savefile->WriteVec3( cameraShakeOffset );
savefile->WriteInt( handedness );
savefile->WriteVec3( pushVelocity );
savefile->WriteString( weaponDef->GetName() );
savefile->WriteString( icon );
savefile->WriteInt( kick_endtime );
savefile->WriteBool( lightOn );
savefile->WriteInt( zoomFov );
savefile->WriteInt( weaponAngleOffsetAverages );
savefile->WriteFloat( weaponAngleOffsetScale );
savefile->WriteFloat( weaponAngleOffsetMax );
savefile->WriteFloat( weaponOffsetTime );
savefile->WriteFloat( weaponOffsetScale );
savefile->WriteBool( nozzleFx );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->WriteInt( nozzleGlowHandle );
savefile->WriteJoint( nozzleJointHandle.view );
savefile->WriteJoint( nozzleJointHandle.world );
savefile->WriteRenderLight( nozzleGlow );
savefile->WriteVec3( nozzleGlowColor );
savefile->WriteMaterial( nozzleGlowShader );
savefile->WriteFloat( nozzleGlowRadius );
savefile->WriteVec3( nozzleGlowOffset );
}
/*
================
hhWeapon::Restore
================
*/
void hhWeapon::Restore( idRestoreGame *savefile ) {
savefile->ReadInt( (int &)status );
savefile->ReadObject( reinterpret_cast<idClass*&>(thread) );
savefile->ReadString( state );
savefile->ReadString( idealState );
savefile->ReadInt( animBlendFrames );
savefile->ReadInt( animDoneTime );
//Re-link script fields
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
WEAPON_NEXTATTACK.LinkTo( scriptObject, "nextAttack" ); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.LinkTo( scriptObject, "WEAPON_ALTATTACK" );
WEAPON_ASIDEWEAPON.LinkTo( scriptObject, "WEAPON_ASIDEWEAPON" );
WEAPON_ALTMODE.LinkTo( scriptObject, "WEAPON_ALTMODE" );
//HUMANHEAD END
owner.Restore( savefile );
worldModel.Restore( savefile );
savefile->ReadStaticObject( physicsObj );
RestorePhysics( &physicsObj );
savefile->ReadObject( reinterpret_cast< idClass *&> ( fireController ) );
savefile->ReadObject( reinterpret_cast< idClass *&> ( altFireController ) );
savefile->ReadTrace( eyeTraceInfo );
savefile->ReadVec3( cameraShakeOffset );
savefile->ReadInt( handedness );
savefile->ReadVec3( pushVelocity );
idStr objectname;
savefile->ReadString( objectname );
weaponDef = gameLocal.FindEntityDef( objectname, false );
if (!weaponDef) {
gameLocal.Error( "Unknown weaponDef: %s\n", objectname );
}
dict = &(weaponDef->dict);
savefile->ReadString( icon );
savefile->ReadInt( kick_endtime );
savefile->ReadBool( lightOn );
savefile->ReadInt( zoomFov );
savefile->ReadInt( weaponAngleOffsetAverages );
savefile->ReadFloat( weaponAngleOffsetScale );
savefile->ReadFloat( weaponAngleOffsetMax );
savefile->ReadFloat( weaponOffsetTime );
savefile->ReadFloat( weaponOffsetScale );
savefile->ReadBool( nozzleFx );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->ReadInt( nozzleGlowHandle );
savefile->ReadJoint( nozzleJointHandle.view );
savefile->ReadJoint( nozzleJointHandle.world );
savefile->ReadRenderLight( nozzleGlow );
savefile->ReadVec3( nozzleGlowColor );
savefile->ReadMaterial( nozzleGlowShader );
savefile->ReadFloat( nozzleGlowRadius );
savefile->ReadVec3( nozzleGlowOffset );
}
/*
================
hhWeapon::Clear
================
*/
void hhWeapon::Clear( void ) {
DeconstructScriptObject();
scriptObject.Free();
WEAPON_ATTACK.Unlink();
WEAPON_RELOAD.Unlink();
WEAPON_RAISEWEAPON.Unlink();
WEAPON_LOWERWEAPON.Unlink();
WEAPON_NEXTATTACK.Unlink(); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.Unlink();
WEAPON_ASIDEWEAPON.Unlink();
WEAPON_ALTMODE.Unlink();
SAFE_DELETE_PTR( fireController );
SAFE_DELETE_PTR( altFireController );
//HUMANEAD END
//memset( &renderEntity, 0, sizeof( renderEntity ) );
renderEntity.entityNum = entityNumber;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.customSkin = NULL;
// set default shader parms
renderEntity.shaderParms[ SHADERPARM_RED ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_GREEN ]= 1.0f;
renderEntity.shaderParms[ SHADERPARM_BLUE ] = 1.0f;
renderEntity.shaderParms[3] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = 0.0f;
renderEntity.shaderParms[5] = 0.0f;
renderEntity.shaderParms[6] = 0.0f;
renderEntity.shaderParms[7] = 0.0f;
// nozzle fx
nozzleFx = false;
memset( &nozzleGlow, 0, sizeof( nozzleGlow ) );
nozzleGlowHandle = -1;
nozzleJointHandle.Clear();
memset( &refSound, 0, sizeof( refSound_t ) );
if ( owner.IsValid() ) {
// don't spatialize the weapon sounds
refSound.listenerId = owner->GetListenerId();
}
// clear out the sounds from our spawnargs since we'll copy them from the weapon def
const idKeyValue *kv = spawnArgs.MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Delete( kv->GetKey() );
kv = spawnArgs.MatchPrefix( "snd_" );
}
weaponDef = NULL;
dict = NULL;
kick_endtime = 0;
icon = "";
pushVelocity.Zero();
status = WP_HOLSTERED;
state = "";
idealState = "";
animBlendFrames = 0;
animDoneTime = 0;
lightOn = false;
zoomFov = 90;
weaponAngleOffsetAverages = 10; //initialize this to default number to prevent infinite loops
FreeModelDef();
}
/*
================
hhWeapon::InitWorldModel
================
*/
void hhWeapon::InitWorldModel( const idDict *dict ) {
idEntity *ent;
ent = worldModel.GetEntity();
if ( !ent || !dict ) {
return;
}
const char *model = dict->GetString( "model_world" );
const char *attach = dict->GetString( "joint_attach" );
if (gameLocal.isMultiplayer) { //HUMANHEAD rww - shadow default based on whether the player shadows
ent->GetRenderEntity()->noShadow = MP_PLAYERNOSHADOW_DEFAULT;
}
if ( model[0] && attach[0] ) {
ent->Show();
ent->SetModel( model );
ent->GetPhysics()->SetContents( 0 );
ent->GetPhysics()->SetClipModel( NULL, 1.0f );
ent->BindToJoint( owner.GetEntity(), attach, true );
ent->GetPhysics()->SetOrigin( vec3_origin );
ent->GetPhysics()->SetAxis( mat3_identity );
// supress model in player views, but allow it in mirrors and remote views
renderEntity_t *worldModelRenderEntity = ent->GetRenderEntity();
if ( worldModelRenderEntity ) {
worldModelRenderEntity->suppressSurfaceInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
} else {
ent->SetModel( "" );
ent->Hide();
}
}
/*
================
hhWeapon::GetWeaponDef
HUMANHEAD: aob - this should only be called after the weapon has just been created
================
*/
void hhWeapon::GetWeaponDef( const char *objectname ) {
//HUMANHEAD: aob - put logic in helper function
ParseDef( objectname );
//HUMANHEAD END
if( owner->inventory.weaponRaised[owner->GetWeaponNum(objectname)] || gameLocal.isMultiplayer )
ProcessEvent( &EV_Weapon_State, "Raise", 0 );
else {
ProcessEvent( &EV_Weapon_State, "NewRaise", 0 );
owner->inventory.weaponRaised[owner->GetWeaponNum(objectname)] = true;
}
}
/*
================
hhWeapon::ParseDef
HUMANHEAD: aob
================
*/
void hhWeapon::ParseDef( const char* objectname ) {
if( !objectname || !objectname[ 0 ] ) {
return;
}
if( !owner.IsValid() ) {
gameLocal.Error( "hhWeapon::ParseDef: no owner" );
}
weaponDef = gameLocal.FindEntityDef( objectname, false );
if (!weaponDef) {
gameLocal.Error( "Unknown weaponDef: %s\n", objectname );
}
dict = &(weaponDef->dict);
// setup the world model
InitWorldModel( dict );
if (!owner.IsValid() || !owner.GetEntity()) {
gameLocal.Error("NULL owner in hhWeapon::ParseDef!");
}
//HUMANHEAD: aob
const idDict* infoDict = gameLocal.FindEntityDefDict( dict->GetString("def_fireInfo"), false );
if( infoDict ) {
fireController = CreateFireController();
if( fireController ) {
fireController->Init( infoDict, this, owner.GetEntity() );
}
}
infoDict = gameLocal.FindEntityDefDict( dict->GetString("def_altFireInfo"), false );
if( infoDict ) {
altFireController = CreateAltFireController();
if( altFireController ) {
altFireController->Init( infoDict, this, owner.GetEntity() );
}
}
//HUMANHEAD END
icon = dict->GetString( "inv_icon" );
// copy the sounds from the weapon view model def into out spawnargs
const idKeyValue *kv = dict->MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Set( kv->GetKey(), kv->GetValue() );
kv = dict->MatchPrefix( "snd_", kv );
}
weaponAngleOffsetAverages = dict->GetInt( "weaponAngleOffsetAverages", "10" );
weaponAngleOffsetScale = dict->GetFloat( "weaponAngleOffsetScale", "0.1" );
weaponAngleOffsetMax = dict->GetFloat( "weaponAngleOffsetMax", "10" );
weaponOffsetTime = dict->GetFloat( "weaponOffsetTime", "400" );
weaponOffsetScale = dict->GetFloat( "weaponOffsetScale", "0.002" );
zoomFov = dict->GetInt( "zoomFov", "70" );
InitScriptObject( dict->GetString("scriptobject") );
nozzleFx = weaponDef->dict.GetBool( "nozzleFx", "0" );
nozzleGlowColor = weaponDef->dict.GetVector("nozzleGlowColor", "1 1 1");
nozzleGlowRadius = weaponDef->dict.GetFloat("nozzleGlowRadius", "10");
nozzleGlowOffset = weaponDef->dict.GetVector( "nozzleGlowOffset", "0 0 0" );
nozzleGlowShader = declManager->FindMaterial( weaponDef->dict.GetString( "mtr_nozzleGlowShader", "" ), false );
GetJointHandle( weaponDef->dict.GetString( "nozzleJoint", "" ), nozzleJointHandle );
//HUMANHEAD bjk
int clipAmmo = owner->inventory.clip[owner->GetWeaponNum(objectname)];
if ( ( clipAmmo < 0 ) || ( clipAmmo > fireController->ClipSize() ) ) {
// first time using this weapon so have it fully loaded to start
clipAmmo = fireController->ClipSize();
if ( clipAmmo > fireController->AmmoAvailable() ) {
clipAmmo = fireController->AmmoAvailable();
}
}
fireController->AddToClip(clipAmmo);
WEAPON_ALTMODE = owner->inventory.altMode[owner->GetWeaponNum(objectname)];
//HUMANHEAD END
Show();
}
/*
================
idWeapon::ShouldConstructScriptObjectAtSpawn
Called during idEntity::Spawn to see if it should construct the script object or not.
Overridden by subclasses that need to spawn the script object themselves.
================
*/
bool hhWeapon::ShouldConstructScriptObjectAtSpawn( void ) const {
return false;
}
/*
================
hhWeapon::InitScriptObject
================
*/
void hhWeapon::InitScriptObject( const char* objectType ) {
if( !objectType || !objectType[0] ) {
gameLocal.Error( "No scriptobject set on '%s'.", dict->GetString("classname") );
}
if( !idStr::Icmp(scriptObject.GetTypeName(), objectType) ) {
//Same script object, don't reload it
return;
}
// setup script object
if( !scriptObject.SetType(objectType) ) {
gameLocal.Error( "Script object '%s' not found on weapon '%s'.", objectType, dict->GetString("classname") );
}
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
WEAPON_NEXTATTACK.LinkTo( scriptObject, "nextAttack" ); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.LinkTo( scriptObject, "WEAPON_ALTATTACK" );
WEAPON_ASIDEWEAPON.LinkTo( scriptObject, "WEAPON_ASIDEWEAPON" );
WEAPON_ALTMODE.LinkTo( scriptObject, "WEAPON_ALTMODE" );
//HUMANHEAD END
// call script object's constructor
ConstructScriptObject();
}
/***********************************************************************
GUIs
***********************************************************************/
/*
================
hhWeapon::Icon
================
*/
const char *hhWeapon::Icon( void ) const {
return icon;
}
/*
================
hhWeapon::UpdateGUI
================
*/
void hhWeapon::UpdateGUI() {
if ( !renderEntity.gui[0] ) {
return;
}
if ( status == WP_HOLSTERED ) {
return;
}
int ammoamount = AmmoAvailable();
int altammoamount = AltAmmoAvailable();
// show remaining ammo
renderEntity.gui[ 0 ]->SetStateInt( "ammoamount", ammoamount );
renderEntity.gui[ 0 ]->SetStateInt( "altammoamount", altammoamount );
renderEntity.gui[ 0 ]->SetStateBool( "ammolow", ammoamount > 0 && ammoamount <= LowAmmo() );
renderEntity.gui[ 0 ]->SetStateBool( "altammolow", altammoamount > 0 && altammoamount <= LowAltAmmo() );
renderEntity.gui[ 0 ]->SetStateBool( "ammoempty", ( ammoamount == 0 ) );
renderEntity.gui[ 0 ]->SetStateBool( "altammoempty", ( altammoamount == 0 ) );
renderEntity.gui[ 0 ]->SetStateInt( "clipammoAmount", AmmoInClip() );
renderEntity.gui[ 0 ]->SetStateInt( "clipaltammoAmount", AltAmmoInClip() );
renderEntity.gui[ 0 ]->StateChanged(gameLocal.time);
}
/***********************************************************************
Model and muzzleflash
***********************************************************************/
/*
================
hhWeapon::GetGlobalJointTransform
This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights
================
*/
bool hhWeapon::GetJointWorldTransform( const char* jointName, idVec3 &offset, idMat3 &axis ) {
weaponJointHandle_t handle;
GetJointHandle( jointName, handle );
return GetJointWorldTransform( handle, offset, axis );
}
/*
================
hhWeapon::GetGlobalJointTransform
This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights
================
*/
bool hhWeapon::GetJointWorldTransform( const weaponJointHandle_t& handle, idVec3 &offset, idMat3 &axis, bool muzzleOnly ) {
//FIXME: this seems to work but may need revisiting
//FIXME: totally forgot about mirrors and portals. This may not work.
if( (!pm_thirdPerson.GetBool() && owner == gameLocal.GetLocalPlayer()) || (gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->spectating && gameLocal.GetLocalPlayer()->spectator == owner->entityNumber) || (gameLocal.isServer && !muzzleOnly)) { //rww - mp server should always create projectiles from the viewmodel
// view model
if ( hhAnimatedEntity::GetJointWorldTransform(handle.view, offset, axis) ) {
return true;
}
} else {
// world model
if ( worldModel.IsValid() && worldModel.GetEntity()->GetJointWorldTransform(handle.world, offset, axis) ) {
return true;
}
}
offset = GetOrigin();
axis = GetAxis();
return false;
}
/*
================
hhWeapon::GetJointHandle
HUMANHEAD: aob
================
*/
void hhWeapon::GetJointHandle( const char* jointName, weaponJointHandle_t& handle ) {
if( dict ) {
handle.view = GetAnimator()->GetJointHandle( jointName );
}
if( worldModel.IsValid() ) {
handle.world = worldModel->GetAnimator()->GetJointHandle( jointName );
}
}
/*
================
hhWeapon::SetPushVelocity
================
*/
void hhWeapon::SetPushVelocity( const idVec3 &pushVelocity ) {
this->pushVelocity = pushVelocity;
}
/***********************************************************************
State control/player interface
***********************************************************************/
/*
================
hhWeapon::Raise
================
*/
void hhWeapon::Raise( void ) {
WEAPON_RAISEWEAPON = true;
WEAPON_ASIDEWEAPON = false;
}
/*
================
hhWeapon::PutAway
================
*/
void hhWeapon::PutAway( void ) {
//hasBloodSplat = false;
WEAPON_LOWERWEAPON = true;
WEAPON_RAISEWEAPON = false; //HUMANHEAD bjk PCF 5-4-06 : fix for weapons being up after death
WEAPON_ASIDEWEAPON = false;
WEAPON_ATTACK = false;
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::PutAside
================
*/
void hhWeapon::PutAside( void ) {
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_RAISEWEAPON = false;
WEAPON_ASIDEWEAPON = true;
WEAPON_ATTACK = false;
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::PutUpright
================
*/
void hhWeapon::PutUpright( void ) {
WEAPON_ASIDEWEAPON = false;
}
/*
================
hhWeapon::SnapDown
HUMANHEAD: aob
================
*/
void hhWeapon::SnapDown() {
ProcessEvent( &EV_Weapon_State, "Down", 0 );
}
/*
================
hhWeapon::SnapUp
HUMANHEAD: aob
================
*/
void hhWeapon::SnapUp() {
ProcessEvent( &EV_Weapon_State, "Up", 0 );
}
/*
================
hhWeapon::Reload
================
*/
void hhWeapon::Reload( void ) {
WEAPON_RELOAD = true;
}
/*
================
hhWeapon::HideWeapon
================
*/
void hhWeapon::HideWeapon( void ) {
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::ShowWeapon
================
*/
void hhWeapon::ShowWeapon( void ) {
Show();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
}
/*
================
hhWeapon::HideWorldModel
================
*/
void hhWeapon::HideWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::ShowWorldModel
================
*/
void hhWeapon::ShowWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
}
/*
================
hhWeapon::OwnerDied
================
*/
void hhWeapon::OwnerDied( void ) {
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::BeginAltAttack
================
*/
void hhWeapon::BeginAltAttack( void ) {
WEAPON_ALTATTACK = true;
//if ( status != WP_OUTOFAMMO ) {
// lastAttack = gameLocal.time;
//}
}
/*
================
hhWeapon::EndAltAttack
================
*/
void hhWeapon::EndAltAttack( void ) {
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::BeginAttack
================
*/
void hhWeapon::BeginAttack( void ) {
//if ( status != WP_OUTOFAMMO ) {
// lastAttack = gameLocal.time;
//}
WEAPON_ATTACK = true;
}
/*
================
hhWeapon::EndAttack
================
*/
void hhWeapon::EndAttack( void ) {
if ( !WEAPON_ATTACK.IsLinked() ) {
return;
}
if ( WEAPON_ATTACK ) {
WEAPON_ATTACK = false;
}
}
/*
================
hhWeapon::isReady
================
*/
bool hhWeapon::IsReady( void ) const {
return !IsHidden() && ( ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) );
}
/*
================
hhWeapon::IsReloading
================
*/
bool hhWeapon::IsReloading( void ) const {
return ( status == WP_RELOAD );
}
/*
================
hhWeapon::IsChangable
================
*/
bool hhWeapon::IsChangable( void ) const {
//HUMANHEAD: aob - same as IsReady except w/o IsHidden check
//Allows us to switch weapons while they are hidden
//Hope this doesn't fuck to many things
return ( ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) );
}
/*
================
hhWeapon::IsHolstered
================
*/
bool hhWeapon::IsHolstered( void ) const {
return ( status == WP_HOLSTERED );
}
/*
================
hhWeapon::IsLowered
================
*/
bool hhWeapon::IsLowered( void ) const {
return ( status == WP_HOLSTERED ) || ( status == WP_LOWERING );
}
/*
================
hhWeapon::IsRising
================
*/
bool hhWeapon::IsRising( void ) const {
return ( status == WP_RISING );
}
/*
================
hhWeapon::IsAside
================
*/
bool hhWeapon::IsAside( void ) const {
return ( status == WP_ASIDE );
}
/*
================
hhWeapon::ShowCrosshair
================
*/
bool hhWeapon::ShowCrosshair( void ) const {
//HUMANHEAD: aob - added cinematic check
return !( state == idStr( WP_RISING ) || state == idStr( WP_LOWERING ) || state == idStr( WP_HOLSTERED ) ) && !owner->InCinematic();
}
/*
=====================
hhWeapon::DropItem
=====================
*/
idEntity* hhWeapon::DropItem( const idVec3 &velocity, int activateDelay, int removeDelay, bool died ) {
if ( !weaponDef || !worldModel.GetEntity() ) {
return NULL;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[0] ) {
return NULL;
}
StopSound( SND_CHANNEL_BODY, !died ); //HUMANHEAD rww - on death, do not broadcast the stop, because the weapon itself is about to be removed
return idMoveableItem::DropItem( classname, worldModel.GetEntity()->GetPhysics()->GetOrigin(), worldModel.GetEntity()->GetPhysics()->GetAxis(), velocity, activateDelay, removeDelay );
}
/*
=====================
hhWeapon::CanDrop
=====================
*/
bool hhWeapon::CanDrop( void ) const {
if ( !weaponDef || !worldModel.GetEntity() ) {
return false;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[ 0 ] ) {
return false;
}
return true;
}
/***********************************************************************
Script state management
***********************************************************************/
/*
=====================
hhWeapon::SetState
=====================
*/
void hhWeapon::SetState( const char *statename, int blendFrames ) {
const function_t *func;
func = scriptObject.GetFunction( statename );
if ( !func ) {
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
thread->CallFunction( this, func, true );
state = statename;
animBlendFrames = blendFrames;
if ( g_debugWeapon.GetBool() ) {
gameLocal.Printf( "%d: weapon state : %s\n", gameLocal.time, statename );
}
idealState = "";
}
/***********************************************************************
Visual presentation
***********************************************************************/
/*
================
hhWeapon::MuzzleRise
HUMANHEAD: aob
================
*/
void hhWeapon::MuzzleRise( idVec3 &origin, idMat3 &axis ) {
if( fireController ) {
fireController->CalculateMuzzleRise( origin, axis );
}
if( altFireController ) {
altFireController->CalculateMuzzleRise( origin, axis );
}
}
/*
================
hhWeapon::ConstructScriptObject
Called during idEntity::Spawn. Calls the constructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
================
*/
idThread *hhWeapon::ConstructScriptObject( void ) {
const function_t *constructor;
//HUMANHEAD: aob
if( !thread ) {
return thread;
}
//HUMANHEAD END
thread->EndThread();
// call script object's constructor
constructor = scriptObject.GetConstructor();
if ( !constructor ) {
gameLocal.Error( "Missing constructor on '%s' for weapon", scriptObject.GetTypeName() );
}
// init the script object's data
scriptObject.ClearObject();
thread->CallFunction( this, constructor, true );
thread->Execute();
return thread;
}
/*
================
hhWeapon::DeconstructScriptObject
Called during idEntity::~idEntity. Calls the destructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
Not called during idGameLocal::MapShutdown.
================
*/
void hhWeapon::DeconstructScriptObject( void ) {
const function_t *destructor;
if ( !thread ) {
return;
}
// don't bother calling the script object's destructor on map shutdown
if ( gameLocal.GameState() == GAMESTATE_SHUTDOWN ) {
return;
}
thread->EndThread();
// call script object's destructor
destructor = scriptObject.GetDestructor();
if ( destructor ) {
// start a thread that will run immediately and end
thread->CallFunction( this, destructor, true );
thread->Execute();
thread->EndThread();
}
// clear out the object's memory
scriptObject.ClearObject();
}
/*
================
hhWeapon::UpdateScript
================
*/
void hhWeapon::UpdateScript( void ) {
int count;
if ( !IsLinked() ) {
return;
}
// only update the script on new frames
if ( !gameLocal.isNewFrame ) {
return;
}
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
// update script state, which may call Event_LaunchProjectiles, among other things
count = 10;
while( ( thread->Execute() || idealState.Length() ) && count-- ) {
// happens for weapons with no clip (like grenades)
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
}
WEAPON_RELOAD = false;
}
/*
================
hhWeapon::PresentWeapon
================
*/
void hhWeapon::PresentWeapon( bool showViewModel ) {
UpdateScript();
//HUMANHEAD rww - added this gui owner logic here
bool allowGuiUpdate = true;
if ( owner.IsValid() && gameLocal.localClientNum != owner->entityNumber ) {
// if updating the hud for a followed client
if ( gameLocal.localClientNum >= 0 && gameLocal.entities[ gameLocal.localClientNum ] && gameLocal.entities[ gameLocal.localClientNum ]->IsType( idPlayer::Type ) ) {
idPlayer *p = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.localClientNum ] );
if ( !p->spectating || p->spectator != owner->entityNumber ) {
allowGuiUpdate = false;
}
} else {
allowGuiUpdate = false;
}
}
if (allowGuiUpdate) {
UpdateGUI();
}
// update animation
UpdateAnimation();
// only show the surface in player view
renderEntity.allowSurfaceInViewID = owner->entityNumber+1;
// crunch the depth range so it never pokes into walls this breaks the machine gun gui
renderEntity.weaponDepthHack = true;
// present the model
if ( showViewModel ) {
Present();
} else {
FreeModelDef();
}
if ( worldModel.GetEntity() && worldModel.GetEntity()->GetRenderEntity() ) {
// deal with the third-person visible world model
// don't show shadows of the world model in first person
#ifdef HUMANHEAD
if ( gameLocal.isMultiplayer || (g_showPlayerShadow.GetBool() && pm_modelView.GetInteger() == 1) || pm_thirdPerson.GetBool()
|| (pm_modelView.GetInteger() == 2 && owner->health <= 0)) {
worldModel->GetRenderEntity()->suppressShadowInViewID = 0;
} else {
worldModel->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1;
worldModel->GetRenderEntity()->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
#else
// deal with the third-person visible world model
// don't show shadows of the world model in first person
if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() || pm_thirdPerson.GetBool() ) {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = 0;
} else {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1;
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
}
#endif // HUMANHEAD pdm
}
// update the muzzle flash light, so it moves with the gun
//HUMANHEAD: aob
if( fireController ) {
fireController->UpdateMuzzleFlash();
}
if( altFireController ) {
altFireController->UpdateMuzzleFlash();
}
//HUMANHEAD END
UpdateNozzleFx(); // expensive
UpdateSound();
}
/*
================
hhWeapon::EnterCinematic
================
*/
void hhWeapon::EnterCinematic( void ) {
StopSound( SND_CHANNEL_ANY, false );
if ( IsLinked() ) {
SetState( "EnterCinematic", 0 );
thread->Execute();
WEAPON_ATTACK = false;
WEAPON_RELOAD = false;
// WEAPON_NETRELOAD = false;
// WEAPON_NETENDRELOAD = false;
WEAPON_RAISEWEAPON = false;
WEAPON_LOWERWEAPON = false;
}
//disabled = true;
LowerWeapon();
}
/*
================
hhWeapon::ExitCinematic
================
*/
void hhWeapon::ExitCinematic( void ) {
//disabled = false;
if ( IsLinked() ) {
SetState( "ExitCinematic", 0 );
thread->Execute();
}
RaiseWeapon();
}
/*
================
hhWeapon::NetCatchup
================
*/
void hhWeapon::NetCatchup( void ) {
if ( IsLinked() ) {
SetState( "NetCatchup", 0 );
thread->Execute();
}
}
/*
================
hhWeapon::GetClipBits
================
*/
int hhWeapon::GetClipBits(void) const {
return ASYNC_PLAYER_INV_CLIP_BITS;
}
/*
================
hhWeapon::GetZoomFov
================
*/
int hhWeapon::GetZoomFov( void ) {
return zoomFov;
}
/*
================
hhWeapon::GetWeaponAngleOffsets
================
*/
void hhWeapon::GetWeaponAngleOffsets( int *average, float *scale, float *max ) {
*average = weaponAngleOffsetAverages;
*scale = weaponAngleOffsetScale;
*max = weaponAngleOffsetMax;
}
/*
================
hhWeapon::GetWeaponTimeOffsets
================
*/
void hhWeapon::GetWeaponTimeOffsets( float *time, float *scale ) {
*time = weaponOffsetTime;
*scale = weaponOffsetScale;
}
/***********************************************************************
Ammo
**********************************************************************/
/*
================
hhWeapon::WriteToSnapshot
================
*/
void hhWeapon::WriteToSnapshot( idBitMsgDelta &msg ) const {
#if 0
//FIXME: need to add altFire stuff too
if( fireController ) {
msg.WriteBits( fireController->AmmoInClip(), GetClipBits() );
} else {
msg.WriteBits( 0, GetClipBits() );
}
msg.WriteBits(worldModel.GetSpawnId(), 32);
#else //rww - forget this silliness, let's do this the Right Way.
msg.WriteBits(owner.GetSpawnId(), 32);
msg.WriteBits(worldModel.GetSpawnId(), 32);
if (fireController) {
fireController->WriteToSnapshot(msg);
}
else { //rwwFIXME this is an ugly hack
msg.WriteBits(0, 32);
msg.WriteBits(0, 32);
msg.WriteBits(0, GetClipBits());
}
if (altFireController) {
altFireController->WriteToSnapshot(msg);
}
else { //rwwFIXME this is an ugly hack
msg.WriteBits(0, 32);
msg.WriteBits(0, 32);
msg.WriteBits(0, GetClipBits());
}
msg.WriteBits(WEAPON_ASIDEWEAPON, 1);
//HUMANHEAD PCF rww 05/09/06 - no need to sync these values
/*
msg.WriteBits(WEAPON_LOWERWEAPON, 1);
msg.WriteBits(WEAPON_RAISEWEAPON, 1);
*/
WriteBindToSnapshot(msg);
#endif
}
/*
================
hhWeapon::ReadFromSnapshot
================
*/
void hhWeapon::ReadFromSnapshot( const idBitMsgDelta &msg ) {
#if 0
//FIXME: need to add altFire stuff too
if( fireController ) {
fireController->AddToClip( msg.ReadBits(GetClipBits()) );
} else {
msg.ReadBits( GetClipBits() );
}
worldModel.SetSpawnId(msg.ReadBits(32));
#else
bool wmInit = false;
owner.SetSpawnId(msg.ReadBits(32));
if (worldModel.SetSpawnId(msg.ReadBits(32))) { //do this once we finally get the entity in the snapshot
wmInit = true;
}
//rwwFIXME this is a little hacky, i think. is there a way to do it in ::Spawn? but, the weapon doesn't know its owner at that point.
if (!dict) {
if (!owner.IsValid() || !owner.GetEntity()) {
gameLocal.Error("NULL owner in hhWeapon::ReadFromSnapshot!");
}
assert(owner.IsValid());
GetWeaponDef(spawnArgs.GetString("classname"));
//owner->ForceWeapon(this); it doesn't like this.
}
assert(fireController);
assert(altFireController);
if (wmInit) { //need to do this once the ent is valid on the client
InitWorldModel( dict );
GetJointHandle( weaponDef->dict.GetString( "nozzleJoint", "" ), nozzleJointHandle );
fireController->UpdateWeaponJoints();
altFireController->UpdateWeaponJoints();
}
fireController->ReadFromSnapshot(msg);
altFireController->ReadFromSnapshot(msg);
WEAPON_ASIDEWEAPON = !!msg.ReadBits(1);
//HUMANHEAD PCF rww 05/09/06 - no need to sync these values
/*
WEAPON_LOWERWEAPON = !!msg.ReadBits(1);
WEAPON_RAISEWEAPON = !!msg.ReadBits(1);
*/
ReadBindFromSnapshot(msg);
#endif
}
/*
================
hhWeapon::ClientPredictionThink
================
*/
void hhWeapon::ClientPredictionThink( void ) {
Think();
}
/***********************************************************************
Script events
***********************************************************************/
/*
hhWeapon::Event_Raise
*/
void hhWeapon::Event_Raise() {
Raise();
}
/*
===============
hhWeapon::Event_WeaponState
===============
*/
void hhWeapon::Event_WeaponState( const char *statename, int blendFrames ) {
const function_t *func;
func = scriptObject.GetFunction( statename );
if ( !func ) {
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
idealState = statename;
animBlendFrames = blendFrames;
thread->DoneProcessing();
}
/*
===============
hhWeapon::Event_WeaponReady
===============
*/
void hhWeapon::Event_WeaponReady( void ) {
status = WP_READY;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_ASIDEWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponOutOfAmmo
===============
*/
void hhWeapon::Event_WeaponOutOfAmmo( void ) {
status = WP_OUTOFAMMO;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_ASIDEWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponReloading
===============
*/
void hhWeapon::Event_WeaponReloading( void ) {
status = WP_RELOAD;
}
/*
===============
hhWeapon::Event_WeaponHolstered
===============
*/
void hhWeapon::Event_WeaponHolstered( void ) {
status = WP_HOLSTERED;
WEAPON_LOWERWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponRising
===============
*/
void hhWeapon::Event_WeaponRising( void ) {
status = WP_RISING;
WEAPON_LOWERWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_ASIDEWEAPON = false;
owner->WeaponRisingCallback();
}
/*
===============
hhWeapon::Event_WeaponAside
===============
*/
void hhWeapon::Event_Weapon_Aside( void ) {
status = WP_ASIDE;
}
/*
===============
hhWeapon::Event_Weapon_PuttingAside
===============
*/
void hhWeapon::Event_Weapon_PuttingAside( void ) {
status = WP_PUTTING_ASIDE;
}
/*
===============
hhWeapon::Event_Weapon_Uprighting
===============
*/
void hhWeapon::Event_Weapon_Uprighting( void ) {
status = WP_UPRIGHTING;
}
/*
===============
hhWeapon::Event_WeaponLowering
===============
*/
void hhWeapon::Event_WeaponLowering( void ) {
status = WP_LOWERING;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD: aob
WEAPON_ASIDEWEAPON = false;
//HUMANHEAD END
owner->WeaponLoweringCallback();
}
/*
===============
hhWeapon::Event_AddToClip
===============
*/
void hhWeapon::Event_AddToClip( int amount ) {
if( fireController ) {
fireController->AddToClip( amount );
}
}
/*
===============
hhWeapon::Event_AmmoInClip
===============
*/
void hhWeapon::Event_AmmoInClip( void ) {
int ammo = AmmoInClip();
idThread::ReturnFloat( ammo );
}
/*
===============
hhWeapon::Event_AmmoAvailable
===============
*/
void hhWeapon::Event_AmmoAvailable( void ) {
int ammoAvail = AmmoAvailable();
idThread::ReturnFloat( ammoAvail );
}
/*
===============
hhWeapon::Event_ClipSize
===============
*/
void hhWeapon::Event_ClipSize( void ) {
idThread::ReturnFloat( ClipSize() );
}
/*
===============
hhWeapon::Event_PlayAnim
===============
*/
void hhWeapon::Event_PlayAnim( int channel, const char *animname ) {
int anim = 0;
anim = GetAnimator()->GetAnim( animname );
if ( !anim ) {
//HUMANHEAD: aob
WEAPON_DEBUG( "missing '%s' animation on '%s'", animname, name.c_str() );
//HUMANHEAD END
GetAnimator()->Clear( channel, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
//Show(); AOB - removed so we can use hidden weapons Hope this doesn't fuck to many things
GetAnimator()->PlayAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = GetAnimator()->CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
if ( anim ) {
worldModel.GetEntity()->GetAnimator()->PlayAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
}
}
}
animBlendFrames = 0;
}
/*
===============
hhWeapon::Event_AnimDone
===============
*/
void hhWeapon::Event_AnimDone( int channel, int blendFrames ) {
if ( animDoneTime - FRAME2MS( blendFrames ) <= gameLocal.time ) {
idThread::ReturnInt( true );
} else {
idThread::ReturnInt( false );
}
}
/*
================
hhWeapon::Event_Next
================
*/
void hhWeapon::Event_Next( void ) {
// change to another weapon if possible
owner->NextBestWeapon();
}
/*
================
hhWeapon::Event_Flashlight
================
*/
void hhWeapon::Event_Flashlight( int enable ) {
/*
if ( enable ) {
lightOn = true;
MuzzleFlashLight();
} else {
lightOn = false;
muzzleFlashEnd = 0;
}
*/
}
/*
================
hhWeapon::Event_FireProjectiles
HUMANHEAD: aob
================
*/
void hhWeapon::Event_FireProjectiles() {
//HUMANHEAD: aob - moved logic to this helper function
LaunchProjectiles( fireController );
//HUMANHEAD END
}
/*
================
hhWeapon::Event_GetOwner
================
*/
void hhWeapon::Event_GetOwner( void ) {
idThread::ReturnEntity( owner.GetEntity() );
}
/*
===============
hhWeapon::Event_UseAmmo
===============
*/
void hhWeapon::Event_UseAmmo( int amount ) {
UseAmmo();
}
/*
===============
hhWeapon::Event_UseAltAmmo
===============
*/
void hhWeapon::Event_UseAltAmmo( int amount ) {
UseAltAmmo();
}
/*
================
hhWeapon::RestoreGUI
HUMANHEAD: aob
================
*/
void hhWeapon::RestoreGUI( const char* guiKey, idUserInterface** gui ) {
if( guiKey && guiKey[0] && gui ) {
AddRenderGui( dict->GetString(guiKey), gui, dict );
}
}
/*
================
hhWeapon::Think
================
*/
void hhWeapon::Think() {
if( thinkFlags & TH_TICKER ) {
if (owner.IsValid()) {
Ticker();
}
}
}
/*
================
hhWeapon::SpawnWorldModel
================
*/
idEntity* hhWeapon::SpawnWorldModel( const char* worldModelDict, idActor* _owner ) {
/*
assert( _owner && worldModelDict );
idEntity* pEntity = NULL;
idDict* pArgs = declManager->FindEntityDefDict( worldModelDict, false );
if( !pArgs ) { return NULL; }
idStr ownerWeaponBindBone = _owner->spawnArgs.GetString( "bone_weapon_bind" );
idStr attachBone = pArgs->GetString( "attach" );
if( attachBone.Length() && ownerWeaponBindBone.Length() ) {
pEntity = gameLocal.SpawnEntityType( idEntity::Type, pArgs );
HH_ASSERT( pEntity );
pEntity->GetPhysics()->SetContents( 0 );
pEntity->GetPhysics()->DisableClip();
pEntity->MoveJointToJoint( attachBone.c_str(), _owner, ownerWeaponBindBone.c_str() );
pEntity->AlignJointToJoint( attachBone.c_str(), _owner, ownerWeaponBindBone.c_str() );
pEntity->BindToJoint( _owner, ownerWeaponBindBone.c_str(), true );
// supress model in player views and in any views on the weapon itself
pEntity->renderEntity.suppressSurfaceInViewID = _owner->entityNumber + 1;
}
*/
return NULL;
}
/*
================
hhWeapon::SetModel
================
*/
void hhWeapon::SetModel( const char *modelname ) {
assert( modelname );
if ( modelDefHandle >= 0 ) {
gameRenderWorld->RemoveDecals( modelDefHandle );
}
hhAnimatedEntity::SetModel( modelname );
// hide the model until an animation is played
Hide();
}
/*
================
hhWeapon::FreeModelDef
================
*/
void hhWeapon::FreeModelDef() {
hhAnimatedEntity::FreeModelDef();
}
/*
================
hhWeapon::GetPhysicsToVisualTransform
================
*/
bool hhWeapon::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) {
bool bResult = hhAnimatedEntity::GetPhysicsToVisualTransform( origin, axis );
assert(!FLOAT_IS_NAN(cameraShakeOffset.x));
assert(!FLOAT_IS_NAN(cameraShakeOffset.y));
assert(!FLOAT_IS_NAN(cameraShakeOffset.z));
if( !cameraShakeOffset.Compare(vec3_zero, VECTOR_EPSILON) ) {
origin = (bResult) ? cameraShakeOffset + origin : cameraShakeOffset;
origin *= GetPhysics()->GetAxis().Transpose();
if( !bResult ) { axis = mat3_identity; }
return true;
}
return bResult;
}
/*
================
hhWeapon::GetMasterDefaultPosition
================
*/
void hhWeapon::GetMasterDefaultPosition( idVec3 &masterOrigin, idMat3 &masterAxis ) const {
idActor* actor = NULL;
idEntity* master = GetBindMaster();
if( master ) {
if( master->IsType(idActor::Type) ) {
actor = static_cast<idActor*>( master );
actor->DetermineOwnerPosition( masterOrigin, masterAxis );
masterOrigin = actor->ApplyLandDeflect( masterOrigin, 1.1f );
} else {
hhAnimatedEntity::GetMasterDefaultPosition( masterOrigin, masterAxis );
}
}
}
/*
================
hhWeapon::SetShaderParm
================
*/
void hhWeapon::SetShaderParm( int parmnum, float value ) {
hhAnimatedEntity::SetShaderParm(parmnum, value);
if ( worldModel.IsValid() ) {
worldModel->SetShaderParm(parmnum, value);
}
}
/*
================
hhWeapon::SetSkin
================
*/
void hhWeapon::SetSkin( const idDeclSkin *skin ) {
hhAnimatedEntity::SetSkin(skin);
if ( worldModel.IsValid() ) {
worldModel->SetSkin(skin);
}
}
/*
================
hhWeapon::PlayCycle
================
*/
void hhWeapon::Event_PlayCycle( int channel, const char *animname ) {
int anim;
anim = GetAnimator()->GetAnim( animname );
if ( !anim ) {
//HUMANHEAD: aob
WEAPON_DEBUG( "missing '%s' animation on '%s'", animname, name.c_str() );
//HUMANHEAD END
GetAnimator()->Clear( channel, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
//Show();AOB - removed so we can use hidden weapons Hope this doesn't fuck to many things
// NLANOTE - Used to be CARandom
GetAnimator()->CycleAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = GetAnimator()->CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
// NLANOTE - Used to be CARandom
worldModel.GetEntity()->GetAnimator()->CycleAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
}
}
animBlendFrames = 0;
}
/*
================
hhWeapon::Event_IsAnimPlaying
================
*/
void hhWeapon::Event_IsAnimPlaying( const char *animname ) {
idThread::ReturnInt( animator.IsAnimPlaying(animname) );
}
/*
================
hhWeapon::Event_EjectBrass
================
*/
void hhWeapon::Event_EjectBrass() {
if( fireController ) {
fireController->EjectBrass();
}
}
/*
================
hhWeapon::Event_EjectAltBrass
================
*/
void hhWeapon::Event_EjectAltBrass() {
if( altFireController ) {
altFireController->EjectBrass();
}
}
/*
================
hhWeapon::Event_PlayAnimWhenReady
================
*/
void hhWeapon::Event_PlayAnimWhenReady( const char* animName ) {
/*
if( !IsReady() && (!dict || !dict->GetBool("pickupHasRaise") || !IsRaising()) ) {
CancelEvents( &EV_PlayAnimWhenReady );
PostEventSec( &EV_PlayAnimWhenReady, 0.5f, animName );
return;
}
PlayAnim( animName, 0, &EV_Weapon_Ready );
*/
}
/*
================
hhWeapon::Event_SpawnFXAlongBone
================
*/
void hhWeapon::Event_SpawnFXAlongBone( idList<idStr>* fxParms ) {
if ( !owner->CanShowWeaponViewmodel() || !fxParms ) {
return;
}
HH_ASSERT( fxParms->Num() == 2 );
hhFxInfo fxInfo;
fxInfo.UseWeaponDepthHack( true );
BroadcastFxInfoAlongBone( dict->GetString((*fxParms)[0].c_str()), (*fxParms)[1].c_str(), &fxInfo, NULL, false ); //rww - default to not broadcast from events
}
/*
==============================
hhWeapon::Event_FireAltProjectiles
==============================
*/
void hhWeapon::Event_FireAltProjectiles() {
LaunchProjectiles( altFireController );
}
// This is called once per frame to precompute where the weapon is pointing. This is used for determining if crosshairs should display as targetted as
// well as fire controllers to update themselves. This must be called before UpdateCrosshairs().
void hhWeapon::PrecomputeTraceInfo() {
// This is needed for fireControllers, even if there are no crosshairs
idVec3 eyePos = owner->GetEyePosition();
idMat3 weaponAxis = GetAxis();
float traceDist = 1024.0f; // was CM_MAX_TRACE_DIST
// Perform eye trace
gameLocal.clip.TracePoint( eyeTraceInfo, eyePos, eyePos + weaponAxis[0] * traceDist,
MASK_SHOT_BOUNDINGBOX | CONTENTS_GAME_PORTAL, owner.GetEntity() );
// CJR: If the trace hit a portal, then force it to trace the max distance, as if it's tracing through the portal
if ( eyeTraceInfo.fraction < 1.0f ) {
idEntity *ent = gameLocal.GetTraceEntity( eyeTraceInfo );
if ( ent->IsType( hhPortal::Type ) ) {
eyeTraceInfo.endpos = eyePos + weaponAxis[0] * traceDist;
eyeTraceInfo.fraction = 1.0f;
}
}
}
/*
==============================
hhWeapon::UpdateCrosshairs
==============================
*/
void hhWeapon::UpdateCrosshairs( bool &crosshair, bool &targeting ) {
idEntity* ent = NULL;
trace_t traceInfo;
crosshair = false;
targeting = false;
if (spawnArgs.GetBool("altModeWeapon")) {
if (WEAPON_ALTMODE) { // Moded weapon in alt-mode
if (altFireController) {
crosshair = altFireController->UsesCrosshair();
}
}
else { // Moded weapon in normal mode
if (fireController) {
crosshair = fireController->UsesCrosshair();
}
}
}
else { // Normal non-moded weapon
if (altFireController && altFireController->UsesCrosshair()) {
crosshair = true;
}
if (fireController && fireController->UsesCrosshair()) {
crosshair = true;
}
}
ent = NULL;
if( crosshair ) {
traceInfo = GetEyeTraceInfo();
if( traceInfo.fraction < 1.0f ) {
ent = gameLocal.GetTraceEntity(traceInfo);
}
targeting = ( ent && ent->fl.takedamage && !(ent->IsType( hhDoor::Type ) || ent->IsType( hhModelDoor::Type ) || ent->IsType( hhConsole::Type ) ) );
}
}
/*
==============================
hhWeapon::GetAmmoType
==============================
*/
ammo_t hhWeapon::GetAmmoType( void ) const {
return (fireController) ? fireController->GetAmmoType() : 0;
}
/*
==============================
hhWeapon::AmmoAvailable
==============================
*/
int hhWeapon::AmmoAvailable( void ) const {
return (fireController) ? fireController->AmmoAvailable() : 0;
}
/*
==============================
hhWeapon::AmmoInClip
==============================
*/
int hhWeapon::AmmoInClip( void ) const {
return (fireController) ? fireController->AmmoInClip() : 0;
}
/*
==============================
hhWeapon::ClipSize
==============================
*/
int hhWeapon::ClipSize( void ) const {
return (fireController) ? fireController->ClipSize() : 0;
}
/*
==============================
hhWeapon::AmmoRequired
==============================
*/
int hhWeapon::AmmoRequired( void ) const {
return (fireController) ? fireController->AmmoRequired() : 0;
}
/*
==============================
hhWeapon::LowAmmo
==============================
*/
int hhWeapon::LowAmmo() {
return (fireController) ? fireController->LowAmmo() : 0;
}
/*
==============================
hhWeapon::GetAltAmmoType
==============================
*/
ammo_t hhWeapon::GetAltAmmoType( void ) const {
return (altFireController) ? altFireController->GetAmmoType() : 0;
}
/*
==============================
hhWeapon::AltAmmoAvailable
==============================
*/
int hhWeapon::AltAmmoAvailable( void ) const {
return (altFireController) ? altFireController->AmmoAvailable() : 0;
}
/*
==============================
hhWeapon::AltAmmoInClip
==============================
*/
int hhWeapon::AltAmmoInClip( void ) const {
return (altFireController) ? altFireController->AmmoInClip() : 0;
}
/*
==============================
hhWeapon::AltClipSize
==============================
*/
int hhWeapon::AltClipSize( void ) const {
return (altFireController) ? altFireController->ClipSize() : 0;
}
/*
==============================
hhWeapon::AltAmmoRequired
==============================
*/
int hhWeapon::AltAmmoRequired( void ) const {
return (altFireController) ? altFireController->AmmoRequired() : 0;
}
/*
==============================
hhWeapon::LowAltAmmo
==============================
*/
int hhWeapon::LowAltAmmo() {
return (altFireController) ? altFireController->LowAmmo() : 0;
}
/*
==============================
hhWeapon::GetAltMode
HUMANHEAD bjk
==============================
*/
bool hhWeapon::GetAltMode() const {
return WEAPON_ALTMODE != 0;
}
/*
==============================
hhWeapon::UseAmmo
==============================
*/
void hhWeapon::UseAmmo() {
if (fireController) {
fireController->UseAmmo();
}
}
/*
==============================
hhWeapon::UseAltAmmo
==============================
*/
void hhWeapon::UseAltAmmo() {
if (altFireController) {
altFireController->UseAmmo();
}
}
/*
==============================
hhWeapon::CheckDeferredProjectiles
HUMANEAD: rww
==============================
*/
void hhWeapon::CheckDeferredProjectiles(void) {
if (fireController) {
fireController->CheckDeferredProjectiles();
}
if (altFireController) {
altFireController->CheckDeferredProjectiles();
}
}
/*
==============================
hhWeapon::LaunchProjectiles
HUMANEAD: aob
==============================
*/
void hhWeapon::LaunchProjectiles( hhWeaponFireController* controller ) {
if ( IsHidden() ) {
return;
}
// wake up nearby monsters
if ( !spawnArgs.GetBool( "silent_fire" ) ) {
gameLocal.AlertAI( owner.GetEntity() );
}
// set the shader parm to the time of last projectile firing,
// which the gun material shaders can reference for single shot barrel glows, etc
SetShaderParm( SHADERPARM_DIVERSITY, gameLocal.random.CRandomFloat() );
SetShaderParm( SHADERPARM_TIMEOFFSET, -MS2SEC( gameLocal.realClientTime ) );
float low = ((float)controller->AmmoAvailable()*controller->AmmoRequired())/controller->LowAmmo();
if( !controller->LaunchProjectiles(pushVelocity) ) {
return;
}
if (!gameLocal.isClient) { //HUMANHEAD rww - let everyone hear this sound, and broadcast it (so don't try to play it for client-projectile weapons)
if( controller->AmmoAvailable()*controller->AmmoRequired() <= controller->LowAmmo() && low > 1 && spawnArgs.FindKey("snd_lowammo")) {
StartSound( "snd_lowammo", SND_CHANNEL_ANY, 0, true, NULL );
}
}
controller->UpdateMuzzleKick();
// add the light for the muzzleflash
controller->MuzzleFlash();
//HUMANEHAD: aob
controller->WeaponFeedback();
//HUMANHEAD END
}
/*
===============
hhWeapon::SetViewAnglesSensitivity
HUMANHEAD: aob
===============
*/
void hhWeapon::SetViewAnglesSensitivity( float fov ) {
if( owner.IsValid() ) {
owner->SetViewAnglesSensitivity( fov / g_fov.GetFloat() );
}
}
/*
===============
hhWeapon::GetDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetDict( const char* objectname ) {
return gameLocal.FindEntityDefDict( objectname, false );
}
/*
===============
hhWeapon::GetFireInfoDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetFireInfoDict( const char* objectname ) {
const idDict* dict = GetDict( objectname );
if( !dict ) {
return NULL;
}
return gameLocal.FindEntityDefDict( dict->GetString("def_fireInfo"), false );
}
/*
===============
hhWeapon::GetAltFireInfoDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetAltFireInfoDict( const char* objectname ) {
const idDict* dict = GetDict( objectname );
if( !dict ) {
return NULL;
}
return gameLocal.FindEntityDefDict( dict->GetString("def_altFireInfo"), false );
}
void hhWeapon::Event_GetString(const char *key) {
if ( fireController ) {
idThread::ReturnString( fireController->GetString(key) );
}
}
void hhWeapon::Event_GetAltString(const char *key) {
if ( altFireController ) {
idThread::ReturnString( altFireController->GetString(key) );
}
}
/*
===============
hhWeapon::Event_AddToAltClip
===============
*/
void hhWeapon::Event_AddToAltClip( int amount ) {
HH_ASSERT( altFireController );
altFireController->AddToClip( amount );
}
/*
===============
hhWeapon::Event_AmmoInClip
===============
*/
void hhWeapon::Event_AltAmmoInClip( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->AmmoInClip() );
}
/*
===============
hhWeapon::Event_AltAmmoAvailable
===============
*/
void hhWeapon::Event_AltAmmoAvailable( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->AmmoAvailable() );
}
/*
===============
hhWeapon::Event_ClipSize
===============
*/
void hhWeapon::Event_AltClipSize( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->ClipSize() );
}
/*
==============================
hhWeapon::Event_GetFireDelay
==============================
*/
void hhWeapon::Event_GetFireDelay() {
HH_ASSERT( fireController );
idThread::ReturnFloat( fireController->GetFireDelay() );
}
/*
==============================
hhWeapon::Event_GetAltFireDelay
==============================
*/
void hhWeapon::Event_GetAltFireDelay() {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->GetFireDelay() );
}
/*
==============================
hhWeapon::Event_HasAmmo
==============================
*/
void hhWeapon::Event_HasAmmo() {
idThread::ReturnInt( fireController->HasAmmo() );
}
/*
==============================
hhWeapon::Event_HasAltAmmo
==============================
*/
void hhWeapon::Event_HasAltAmmo() {
idThread::ReturnInt( altFireController->HasAmmo() );
}
/*
===============
hhWeapon::Event_SetViewAnglesSensitivity
HUMANHEAD: aob
===============
*/
void hhWeapon::Event_SetViewAnglesSensitivity( float fov ) {
SetViewAnglesSensitivity( fov );
}
/*
================
hhWeapon::UpdateNozzleFx
================
*/
void hhWeapon::UpdateNozzleFx( void ) {
if ( !nozzleFx || !g_projectileLights.GetBool()) {
return;
}
if ( nozzleJointHandle.view == INVALID_JOINT ) {
return;
}
//
// vent light
//
if ( nozzleGlowHandle == -1 ) {
memset(&nozzleGlow, 0, sizeof(nozzleGlow));
if ( owner.IsValid() ) {
nozzleGlow.allowLightInViewID = owner->entityNumber+1;
}
nozzleGlow.pointLight = true;
nozzleGlow.noShadows = true;
nozzleGlow.lightRadius.x = nozzleGlowRadius;
nozzleGlow.lightRadius.y = nozzleGlowRadius;
nozzleGlow.lightRadius.z = nozzleGlowRadius;
nozzleGlow.shader = nozzleGlowShader;
GetJointWorldTransform( nozzleJointHandle, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlow.origin += nozzleGlowOffset * nozzleGlow.axis;
nozzleGlowHandle = gameRenderWorld->AddLightDef(&nozzleGlow);
}
GetJointWorldTransform(nozzleJointHandle, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlow.origin += nozzleGlowOffset * nozzleGlow.axis;
nozzleGlow.shaderParms[ SHADERPARM_RED ] = nozzleGlowColor.x;
nozzleGlow.shaderParms[ SHADERPARM_GREEN ] = nozzleGlowColor.y;
nozzleGlow.shaderParms[ SHADERPARM_BLUE ] = nozzleGlowColor.z;
// Copy parms from the weapon into this light
for( int i = 4; i < 8; i++ ) {
nozzleGlow.shaderParms[ i ] = GetRenderEntity()->shaderParms[ i ];
}
gameRenderWorld->UpdateLightDef(nozzleGlowHandle, &nozzleGlow);
}
void hhWeapon::Event_HideWeapon(void) {
HideWeapon();
}
void hhWeapon::Event_ShowWeapon(void) {
ShowWeapon();
}
/*
===============
hhWeapon::FillDebugVars
===============
*/
void hhWeapon::FillDebugVars(idDict *args, int page) {
idStr text;
switch(page) {
case 1:
args->SetBool("WEAPON_LOWERWEAPON", WEAPON_LOWERWEAPON != 0);
args->SetBool("WEAPON_RAISEWEAPON", WEAPON_RAISEWEAPON != 0);
args->SetBool("WEAPON_ASIDEWEAPON", WEAPON_ASIDEWEAPON != 0);
args->SetBool("WEAPON_ATTACK", WEAPON_ATTACK != 0);
args->SetBool("WEAPON_ALTATTACK", WEAPON_ALTATTACK != 0);
args->SetBool("WEAPON_ALTMODE", WEAPON_ALTMODE != 0);
args->SetBool("WEAPON_RELOAD", WEAPON_RELOAD != 0);
break;
}
}
| 24.749802 | 321 | 0.648869 | AMS21 |
6eb0235879f977d48605c503d1bae02b99905776 | 1,543 | cpp | C++ | Centipede/GameComponents/Player.cpp | anunez97/centipede | 871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8 | [
"MIT"
] | null | null | null | Centipede/GameComponents/Player.cpp | anunez97/centipede | 871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8 | [
"MIT"
] | null | null | null | Centipede/GameComponents/Player.cpp | anunez97/centipede | 871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8 | [
"MIT"
] | null | null | null | // Player
#include "Player.h"
#include "MushroomField.h"
#include "BlasterFactory.h"
#include "Settings.h"
#include "Grid.h"
#include "PlayerManager.h"
#include "KeyboardController.h"
#include "Blaster.h"
Player::Player()
:lives(3), score(0), pController(0), pBlaster(0), wave(1)
{
pGrid = new Grid;
pField = new MushroomField;
pField->SetGrid(pGrid);
}
Player::~Player()
{
delete pGrid;
delete pField;
}
void Player::SetController(Controller* c)
{
pController = c;
}
void Player::Initialize()
{
pField->Initialize();
pBlaster = BlasterFactory::CreateBlaster(
sf::Vector2f(WindowManager::Window().getDefaultView().getSize().x / 2.0f, Grid::gridtoPixels(Settings::BROWBORDER)), this);
pController->SetBlaster(pBlaster);
pController->Enable();
lives--;
}
void Player::Deinitialize()
{
pField->Deinitialize();
pController->Disable();
pBlaster->MarkForDestroy();
}
void Player::SetWave(int w)
{
wave = w;
}
MushroomField* Player::GetField()
{
return pField;
}
Blaster* Player::GetBlaster()
{
return pBlaster;
}
Grid* Player::GetGrid()
{
return pGrid;
}
int Player::GetScore()
{
return score;
}
int Player::GetWave()
{
return wave;
}
int Player::GetLives()
{
return lives;
}
void Player::AddScore(int val)
{
score += val;
}
void Player::AddLife()
{
lives++;
}
void Player::PlayerDeath()
{
BlasterFactory::PlayerDeath();
pController->Disable();
pController->SetBlaster(0);
PlayerManager::SwitchPlayer();
} | 15.585859 | 126 | 0.652625 | anunez97 |
6eb04f751f7d32c88637bc22fb504b39e1237eb9 | 21,193 | cpp | C++ | src/UI/Reports/FactoryReport.cpp | gogoprog/OPHD | 70604dda83042ef9124728bebeaa70eb57f3dfca | [
"BSD-3-Clause"
] | null | null | null | src/UI/Reports/FactoryReport.cpp | gogoprog/OPHD | 70604dda83042ef9124728bebeaa70eb57f3dfca | [
"BSD-3-Clause"
] | null | null | null | src/UI/Reports/FactoryReport.cpp | gogoprog/OPHD | 70604dda83042ef9124728bebeaa70eb57f3dfca | [
"BSD-3-Clause"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "FactoryReport.h"
#include "../../Constants.h"
#include "../../FontManager.h"
#include "../../StructureManager.h"
#include "../../Things/Structures/SurfaceFactory.h"
#include "../../Things/Structures/SeedFactory.h"
#include "../../Things/Structures/UndergroundFactory.h"
#include <array>
using namespace NAS2D;
static int SORT_BY_PRODUCT_POSITION = 0;
static int STATUS_LABEL_POSITION = 0;
static int WIDTH_RESOURCES_REQUIRED_LABEL = 0;
static Rectangle_2d FACTORY_LISTBOX;
static Rectangle_2d DETAIL_PANEL;
static Font* FONT = nullptr;
static Font* FONT_BOLD = nullptr;
static Font* FONT_MED = nullptr;
static Font* FONT_MED_BOLD = nullptr;
static Font* FONT_BIG = nullptr;
static Font* FONT_BIG_BOLD = nullptr;
static Factory* SELECTED_FACTORY = nullptr;
static Image* FACTORY_SEED = nullptr;
static Image* FACTORY_AG = nullptr;
static Image* FACTORY_UG = nullptr;
static Image* FACTORY_IMAGE = nullptr;
std::array<Image*, PRODUCT_COUNT> PRODUCT_IMAGE_ARRAY;
static Image* _PRODUCT_NONE = nullptr;
static std::string FACTORY_STATUS;
static const std::string RESOURCES_REQUIRED = "Resources Required";
static ProductType SELECTED_PRODUCT_TYPE = PRODUCT_NONE;
/**
* C'tor
*/
FactoryReport::FactoryReport()
{
init();
}
/**
* D'tor
*/
FactoryReport::~FactoryReport()
{
delete FACTORY_SEED;
delete FACTORY_AG;
delete FACTORY_UG;
delete _PRODUCT_NONE;
SELECTED_FACTORY = nullptr;
for (auto img : PRODUCT_IMAGE_ARRAY) { delete img; }
}
/**
* Sets up UI positions.
*/
void FactoryReport::init()
{
FONT = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_NORMAL);
FONT_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_NORMAL);
FONT_MED = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_MEDIUM);
FONT_MED_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_MEDIUM);
FONT_BIG = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_HUGE);
FONT_BIG_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_HUGE);
FACTORY_SEED = new Image("ui/interface/factory_seed.png");
FACTORY_AG = new Image("ui/interface/factory_ag.png");
FACTORY_UG = new Image("ui/interface/factory_ug.png");
/// \todo Decide if this is the best place to have these images live or if it should be done at program start.
PRODUCT_IMAGE_ARRAY.fill(nullptr);
PRODUCT_IMAGE_ARRAY[PRODUCT_DIGGER] = new Image("ui/interface/product_robodigger.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_DOZER] = new Image("ui/interface/product_robodozer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MINER] = new Image("ui/interface/product_robominer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_EXPLORER] = new Image("ui/interface/product_roboexplorer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_TRUCK] = new Image("ui/interface/product_truck.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_ROAD_MATERIALS] = new Image("ui/interface/product_road_materials.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MAINTENANCE_PARTS] = new Image("ui/interface/product_maintenance_parts.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_CLOTHING] = new Image("ui/interface/product_clothing.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MEDICINE] = new Image("ui/interface/product_medicine.png");
_PRODUCT_NONE = new Image("ui/interface/product_none.png");
add(&lstFactoryList, 10, 63);
lstFactoryList.selectionChanged().connect(this, &FactoryReport::lstFactoryListSelectionChanged);
add(&btnShowAll, 10, 10);
btnShowAll.size(75, 20);
btnShowAll.type(Button::BUTTON_TOGGLE);
btnShowAll.toggle(true);
btnShowAll.text("All");
btnShowAll.click().connect(this, &FactoryReport::btnShowAllClicked);
add(&btnShowSurface, 87, 10);
btnShowSurface.size(75, 20);
btnShowSurface.type(Button::BUTTON_TOGGLE);
btnShowSurface.text("Surface");
btnShowSurface.click().connect(this, &FactoryReport::btnShowSurfaceClicked);
add(&btnShowUnderground, 164, 10);
btnShowUnderground.size(75, 20);
btnShowUnderground.type(Button::BUTTON_TOGGLE);
btnShowUnderground.text("Underground");
btnShowUnderground.click().connect(this, &FactoryReport::btnShowUndergroundClicked);
add(&btnShowActive, 10, 33);
btnShowActive.size(75, 20);
btnShowActive.type(Button::BUTTON_TOGGLE);
btnShowActive.text("Active");
btnShowActive.click().connect(this, &FactoryReport::btnShowActiveClicked);
add(&btnShowIdle, 87, 33);
btnShowIdle.size(75, 20);
btnShowIdle.type(Button::BUTTON_TOGGLE);
btnShowIdle.text("Idle");
btnShowIdle.click().connect(this, &FactoryReport::btnShowIdleClicked);
add(&btnShowDisabled, 164, 33);
btnShowDisabled.size(75, 20);
btnShowDisabled.type(Button::BUTTON_TOGGLE);
btnShowDisabled.text("Disabled");
btnShowDisabled.click().connect(this, &FactoryReport::btnShowDisabledClicked);
int position_x = Utility<Renderer>::get().width() - 110;
add(&btnIdle, position_x, 35);
btnIdle.type(Button::BUTTON_TOGGLE);
btnIdle.size(140, 30);
btnIdle.text("Idle");
btnIdle.click().connect(this, &FactoryReport::btnIdleClicked);
add(&btnClearProduction, position_x, 75);
btnClearProduction.size(140, 30);
btnClearProduction.text("Clear Production");
btnClearProduction.click().connect(this, &FactoryReport::btnClearProductionClicked);
add(&btnTakeMeThere, position_x, 115);
btnTakeMeThere.size(140, 30);
btnTakeMeThere.text(constants::BUTTON_TAKE_ME_THERE);
btnTakeMeThere.click().connect(this, &FactoryReport::btnTakeMeThereClicked);
add(&btnApply, 0, 0);
btnApply.size(140, 30);
btnApply.text("Apply");
btnApply.click().connect(this, &FactoryReport::btnApplyClicked);
add(&cboFilterByProduct, 250, 33);
cboFilterByProduct.size(200, 20);
cboFilterByProduct.addItem(constants::NONE, PRODUCT_NONE);
cboFilterByProduct.addItem(constants::CLOTHING, PRODUCT_CLOTHING);
cboFilterByProduct.addItem(constants::MAINTENANCE_SUPPLIES, PRODUCT_MAINTENANCE_PARTS);
cboFilterByProduct.addItem(constants::MEDICINE, PRODUCT_MEDICINE);
cboFilterByProduct.addItem(constants::ROBODIGGER, PRODUCT_DIGGER);
cboFilterByProduct.addItem(constants::ROBODOZER, PRODUCT_DOZER);
cboFilterByProduct.addItem(constants::ROBOEXPLORER, PRODUCT_EXPLORER);
cboFilterByProduct.addItem(constants::ROBOMINER, PRODUCT_MINER);
cboFilterByProduct.addItem(constants::ROAD_MATERIALS, PRODUCT_ROAD_MATERIALS);
cboFilterByProduct.addItem(constants::TRUCK, PRODUCT_TRUCK);
cboFilterByProduct.selectionChanged().connect(this, &FactoryReport::cboFilterByProductSelectionChanged);
add(&lstProducts, cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 20, rect().y() + 230);
txtProductDescription.font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_NORMAL);
txtProductDescription.height(128);
txtProductDescription.textColor(0, 185, 0);
txtProductDescription.text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
SORT_BY_PRODUCT_POSITION = cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() - FONT->width("Filter by Product");
WIDTH_RESOURCES_REQUIRED_LABEL = FONT_MED_BOLD->width(RESOURCES_REQUIRED);
Control::resized().connect(this, &FactoryReport::resized);
fillLists();
}
/**
* Override of the interface provided by ReportInterface class.
*
* \note Pointer
*/
void FactoryReport::selectStructure(Structure* structure)
{
lstFactoryList.currentSelection(dynamic_cast<Factory*>(structure));
}
void FactoryReport::clearSelection()
{
lstFactoryList.clearSelection();
SELECTED_FACTORY = nullptr;
}
/**
* Pass-through function to simulate clicking on the Show All button.
*/
void FactoryReport::refresh()
{
btnShowAllClicked();
}
/**
* Fills the factory list with all available factories.
*/
void FactoryReport::fillLists()
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto factory : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
lstFactoryList.addItem(static_cast<Factory*>(factory));
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on product type.
*/
void FactoryReport::fillFactoryList(ProductType type)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
Factory* factory = static_cast<Factory*>(f);
if (factory->productType() == type)
{
lstFactoryList.addItem(factory);
}
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on surface/subterranean
*/
void FactoryReport::fillFactoryList(bool surface)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
Factory* factory = static_cast<Factory*>(f);
if (surface && (factory->name() == constants::SURFACE_FACTORY || factory->name() == constants::SEED_FACTORY))
{
lstFactoryList.addItem(factory);
}
else if (!surface && factory->name() == constants::UNDERGROUND_FACTORY)
{
lstFactoryList.addItem(factory);
}
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on structure state.
*/
void FactoryReport::fillFactoryList(Structure::StructureState state)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
if (f->state() == state)
{
lstFactoryList.addItem(static_cast<Factory*>(f));
}
}
lstFactoryList.setSelection(0);
checkFactoryActionControls();
}
/**
* Sets visibility for factory action controls.
*/
void FactoryReport::checkFactoryActionControls()
{
bool actionControlVisible = !lstFactoryList.empty();
btnIdle.visible(actionControlVisible);
btnClearProduction.visible(actionControlVisible);
btnTakeMeThere.visible(actionControlVisible);
btnApply.visible(actionControlVisible);
lstProducts.visible(actionControlVisible);
if (actionControlVisible) { lstFactoryList.setSelection(0); }
}
/**
*
*/
void FactoryReport::resized(Control* c)
{
FACTORY_LISTBOX.x(positionX() + 10);
FACTORY_LISTBOX.y(cboFilterByProduct.positionY() + cboFilterByProduct.height() + 10);
FACTORY_LISTBOX.width(cboFilterByProduct.positionX() + cboFilterByProduct.width() - 10);
FACTORY_LISTBOX.height(height() - 74);
lstFactoryList.size(FACTORY_LISTBOX.width(), FACTORY_LISTBOX.height());
DETAIL_PANEL(cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 20,
rect().y() + 10,
rect().width() - (cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width()) - 30,
rect().y() + rect().height() - 69);
STATUS_LABEL_POSITION = DETAIL_PANEL.x() + FONT_MED_BOLD->width("Status") + 158;
int position_x = rect().width() - 150;
btnIdle.position(position_x, btnIdle.positionY());
btnClearProduction.position(position_x, btnClearProduction.positionY());
btnTakeMeThere.position(position_x, btnTakeMeThere.positionY());
btnApply.position(position_x, rect().height() + 8);
lstProducts.size(DETAIL_PANEL.width() / 3, DETAIL_PANEL.height() - 219);
lstProducts.selectionChanged().connect(this, &FactoryReport::lstProductsSelectionChanged);
txtProductDescription.position(lstProducts.positionX() + lstProducts.width() + 158, lstProducts.positionY());
txtProductDescription.width(rect().width() - txtProductDescription.positionX() - 30);
}
/**
* This has been overridden to handle some UI elements that need
* special handling.
*/
void FactoryReport::visibilityChanged(bool visible)
{
if (!SELECTED_FACTORY) { return; }
Structure::StructureState _state = SELECTED_FACTORY->state();
btnApply.visible(visible && (_state == Structure::OPERATIONAL || _state == Structure::IDLE));
checkFactoryActionControls();
}
/**
*
*/
void FactoryReport::filterButtonClicked(bool clearCbo)
{
btnShowAll.toggle(false);
btnShowSurface.toggle(false);
btnShowUnderground.toggle(false);
btnShowActive.toggle(false);
btnShowIdle.toggle(false);
btnShowDisabled.toggle(false);
if (clearCbo) { cboFilterByProduct.clearSelection(); }
}
/**
*
*/
void FactoryReport::btnShowAllClicked()
{
filterButtonClicked(true);
btnShowAll.toggle(true);
fillLists();
}
/**
*
*/
void FactoryReport::btnShowSurfaceClicked()
{
filterButtonClicked(true);
btnShowSurface.toggle(true);
fillFactoryList(true);
}
/**
*
*/
void FactoryReport::btnShowUndergroundClicked()
{
filterButtonClicked(true);
btnShowUnderground.toggle(true);
fillFactoryList(false);
}
/**
*
*/
void FactoryReport::btnShowActiveClicked()
{
filterButtonClicked(true);
btnShowActive.toggle(true);
fillFactoryList(Structure::OPERATIONAL);
}
/**
*
*/
void FactoryReport::btnShowIdleClicked()
{
filterButtonClicked(true);
btnShowIdle.toggle(true);
fillFactoryList(Structure::IDLE);
}
/**
*
*/
void FactoryReport::btnShowDisabledClicked()
{
filterButtonClicked(true);
btnShowDisabled.toggle(true);
fillFactoryList(Structure::DISABLED);
}
/**
*
*/
void FactoryReport::btnIdleClicked()
{
SELECTED_FACTORY->forceIdle(btnIdle.toggled());
FACTORY_STATUS = structureStateDescription(SELECTED_FACTORY->state());
}
/**
*
*/
void FactoryReport::btnClearProductionClicked()
{
SELECTED_FACTORY->productType(PRODUCT_NONE);
lstProducts.clearSelection();
cboFilterByProductSelectionChanged();
}
/**
*
*/
void FactoryReport::btnTakeMeThereClicked()
{
takeMeThereCallback()(SELECTED_FACTORY);
}
/**
*
*/
void FactoryReport::btnApplyClicked()
{
SELECTED_FACTORY->productType(SELECTED_PRODUCT_TYPE);
cboFilterByProductSelectionChanged();
}
/**
*
*/
void FactoryReport::lstFactoryListSelectionChanged()
{
SELECTED_FACTORY = lstFactoryList.selectedFactory();
if (!SELECTED_FACTORY)
{
checkFactoryActionControls();
return;
}
/// \fixme Ugly
if (SELECTED_FACTORY->name() == constants::SEED_FACTORY) { FACTORY_IMAGE = FACTORY_SEED; }
else if (SELECTED_FACTORY->name() == constants::SURFACE_FACTORY) { FACTORY_IMAGE = FACTORY_AG; }
else if (SELECTED_FACTORY->name() == constants::UNDERGROUND_FACTORY) { FACTORY_IMAGE = FACTORY_UG; }
FACTORY_STATUS = structureStateDescription(SELECTED_FACTORY->state());
btnIdle.toggle(SELECTED_FACTORY->state() == Structure::IDLE);
btnIdle.enabled(SELECTED_FACTORY->state() == Structure::OPERATIONAL || SELECTED_FACTORY->state() == Structure::IDLE);
btnClearProduction.enabled(SELECTED_FACTORY->state() == Structure::OPERATIONAL || SELECTED_FACTORY->state() == Structure::IDLE);
lstProducts.dropAllItems();
if (SELECTED_FACTORY->state() != Structure::DESTROYED)
{
const Factory::ProductionTypeList& _pl = SELECTED_FACTORY->productList();
for (auto item : _pl)
{
lstProducts.addItem(productDescription(item), static_cast<int>(item));
}
}
lstProducts.clearSelection();
lstProducts.setSelectionByName(productDescription(SELECTED_FACTORY->productType()));
SELECTED_PRODUCT_TYPE = SELECTED_FACTORY->productType();
Structure::StructureState _state = SELECTED_FACTORY->state();
btnApply.visible(_state == Structure::OPERATIONAL || _state == Structure::IDLE);
}
/**
*
*/
void FactoryReport::lstProductsSelectionChanged()
{
SELECTED_PRODUCT_TYPE = static_cast<ProductType>(lstProducts.selectionTag());
}
/**
*
*/
void FactoryReport::cboFilterByProductSelectionChanged()
{
if (cboFilterByProduct.currentSelection() == constants::NO_SELECTION) { return; }
filterButtonClicked(false);
fillFactoryList(static_cast<ProductType>(cboFilterByProduct.selectionTag()));
}
/**
*
*/
void FactoryReport::drawDetailPane(Renderer& r)
{
Color_4ub text_color(0, 185, 0, 255);
r.drawImage(*FACTORY_IMAGE, DETAIL_PANEL.x(), DETAIL_PANEL.y() + 25);
r.drawText(*FONT_BIG_BOLD, SELECTED_FACTORY->name(), DETAIL_PANEL.x(), DETAIL_PANEL.y() - 8, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_MED_BOLD, "Status", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 20, text_color.red(), text_color.green(), text_color.blue());
if (SELECTED_FACTORY->disabled() || SELECTED_FACTORY->destroyed()) { text_color(255, 0, 0, 255); }
r.drawText(*FONT_MED, FACTORY_STATUS, STATUS_LABEL_POSITION, DETAIL_PANEL.y() + 20, text_color.red(), text_color.green(), text_color.blue());
text_color(0, 185, 0, 255);
r.drawText(*FONT_MED_BOLD, RESOURCES_REQUIRED, DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 60, text_color.red(), text_color.green(), text_color.blue());
// MINERAL RESOURCES
r.drawText(*FONT_BOLD, "Common Metals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 80, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Common Minerals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 95, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Rare Metals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 110, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Rare Minerals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 125, text_color.red(), text_color.green(), text_color.blue());
const ProductionCost& _pc = productCost(SELECTED_FACTORY->productType());
r.drawText(*FONT, std::to_string(_pc.commonMetals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.commonMetals())), DETAIL_PANEL.y() + 80, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.commonMinerals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.commonMinerals())), DETAIL_PANEL.y() + 95, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.rareMetals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.rareMetals())), DETAIL_PANEL.y() + 110, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.rareMinerals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.rareMinerals())), DETAIL_PANEL.y() + 125, text_color.red(), text_color.green(), text_color.blue());
// POPULATION
SELECTED_FACTORY->populationAvailable()[0] == SELECTED_FACTORY->populationRequirements()[0] ? text_color(0, 185, 0, 255) : text_color(255, 0, 0, 255);
r.drawText(*FONT_BOLD, "Workers", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 140, text_color.red(), text_color.green(), text_color.blue());
std::string _scratch = string_format("%i / %i", SELECTED_FACTORY->populationAvailable()[0], SELECTED_FACTORY->populationRequirements()[0]);
r.drawText(*FONT, _scratch, DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(_scratch), DETAIL_PANEL.y() + 140, text_color.red(), text_color.green(), text_color.blue());
}
/**
*
*/
void FactoryReport::drawProductPane(Renderer& r)
{
r.drawText(*FONT_BIG_BOLD, "Production", DETAIL_PANEL.x(), DETAIL_PANEL.y() + 180, 0, 185, 0);
int position_x = DETAIL_PANEL.x() + lstProducts.width() + 20;
if (SELECTED_PRODUCT_TYPE != PRODUCT_NONE)
{
r.drawText(*FONT_BIG_BOLD, productDescription(SELECTED_PRODUCT_TYPE), position_x, DETAIL_PANEL.y() + 180, 0, 185, 0);
r.drawImage(*PRODUCT_IMAGE_ARRAY[SELECTED_PRODUCT_TYPE], position_x, lstProducts.positionY());
txtProductDescription.update();
}
if (SELECTED_FACTORY->productType() == PRODUCT_NONE) { return; }
r.drawText(*FONT_BIG_BOLD, "Progress", position_x, DETAIL_PANEL.y() + 358, 0, 185, 0);
r.drawText(*FONT_MED, "Building " + productDescription(SELECTED_FACTORY->productType()), position_x, DETAIL_PANEL.y() + 393, 0, 185, 0);
float percent = 0.0f;
if (SELECTED_FACTORY->productType() != PRODUCT_NONE) { percent = static_cast<float>(SELECTED_FACTORY->productionTurnsCompleted()) / static_cast<float>(SELECTED_FACTORY->productionTurnsToComplete()); }
drawBasicProgressBar(position_x, DETAIL_PANEL.y() + 413, rect().width() - position_x - 10, 30, percent, 4);
std::string _turns = string_format("%i / %i", SELECTED_FACTORY->productionTurnsCompleted(), SELECTED_FACTORY->productionTurnsToComplete());
r.drawText(*FONT_MED_BOLD, "Turns", position_x, DETAIL_PANEL.y() + 449, 0, 185, 0);
r.drawText(*FONT_MED, _turns, rect().width() - FONT_MED->width(_turns) - 10, DETAIL_PANEL.y() + 449, 0, 185, 0);
}
/**
*
*/
void FactoryReport::update()
{
if (!visible()) { return; }
Renderer& r = Utility<Renderer>::get();
r.drawLine(cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 10, rect().y() + 10, cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 10, rect().y() + rect().height() - 10, 0, 185, 0);
r.drawText(*FONT, "Filter by Product", SORT_BY_PRODUCT_POSITION, rect().y() + 10, 0, 185, 0);
if (SELECTED_FACTORY)
{
drawDetailPane(r);
drawProductPane(r);
}
UIContainer::update();
}
| 32.806502 | 477 | 0.750106 | gogoprog |
6eb137bdfbd0fc38213efd55d1944c4146b05242 | 2,776 | hpp | C++ | src/parser/symbols/letterlike.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | 4 | 2021-04-02T02:52:05.000Z | 2021-12-11T00:42:35.000Z | src/parser/symbols/letterlike.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | src/parser/symbols/letterlike.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | #pragma once
#include "mfl/code_point.hpp"
#include <array>
#include <utility>
namespace mfl::parser
{
constexpr auto letterlike_symbols = std::array<std::pair<const char*, code_point>, 93>{{
{"AA", 0x00c5},
{"AE", 0x00c6},
{"BbbC", 0x2102},
{"BbbN", 0x2115},
{"BbbP", 0x2119},
{"BbbQ", 0x211a},
{"BbbR", 0x211d},
{"BbbZ", 0x2124},
{"Finv", 0x2132},
{"Game", 0x2141},
{"Im", 0x2111},
{"L", 0x0141},
{"O", 0x00d8},
{"OE", 0x0152},
{"P", 0x00b6},
{"Re", 0x211c},
{"S", 0x00a7},
{"Thorn", 0x00de},
{"Upsilon", 0x03a5},
{"ae", 0x00e6},
{"aleph", 0x2135},
{"backprime", 0x2035},
{"backslash", 0x005c},
{"beth", 0x2136},
{"blacksquare", 0x25a0},
{"cent", 0x00a2},
{"checkmark", 0x2713},
{"circledR", 0x00ae},
{"circledS", 0x24c8},
{"clubsuit", 0x2663},
{"clubsuitopen", 0x2667},
{"copyright", 0x00a9},
{"daleth", 0x2138},
{"danger", 0x26a0},
{"degree", 0x00b0},
{"diamondsuit", 0x2662},
{"digamma", 0x03dd},
{"ell", 0x2113},
{"emptyset", 0x2205},
{"eth", 0x00f0},
{"exists", 0x2203},
{"flat", 0x266d},
{"forall", 0x2200},
{"frakC", 0x212d},
{"frakZ", 0x2128},
{"gimel", 0x2137},
{"hbar", 0x0127},
{"heartsuit", 0x2661},
{"hslash", 0x210f},
{"i", 0x0131},
{"imath", 0x0131},
{"infty", 0x221e},
{"jmath", 0x0237},
{"l", 0x0142},
{"lambdabar", 0x019b},
{"macron", 0x00af},
{"maltese", 0x2720},
{"mho", 0x2127},
{"nabla", 0x2207},
{"natural", 0x266e},
{"nexists", 0x2204},
{"o", 0x00f8},
{"oe", 0x0153},
{"partial", 0x2202},
{"perthousand", 0x2030},
{"prime", 0x2032},
{"scrB", 0x212c},
{"scrE", 0x2130},
{"scrF", 0x2131},
{"scrH", 0x210b},
{"scrI", 0x2110},
{"scrL", 0x2112},
{"scrM", 0x2133},
{"scrR", 0x211b},
{"scre", 0x212f},
{"scrg", 0x210a},
{"scro", 0x2134},
{"sharp", 0x266f},
{"spadesuit", 0x2660},
{"spadesuitopen", 0x2664},
{"ss", 0x00df},
{"sterling", 0x00a3},
{"surd", 0x221a},
{"textasciiacute", 0x00b4},
{"textasciicircum", 0x005e},
{"textasciigrave", 0x0060},
{"textasciitilde", 0x007e},
{"thorn", 0x00fe},
{"underbar", 0x0331},
{"varkappa", 0x03f0},
{"varnothing", 0x2205},
{"wp", 0x2118},
{"yen", 0x00a5},
}};
}
| 26.188679 | 92 | 0.440562 | cpp-niel |
6eb333ffd0637682d57f8119b1498e63397f860e | 2,727 | cpp | C++ | Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | 1 | 2021-07-13T19:21:57.000Z | 2021-07-13T19:21:57.000Z | Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | null | null | null | Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | null | null | null | #include "Experimentals/SuppressPlayerLoginInfo.hpp"
#include "API/CNWSPlayer.hpp"
#include "API/CNWSMessage.hpp"
#include "API/Functions.hpp"
#include "API/Globals.hpp"
#include "API/Constants.hpp"
namespace Experimental {
using namespace NWNXLib;
using namespace NWNXLib::API;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_AddHook;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_AllHook;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_DeleteHook;
SuppressPlayerLoginInfo::SuppressPlayerLoginInfo()
{
s_SendServerToPlayerPlayerList_AddHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AddEjP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_AddHook, Hooks::Order::Late);
s_SendServerToPlayerPlayerList_AllHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AllEP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_AllHook, Hooks::Order::Late);
s_SendServerToPlayerPlayerList_DeleteHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage35SendServerToPlayerPlayerList_DeleteEjP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_DeleteHook, Hooks::Order::Late);
static auto s_ReplacedFunc = Hooks::HookFunction(API::Functions::_ZN11CNWSMessage49HandlePlayerToServerPlayModuleCharacterList_StartEP10CNWSPlayer,
(void*)&HandlePlayerToServerPlayModuleCharacterList_StartHook, Hooks::Order::Final);
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_AddHook(CNWSMessage *pThis, uint32_t nPlayerId, CNWSPlayer *pNewPlayer)
{
return nPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_AddHook->CallOriginal<int32_t>(pThis, nPlayerId, pNewPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_AllHook(CNWSMessage *pThis, CNWSPlayer *pPlayer)
{
return pPlayer->m_nPlayerID == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_AllHook->CallOriginal<int32_t>(pThis, pPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_DeleteHook(CNWSMessage *pThis, uint32_t nPlayerId, CNWSPlayer *pNewPlayer)
{
return nPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_DeleteHook->CallOriginal<int32_t>(pThis, nPlayerId, pNewPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::HandlePlayerToServerPlayModuleCharacterList_StartHook(
CNWSMessage* pThis, CNWSPlayer* pPlayer)
{
if (pThis->MessageReadOverflow(true) || pThis->MessageReadUnderflow(true))
return false;
pPlayer->m_bPlayModuleListingCharacters = true;
return true;
}
}
| 45.45 | 165 | 0.807847 | Mefi100 |
6eb6fe112022e783839e132a269c3f48b17ebea5 | 2,993 | hpp | C++ | physic.hpp | Bethoth/SComputer | ce3547a0b7065f4422050ca03f3b05c50dee1772 | [
"MIT"
] | null | null | null | physic.hpp | Bethoth/SComputer | ce3547a0b7065f4422050ca03f3b05c50dee1772 | [
"MIT"
] | null | null | null | physic.hpp | Bethoth/SComputer | ce3547a0b7065f4422050ca03f3b05c50dee1772 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <string>
#include <cmath>
#include <optional>
#include "maths.hpp"
using std::stod;
namespace physic {
const double G = 6.67e-11;
std::optional<double> voluminal_mass(const std::string& rho, const std::string& mass, const std::string& volume) {
const bool rho_is_searched = rho == "searched";
const bool mass_is_searched = mass == "searched";
const bool volume_is_searched = volume == "searched";
if (rho_is_searched && !mass_is_searched && !volume_is_searched) {
double int_mass = stod(mass);
double int_volume = stod(volume);
return std::round((int_mass / int_volume) * options::rounder) / options::rounder;
}
else if (mass_is_searched && !rho_is_searched && !volume_is_searched) {
double int_rho = stod(rho);
double int_volume = stod(volume);
return std::round((int_rho * int_volume) * options::rounder) / options::rounder;
}
else if (volume_is_searched && !rho_is_searched && !mass_is_searched) {
double int_rho = stod(rho);
double int_mass = stod(mass);
return std::round((int_mass / int_rho) * options::rounder) / options::rounder;
}
return {};
}
std::optional<double> gravitational_force(const std::string& F, const std::string& mass_a, const std::string& mass_b, const std::string& distance) {
const bool F_is_searched = F == "searched";
const bool mass_a_is_searched = mass_a == "searched";
const bool mass_b_is_searched = mass_b == "searched";
const bool distance_is_searched = distance == "searched";
if (F_is_searched && !mass_a_is_searched && !mass_b_is_searched && !distance_is_searched) {
double int_mass_a = stod(mass_a);
double int_mass_b = stod(mass_b);
double int_distance = stod(distance);
return std::round((G * (int_mass_a * int_mass_b) / std::pow(int_distance, 2)) * options::rounder) / options::rounder;
}
else if (distance_is_searched && !mass_a_is_searched && !mass_b_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_mass_a = stod(mass_a);
double int_mass_b = stod(mass_b);
return std::round(std::sqrt((G * int_mass_a * int_mass_b) / int_F) * options::rounder) / options::rounder;
}
else if (mass_a_is_searched && !distance_is_searched && !mass_b_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_distance = stod(distance);
double int_mass_b = stod(mass_b);
return std::round(((int_F * std::pow(int_distance, 2)) / (G * int_mass_b)) * options::rounder) / options::rounder;
}
else if (mass_b_is_searched && !distance_is_searched && !mass_a_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_distance = stod(distance);
double int_mass_a = stod(mass_a);
return std::round(((int_F * std::pow(int_distance, 2)) / (G * int_mass_a)) * options::rounder) / options::rounder;
}
return {};
}
std::array<std::string, 2> figures = { "Voluminal mass", "Gravitational force" };
int figures_size = std::tuple_size<std::array<std::string, 2>>::value;
}
| 39.906667 | 149 | 0.696625 | Bethoth |
6eb9947dd875ba85d14cb31d167e62ee8aefe111 | 321 | cpp | C++ | atcoder/abc092/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | atcoder/abc092/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | atcoder/abc092/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int n;
int d;
int x;
cin >> n;
cin >> d >> x;
int a;
int result = x;
for(int i = 0; i < n; i++){
cin >> a;
result += d / a;
if(d % a != 0){
result += 1;
}
}
cout << result << endl;
}
| 14.590909 | 31 | 0.383178 | yuik46 |
6ebd6a92172b5081434b69543f6a97c823542698 | 5,565 | cpp | C++ | Partmod/free_space_manager.cpp | Null665/partmod | 11f2b90c745e27bdb47b105e0bf45834c62d3527 | [
"BSD-3-Clause"
] | 1 | 2017-02-12T15:10:38.000Z | 2017-02-12T15:10:38.000Z | Partmod/free_space_manager.cpp | Null665/partmod | 11f2b90c745e27bdb47b105e0bf45834c62d3527 | [
"BSD-3-Clause"
] | 1 | 2016-06-03T18:20:16.000Z | 2016-10-10T22:22:41.000Z | Partmod/free_space_manager.cpp | Null665/partmod | 11f2b90c745e27bdb47b105e0bf45834c62d3527 | [
"BSD-3-Clause"
] | null | null | null | #include "free_space_manager.h"
#include "disk.h"
#include "disk_exception.h"
#include <algorithm>
using namespace std;
bool cmp_frs(FREE_SPACE a,FREE_SPACE b)
{
return a.begin_sector < b.begin_sector;
}
void FreeSpaceManager::sort_vectors()
{
sort(free_space.begin(),free_space.end(),cmp_frs);
}
FreeSpaceManager::~FreeSpaceManager()
{
free_space.clear();
free_space.resize(0);
}
uint32_t FreeSpaceManager::CountFreeSpaces()
{
return free_space.size();
}
const FREE_SPACE &FreeSpaceManager::GetFreeSpace(uint32_t f)
{
if(f>CountFreeSpaces())
throw DiskException(ERR_OUT_OF_BOUNDS);
return free_space[f];
}
//
// FINALLY THIS SHIT WORKS!!!
//
void FreeSpaceManager::FindFreeSpace(PartitionManager *partman,uint64_t num_sect,int bps,int spt)
{
free_space.clear();
uint64_t NSECT_MB=MB/bps; // Numbert of disk sectors in megabyte
bool found_gpt;
try
{
partman->GetPartition(0).flags&PART_MBR_GPT ? found_gpt=true : found_gpt=false;
}
catch(...) {found_gpt=false;}
if(found_gpt)
find_in(partman,num_sect,0,PART_PRIMARY | PART_EXTENDED | PART_MBR_GPT,0,FREE_UNALLOCATED,NSECT_MB,1);
else
find_in(partman,num_sect,0,PART_PRIMARY | PART_EXTENDED | PART_MBR_GPT,0,FREE_UNALLOCATED,NSECT_MB,1); //spt
if(partman->CountPartitions(PART_EXTENDED)!=0)
find_in(partman,num_sect,PART_EXTENDED,PART_LOGICAL,spt,FREE_EXTENDED,NSECT_MB);
if(partman->CountPartitions(PART_MBR_GPT)!=0)
find_in(partman,num_sect,PART_MBR_GPT,PART_GPT,spt,FREE_GPT,NSECT_MB);
this->sort_vectors();
return;
}
void FreeSpaceManager::find_in(PartitionManager *partman,
uint64_t num_sect, // Number of sectors on disk
uint32_t parent_flag, // Parent flag: (optional)PART_EXTENDED, PART_MBR_GPT
uint32_t child_flag, // Child flag: PART_LOGICAL, PART_GPT
uint32_t sect_between, // Number of sectors between partition and the free space
uint32_t free_space_type, // FREE_EXTENDED, FREE_GPT, FREE_UNALLOCATED
uint32_t resolution, // Min size of the free space
uint32_t reserved_space // Number of reseved sectors at the beginning of disk
)
{
GEN_PART part_curr,part_next;
FREE_SPACE tmp;
// Special case:
// there are no partitions and we need to find unallocated space
if(partman->CountPartitions()==0 && parent_flag==0)
{
tmp.begin_sector=reserved_space;
tmp.length=num_sect-tmp.begin_sector;
tmp.type=FREE_UNALLOCATED;
free_space.push_back(tmp);
return;
}
// there are no partitions and we are trying to find free space on something else (PART_EXTENDED or PART_MBR_GPT)
else if(partman->CountPartitions()==0 && parent_flag!=0)
{
return;
}
for(unsigned i=0,j=1;i<partman->CountPartitions()-1,j<partman->CountPartitions(); i++,j++)
{
part_curr=partman->GetPartition(i);
if( !(part_curr.flags&child_flag))
continue;
part_next=partman->GetPartition(j);
if( !(part_next.flags&child_flag))
{
i--;
continue;
}
tmp.begin_sector=part_curr.begin_sector+part_curr.length;
tmp.length=part_next.begin_sector-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
// ----------
GEN_PART part_parent,last_logical;
bool found=false;
if(parent_flag==0)
{
part_parent.begin_sector=reserved_space;
part_parent.length=num_sect-part_parent.begin_sector;
}
else
{
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&parent_flag)
{
part_parent=partman->GetPartition(i);
found=true;
break;
}
if(!found)
return;
}
found=false;
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&child_flag)
{
last_logical=partman->GetPartition(i);
found=true;
}
if(found==false)
{
tmp.begin_sector=part_parent.begin_sector;
tmp.length=part_parent.length;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
else
{
// Find free space between the parent and last child partition
tmp.begin_sector=last_logical.begin_sector+last_logical.length;
tmp.length= (part_parent.begin_sector+part_parent.length)-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
// Find free space between the parent and first child partition
GEN_PART first_logical;
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&child_flag)
{
first_logical=partman->GetPartition(i);
break;
}
tmp.begin_sector=part_parent.begin_sector;
tmp.length= first_logical.begin_sector-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
}
| 25.527523 | 116 | 0.654447 | Null665 |
6ebff0ee1d9f67afa95d19050693d78b9c8d6a70 | 1,828 | cpp | C++ | tests/src/Helpers/TestRoutes.cpp | nemu-framework/core | dea0ab4382684d0efc7f387e8a69a51a170c9305 | [
"MIT"
] | null | null | null | tests/src/Helpers/TestRoutes.cpp | nemu-framework/core | dea0ab4382684d0efc7f387e8a69a51a170c9305 | [
"MIT"
] | 3 | 2022-03-26T12:52:32.000Z | 2022-03-28T19:35:21.000Z | tests/src/Helpers/TestRoutes.cpp | nemu-framework/core | dea0ab4382684d0efc7f387e8a69a51a170c9305 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2019 Xavier Leclercq
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 "TestRoutes.h"
TestRoutes::TestRoutes()
: m_visitedRoutes(std::make_shared<std::vector<std::string>>())
{
setDefaultRoute(Nemu::Route("",
[](const Nemu::WebRequest& request, Nemu::WebResponseBuilder& response, void* handlerData)
{
response.setStatus(404);
TestRoutes* routes = reinterpret_cast<TestRoutes*>(handlerData);
std::lock_guard<std::mutex> guard(routes->m_visitedRoutesMutex);
routes->m_visitedRoutes->push_back(request.URI());
},
std::shared_ptr<TestRoutes>(this, [](TestRoutes*) {})));
}
const std::vector<std::string>& TestRoutes::visitedRoutes() const
{
return *m_visitedRoutes;
}
| 41.545455 | 98 | 0.715536 | nemu-framework |
6ec047d8a2d0a5e30086b6632aefb5e40e2b136e | 292 | hpp | C++ | src/Qt5Network/QNetworkCookieJar.hpp | dafrito/luacxx | 278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad | [
"MIT"
] | 128 | 2015-01-07T19:47:09.000Z | 2022-01-22T19:42:14.000Z | src/Qt5Network/QNetworkCookieJar.hpp | dafrito/luacxx | 278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad | [
"MIT"
] | null | null | null | src/Qt5Network/QNetworkCookieJar.hpp | dafrito/luacxx | 278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad | [
"MIT"
] | 24 | 2015-01-07T19:47:10.000Z | 2022-01-25T17:42:37.000Z | #ifndef luacxx_QNetworkCookieJar_INCLUDED
#define luacxx_QNetworkCookieJar_INCLUDED
#include "../stack.hpp"
#include <QNetworkCookieJar>
LUA_METATABLE_BUILT(QNetworkCookieJar)
extern "C" int luaopen_luacxx_QNetworkCookieJar(lua_State* const);
#endif // luacxx_QNetworkCookieJar_INCLUDED
| 22.461538 | 66 | 0.84589 | dafrito |
6ec84435134d26540a86ea3ea7a58b7de7f6e4dd | 1,472 | hpp | C++ | include/threepp/math/float_view.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null | include/threepp/math/float_view.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null | include/threepp/math/float_view.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null |
#ifndef THREEPP_FLOAT_VIEW_HPP
#define THREEPP_FLOAT_VIEW_HPP
#include <functional>
#include <utility>
#include <optional>
namespace threepp {
class float_view {
public:
float value{};
float operator()() const {
return value;
}
float_view &operator=(float v) {
this->value = v;
if (f_) f_.value()();
return *this;
}
float_view &operator*=(float f) {
value *= f;
if (f_) f_.value()();
return *this;
}
float_view &operator/=(float f) {
value /= f;
if (f_) f_.value()();
return *this;
}
float_view &operator+=(float f) {
value += f;
if (f_) f_.value()();
return *this;
}
float_view &operator-=(float f) {
value -= f;
if (f_) f_.value()();
return *this;
}
float_view &operator++() {
value++;
if (f_) f_.value()();
return *this;
}
float_view &operator--() {
value--;
if (f_) f_.value()();
return *this;
}
private:
std::optional<std::function<void()>> f_;
void setCallback(std::function<void()> f) {
f_ = std::move(f);
}
friend class Euler;
};
}// namespace threepp
#endif//THREEPP_FLOAT_VIEW_HPP
| 18.871795 | 51 | 0.44837 | maidamai0 |
6ec9087c5d75826f569be263ef3cfecfaca5e0f8 | 1,415 | cpp | C++ | episode3/episode3/episode3.cpp | thenets/ngon_cs_s2 | ffbfd5ef9f213355aafa1aca1a1e318be784a8d6 | [
"MIT"
] | null | null | null | episode3/episode3/episode3.cpp | thenets/ngon_cs_s2 | ffbfd5ef9f213355aafa1aca1a1e318be784a8d6 | [
"MIT"
] | null | null | null | episode3/episode3/episode3.cpp | thenets/ngon_cs_s2 | ffbfd5ef9f213355aafa1aca1a1e318be784a8d6 | [
"MIT"
] | null | null | null | #include <iostream>
int max(int a, int b) {
return a > b ? a : b;
}
bool isLowercase(char c)
{
if (c >= 'a' and c <= 'z')
return true;
return false;
}
bool isUppercase(char c)
{
if (c >= 'A' and c <= 'Z')
return true;
return false;
}
bool isLetter(char c)
{
if (isUppercase(c) or isLowercase(c))
return true;
return false;
}
char invertCase(char c)
{
int alphabet_size = 'z' - 'a';
int jump_size = 'a' - 'Z' + alphabet_size;
if (isLowercase(c))
return c - jump_size;
if (isUppercase(c))
return c + jump_size;
return c;
}
int main()
{
// Print the lowercase alphabet
{
char c = 'a';
while (isLowercase(c))
{
std::cout << c;
c++;
}
std::cout << "\n";
}
// Print the entire alphabet
{
char c{};
while (c <= max('z', 'Z'))
{
if (isLetter(c))
std::cout << invertCase(c);
c++;
}
std::cout << "\n";
}
// Print the entire alphabet (optimized way)
{
char c = 'a';
char end_lowercase = 'z' + 1;
char end_uppercase = 'Z' + 1;
while (c != end_uppercase)
{
if (c == end_lowercase)
c = 'A';
std::cout << c;
c++;
}
std::cout << "\n";
}
}
| 17.048193 | 48 | 0.435336 | thenets |
6ecd27327e29418e36ffd3b391dc26babac7cdd4 | 8,330 | cpp | C++ | hash/appl_hash_test.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | hash/appl_hash_test.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | hash/appl_hash_test.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | /* See LICENSE for license details */
/*
*/
#include <stdio.h>
#include <string.h>
#include <appl.h>
#include <hash/appl_hash_test.h>
#include <misc/appl_unused.h>
/*
*/
struct appl_hash_test_node
{
struct appl_list
o_list;
/* -- */
char const *
p_string;
int
i_string_len;
#define PADDING (APPL_SIZEOF_PTR + APPL_SIZEOF_INT)
#include <misc/appl_padding.h>
}; /* struct appl_hash_test_node */
union appl_hash_test_node_ptr
{
struct appl_list *
p_list;
struct appl_hash_test_node *
p_hash_test_node;
};
/*
*/
static
int
appl_hash_test_compare_string(
void * const
p_context,
void const * const
p_key,
unsigned long int const
i_key_len,
struct appl_list * const
p_list)
{
int
i_compare_result;
union appl_hash_test_node_ptr
o_hash_test_node_ptr;
struct appl_hash_test_node const *
p_hash_test_node;
appl_unused(
p_context,
i_key_len);
o_hash_test_node_ptr.p_list =
p_list;
p_hash_test_node =
o_hash_test_node_ptr.p_hash_test_node;
i_compare_result =
strcmp(
p_hash_test_node->p_string,
static_cast<char const *>(
p_key));
return
i_compare_result;
} /* appl_hash_test_compare_string() */
/*
*/
static
unsigned long int
appl_hash_test_index_string(
void * const
p_context,
void const * const
p_key,
unsigned long int const
i_key_len)
{
appl_unused(
p_context,
i_key_len);
unsigned char const * const
p_uchar =
static_cast<unsigned char const *>(
p_key);
return
*(
p_uchar);
} /* appl_hash_test_index_string() */
/*
*/
static
enum appl_status
appl_hash_test_create_node(
struct appl_context * const
p_context,
char const * const
p_string,
struct appl_hash_test_node * * const
r_node)
{
enum appl_status
e_status;
struct appl_hash_test_node *
p_node;
e_status =
appl_heap_alloc_structure(
p_context,
&(
p_node));
if (
appl_status_ok
== e_status)
{
appl_list_init(
&(
p_node->o_list));
p_node->p_string =
p_string;
p_node->i_string_len =
static_cast<int>(
strlen(
p_string));
*(
r_node) =
p_node;
}
return
e_status;
} /* appl_hash_test_create_node() */
/*
*/
static
void
appl_hash_test_destroy_node(
struct appl_context * const
p_context,
struct appl_hash_test_node * const
p_node)
{
void *
p_placement;
appl_size_t
i_placement_length;
p_placement =
static_cast<void *>(
p_node);
i_placement_length =
sizeof(
struct appl_hash_test_node);
appl_list_join(
&(
p_node->o_list),
&(
p_node->o_list));
appl_heap_free(
p_context,
i_placement_length,
p_placement);
} /* appl_hash_test_destroy_node() */
/*
*/
static
void
appl_hash_test_dump_callback(
void * const
p_context,
struct appl_list * const
p_list)
{
struct appl_hash_test_node *
p_node;
appl_unused(
p_context);
p_node =
reinterpret_cast<struct appl_hash_test_node *>(
p_list);
printf(
"[%s]\n",
p_node->p_string);
} /* appl_hash_test_dump_callback() */
/*
*/
static
void
appl_hash_test_dump(
struct appl_hash * const
p_hash)
{
appl_hash_iterate(
p_hash,
&(
appl_hash_test_dump_callback),
static_cast<void *>(
p_hash));
} /* appl_hash_test_dump() */
/*
Function: appl_hash_test()
Description:
Test of appl_hash module.
*/
void
appl_hash_test_1(
struct appl_context * const
p_context)
{
{
enum appl_status
e_status;
struct appl_hash *
p_hash;
struct appl_hash_descriptor
o_hash_descriptor;
o_hash_descriptor.p_compare =
&(
appl_hash_test_compare_string);
o_hash_descriptor.p_index =
&(
appl_hash_test_index_string);
o_hash_descriptor.i_max_index =
16ul;
e_status =
appl_hash_create(
p_context,
&(
o_hash_descriptor),
&(
p_hash));
if (
appl_status_ok
== e_status)
{
{
struct appl_object *
p_object;
p_object =
appl_hash_parent(
p_hash);
appl_unused(
p_object);
}
static char const g_good_key1[] = "felix";
static char const g_good_key2[] = "falafel";
static char const g_bad_key[] = "bad";
/* create some nodes */
struct appl_hash_test_node *
p_node1;
e_status =
appl_hash_test_create_node(
p_context,
g_good_key1,
&(
p_node1));
if (
appl_status_ok
== e_status)
{
/* insert into hash table */
appl_hash_insert(
p_hash,
static_cast<void const *>(
p_node1->p_string),
static_cast<unsigned long int>(
p_node1->i_string_len),
&(
p_node1->o_list));
struct appl_hash_test_node *
p_node2;
e_status =
appl_hash_test_create_node(
p_context,
g_good_key2,
&(
p_node2));
if (
appl_status_ok
== e_status)
{
appl_hash_insert(
p_hash,
static_cast<void const *>(
p_node2->p_string),
static_cast<unsigned long int>(
p_node2->i_string_len),
&(
p_node2->o_list));
/* Verify */
appl_hash_test_dump(
p_hash);
// Lookup good and bad
{
struct appl_list *
p_lookup_result;
appl_hash_lookup(
p_hash,
g_good_key1,
static_cast<unsigned long int>(sizeof(g_good_key1) - 1),
&(
p_lookup_result));
appl_hash_lookup(
p_hash,
g_good_key2,
static_cast<unsigned long int>(sizeof(g_good_key2) - 1),
&(
p_lookup_result));
appl_hash_lookup(
p_hash,
g_bad_key,
static_cast<unsigned long int>(sizeof(g_bad_key) - 1),
&(
p_lookup_result));
}
appl_hash_test_destroy_node(
p_context,
p_node2);
}
appl_hash_test_destroy_node(
p_context,
p_node1);
}
/* locate nodes */
/* remove nodes */
/* iterate */
appl_hash_destroy(
p_hash);
}
}
} /* appl_hash_test() */
/* end-of-file: appl_hash_test.c */
| 19.739336 | 84 | 0.460384 | fboucher9 |
6ed2838e809f41f084155b727183638f3ee85b12 | 287 | cpp | C++ | 628.三个数的最大乘积/maximumProduct.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2019-10-21T14:40:39.000Z | 2019-10-21T14:40:39.000Z | 628.三个数的最大乘积/maximumProduct.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | null | null | null | 628.三个数的最大乘积/maximumProduct.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2020-11-04T07:33:34.000Z | 2020-11-04T07:33:34.000Z | class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(),nums.end());
int first=nums[0]*nums[1]*nums[nums.size()-1];
int second=nums[nums.size()-1]*nums[nums.size()-2]*nums[nums.size()-3];
return max(first,second);
}
}; | 26.090909 | 79 | 0.585366 | YichengZhong |
6ed3e03729815f12c9f7265a696a4b63af6dbb5b | 291 | hpp | C++ | include/unordered_map/details/align_helper.hpp | Wizermil/unordered_map | 4d60bf16384b7ea9db1d43d8b15313f8752490ee | [
"MIT"
] | null | null | null | include/unordered_map/details/align_helper.hpp | Wizermil/unordered_map | 4d60bf16384b7ea9db1d43d8b15313f8752490ee | [
"MIT"
] | null | null | null | include/unordered_map/details/align_helper.hpp | Wizermil/unordered_map | 4d60bf16384b7ea9db1d43d8b15313f8752490ee | [
"MIT"
] | null | null | null | #pragma once
#include "unordered_map/details/config.hpp"
#include "unordered_map/details/type.hpp"
namespace wiz::details {
WIZ_HIDE_FROM_ABI constexpr usize next_aligned(usize sz, usize a_minus_one) noexcept { return (sz + a_minus_one) & ~a_minus_one; }
} // namespace wiz::details
| 26.454545 | 134 | 0.762887 | Wizermil |
6ed439ae01ec6187b401af8f78ee13a8a24300a5 | 10,283 | cpp | C++ | src/FealStream.cpp | ruben2020/leaf | 2927582ad2f6af0f683ad4e73a80c79f997857fa | [
"Apache-2.0"
] | null | null | null | src/FealStream.cpp | ruben2020/leaf | 2927582ad2f6af0f683ad4e73a80c79f997857fa | [
"Apache-2.0"
] | null | null | null | src/FealStream.cpp | ruben2020/leaf | 2927582ad2f6af0f683ad4e73a80c79f997857fa | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 ruben2020 https://github.com/ruben2020
*
* Licensed under the Apache License, Version 2.0
* with LLVM Exceptions (the "License");
* you may not use this file except in compliance with the License.
* You can find a copy of the License in the LICENSE file.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#include "feal.h"
#if defined (_WIN32)
#define BUFCAST(x) (char *) x
#define CLOSESOCKET(x) closesocket(x)
#else
#define BUFCAST(x) (void *) x
#define CLOSESOCKET(x) close(x)
#endif
feal::EventId_t feal::EvtIncomingConn::getId(void)
{
return getIdOfType<EvtIncomingConn>();
}
feal::EventId_t feal::EvtDataReadAvail::getId(void)
{
return getIdOfType<EvtDataReadAvail>();
}
feal::EventId_t feal::EvtDataWriteAvail::getId(void)
{
return getIdOfType<EvtDataWriteAvail>();
}
feal::EventId_t feal::EvtClientShutdown::getId(void)
{
return getIdOfType<EvtClientShutdown>();
}
feal::EventId_t feal::EvtServerShutdown::getId(void)
{
return getIdOfType<EvtServerShutdown>();
}
feal::EventId_t feal::EvtConnectedToServer::getId(void)
{
return getIdOfType<EvtConnectedToServer>();
}
feal::EventId_t feal::EvtConnectionShutdown::getId(void)
{
return getIdOfType<EvtConnectionShutdown>();
}
void feal::StreamGeneric::shutdownTool(void)
{
disconnect_and_reset();
}
feal::errenum feal::StreamGeneric::create_and_bind(feal::ipaddr* fa)
{
errenum res = FEAL_OK;
int ret;
if (fa == nullptr) return res;
sockaddr_ip su;
memset(&su, 0, sizeof(su));
ret = ipaddr_feal2posix(fa, &su);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
sockfd = socket(fa->family, SOCK_STREAM, 0);
if (sockfd == FEAL_INVALID_SOCKET)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
socklen_t length = sizeof(su.in);
if (fa->family == feal::ipaddr::INET6)
{
setipv6only(sockfd);
length = sizeof(su.in6);
}
setnonblocking(sockfd);
ret = ::bind(sockfd, &(su.sa), length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#if defined(unix) || defined(__unix__) || defined(__unix)
feal::errenum feal::StreamGeneric::create_and_bind(struct sockaddr_un* su)
{
errenum res = FEAL_OK;
int ret;
if (su == nullptr) return res;
sockfd = socket(su->sun_family, SOCK_STREAM, 0);
if (sockfd == FEAL_INVALID_SOCKET)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
setnonblocking(sockfd);
socklen_t length = sizeof(su->sun_family) + strlen(su->sun_path) + 1;
ret = bind(sockfd, (const struct sockaddr*) su, length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#endif
feal::errenum feal::StreamGeneric::recv(void *buf,
uint32_t len, int32_t* bytes, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
ssize_t numbytes = ::recv(fd, BUFCAST(buf), (size_t) len, MSG_DONTWAIT);
#if defined (_WIN32)
do_client_read_start(fd);
#endif
if (numbytes == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (bytes) *bytes = (int32_t) numbytes;
return res;
}
feal::errenum feal::StreamGeneric::send(void *buf,
uint32_t len, int32_t* bytes, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
ssize_t numbytes = ::send(fd, BUFCAST(buf), (size_t) len, MSG_DONTWAIT);
if (numbytes == FEAL_SOCKET_ERROR)
{
if ((FEAL_GETSOCKETERRNO == EAGAIN)||(FEAL_GETSOCKETERRNO == EWOULDBLOCK))
{
do_send_avail_notify(fd);
}
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (bytes) *bytes = (int32_t) numbytes;
return res;
}
feal::errenum feal::StreamGeneric::disconnect_client(feal::socket_t client_sockfd)
{
errenum res = FEAL_OK;
mapReaders.erase(client_sockfd);
if (do_client_shutdown(client_sockfd) == -1)
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
feal::errenum feal::StreamGeneric::disconnect_and_reset(void)
{
for (auto it=mapReaders.begin(); it!=mapReaders.end(); ++it)
do_client_shutdown(it->first);
mapReaders.clear();
errenum res = FEAL_OK;
if (do_full_shutdown() == -1)
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
if (serverThread.joinable()) serverThread.join();
if (connectThread.joinable()) connectThread.join();
return res;
}
feal::errenum feal::StreamGeneric::getpeername(feal::ipaddr* fa, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
sockaddr_ip su;
memset(&su, 0, sizeof(su));
socklen_t length = sizeof(su);
int ret = ::getpeername(fd, &(su.sa), &length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (fa) ipaddr_posix2feal(&su, fa);
return res;
}
#if defined(unix) || defined(__unix__) || defined(__unix)
feal::errenum feal::StreamGeneric::getpeername(struct sockaddr_un* su, feal::socket_t fd)
{
errenum res = FEAL_OK;
struct sockaddr_un an;
if (fd == -1) fd = sockfd;
socklen_t length = sizeof(an);
int ret = ::getpeername(fd, (struct sockaddr*) su, &length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
feal::errenum feal::StreamGeneric::getpeereid(uid_t* euid, gid_t* egid)
{
return getpeereid(sockfd, euid, egid);
}
feal::errenum feal::StreamGeneric::getpeereid(feal::socket_t fd, uid_t* euid, gid_t* egid)
{
errenum res = FEAL_OK;
int ret;
#if defined (__linux__)
socklen_t len;
struct ucred ucred;
len = sizeof(struct ucred);
ret = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len);
if (ret != FEAL_SOCKET_ERROR)
{
*euid = (uid_t) ucred.uid;
*egid = (gid_t) ucred.gid;
}
#else
ret = ::getpeereid(fd, euid, egid);
#endif
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#endif
void feal::StreamGeneric::serverLoopLauncher(StreamGeneric *p)
{
if (p) p->serverLoop();
}
void feal::StreamGeneric::connectLoopLauncher(StreamGeneric *p)
{
if (p) p->connectLoop();
}
int feal::StreamGeneric::accept_new_conn(void)
{
sockaddr_ip su;
memset(&su, 0, sizeof(su));
socklen_t socklength = sizeof(su);
socket_t sock_conn_fd = accept(sockfd, &(su.sa), &socklength);
std::shared_ptr<EvtIncomingConn> incomingevt = std::make_shared<EvtIncomingConn>();
incomingevt.get()->client_sockfd = sock_conn_fd;
if (sock_conn_fd == FEAL_INVALID_SOCKET)
{
incomingevt.get()->errnum = static_cast<errenum>(FEAL_GETSOCKETERRNO);
}
else
{
incomingevt.get()->errnum = FEAL_OK;
}
receiveEvent(incomingevt);
return sock_conn_fd;
}
void feal::StreamGeneric::client_read_avail(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtDataReadAvail> evt = std::make_shared<EvtDataReadAvail>();
evt.get()->sockfd = client_sockfd;
evt.get()->datalen = datareadavaillen(client_sockfd);
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evt);
}
}
}
void feal::StreamGeneric::client_write_avail(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtDataWriteAvail> evt = std::make_shared<EvtDataWriteAvail>();
evt.get()->sockfd = client_sockfd;
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evt);
}
}
}
void feal::StreamGeneric::client_shutdown(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtClientShutdown> evtclshutdown = std::make_shared<EvtClientShutdown>();
evtclshutdown.get()->client_sockfd = client_sockfd;
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evtclshutdown);
}
}
mapReaders.erase(client_sockfd);
}
void feal::StreamGeneric::server_shutdown(void)
{
std::shared_ptr<EvtServerShutdown> evt = std::make_shared<EvtServerShutdown>();
receiveEvent(evt);
}
void feal::StreamGeneric::connected_to_server(feal::socket_t fd)
{
std::shared_ptr<EvtConnectedToServer> evt = std::make_shared<EvtConnectedToServer>();
evt.get()->server_sockfd = fd;
receiveEvent(evt);
}
void feal::StreamGeneric::connection_read_avail(void)
{
std::shared_ptr<EvtDataReadAvail> evt = std::make_shared<EvtDataReadAvail>();
evt.get()->sockfd = sockfd;
evt.get()->datalen = datareadavaillen(sockfd);
receiveEvent(evt);
}
void feal::StreamGeneric::connection_write_avail(void)
{
std::shared_ptr<EvtDataWriteAvail> evt = std::make_shared<EvtDataWriteAvail>();
evt.get()->sockfd = sockfd;
receiveEvent(evt);
}
void feal::StreamGeneric::connection_shutdown(void)
{
std::shared_ptr<EvtConnectionShutdown> evt = std::make_shared<EvtConnectionShutdown>();
receiveEvent(evt);
}
void feal::StreamGeneric::receiveEvent(std::shared_ptr<Event> pevt){(void)pevt;}
| 27.791892 | 93 | 0.664495 | ruben2020 |
6ed43db9683a69209dcd8456a6ebf6cc857b15a7 | 1,383 | cpp | C++ | engine/Engine/src/game/parameter/ParameterType.cpp | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | null | null | null | engine/Engine/src/game/parameter/ParameterType.cpp | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | 10 | 2018-03-20T21:32:16.000Z | 2018-04-23T19:42:59.000Z | engine/Engine/src/game/parameter/ParameterType.cpp | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | null | null | null | #include "ghpch.h"
#include "ParameterType.h"
#include "core/Pointer.h"
namespace Ghurund {
using namespace ::DirectX;
const ParameterType ParameterType::INT = ParameterType(ParameterTypeEnum::INT, "int", sizeof(int));
const ParameterType ParameterType::INT2 = ParameterType(ParameterTypeEnum::INT2, "int2", sizeof(XMINT2));
const ParameterType ParameterType::FLOAT = ParameterType(ParameterTypeEnum::FLOAT, "float", sizeof(float));
const ParameterType ParameterType::FLOAT2 = ParameterType(ParameterTypeEnum::FLOAT2, "float2", sizeof(XMFLOAT2));
const ParameterType ParameterType::FLOAT3 = ParameterType(ParameterTypeEnum::FLOAT3, "float3", sizeof(XMFLOAT3));
const ParameterType ParameterType::MATRIX = ParameterType(ParameterTypeEnum::MATRIX, "matrix", sizeof(XMFLOAT4X4));
const ParameterType ParameterType::COLOR = ParameterType(ParameterTypeEnum::COLOR, "color", sizeof(XMFLOAT4));
const ParameterType ParameterType::TEXTURE = ParameterType(ParameterTypeEnum::TEXTURE, "texture", sizeof(Pointer*));
const EnumValues<ParameterTypeEnum, ParameterType> ParameterType::VALUES = {
&ParameterType::INT,
&ParameterType::INT2,
&ParameterType::FLOAT,
&ParameterType::FLOAT2,
&ParameterType::FLOAT3,
&ParameterType::MATRIX,
&ParameterType::COLOR,
&ParameterType::TEXTURE
};
} | 49.392857 | 120 | 0.735358 | Kartikeyapan598 |
6ed6f82f450ae78f18aa2c743cdf90f9bd3435f9 | 452 | hpp | C++ | Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #pragma once
#include "foundation/Axis.Mint.hpp"
#include "AxisString.hpp"
namespace axis { namespace foundation { namespace definitions {
class AXISMINT_API ElementBlockSyntax
{
private:
ElementBlockSyntax(void);
public:
~ElementBlockSyntax(void);
static const axis::String::char_type * BlockName;
static const axis::String::char_type * SetIdAttributeName;
friend class AxisInputLanguage;
};
} } } // namespace axis::foundation::definitions
| 21.52381 | 63 | 0.776549 | renato-yuzup |
6ed9830a8e46658d328c233054830732c8b6ef62 | 7,566 | cpp | C++ | code_reading/oceanbase-master/src/observer/ob_root_service_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/observer/ob_root_service_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/observer/ob_root_service_monitor.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX SERVER
#include "ob_root_service_monitor.h"
#include "common/ob_partition_key.h"
#include "share/partition_table/ob_ipartition_table.h"
#include "share/ob_rpc_struct.h"
#include "share/ob_common_rpc_proxy.h"
#include "storage/ob_partition_service.h"
#include "rootserver/ob_root_service.h"
#include "observer/ob_server_struct.h"
#include "share/ob_server_status.h"
#include "lib/thread/ob_thread_name.h"
namespace oceanbase {
using namespace common;
using namespace obrpc;
using namespace share;
using namespace rootserver;
using namespace storage;
namespace observer {
ObRootServiceMonitor::ObRootServiceMonitor(ObRootService& root_service, ObPartitionService& partition_service_)
: inited_(false), root_service_(root_service), fail_count_(0), partition_service_(partition_service_)
{}
ObRootServiceMonitor::~ObRootServiceMonitor()
{
if (inited_) {
stop();
}
}
int ObRootServiceMonitor::init()
{
int ret = OB_SUCCESS;
if (inited_) {
ret = OB_INIT_TWICE;
LOG_WARN("init twice", K(ret));
} else {
const int thread_count = 1;
this->set_thread_count(thread_count);
inited_ = true;
}
return ret;
}
void ObRootServiceMonitor::run1()
{
int ret = OB_SUCCESS;
ObRSThreadFlag rs_work;
if (!inited_) {
ret = OB_NOT_INIT;
LOG_WARN("not init", K(ret));
} else {
LOG_INFO("root service monitor thread start");
lib::set_thread_name("RSMonitor");
while (!has_set_stop()) {
if (OB_FAIL(monitor_root_service())) {
LOG_WARN("monitor root service failed", K(ret));
}
if (!has_set_stop()) {
usleep(MONITOR_ROOT_SERVICE_INTERVAL_US);
}
}
LOG_INFO("root service monitor thread exit");
}
}
int ObRootServiceMonitor::start()
{
int ret = OB_SUCCESS;
if (!inited_) {
ret = OB_NOT_INIT;
LOG_WARN("not init", K(ret));
} else if (OB_FAIL(share::ObThreadPool::start())) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("start root service monitor thread failed", K(ret));
}
return ret;
}
void ObRootServiceMonitor::stop()
{
int ret = OB_SUCCESS;
if (!inited_) {
ret = OB_NOT_INIT;
LOG_WARN("not init", K(ret));
} else if (!has_set_stop()) {
share::ObThreadPool::stop();
}
}
int ObRootServiceMonitor::monitor_root_service()
{
int ret = OB_SUCCESS;
if (!inited_) {
ret = OB_NOT_INIT;
LOG_WARN("not init", K(ret));
} else {
const ObPartitionKey root_partition(combine_id(OB_SYS_TENANT_ID, OB_ALL_CORE_TABLE_TID),
ObIPartitionTable::ALL_CORE_TABLE_PARTITION_ID,
ObIPartitionTable::ALL_CORE_TABLE_PARTITION_NUM);
ObRole role = FOLLOWER;
if (partition_service_.is_partition_exist(root_partition)) {
if (OB_FAIL(partition_service_.get_role(root_partition, role))) {
if (OB_ENTRY_NOT_EXIST == ret) {
role = FOLLOWER;
ret = OB_SUCCESS;
} else {
LOG_WARN("get partition role failed", K(root_partition), K(ret));
}
}
}
if (OB_FAIL(ret)) {
} else if (root_service_.is_stopping()) {
// need exit
if (OB_FAIL(root_service_.stop_service())) {
LOG_WARN("root service stop service failed", K(ret));
} else {
LOG_INFO("root service stop service finish success");
}
} else if (root_service_.is_need_stop()) {
LOG_INFO("root service is starting, stop_service need wait");
} else {
if (is_strong_leader(role)) {
if (root_service_.in_service()) {
// already started or is starting
// nothing todo
} else if (!root_service_.can_start_service()) {
LOG_ERROR("bug here. root service can not start service");
} else {
LOG_INFO("try to start root service");
DEBUG_SYNC(BEFORE_START_RS);
if (OB_FAIL(try_start_root_service())) {
LOG_WARN("fail to start root service", K(ret));
} else {
LOG_INFO("start root service success");
}
}
} else {
// possible follower or doesn't have role yet
// DEBUG_SYNC(BEFORE_STOP_RS);
// leader does not exist.
if (!root_service_.is_start()) {
// nothing todo
} else {
if (OB_FAIL(root_service_.revoke_rs())) {
LOG_WARN("fail to revoke rootservice", KR(ret));
if (root_service_.is_need_stop()) {
// nothing todo
} else if (root_service_.is_stopping()) {
if (OB_FAIL(root_service_.stop_service())) {
LOG_WARN("root service stop service failed", K(ret));
} else {
LOG_INFO("root service stop service finish success");
}
} else {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("inalid root service status", KR(ret));
}
}
}
}
}
}
return ret;
}
int ObRootServiceMonitor::try_start_root_service()
{
int ret = OB_SUCCESS;
ObMemberList member_list;
const ObPartitionKey root_partition(combine_id(OB_SYS_TENANT_ID, OB_ALL_CORE_TABLE_TID),
ObIPartitionTable::ALL_CORE_TABLE_PARTITION_ID,
ObIPartitionTable::ALL_CORE_TABLE_PARTITION_NUM);
if (OB_FAIL(partition_service_.get_leader_curr_member_list(root_partition, member_list))) {
LOG_WARN("fail to get leader current member list", K(ret));
} else if (OB_ISNULL(GCTX.srv_rpc_proxy_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("get invalid svr_rpc_proxy", K(ret));
} else {
ObMember member;
ObGetRootserverRoleResult result;
bool stopped = true;
const int64_t TIMEOUT = 1 * 1000 * 1000;
const ObCommonRpcProxy& rpc_proxy = *GCTX.rs_rpc_proxy_;
for (int64_t i = 0; i < member_list.get_member_number() && OB_SUCC(ret) && stopped; i++) {
if (OB_FAIL(member_list.get_member_by_index(i, member))) {
LOG_WARN("fail to get member", K(ret), K(i));
} else if (OB_FAIL(rpc_proxy.to_addr(member.get_server()).timeout(TIMEOUT).get_root_server_status(result))) {
LOG_WARN("fail to check root service stop", K(ret));
} else {
LOG_INFO("get rootserver status", K(result.status_), K(member.get_server()));
stopped = (result.status_ == status::INIT);
}
}
if (OB_FAIL(ret)) {
LOG_WARN("fail to check root service stopped, start service later", K(ret));
ret = OB_SUCCESS;
if (!has_set_stop()) {
usleep(2 * MONITOR_ROOT_SERVICE_INTERVAL_US);
}
} else if (!stopped) {
LOG_WARN("already have root service in service, start service later");
ret = OB_SUCCESS;
if (!has_set_stop()) {
usleep(2 * MONITOR_ROOT_SERVICE_INTERVAL_US);
}
}
if (OB_SUCC(ret)) {
LOG_INFO("try to start root service");
if (OB_FAIL(root_service_.start_service())) {
LOG_WARN("root service start service failed", K(ret));
} else {
LOG_INFO("root service start service success", K(ret));
}
}
}
return ret;
}
} // end namespace observer
} // end namespace oceanbase
| 31.924051 | 115 | 0.648824 | wangcy6 |
6edc886b9560de46f95509370ffe6ef1d84e329f | 1,562 | hpp | C++ | library/felix/maxflow.hpp | fffelix-huang/CP | ed7b481a6643bee1b6d89dec0be89aea205114ca | [
"MIT"
] | 1 | 2021-12-16T13:57:11.000Z | 2021-12-16T13:57:11.000Z | library/felix/maxflow.hpp | fffelix-huang/CP | ed7b481a6643bee1b6d89dec0be89aea205114ca | [
"MIT"
] | null | null | null | library/felix/maxflow.hpp | fffelix-huang/CP | ed7b481a6643bee1b6d89dec0be89aea205114ca | [
"MIT"
] | null | null | null | #ifndef FELIX_MAXFLOW_HPP
#define FELIX_MAXFLOW_HPP 1
#include <vector>
#include <queue>
#include <numeric>
namespace felix {
template<class T>
class mf_graph {
public:
struct Edge {
int to;
T cap;
Edge(int _to, T _cap) : to(_to), cap(_cap) {}
};
static constexpr T inf = std::numeric_limits<T>::max() / 3 - 5;
int n;
std::vector<Edge> e;
std::vector<std::vector<int>> g;
std::vector<int> cur, h;
mf_graph(int _n) : n(_n), g(_n) {}
void add_edge(int u, int v, T c) {
debug() << show(u) show(v) show(c);
g[u].push_back(e.size());
e.emplace_back(v, c);
g[v].push_back(e.size());
e.emplace_back(u, 0);
}
bool bfs(int s, int t) {
h.assign(n, -1);
std::queue<int> que;
h[s] = 0;
que.push(s);
while(!que.empty()) {
int u = que.front();
que.pop();
for(int i : g[u]) {
int v = e[i].to;
T c = e[i].cap;
if(c > 0 && h[v] == -1) {
h[v] = h[u] + 1;
if(v == t) {
return true;
}
que.push(v);
}
}
}
return false;
}
T dfs(int u, int t, T f) {
if(u == t) {
return f;
}
T r = f;
for(int &i = cur[u]; i < int(g[u].size()); ++i) {
int j = g[u][i];
int v = e[j].to;
T c = e[j].cap;
if(c > 0 && h[v] == h[u] + 1) {
T a = dfs(v, t, std::min(r, c));
e[j].cap -= a;
e[j ^ 1].cap += a;
r -= a;
if (r == 0) {
return f;
}
}
}
return f - r;
}
T flow(int s, int t) {
T ans = 0;
while(bfs(s, t)) {
cur.assign(n, 0);
ans += dfs(s, t, inf);
}
return ans;
}
};
} // namespace felix
#endif // FELIX_MAXFLOW_HPP
| 16.617021 | 64 | 0.495519 | fffelix-huang |
6ede0060d2d169dbf4110b4f333770a7d3a75050 | 1,905 | cpp | C++ | numpy_benchmarks/benchmarks/periodic_dist.cpp | adriendelsalle/numpy-benchmarks | 5c09448d045726b347e868756f9e1b004d0876ea | [
"BSD-3-Clause"
] | 33 | 2015-03-18T23:16:55.000Z | 2021-12-17T11:00:01.000Z | numpy_benchmarks/benchmarks/periodic_dist.cpp | adriendelsalle/numpy-benchmarks | 5c09448d045726b347e868756f9e1b004d0876ea | [
"BSD-3-Clause"
] | 8 | 2015-04-17T15:14:15.000Z | 2021-02-24T13:34:55.000Z | numpy_benchmarks/benchmarks/periodic_dist.cpp | adriendelsalle/numpy-benchmarks | 5c09448d045726b347e868756f9e1b004d0876ea | [
"BSD-3-Clause"
] | 12 | 2015-04-17T12:24:31.000Z | 2021-01-27T08:06:01.000Z | #include "xtensor/xnoalias.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xrandom.hpp"
#include "xtensor/xview.hpp"
#include "xtensor/xfixed.hpp"
#include "xtensor/xpad.hpp"
#include "xtensor/xindex_view.hpp"
#define FORCE_IMPORT_ARRAY
#include "xtensor-python/pyarray.hpp"
#include "xtensor-python/pytensor.hpp"
using namespace xt;
template<typename X, typename Y, typename Z>
auto periodic_dist(X const& x, Y const& y, Z const& z, long L, bool periodicX, bool periodicY, bool periodicZ)
{
auto N = x.size();
using shape_type = decltype(N);
xarray<double> xtemp = tile(x, N);
xtemp.reshape({N, N});
xtensor<double, 2> dx = xtemp - transpose(xtemp);
xarray<double> ytemp = tile(y, N);
ytemp.reshape({N, N});
xtensor<double, 2> dy = ytemp - transpose(ytemp);
xarray<double> ztemp = tile(z, N);
ztemp.reshape({N, N});
xtensor<double, 2> dz = ztemp - transpose(ztemp);
if(periodicX) {
filter(dx, dx>L/2) = filter(dx, dx > L/2) - L;
filter(dx, dx<-L/2) = filter(dx, dx < -L/2) + L;
}
if(periodicY) {
filter(dy, dy>L/2) = filter(dy, dy > L/2) - L;
filter(dy, dy<-L/2) = filter(dy, dy < -L/2) + L;
}
if(periodicZ) {
filter(dz, dz>L/2) = filter(dz, dz > L/2) - L;
filter(dz, dz<-L/2) = filter(dz, dz < -L/2) + L;
}
xtensor<double, 2> d = sqrt(square(dx) + square(dy) + square(dz));
filter(d, equal(d, 0)) = -1;
return std::make_tuple(d, dx, dy, dz);
}
std::tuple<pytensor<double, 2>, pytensor<double, 2>, pytensor<double, 2>, pytensor<double, 2>>
py_periodic_dist(pytensor<double, 1> const& x, pytensor<double, 1> const& y, pytensor<double, 1> const& z, long L, bool periodicX, bool periodicY, bool periodicZ)
{
return periodic_dist(x, y, z, L, periodicX, periodicY, periodicZ);
}
PYBIND11_MODULE(xtensor_periodic_dist, m)
{
import_numpy();
m.def("periodic_dist", py_periodic_dist);
}
| 27.608696 | 162 | 0.655118 | adriendelsalle |
6ee2a7582bd29f96c6ec8838d399081ce4086521 | 2,170 | cpp | C++ | test/huge_page_test.cpp | WeipingQu/memkind | f1c4ac9efd17e45b5bd669023a018e8b47bda398 | [
"BSD-3-Clause"
] | null | null | null | test/huge_page_test.cpp | WeipingQu/memkind | f1c4ac9efd17e45b5bd669023a018e8b47bda398 | [
"BSD-3-Clause"
] | null | null | null | test/huge_page_test.cpp | WeipingQu/memkind | f1c4ac9efd17e45b5bd669023a018e8b47bda398 | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-2-Clause
/* Copyright (C) 2016 - 2020 Intel Corporation. */
#include "common.h"
#include "allocator_perf_tool/HugePageUnmap.hpp"
#include "allocator_perf_tool/HugePageOrganizer.hpp"
#include "TimerSysTime.hpp"
#include "Thread.hpp"
/*
* This test was created because of the munmap() fail in jemalloc.
* There are two root causes of the error:
* - kernel bug (munmap() fails when the size is not aligned)
* - heap Manager doesn’t provide size aligned to 2MB pages for munmap()
* Test allocates 2000MB using Huge Pages (50threads*10operations*4MBalloc_size),
* but it needs extra Huge Pages due to overhead caused by heap management.
*/
class HugePageTest: public :: testing::Test
{
protected:
void run()
{
unsigned mem_operations_num = 10;
size_t threads_number = 50;
bool touch_memory = true;
size_t size_1MB = 1024*1024;
size_t alignment = 2*size_1MB;
size_t alloc_size = 4*size_1MB;
std::vector<Thread *> threads;
std::vector<Task *> tasks;
TimerSysTime timer;
timer.start();
// This bug occurs more frequently under stress of multithreaded allocations.
for (int i=0; i<threads_number; i++) {
Task *task = new HugePageUnmap(mem_operations_num, touch_memory, alignment,
alloc_size, HBW_PAGESIZE_2MB);
tasks.push_back(task);
threads.push_back(new Thread(task));
}
float elapsed_time = timer.getElapsedTime();
ThreadsManager threads_manager(threads);
threads_manager.start();
threads_manager.barrier();
threads_manager.release();
//task release
for (int i=0; i<tasks.size(); i++) {
delete tasks[i];
}
RecordProperty("threads_number", threads_number);
RecordProperty("memory_operations_per_thread", mem_operations_num);
RecordProperty("elapsed_time", elapsed_time);
}
};
// Test passes when there is no crash.
TEST_F(HugePageTest, test_TC_MEMKIND_ext_UNMAP_HUGE_PAGE)
{
HugePageOrganizer huge_page_organizer(1024);
run();
}
| 31 | 87 | 0.660369 | WeipingQu |
6ee31609c9d7542d46eb1439d70d83dc5c6ff7d4 | 2,493 | hpp | C++ | include/franka_o80/actuator.hpp | Data-Science-in-Mechanical-Engineering/franka_o80 | 3457f5d844fa504b15bcc6a3265a5beecfb239c4 | [
"MIT"
] | null | null | null | include/franka_o80/actuator.hpp | Data-Science-in-Mechanical-Engineering/franka_o80 | 3457f5d844fa504b15bcc6a3265a5beecfb239c4 | [
"MIT"
] | null | null | null | include/franka_o80/actuator.hpp | Data-Science-in-Mechanical-Engineering/franka_o80 | 3457f5d844fa504b15bcc6a3265a5beecfb239c4 | [
"MIT"
] | 1 | 2022-01-28T09:52:11.000Z | 2022-01-28T09:52:11.000Z | #pragma once
namespace franka_o80
{
///Actuator number
static const int actuator_number = 65;
///Actuator number corresponding to robot control mode. Contains `franka_o80::RobotMode` values
static const int robot_mode = 0;
///Actuator number corresponding to robot control mode. Contains `franka_o80::RobotMode` values
static const int gripper_mode = 1;
///Actuator number corresponding to error indicator. Contains `franka_o80::Error` values
static const int control_error = 2;
///Actuator numbers corresponding to reset signal
static const int control_reset = 3;
///Actuator number corresponding to gripper width
static const int gripper_width = 4;
///Actuator number corresponding to gripper velocity
static const int gripper_velocity = 5;
///Actuator number corresponding to gripper force
static const int gripper_force = 6;
///Actuator number corresponding to gripper temperature
static const int gripper_temperature = 7;
///Actuator numbers corresponding to robot angular positions
static const int joint_position[7] = { 8, 9, 10, 11, 12, 13, 14 };
///Actuator numbers corresponding to robot angular velocities
static const int joint_velocity[7] = { 15, 16, 17, 18, 19, 20, 21 };
///Actuator numbers corresponding to robot torques
static const int joint_torque[7] = { 22, 23, 24, 25, 26, 27, 28 };
///Actuator numbers corresponding to effector position
static const int cartesian_position[3] = { 29, 30, 31 };
///Actuator numbers corresponding to effector orientation. Contains quaternion values
static const int cartesian_orientation = 32;
///Actuator numbers corresponding to effector translation velocity
static const int cartesian_velocity[3] = { 33, 34, 35 };
///Actuator numbers corresponding to effector rotation velocity (WRT)
static const int cartesian_rotation[3] = { 36, 37, 38 };
///Actuator numbers corresponding to joint-space stiffness
static const int joint_stiffness[7] = { 39, 40, 41, 42, 43, 44, 45 };
///Actuator numbers corresponding to joint-space damping
static const int joint_damping[7] = { 46, 47, 48, 49, 50, 51, 52 };
///Actuator numbers corresponding to cartesian stiffness (for velocity and rotation)
static const int cartesian_stiffness[6] = { 53, 54, 55, 56, 57, 58 };
///Actuator numbers corresponding to cartesian damping (for velocity and rotation)
static const int cartesian_damping[6] = { 59, 60, 61, 62, 63, 64 };
} // namespace franka_o80 | 48.882353 | 95 | 0.734456 | Data-Science-in-Mechanical-Engineering |
6ee4764d0c7fe64deb3fbca465e42a5eb45c1215 | 8,658 | cc | C++ | rest/testing/service_peer_link_test.cc | kstepanmpmg/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 665 | 2015-12-09T17:00:14.000Z | 2022-03-25T07:46:46.000Z | rest/testing/service_peer_link_test.cc | tomzhang/mldb | a09cf2d9ca454d1966b9e49ae69f2fe6bf571494 | [
"Apache-2.0"
] | 797 | 2015-12-09T19:48:19.000Z | 2022-03-07T02:19:47.000Z | rest/testing/service_peer_link_test.cc | matebestek/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 103 | 2015-12-25T04:39:29.000Z | 2022-02-03T02:55:22.000Z | // This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* service_peer_test.cc
Jeremy Barnes, 4 March 2014
Copyright (c) 2014 mldb.ai inc. All rights reserved.
*/
#include "mldb/rest/service_peer.h"
#include "temporary_etcd_server.h"
#include "mldb/rest/etcd_client.h"
#include "mldb/rest/rest_service_endpoint.h"
#include "mldb/rest/rest_request_router.h"
#include <boost/algorithm/string.hpp>
#include <sys/wait.h>
#include "test_peer.h"
#include <chrono>
#include <thread>
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace MLDB;
BOOST_AUTO_TEST_CASE(test_peer_generic_links)
{
signal(SIGPIPE, SIG_IGN);
signal(SIGSEGV, SIG_IGN);
string etcdUri = getEtcdUri();
string etcdPath = getEtcdPath();
clearEtcd(etcdUri, etcdPath);
auto peer1 = std::make_shared<TestPeer>("peer1", etcdUri, etcdPath);
peer1->init(PortRange(15000, 16000), "127.0.0.1");
peer1->start();
auto peer2 = std::make_shared<TestPeer>("peer2", etcdUri, etcdPath);
peer2->init(PortRange(15000, 16000), "127.0.0.1");
peer2->start();
WatchT<string> p1w = peer1->watch({"peers", "names:peer2"}, true /* catchUp*/);
BOOST_CHECK_EQUAL(p1w.wait(1.0), "+peer2");
WatchT<string> p2w = peer2->watch({"peers", "names:peer1"}, true /* catchUp*/);
BOOST_CHECK_EQUAL(p2w.wait(1.0), "+peer1");
BOOST_CHECK_EQUAL(peer1->knownPeers(),
vector<string>({"peer1", "peer2"}));
ResourcePath peer1Address{"peers", "peer1"};
auto link = peer1->createLink(peer1Address, "subscription", string("hello"));
BOOST_CHECK_EQUAL(link->getRemoteAddress(), peer1Address);
BOOST_CHECK_EQUAL(link->getLocalAddress(), ResourcePath{});
// NOTE: possible race condition there
BOOST_CHECK_EQUAL(link->getState(), LS_CONNECTING);
cerr << "waiting for connected" << endl;
// Wait for the link to get connected (give it one second)
link->waitUntilConnected(1.0);
BOOST_CHECK_EQUAL(link->getState(), LS_CONNECTED);
auto subStatus = peer1->subscriptions.getStatus();
cerr << jsonEncode(subStatus) << endl;
BOOST_REQUIRE_EQUAL(subStatus.size(), 1);
BOOST_CHECK_EQUAL(subStatus.at(0).state, LS_CONNECTED);
BOOST_CHECK_EQUAL(subStatus.at(0).remoteAddress, peer1Address);
cerr << "connected" << endl;
peer1->subscriptions.clear();
cerr << "waiting for disconnected" << endl;
link->waitUntilDisconnected(1.0);
cerr << "disconnected" << endl;
#if 0 // temporary; should be re-enabled
// Now create one to an unknown link channel
auto link2 = peer1->createLink({"peers", "peer1"},
"subscription2",
string("hello"));
// possible race condition
BOOST_CHECK_EQUAL(link2->getState(), LS_CONNECTING);
{
MLDB_TRACE_EXCEPTIONS(false);
BOOST_CHECK_THROW(link2->waitUntilConnected(1.0), std::exception);
}
BOOST_CHECK_EQUAL(link2->getState(), LS_ERROR);
#endif
BOOST_CHECK_EQUAL(peer2->subscriptions.size(), 0);
auto link3 = peer1->createLink({"peers", "peer2"},
"subscription",
string("hello"));
// Wait for the link to get connected (give it one second)
link3->waitUntilConnected(1.0);
std::this_thread::sleep_for(std::chrono::seconds(1));
BOOST_CHECK_EQUAL(peer2->subscriptions.size(), 1);
cerr << jsonEncode(peer2->getRemoteLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer2->getLocalLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer1->getRemoteLinksForPeer("peer2")) << endl;
cerr << jsonEncode(peer1->getLocalLinksForPeer("peer2")) << endl;
cerr << "-------------- reseting ---------------" << endl;
link3.reset();
cerr << "-------------- reset done -------------" << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cerr << "-------------- sleep done -------------" << endl;
cerr << jsonEncode(peer2->getRemoteLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer2->getLocalLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer1->getRemoteLinksForPeer("peer2")) << endl;
cerr << jsonEncode(peer1->getLocalLinksForPeer("peer2")) << endl;
BOOST_CHECK_EQUAL(peer2->getRemoteLinksForPeer("peer1").size(), 0);
BOOST_CHECK_EQUAL(peer2->getLocalLinksForPeer("peer1").size(), 0);
BOOST_CHECK_EQUAL(peer1->getRemoteLinksForPeer("peer2").size(), 0);
BOOST_CHECK_EQUAL(peer1->getLocalLinksForPeer("peer2").size(), 0);
BOOST_CHECK_EQUAL(peer2->subscriptions.size(), 0);
auto link4 = peer1->createLink({"peers", "peer2"},
"subscription",
string("hello"));
// Wait for the link to get connected (give it one second)
link4->waitUntilConnected(1.0);
std::this_thread::sleep_for(std::chrono::seconds(1));
BOOST_CHECK_EQUAL(peer2->subscriptions.size(), 1);
cerr << jsonEncode(peer2->getRemoteLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer2->getLocalLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer1->getRemoteLinksForPeer("peer2")) << endl;
cerr << jsonEncode(peer1->getLocalLinksForPeer("peer2")) << endl;
peer2->subscriptions.clear();
cerr << "waiting for disconnected" << endl;
link4->waitUntilDisconnected(1.0);
cerr << "disconnected" << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cerr << jsonEncode(peer2->getRemoteLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer2->getLocalLinksForPeer("peer1")) << endl;
cerr << jsonEncode(peer1->getRemoteLinksForPeer("peer2")) << endl;
cerr << jsonEncode(peer1->getLocalLinksForPeer("peer2")) << endl;
BOOST_CHECK_EQUAL(peer2->getRemoteLinksForPeer("peer1").size(), 0);
BOOST_CHECK_EQUAL(peer2->getLocalLinksForPeer("peer1").size(), 0);
BOOST_CHECK_EQUAL(peer1->getRemoteLinksForPeer("peer2").size(), 0);
BOOST_CHECK_EQUAL(peer1->getLocalLinksForPeer("peer2").size(), 0);
BOOST_CHECK_EQUAL(peer2->subscriptions.size(), 0);
}
BOOST_AUTO_TEST_CASE(test_peer_link_messages)
{
signal(SIGPIPE, SIG_IGN);
signal(SIGSEGV, SIG_IGN);
string etcdUri = getEtcdUri();
string etcdPath = getEtcdPath();
clearEtcd(etcdUri, etcdPath);
auto peer1 = std::make_shared<TestPeer>("peer1", etcdUri, etcdPath);
peer1->init(PortRange(15000, 16000), "127.0.0.1");
peer1->start();
auto peer2 = std::make_shared<TestPeer>("peer2", etcdUri, etcdPath);
peer2->init(PortRange(15000, 16000), "127.0.0.1");
peer2->start();
WatchT<string> p1w = peer1->watch({"peers", "names:peer2"}, true /* catchUp*/);
BOOST_CHECK_EQUAL(p1w.wait(1.0), "+peer2");
WatchT<string> p2w = peer2->watch({"peers", "names:peer1"}, true /* catchUp*/);
BOOST_CHECK_EQUAL(p2w.wait(1.0), "+peer1");
// The two peers have discovered each other
cerr << "------------ creating link" << endl;
auto link = peer1->createLink({"peers", "peer2"},
"subscription",
string("hello"));
// Wait for the link to get connected (give it one second)
link->waitUntilConnected(1.0);
cerr << "------------ link is connected" << endl;
BOOST_CHECK_EQUAL(link->getState(), LS_CONNECTED);
cerr << jsonEncode(peer2->subscriptions.getStatus()) << endl;
// Send a message back from the accepted link to the linker
WatchT<Any> onRecvBwd = link->onRecv();
auto onSubBack = [&] (LinkToken & token)
{
token.send(string("world"));
};
peer2->subscriptions.forEach(onSubBack);
Any msgBack = onRecvBwd.wait(1.0);
BOOST_CHECK_EQUAL(msgBack.as<std::string>(), "world");
// Watch for a message coming through
WatchT<Any> onRecv;
auto onSub = [&] (LinkToken & token)
{
BOOST_CHECK(!onRecv.attached());
onRecv = token.onRecv();
};
peer2->subscriptions.forEach(onSub);
BOOST_CHECK(onRecv.attached());
// Send a message through
link->send(string("hello"));
// Wait to receive it
Any msg = onRecv.wait(1.0);
BOOST_CHECK_EQUAL(msg.as<std::string>(), "hello");
auto lst = link->getStatus();
BOOST_CHECK_EQUAL(lst.messagesReceived, 1);
BOOST_CHECK_EQUAL(lst.messagesSent, 1);
auto sst = peer2->subscriptions.getStatus();
BOOST_CHECK_EQUAL(sst.at(0).messagesReceived, 1);
BOOST_CHECK_EQUAL(sst.at(0).messagesSent, 1);
}
| 31.714286 | 83 | 0.638716 | kstepanmpmg |
6ee5312f3b09eac6769a296dcd6b0f44d8eeb5d6 | 2,461 | cpp | C++ | dev/spark/Gem/Code/Utils/Filter.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 2 | 2020-08-20T03:40:24.000Z | 2021-02-07T20:31:43.000Z | dev/spark/Gem/Code/Utils/Filter.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | null | null | null | dev/spark/Gem/Code/Utils/Filter.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | #include "spark_precompiled.h"
#include "Filter.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
namespace spark
{
static AZStd::stack<FilterResult*> resultsStack;
void FilterResult::FilterResultScriptConstructor(FilterResult* self, AZ::ScriptDataContext& dc)
{
if (dc.GetNumArguments() == 0)
{
*self = FilterResult();
return;
}
else if (dc.GetNumArguments() >= 1)
{
new(self) FilterResult{ };
if (dc.IsNumber(0))
{
int type = 0;
dc.ReadArg(0, type);
self->action = (FilterResult::FilterAction)type;
if (!resultsStack.empty()) {
//when there are multiple handler of the same filter, do the thing only if the priority is greater or equal
auto &top = resultsStack.top();
if (self->action >= top->action)
{
top->action = self->action;
top->ScriptConstructor(dc);
}
}
return;
}
}
dc.GetScriptContext()->Error(AZ::ScriptContext::ErrorType::Error, true, "Invalid arguments passed to FilterResult().");
new(self) FilterResult();
}
void FilterResult::Reflect(AZ::ReflectContext* reflection)
{
if (auto serializationContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializationContext->Class<FilterResult>()
->Version(1)
->Field("action", &FilterResult::action);
}
if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(reflection))
{
behaviorContext->Class<FilterResult>("FilterResult")
->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value)
->Attribute(AZ::Script::Attributes::ConstructorOverride, &FilterResultScriptConstructor)
->Enum<(int)FilterResult::FILTER_IGNORE>("FILTER_IGNORE")
->Enum<(int)FilterResult::FILTER_PREVENT>("FILTER_PREVENT")
->Enum<(int)FilterResult::FILTER_MODIFY>("FILTER_MODIFY")
->Enum<(int)FilterResult::FILTER_FORCE>("FILTER_FORCE")
;
}
}
void FilterResult::Push()
{
resultsStack.push(this);
}
void FilterResult::Pop()
{
AZ_Assert(!resultsStack.empty(), "FilterResult::Pop() called, but stack is empty!");
AZ_Assert(resultsStack.top()==this, "FilterResult::Pop() called, but the top of the stack does not match!");
resultsStack.pop();
}
AZStd::stack<FilterResult*>& FilterResult::GetStack()
{
return resultsStack;
}
FilterResult* FilterResult::GetStackTop()
{
return resultsStack.empty() ? nullptr : resultsStack.top();
}
}
| 25.371134 | 121 | 0.686306 | chrisinajar |
6ee773b2c4ba39334e1f478c53bd4b59776b933d | 203 | hpp | C++ | src/modules/osg/generated_code/FrontFace.pypp.hpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/FrontFace.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/FrontFace.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#ifndef FrontFace_hpp__pyplusplus_wrapper
#define FrontFace_hpp__pyplusplus_wrapper
void register_FrontFace_class();
#endif//FrontFace_hpp__pyplusplus_wrapper
| 22.555556 | 41 | 0.847291 | JaneliaSciComp |
6ee9f5eff929c9c70575f862fcd112847b4376d9 | 977 | cpp | C++ | main_server/src/entities/hourly_rate/hourly_rate.cpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | main_server/src/entities/hourly_rate/hourly_rate.cpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | main_server/src/entities/hourly_rate/hourly_rate.cpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | #include "hourly_rate.hpp"
HourlyRate::HourlyRate(){}
HourlyRate::HourlyRate(int id) : id(id) {}
HourlyRate::HourlyRate(int id, float amount): id(id), amount(amount) {}
void HourlyRate::setId(int id){
this->id = id;
}
void HourlyRate::setAmount(float amount){
this->amount = amount;
}
int HourlyRate::getId() const{
return id;
}
float HourlyRate::getAmount() const{
return amount;
}
HourlyRate& HourlyRate::operator= (const HourlyRate& h1){
id = h1.id;
amount = h1.amount;
return *this;
}
bool operator== (const HourlyRate& h1, const HourlyRate& h2)
{
return h1.id == h2.id;
}
std::ostream& operator<<(std::ostream& os, const HourlyRate& h)
{
os << "HourlyRate - Id: " << h.id << ", Amount: " << h.amount << std::endl;
return os;
}
// HourlyRateException::HourlyRateException(const std::string & message):_message(message) {}
// const char * HourlyRateException::what() const throw() {
// return _message.c_str();
// }
| 20.787234 | 93 | 0.651996 | GrassoMichele |
6eebb790af7bd43fe9d2373147c269e0b47407b7 | 1,013 | cpp | C++ | TestExcel/pageMargins.cpp | antonyenergy-dev/QXlsx | 865c0de9f8bf019100b90ef2528422d55ee92206 | [
"MIT"
] | 1 | 2020-01-03T14:00:29.000Z | 2020-01-03T14:00:29.000Z | TestExcel/pageMargins.cpp | antonyenergy-dev/QXlsx | 865c0de9f8bf019100b90ef2528422d55ee92206 | [
"MIT"
] | null | null | null | TestExcel/pageMargins.cpp | antonyenergy-dev/QXlsx | 865c0de9f8bf019100b90ef2528422d55ee92206 | [
"MIT"
] | 1 | 2021-04-03T23:11:39.000Z | 2021-04-03T23:11:39.000Z | // pageMargins.cpp
#include <QtGlobal>
#include <QObject>
#include <QString>
#include <QDebug>
#include "xlsxdocument.h"
#include "xlsxchartsheet.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"
#include "xlsxrichstring.h"
#include "xlsxworkbook.h"
using namespace QXlsx;
#include <cstdio>
#include <iostream>
// using namespace std;
int pageMargin(bool isTest);
int pages()
{
pageMargin(true);
return 0;
}
int pageMargin(bool isTest)
{
if (!isTest)
return (-1);
// TODO:
/*
Document xlsx;
xlsx.write("A1", "Hello QtXlsx!"); // current file is utf-8 character-set.
xlsx.write("A2", 12345);
xlsx.write("A3", "=44+33"); // cell value is 77.
xlsx.write("A4", true);
xlsx.write("A5", "http://qt-project.org");
xlsx.write("A6", QDate(2013, 12, 27));
xlsx.write("A7", QTime(6, 30));
if (!xlsx.saveAs("WriteExcel.xlsx"))
{
qDebug() << "[WriteExcel] failed to save excel file";
return (-2);
}
*/
return 0;
}
| 17.77193 | 78 | 0.611056 | antonyenergy-dev |
6eef0975793233a2fd83d773d95c7e7ac8f7ab6f | 598 | cpp | C++ | problems/104.Maximum_Depth_of_Binary_Tree/AC_recursive_n.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | problems/104.Maximum_Depth_of_Binary_Tree/AC_recursive_n.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | problems/104.Maximum_Depth_of_Binary_Tree/AC_recursive_n.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | /*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_recursive_n.cpp
* Create Date: 2014-12-19 08:48:06
* Descripton: recursive
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxDepth(TreeNode *root) {
if (root == NULL)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
int main() {
return 0;
}
| 16.611111 | 68 | 0.590301 | subramp-prep |
6ef036e9eae822b44864ca9595b31fa50868afd6 | 12,437 | cpp | C++ | Editor/LevelEditor/DOShuffle.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | Editor/LevelEditor/DOShuffle.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | Editor/LevelEditor/DOShuffle.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //---------------------------------------------------------------------------
#include "stdafx.h"
#pragma hdrstop
#include "DOShuffle.h"
#include "ChoseForm.h"
#include "ImageThumbnail.h"
#include "xr_trims.h"
#include "Library.h"
#include "DOOneColor.h"
#include "EditObject.h"
#include "Scene.h"
#include "DetailObjects.h"
#include "D3DUtils.h"
#include "PropertiesDetailObject.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TfrmDOShuffle *TfrmDOShuffle::form=0;
static DDVec DOData;
SDOData::SDOData(){
DOData.push_back(this);
}
//---------------------------------------------------------------------------
// Constructors
//---------------------------------------------------------------------------
bool __fastcall TfrmDOShuffle::Run(){
VERIFY(!form);
form = new TfrmDOShuffle(0);
// show
return (form->ShowModal()==mrOk);
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormShow(TObject *Sender)
{
bColorIndModif = false;
GetInfo();
}
//---------------------------------------------------------------------------
void TfrmDOShuffle::GetInfo(){
// init
tvItems->IsUpdating = true;
tvItems->Selected = 0;
tvItems->Items->Clear();
// fill
CDetailManager* DM=Scene.m_DetailObjects;
VERIFY(DM);
// objects
for (DOIt d_it=DM->m_Objects.begin(); d_it!=DM->m_Objects.end(); d_it++){
SDOData* dd = new SDOData;
dd->m_RefName = (*d_it)->GetName();
dd->m_fMinScale = (*d_it)->m_fMinScale;
dd->m_fMaxScale = (*d_it)->m_fMaxScale;
dd->m_fDensityFactor = (*d_it)->m_fDensityFactor;
dd->m_dwFlags = (*d_it)->m_dwFlags;
AddItem(0,(*d_it)->GetName(),(void*)dd);
}
// indices
ColorIndexPairIt S = DM->m_ColorIndices.begin();
ColorIndexPairIt E = DM->m_ColorIndices.end();
ColorIndexPairIt it= S;
for(; it!=E; it++){
TfrmOneColor* OneColor = new TfrmOneColor(0);
color_indices.push_back(OneColor);
OneColor->Parent = form->sbDO;
OneColor->ShowIndex(this);
OneColor->mcColor->Brush->Color = (TColor)rgb2bgr(it->first);
for (d_it=it->second.begin(); d_it!=it->second.end(); d_it++)
OneColor->AppendObject((*d_it)->GetName());
}
// redraw
tvItems->IsUpdating = false;
}
void TfrmDOShuffle::ApplyInfo(){
CDetailManager* DM=Scene.m_DetailObjects;
VERIFY(DM);
bool bNeedUpdate = false;
// update objects
DM->MarkAllObjectsAsDel();
for ( TElTreeItem* node = tvItems->Items->GetFirstNode(); node; node = node->GetNext()){
CDetail* DO = DM->FindObjectByName(AnsiString(node->Text).c_str());
if (DO) DO->m_bMarkDel = false;
else{
DO = DM->AppendObject(AnsiString(node->Text).c_str());
bNeedUpdate = true;
}
// update data
SDOData* DD = (SDOData*)node->Data;
DO->m_fMinScale = DD->m_fMinScale;
DO->m_fMaxScale = DD->m_fMaxScale;
DO->m_fDensityFactor= DD->m_fDensityFactor;
DO->m_dwFlags = DD->m_dwFlags;
}
if (DM->RemoveObjects(true)) bNeedUpdate=true;
// update indices
DM->RemoveColorIndices();
for (DWORD k=0; k<color_indices.size(); k++){
TfrmOneColor* OneColor = color_indices[k];
DWORD clr = bgr2rgb(OneColor->mcColor->Brush->Color);
for ( TElTreeItem* node = OneColor->tvDOList->Items->GetFirstNode(); node; node = node->GetNext())
DM->AppendIndexObject(clr,AnsiString(node->Text).c_str(),false);
}
if (bNeedUpdate||bColorIndModif){
ELog.DlgMsg(mtInformation,"Object list changed. Update objects needed!");
DM->InvalidateSlots();
}
}
//---------------------------------------------------------------------------
// implementation
//---------------------------------------------------------------------------
__fastcall TfrmDOShuffle::TfrmDOShuffle(TComponent* Owner)
: TForm(Owner)
{
DEFINE_INI(fsStorage);
}
//---------------------------------------------------------------------------
TElTreeItem* TfrmDOShuffle::FindItem(const char* s)
{
for ( TElTreeItem* node = tvItems->Items->GetFirstNode(); node; node = node->GetNext())
if (node->Data && (AnsiString(node->Text) == s)) return node;
return 0;
}
//---------------------------------------------------------------------------
TElTreeItem* TfrmDOShuffle::AddItem(TElTreeItem* node, const char* name, void* obj)
{
TElTreeItem* obj_node = tvItems->Items->AddChildObject(node, name, obj);
obj_node->ParentStyle = false;
obj_node->Bold = false;
return obj_node;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebOkClick(TObject *Sender)
{
ApplyInfo();
Close();
ModalResult = mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebCancelClick(TObject *Sender)
{
Close();
ModalResult = mrCancel;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormKeyDown(TObject *Sender, WORD &Key,
TShiftState Shift)
{
if (Key==VK_ESCAPE) ebCancel->Click();
if (Key==VK_RETURN) ebOk->Click();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormClose(TObject *Sender, TCloseAction &Action)
{
for (DDIt it=DOData.begin(); it!=DOData.end(); it++)
_DELETE(*it);
DOData.clear();
for (DWORD k=0; k<color_indices.size(); k++)
_DELETE(color_indices[k]);
color_indices.clear();
_DELETE(m_Thm);
if (ModalResult==mrOk)
Scene.m_DetailObjects->InvalidateCache();
Action = caFree;
form = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsItemFocused(TObject *Sender)
{
TElTreeItem* Item = tvItems->Selected;
_DELETE(m_Thm);
if (Item&&Item->Data){
AnsiString nm = Item->Text;
m_Thm = new EImageThumbnail(nm.c_str(),EImageThumbnail::EITObject);
SDOData* dd = (SDOData*)Item->Data;
lbItemName->Caption = "\""+dd->m_RefName+"\"";
AnsiString temp; temp.sprintf("Density: %1.2f\nScale: [%3.1f, %3.1f)\nNo waving: %s",dd->m_fDensityFactor,dd->m_fMinScale,dd->m_fMaxScale,(dd->m_dwFlags&DO_NO_WAVING)?"on":"off");
lbInfo->Caption = temp;
}else{
lbItemName->Caption = "-";
lbInfo->Caption = "-";
}
if (m_Thm&&m_Thm->Valid()) pbImagePaint(Sender);
else pbImage->Repaint();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::pbImagePaint(TObject *Sender)
{
if (m_Thm) m_Thm->Draw(paImage,pbImage,true);
}
//---------------------------------------------------------------------------
bool __fastcall LookupFunc(TElTreeItem* Item, void* SearchDetails){
char s1 = *(char*)SearchDetails;
char s2 = *AnsiString(Item->Text).c_str();
return (s1==tolower(s2));
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsKeyPress(TObject *Sender, char &Key)
{
TElTreeItem* node = tvItems->Items->LookForItemEx(tvItems->Selected,-1,false,false,false,&Key,LookupFunc);
if (!node) node = tvItems->Items->LookForItemEx(0,-1,false,false,false,&Key,LookupFunc);
if (node){
tvItems->Selected = node;
tvItems->EnsureVisible(node);
}
}
//---------------------------------------------------------------------------
static TElTreeItem* DragItem=0;
void __fastcall TfrmDOShuffle::tvMultiDragDrop(TObject *Sender,
TObject *Source, int X, int Y)
{
TElTreeItem* node = ((TElTree*)Sender)->GetItemAtY(Y);
if (node)
DragItem->MoveToIns(0,node->Index);
DragItem = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvMultiDragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept)
{
Accept = false;
TElTreeItem* node = ((TElTree*)Sender)->GetItemAtY(Y);
if ((Sender==Source)&&(node!=DragItem)) Accept=true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvMultiStartDrag(TObject *Sender,
TDragObject *&DragObject)
{
DragItem = ((TElTree*)Sender)->Selected;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebAddObjectClick(TObject *Sender)
{
LPCSTR S = TfrmChoseItem::SelectObject(true,0,0);
if (S){
AStringVec lst;
SequenceToList(lst, S);
for (AStringIt s_it=lst.begin(); s_it!=lst.end(); s_it++)
if (!FindItem(s_it->c_str())){
if (tvItems->Items->Count>=dm_max_objects){
ELog.DlgMsg(mtInformation,"Maximum detail objects in scene '%d'",dm_max_objects);
return;
}
SDOData* dd = new SDOData;
dd->m_RefName = s_it->c_str();
dd->m_fMinScale = 0.5f;
dd->m_fMaxScale = 2.f;
dd->m_fDensityFactor= 1.f;
dd->m_dwFlags = 0;
AddItem(0,s_it->c_str(),(void*)dd);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebDelObjectClick(TObject *Sender)
{
if (tvItems->Selected){
ModifColorInd();
for (DWORD k=0; k<color_indices.size(); k++)
color_indices[k]->RemoveObject(tvItems->Selected->Text);
tvItems->Selected->Delete();
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebAppendIndexClick(TObject *Sender)
{
ModifColorInd();
color_indices.push_back(new TfrmOneColor(0));
color_indices.back()->Parent = sbDO;
color_indices.back()->ShowIndex(this);
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::RemoveColorIndex(TfrmOneColor* p){
form->ModifColorInd();
form->color_indices.erase(find(form->color_indices.begin(),form->color_indices.end(),p));
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebMultiClearClick(TObject *Sender)
{
ModifColorInd();
for (DWORD k=0; k<color_indices.size(); k++)
_DELETE(color_indices[k]);
color_indices.clear();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDragDrop(TObject *Sender,
TObject *Source, int X, int Y)
{
TfrmOneColor* OneColor = (TfrmOneColor*)((TElTree*)Source)->Parent;
if (OneColor&&OneColor->FDragItem){
OneColor->FDragItem->Delete();
ModifColorInd();
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept)
{
Accept = false;
if (Source == tvItems) return;
TElTreeItem* node;
Accept = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsStartDrag(TObject *Sender,
TDragObject *&DragObject)
{
FDragItem = tvItems->ItemFocused;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebDOPropertiesClick(TObject *Sender)
{
if (tvItems->Selected&&tvItems->Selected->Data){
bool bChange;
DDVec lst;
lst.push_back(((SDOData*)tvItems->Selected->Data));
TElTreeItem* node = tvItems->Selected;
if (frmPropertiesSectorRun(lst,bChange)==mrOk){
tvItems->Selected = 0;
tvItems->Selected = node;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDblClick(TObject *Sender)
{
ebDOProperties->Click();
}
//---------------------------------------------------------------------------
| 34.451524 | 183 | 0.508 | ixray-team |
6ef20269959ae5ffc807efc792952ac7e2822e33 | 16,995 | hpp | C++ | opencv_contrib-3.3.0/modules/surface_matching/src/c_utils.hpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | 2 | 2020-05-27T13:28:03.000Z | 2021-03-21T15:39:11.000Z | opencv_contrib-3.3.0/modules/surface_matching/src/c_utils.hpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | null | null | null | opencv_contrib-3.3.0/modules/surface_matching/src/c_utils.hpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | 1 | 2019-03-01T09:46:20.000Z | 2019-03-01T09:46:20.000Z | //
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2014, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
// Author: Tolga Birdal <tbirdal AT gmail.com>
#ifndef __OPENCV_SURFACE_MATCHING_UTILS_HPP_
#define __OPENCV_SURFACE_MATCHING_UTILS_HPP_
#include <cmath>
#include <cstdio>
namespace cv
{
namespace ppf_match_3d
{
const float EPS = 1.192092896e-07F; /* smallest such that 1.0+FLT_EPSILON != 1.0 */
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
static inline double TNorm3(const double v[])
{
return (sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]));
}
static inline void TNormalize3(double v[])
{
double normTemp=TNorm3(v);
if (normTemp>0)
{
v[0]/=normTemp;
v[1]/=normTemp;
v[2]/=normTemp;
}
}
static inline double TDot3(const double a[3], const double b[3])
{
return ((a[0])*(b[0])+(a[1])*(b[1])+(a[2])*(b[2]));
}
static inline void TCross(const double a[], const double b[], double c[])
{
c[0] = (a[1])*(b[2])-(a[2])*(b[1]);
c[1] = (a[2])*(b[0])-(a[0])*(b[2]);
c[2] = (a[0])*(b[1])-(a[1])*(b[0]);
}
static inline double TAngle3Normalized(const double a[3], const double b[3])
{
/*
angle = atan2(a dot b, |a x b|) # Bertram (accidental mistake)
angle = atan2(|a x b|, a dot b) # Tolga Birdal (correction)
angle = acos(a dot b) # Hamdi Sahloul (simplification, a & b are normalized)
*/
return acos(TDot3(a, b));
}
static inline void matrixProduct33(double *A, double *B, double *R)
{
R[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
R[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
R[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
R[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
R[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
R[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
R[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
R[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
R[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
}
// A is a vector
static inline void matrixProduct133(double *A, double *B, double *R)
{
R[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
R[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
R[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
}
static inline void matrixProduct331(const double A[9], const double b[3], double r[3])
{
r[0] = A[0] * b[0] + A[1] * b[1] + A[2] * b[2];
r[1] = A[3] * b[0] + A[4] * b[1] + A[5] * b[2];
r[2] = A[6] * b[0] + A[7] * b[1] + A[8] * b[2];
}
static inline void matrixTranspose33(double *A, double *At)
{
At[0] = A[0];
At[4] = A[4];
At[8] = A[8];
At[1] = A[3];
At[2] = A[6];
At[3] = A[1];
At[5] = A[7];
At[6] = A[2];
At[7] = A[5];
}
static inline void matrixProduct44(const double A[16], const double B[16], double R[16])
{
R[0] = A[0] * B[0] + A[1] * B[4] + A[2] * B[8] + A[3] * B[12];
R[1] = A[0] * B[1] + A[1] * B[5] + A[2] * B[9] + A[3] * B[13];
R[2] = A[0] * B[2] + A[1] * B[6] + A[2] * B[10] + A[3] * B[14];
R[3] = A[0] * B[3] + A[1] * B[7] + A[2] * B[11] + A[3] * B[15];
R[4] = A[4] * B[0] + A[5] * B[4] + A[6] * B[8] + A[7] * B[12];
R[5] = A[4] * B[1] + A[5] * B[5] + A[6] * B[9] + A[7] * B[13];
R[6] = A[4] * B[2] + A[5] * B[6] + A[6] * B[10] + A[7] * B[14];
R[7] = A[4] * B[3] + A[5] * B[7] + A[6] * B[11] + A[7] * B[15];
R[8] = A[8] * B[0] + A[9] * B[4] + A[10] * B[8] + A[11] * B[12];
R[9] = A[8] * B[1] + A[9] * B[5] + A[10] * B[9] + A[11] * B[13];
R[10] = A[8] * B[2] + A[9] * B[6] + A[10] * B[10] + A[11] * B[14];
R[11] = A[8] * B[3] + A[9] * B[7] + A[10] * B[11] + A[11] * B[15];
R[12] = A[12] * B[0] + A[13] * B[4] + A[14] * B[8] + A[15] * B[12];
R[13] = A[12] * B[1] + A[13] * B[5] + A[14] * B[9] + A[15] * B[13];
R[14] = A[12] * B[2] + A[13] * B[6] + A[14] * B[10] + A[15] * B[14];
R[15] = A[12] * B[3] + A[13] * B[7] + A[14] * B[11] + A[15] * B[15];
}
static inline void matrixProduct441(const double A[16], const double B[4], double R[4])
{
R[0] = A[0] * B[0] + A[1] * B[1] + A[2] * B[2] + A[3] * B[3];
R[1] = A[4] * B[0] + A[5] * B[1] + A[6] * B[2] + A[7] * B[3];
R[2] = A[8] * B[0] + A[9] * B[1] + A[10] * B[2] + A[11] * B[3];
R[3] = A[12] * B[0] + A[13] * B[1] + A[14] * B[2] + A[15] * B[3];
}
static inline void matrixPrint(double *A, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
{
printf(" ");
for (j = 0; j < n; j++)
{
printf(" %0.6f ", A[i * n + j]);
}
printf("\n");
}
}
static inline void matrixIdentity(int n, double *A)
{
int i;
for (i = 0; i < n*n; i++)
{
A[i] = 0.0;
}
for (i = 0; i < n; i++)
{
A[i * n + i] = 1.0;
}
}
static inline void rtToPose(const double R[9], const double t[3], double Pose[16])
{
Pose[0]=R[0];
Pose[1]=R[1];
Pose[2]=R[2];
Pose[4]=R[3];
Pose[5]=R[4];
Pose[6]=R[5];
Pose[8]=R[6];
Pose[9]=R[7];
Pose[10]=R[8];
Pose[3]=t[0];
Pose[7]=t[1];
Pose[11]=t[2];
Pose[15] = 1;
}
static inline void poseToRT(const double Pose[16], double R[9], double t[3])
{
R[0] = Pose[0];
R[1] = Pose[1];
R[2] = Pose[2];
R[3] = Pose[4];
R[4] = Pose[5];
R[5] = Pose[6];
R[6] = Pose[8];
R[7] = Pose[9];
R[8] = Pose[10];
t[0]=Pose[3];
t[1]=Pose[7];
t[2]=Pose[11];
}
static inline void poseToR(const double Pose[16], double R[9])
{
R[0] = Pose[0];
R[1] = Pose[1];
R[2] = Pose[2];
R[3] = Pose[4];
R[4] = Pose[5];
R[5] = Pose[6];
R[6] = Pose[8];
R[7] = Pose[9];
R[8] = Pose[10];
}
/**
* \brief Axis angle to rotation but only compute y and z components
*/
static inline void aaToRyz(double angle, const double r[3], double row2[3], double row3[3])
{
const double sinA=sin(angle);
const double cosA=cos(angle);
const double cos1A=(1-cosA);
row2[0] = 0.f;
row2[1] = cosA;
row2[2] = 0.f;
row3[0] = 0.f;
row3[1] = 0.f;
row3[2] = cosA;
row2[0] += r[2] * sinA;
row2[2] += -r[0] * sinA;
row3[0] += -r[1] * sinA;
row3[1] += r[0] * sinA;
row2[0] += r[1] * r[0] * cos1A;
row2[1] += r[1] * r[1] * cos1A;
row2[2] += r[1] * r[2] * cos1A;
row3[0] += r[2] * r[0] * cos1A;
row3[1] += r[2] * r[1] * cos1A;
row3[2] += r[2] * r[2] * cos1A;
}
/**
* \brief Axis angle to rotation
*/
static inline void aaToR(double angle, const double r[3], double R[9])
{
const double sinA=sin(angle);
const double cosA=cos(angle);
const double cos1A=(1-cosA);
double *row1 = &R[0];
double *row2 = &R[3];
double *row3 = &R[6];
row1[0] = cosA;
row1[1] = 0.0f;
row1[2] = 0.f;
row2[0] = 0.f;
row2[1] = cosA;
row2[2] = 0.f;
row3[0] = 0.f;
row3[1] = 0.f;
row3[2] = cosA;
row1[1] += -r[2] * sinA;
row1[2] += r[1] * sinA;
row2[0] += r[2] * sinA;
row2[2] += -r[0] * sinA;
row3[0] += -r[1] * sinA;
row3[1] += r[0] * sinA;
row1[0] += r[0] * r[0] * cos1A;
row1[1] += r[0] * r[1] * cos1A;
row1[2] += r[0] * r[2] * cos1A;
row2[0] += r[1] * r[0] * cos1A;
row2[1] += r[1] * r[1] * cos1A;
row2[2] += r[1] * r[2] * cos1A;
row3[0] += r[2] * r[0] * cos1A;
row3[1] += r[2] * r[1] * cos1A;
row3[2] += r[2] * r[2] * cos1A;
}
/**
* \brief Compute a rotation in order to rotate around X direction
*/
static inline void getUnitXRotation(double angle, double R[9])
{
const double sinA=sin(angle);
const double cosA=cos(angle);
double *row1 = &R[0];
double *row2 = &R[3];
double *row3 = &R[6];
row1[0] = 1;
row1[1] = 0.0f;
row1[2] = 0.f;
row2[0] = 0.f;
row2[1] = cosA;
row2[2] = -sinA;
row3[0] = 0.f;
row3[1] = sinA;
row3[2] = cosA;
}
/**
* \brief Compute a transformation in order to rotate around X direction
*/
static inline void getUnitXRotation_44(double angle, double T[16])
{
const double sinA=sin(angle);
const double cosA=cos(angle);
double *row1 = &T[0];
double *row2 = &T[4];
double *row3 = &T[8];
row1[0] = 1;
row1[1] = 0.0f;
row1[2] = 0.f;
row2[0] = 0.f;
row2[1] = cosA;
row2[2] = -sinA;
row3[0] = 0.f;
row3[1] = sinA;
row3[2] = cosA;
row1[3]=0;
row2[3]=0;
row3[3]=0;
T[3]=0;
T[7]=0;
T[11]=0;
T[15] = 1;
}
/**
* \brief Compute the yz components of the transformation needed to rotate n1 onto x axis and p1 to origin
*/
static inline void computeTransformRTyz(const double p1[4], const double n1[4], double row2[3], double row3[3], double t[3])
{
// dot product with x axis
double angle=acos( n1[0] );
// cross product with x axis
double axis[3]={0, n1[2], -n1[1]};
double axisNorm;
// we try to project on the ground plane but it's already parallel
if (n1[1]==0 && n1[2]==0)
{
axis[1]=1;
axis[2]=0;
}
else
{
axisNorm=sqrt(axis[2]*axis[2]+axis[1]*axis[1]);
if (axisNorm>EPS)
{
axis[1]/=axisNorm;
axis[2]/=axisNorm;
}
}
aaToRyz(angle, axis, row2, row3);
t[1] = row2[0] * (-p1[0]) + row2[1] * (-p1[1]) + row2[2] * (-p1[2]);
t[2] = row3[0] * (-p1[0]) + row3[1] * (-p1[1]) + row3[2] * (-p1[2]);
}
/**
* \brief Compute the transformation needed to rotate n1 onto x axis and p1 to origin
*/
static inline void computeTransformRT(const double p1[4], const double n1[4], double R[9], double t[3])
{
// dot product with x axis
double angle=acos( n1[0] );
// cross product with x axis
double axis[3]={0, n1[2], -n1[1]};
double axisNorm;
double *row1, *row2, *row3;
// we try to project on the ground plane but it's already parallel
if (n1[1]==0 && n1[2]==0)
{
axis[1]=1;
axis[2]=0;
}
else
{
axisNorm=sqrt(axis[2]*axis[2]+axis[1]*axis[1]);
if (axisNorm>EPS)
{
axis[1]/=axisNorm;
axis[2]/=axisNorm;
}
}
aaToR(angle, axis, R);
row1 = &R[0];
row2 = &R[3];
row3 = &R[6];
t[0] = row1[0] * (-p1[0]) + row1[1] * (-p1[1]) + row1[2] * (-p1[2]);
t[1] = row2[0] * (-p1[0]) + row2[1] * (-p1[1]) + row2[2] * (-p1[2]);
t[2] = row3[0] * (-p1[0]) + row3[1] * (-p1[1]) + row3[2] * (-p1[2]);
}
/**
* \brief Flip a normal to the viewing direction
*
* \param [in] point Scene point
* \param [in] vp_x X component of view direction
* \param [in] vp_y Y component of view direction
* \param [in] vp_z Z component of view direction
* \param [in] nx X component of normal
* \param [in] ny Y component of normal
* \param [in] nz Z component of normal
*/
static inline void flipNormalViewpoint(const float* point, double vp_x, double vp_y, double vp_z, double *nx, double *ny, double *nz)
{
double cos_theta;
// See if we need to flip any plane normals
vp_x -= (double)point[0];
vp_y -= (double)point[1];
vp_z -= (double)point[2];
// Dot product between the (viewpoint - point) and the plane normal
cos_theta = (vp_x * (*nx) + vp_y * (*ny) + vp_z * (*nz));
// Flip the plane normal
if (cos_theta < 0)
{
(*nx) *= -1;
(*ny) *= -1;
(*nz) *= -1;
}
}
/**
* \brief Flip a normal to the viewing direction
*
* \param [in] point Scene point
* \param [in] vp_x X component of view direction
* \param [in] vp_y Y component of view direction
* \param [in] vp_z Z component of view direction
* \param [in] nx X component of normal
* \param [in] ny Y component of normal
* \param [in] nz Z component of normal
*/
static inline void flipNormalViewpoint_32f(const float* point, float vp_x, float vp_y, float vp_z, float *nx, float *ny, float *nz)
{
float cos_theta;
// See if we need to flip any plane normals
vp_x -= (float)point[0];
vp_y -= (float)point[1];
vp_z -= (float)point[2];
// Dot product between the (viewpoint - point) and the plane normal
cos_theta = (vp_x * (*nx) + vp_y * (*ny) + vp_z * (*nz));
// Flip the plane normal
if (cos_theta < 0)
{
(*nx) *= -1;
(*ny) *= -1;
(*nz) *= -1;
}
}
/**
* \brief Convert a rotation matrix to axis angle representation
*
* \param [in] R Rotation matrix
* \param [in] axis Axis vector
* \param [in] angle Angle in radians
*/
static inline void dcmToAA(double *R, double *axis, double *angle)
{
double d1 = R[7] - R[5];
double d2 = R[2] - R[6];
double d3 = R[3] - R[1];
double norm = sqrt(d1 * d1 + d2 * d2 + d3 * d3);
double x = (R[7] - R[5]) / norm;
double y = (R[2] - R[6]) / norm;
double z = (R[3] - R[1]) / norm;
*angle = acos((R[0] + R[4] + R[8] - 1.0) * 0.5);
axis[0] = x;
axis[1] = y;
axis[2] = z;
}
/**
* \brief Convert axis angle representation to rotation matrix
*
* \param [in] axis Axis Vector
* \param [in] angle Angle (In radians)
* \param [in] R 3x3 Rotation matrix
*/
static inline void aaToDCM(double *axis, double angle, double *R)
{
double ident[9]={1,0,0,0,1,0,0,0,1};
double n[9] = { 0.0, -axis[2], axis[1],
axis[2], 0.0, -axis[0],
-axis[1], axis[0], 0.0
};
double nsq[9];
double c, s;
int i;
//c = 1-cos(angle);
c = cos(angle);
s = sin(angle);
matrixProduct33(n, n, nsq);
for (i = 0; i < 9; i++)
{
const double sni = n[i]*s;
const double cnsqi = nsq[i]*(c);
R[i]=ident[i]+sni+cnsqi;
}
// The below code is the matrix based implemntation of the above
// double nsq[9], sn[9], cnsq[9], tmp[9];
//matrix_scale(3, 3, n, s, sn);
//matrix_scale(3, 3, nsq, (1 - c), cnsq);
//matrix_sum(3, 3, 3, 3, ident, sn, tmp);
//matrix_sum(3, 3, 3, 3, tmp, cnsq, R);
}
/**
* \brief Convert a discrete cosine matrix to quaternion
*
* \param [in] R Rotation Matrix
* \param [in] q Quaternion
*/
static inline void dcmToQuat(double *R, double *q)
{
double n4; // the norm of quaternion multiplied by 4
double tr = R[0] + R[4] + R[8]; // trace of martix
double factor;
if (tr > 0.0)
{
q[1] = R[5] - R[7];
q[2] = R[6] - R[2];
q[3] = R[1] - R[3];
q[0] = tr + 1.0;
n4 = q[0];
}
else
if ((R[0] > R[4]) && (R[0] > R[8]))
{
q[1] = 1.0 + R[0] - R[4] - R[8];
q[2] = R[3] + R[1];
q[3] = R[6] + R[2];
q[0] = R[5] - R[7];
n4 = q[1];
}
else
if (R[4] > R[8])
{
q[1] = R[3] + R[1];
q[2] = 1.0 + R[4] - R[0] - R[8];
q[3] = R[7] + R[5];
q[0] = R[6] - R[2];
n4 = q[2];
}
else
{
q[1] = R[6] + R[2];
q[2] = R[7] + R[5];
q[3] = 1.0 + R[8] - R[0] - R[4];
q[0] = R[1] - R[3];
n4 = q[3];
}
factor = 0.5 / sqrt(n4);
q[0] *= factor;
q[1] *= factor;
q[2] *= factor;
q[3] *= factor;
}
/**
* \brief Convert quaternion to a discrete cosine matrix
*
* \param [in] q Quaternion (w is at first element)
* \param [in] R Rotation Matrix
*
*/
static inline void quatToDCM(double *q, double *R)
{
double sqw = q[0] * q[0];
double sqx = q[1] * q[1];
double sqy = q[2] * q[2];
double sqz = q[3] * q[3];
double tmp1, tmp2;
R[0] = sqx - sqy - sqz + sqw; // since sqw + sqx + sqy + sqz = 1
R[4] = -sqx + sqy - sqz + sqw;
R[8] = -sqx - sqy + sqz + sqw;
tmp1 = q[1] * q[2];
tmp2 = q[3] * q[0];
R[1] = 2.0 * (tmp1 + tmp2);
R[3] = 2.0 * (tmp1 - tmp2);
tmp1 = q[1] * q[3];
tmp2 = q[2] * q[0];
R[2] = 2.0 * (tmp1 - tmp2);
R[6] = 2.0 * (tmp1 + tmp2);
tmp1 = q[2] * q[3];
tmp2 = q[1] * q[0];
R[5] = 2.0 * (tmp1 + tmp2);
R[7] = 2.0 * (tmp1 - tmp2);
}
} // namespace ppf_match_3d
} // namespace cv
#endif
| 25.327869 | 133 | 0.533098 | AmericaGL |
6ef4330113e8fee3d2cb0d3e541194ca7b600a82 | 2,958 | cc | C++ | paddle/fluid/distributed/ps/table/sparse_geo_table.cc | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | 2 | 2022-03-30T09:55:45.000Z | 2022-03-30T09:55:49.000Z | paddle/fluid/distributed/ps/table/sparse_geo_table.cc | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/distributed/ps/table/sparse_geo_table.cc | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | 1 | 2022-03-02T11:36:03.000Z | 2022-03-02T11:36:03.000Z | // Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/distributed/ps/table/sparse_geo_table.h"
namespace paddle {
namespace distributed {
int32_t SparseGeoTable::pull_geo_param(const uint32_t trainer_id,
std::vector<float>* values,
std::vector<uint64_t>* ids) {
geo_recorder->GetAndClear(trainer_id, ids);
auto dim = _config.common().dims()[0];
std::vector<uint32_t> frequencies;
frequencies.resize(ids->size(), 1);
auto pull_value = PullSparseValue(ids->size(), dim);
pull_value.is_training_ = true;
pull_value.feasigns_ = ids->data();
pull_value.frequencies_ = frequencies.data();
values->resize(ids->size() * dim);
CommonSparseTable::pull_sparse(values->data(), pull_value);
return 0;
}
int32_t SparseGeoTable::push_sparse(const uint64_t* keys, const float* values,
size_t num) {
std::vector<uint64_t> ids;
ids.resize(num);
std::copy_n(keys, num, ids.begin());
geo_recorder->Update(ids);
CommonSparseTable::push_sparse(keys, values, num);
return 0;
}
int32_t SparseGeoTable::initialize_value() {
auto common = _config.common();
shard_values_.reserve(task_pool_size_);
for (int x = 0; x < task_pool_size_; ++x) {
auto shard = std::make_shared<ValueBlock>(
value_names_, value_dims_, value_offsets_, value_idx_,
initializer_attrs_, common.entry());
shard_values_.emplace_back(shard);
}
auto accessor = _config.accessor();
std::vector<uint64_t> feasigns;
for (size_t x = 0; x < accessor.fea_dim(); ++x) {
if (x % _shard_num == _shard_idx) {
feasigns.push_back(x);
}
}
VLOG(3) << "has " << feasigns.size() << " ids need to be pre inited";
auto buckets = bucket(feasigns.size(), 10);
for (int x = 0; x < 10; ++x) {
auto bucket_feasigns = buckets[x + 1] - buckets[x];
std::vector<uint64_t> ids(bucket_feasigns);
std::copy(feasigns.begin() + buckets[x], feasigns.begin() + buckets[x + 1],
ids.begin());
std::vector<uint32_t> fres;
fres.resize(ids.size(), 1);
auto pull_value = PullSparseValue(ids, fres, param_dim_);
std::vector<float> pulls;
pulls.resize(bucket_feasigns * param_dim_);
pull_sparse(pulls.data(), pull_value);
}
return 0;
}
} // namespace distributed
} // namespace paddle
| 32.152174 | 79 | 0.667343 | ZibinGuo |
6ef4630fb60252ff3ead8fda9d590727def2f723 | 5,886 | cpp | C++ | source/Win32/XCondition.cpp | MultiSight/multisight-xsdk | 02268e1aeb1313cfb2f9515d08d131a4389e49f2 | [
"BSL-1.0"
] | null | null | null | source/Win32/XCondition.cpp | MultiSight/multisight-xsdk | 02268e1aeb1313cfb2f9515d08d131a4389e49f2 | [
"BSL-1.0"
] | null | null | null | source/Win32/XCondition.cpp | MultiSight/multisight-xsdk | 02268e1aeb1313cfb2f9515d08d131a4389e49f2 | [
"BSL-1.0"
] | null | null | null |
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// XSDK
// Copyright (c) 2015 Schneider Electric
//
// Use, modification, and distribution is subject to the Boost Software License,
// Version 1.0 (See accompanying file LICENSE).
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "XSDK/XCondition.h"
#include "XSDK/Errors.h"
#include "XSDK/TimeUtils.h"
#include "XSDK/XMonoClock.h"
#define MICROS_IN_SECOND 1000000
using namespace XSDK;
XCondition::XCondition( XMutex& lok ) :
_lok( lok ),
_numWaitingThreads( 0 )
{
InitializeCriticalSection( &_threadCountLock );
// We have to use both types of Win32 events to get the exact behavior we
// expect from a POSIX condition variable. We use an auto-reset event for
// the signal() call so only a single thread is woken up. We rely on the
// "stickyness" of a manual-reset event to properly implement broadcast().
_events[SIGNAL] = CreateEvent( NULL, false, false, NULL ); // auto-reset event
_events[BROADCAST] = CreateEvent( NULL, true, false, NULL ); // manual-reset event
if( _events[SIGNAL] == NULL || _events[BROADCAST] == NULL )
X_THROW(( "Unable to allocate Win32 event objects." ));
}
XCondition::~XCondition() throw()
{
if( _events[SIGNAL] )
CloseHandle( _events[SIGNAL] );
if( _events[BROADCAST] )
CloseHandle( _events[BROADCAST] );
DeleteCriticalSection( &_threadCountLock );
}
void XCondition::Wait()
{
// We keep track of the number of waiting threads so we can guarantee that
// all waiting threads are woken up by a broadcast() call.
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads++;
LeaveCriticalSection( &_threadCountLock );
// Release the lock before waiting... this is standard POSIX condition
// semantics.
_lok.Release();
// NOTE: We avoid the "lost wakeup" bug common in many Win32 condition
// implementations because we are using a manual-reset event. If we were
// only using an auto-reset event, it would be possible to lose a signal
// right here due to a race condition.
// Wait for either event to be signaled.
DWORD result = WaitForMultipleObjects( MAX_EVENTS, _events, false, INFINITE );
if( ( result < WAIT_OBJECT_0 ) || ( result > WAIT_OBJECT_0 + MAX_EVENTS ) )
{
X_THROW(( "An error occurred what waiting for the Win32 event objects. Errorcode = 0x%08X.",
GetLastError() ));
}
// The following code is only required for the broadcast(). Basically, if
// broadcast was called AND we are the last waiting thread, then reset the
// manual-reset event.
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads--;
bool lastThreadWaiting = ( result == WAIT_OBJECT_0 + BROADCAST ) && ( _numWaitingThreads == 0 );
LeaveCriticalSection( &_threadCountLock );
if( lastThreadWaiting )
ResetEvent( _events[BROADCAST] );
// Reacquire the lock before returning... again, this is standard POSIX
// condition semantics.
_lok.Acquire();
}
//bool XCondition::WaitUntil( time_t secondsAbsolute, time_t microsecondsAbsolute )
bool XCondition::WaitUntil( uint64_t then )
{
//
// NOTE: See the Wait() method for more details about how this works
// on Windows.
//
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads++;
LeaveCriticalSection( &_threadCountLock );
// Convert the absolute wait timeout into a relative time. Windows wait
// functions only operate on relative time (in milliseconds).
int timeoutMS = (int)(ConvertTimeScale( then - XMonoClock::GetTime(), XMonoClock::GetFrequency(), 1000 ));
if( timeoutMS < 0 )
timeoutMS = 0;
bool timedOut = false;
_lok.Release();
DWORD result = WaitForMultipleObjects( MAX_EVENTS, _events, false, (DWORD)timeoutMS );
if( result == WAIT_TIMEOUT )
timedOut = true;
if( !timedOut && ( ( result < WAIT_OBJECT_0 ) || ( result > WAIT_OBJECT_0 + MAX_EVENTS ) ) )
{
X_THROW(( "An error occurred what waiting for the Win32 event objects. Errorcode = 0x%08X.",
GetLastError() ));
}
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads--;
bool lastThreadWaiting = ( result == WAIT_OBJECT_0 + BROADCAST ) && ( _numWaitingThreads == 0 );
LeaveCriticalSection( &_threadCountLock );
if( lastThreadWaiting )
ResetEvent( _events[BROADCAST] );
_lok.Acquire();
return timedOut;
}
void XCondition::Signal()
{
EnterCriticalSection( &_threadCountLock );
bool threadsWaiting = _numWaitingThreads > 0;
LeaveCriticalSection( &_threadCountLock );
if( threadsWaiting )
SetEvent( _events[SIGNAL] );
}
void XCondition::Broadcast()
{
EnterCriticalSection( &_threadCountLock );
bool threadsWaiting = _numWaitingThreads > 0;
LeaveCriticalSection( &_threadCountLock );
if( threadsWaiting )
SetEvent( _events[BROADCAST] );
}
uint64_t XCondition::FutureMonotonicTime( time_t secondsAbsolute, time_t microsecondsAbsolute )
{
struct timeval future = { secondsAbsolute, microsecondsAbsolute };
struct timeval now;
x_gettimeofday( &now );
struct timeval delta;
timersub( &future, &now, &delta );
const double deltaSeconds = (((double)((delta.tv_sec * MICROS_IN_SECOND) + delta.tv_usec)) / MICROS_IN_SECOND);
return XMonoClock::GetTime() + (uint64_t)(deltaSeconds * XMonoClock::GetFrequency());
}
uint64_t XCondition::FutureMonotonicTime( XDuration timeFromNow )
{
const double deltaSeconds = ((double)timeFromNow.Total(HNSECS)) / convert(SECONDS, HNSECS, 1);
return deltaSeconds > 0 ? XMonoClock::GetTime() + (uint64_t)(deltaSeconds * XMonoClock::GetFrequency())
: XMonoClock::GetTime();
}
| 33.634286 | 115 | 0.666157 | MultiSight |
6ef4e0df22cae77eefa9664ef8696f04eb88ce9e | 722 | hpp | C++ | include/back_off.hpp | cblauvelt/connection-pool | ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d | [
"MIT"
] | null | null | null | include/back_off.hpp | cblauvelt/connection-pool | ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d | [
"MIT"
] | 7 | 2022-02-02T04:57:24.000Z | 2022-03-20T23:07:02.000Z | include/back_off.hpp | cblauvelt/connection-pool | ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d | [
"MIT"
] | 1 | 2021-09-19T17:55:20.000Z | 2021-09-19T17:55:20.000Z | #pragma once
#include <chrono>
#include <random>
#include <stdexcept>
#include "types.hpp"
namespace cpool {
inline milliseconds
timer_delay(uint8_t num_retries,
std::chrono::milliseconds maximum_backoff = 32s) {
// prevent int rollover
int retries = std::min(num_retries, (uint8_t)29);
std::random_device
rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(1, 500);
milliseconds retry_time =
seconds((int)std::pow(2, retries)) + milliseconds(distrib(gen));
return std::min(retry_time, maximum_backoff);
}
} // namespace cpool
| 24.896552 | 80 | 0.693906 | cblauvelt |
6ef50c9002cb8fad355e0a9992ff005f2543ce57 | 119 | cpp | C++ | f9_os/inc/os/vnode.cpp | ghsecuritylab/arm-cortex-v7-unix | cd499fa94d6ee6cd78a31387f3512d997335df52 | [
"Apache-2.0"
] | null | null | null | f9_os/inc/os/vnode.cpp | ghsecuritylab/arm-cortex-v7-unix | cd499fa94d6ee6cd78a31387f3512d997335df52 | [
"Apache-2.0"
] | null | null | null | f9_os/inc/os/vnode.cpp | ghsecuritylab/arm-cortex-v7-unix | cd499fa94d6ee6cd78a31387f3512d997335df52 | [
"Apache-2.0"
] | 1 | 2020-03-08T01:08:38.000Z | 2020-03-08T01:08:38.000Z | /*
* vnode.cpp
*
* Created on: May 3, 2017
* Author: Paul
*/
#include <os/vnode.hpp>
namespace os {
};
| 7.933333 | 27 | 0.529412 | ghsecuritylab |
6ef57bddc556034f284838f43f68d0cfdece60b1 | 4,861 | cpp | C++ | src/Engine/Platform/Thread.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | 2 | 2020-02-03T04:58:17.000Z | 2021-03-13T06:03:52.000Z | src/Engine/Platform/Thread.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | null | null | null | src/Engine/Platform/Thread.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Thread.h"
//=============================================================================
SE_NAMESPACE_BEGIN
#if SE_PLATFORM_WINDOWS
//-----------------------------------------------------------------------------
bool Mutex::Init(uint32_t spinCount, const char *name)
{
return InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION*)&handle, (DWORD)spinCount);
}
//-----------------------------------------------------------------------------
void Mutex::Destroy()
{
CRITICAL_SECTION* cs = (CRITICAL_SECTION*)&handle;
DeleteCriticalSection(cs);
handle = {};
}
//-----------------------------------------------------------------------------
void Mutex::Acquire()
{
EnterCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
bool Mutex::TryAcquire()
{
return TryEnterCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
void Mutex::Release()
{
LeaveCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
bool ConditionVariable::Init(const char *name)
{
handle = (CONDITION_VARIABLE*)conf_calloc(1, sizeof(CONDITION_VARIABLE));
InitializeConditionVariable((PCONDITION_VARIABLE)handle);
return true;
}
//-----------------------------------------------------------------------------
void ConditionVariable::Destroy()
{
conf_free(handle);
}
//-----------------------------------------------------------------------------
void ConditionVariable::Wait(const Mutex &mutex, uint32_t ms)
{
SleepConditionVariableCS((PCONDITION_VARIABLE)handle, (PCRITICAL_SECTION)&mutex.handle, ms);
}
//-----------------------------------------------------------------------------
void ConditionVariable::WakeOne()
{
WakeConditionVariable((PCONDITION_VARIABLE)handle);
}
//-----------------------------------------------------------------------------
void ConditionVariable::WakeAll()
{
WakeAllConditionVariable((PCONDITION_VARIABLE)handle);
}
//-----------------------------------------------------------------------------
ThreadID Thread::mainThreadID;
//-----------------------------------------------------------------------------
void Thread::SetMainThread()
{
mainThreadID = GetCurrentThreadID();
}
//-----------------------------------------------------------------------------
ThreadID Thread::GetCurrentThreadID()
{
return GetCurrentThreadId();
}
//-----------------------------------------------------------------------------
char* thread_name()
{
__declspec(thread) static char name[MAX_THREAD_NAME_LENGTH + 1];
return name;
}
//-----------------------------------------------------------------------------
void Thread::GetCurrentThreadName(char *buffer, int size)
{
if ( const char* name = thread_name() )
snprintf(buffer, (size_t)size, "%s", name);
else
buffer[0] = 0;
}
//-----------------------------------------------------------------------------
void Thread::SetCurrentThreadName(const char *name)
{
strcpy_s(thread_name(), MAX_THREAD_NAME_LENGTH + 1, name);
}
//-----------------------------------------------------------------------------
bool Thread::IsMainThread()
{
return GetCurrentThreadID() == mainThreadID;
}
//-----------------------------------------------------------------------------
DWORD WINAPI ThreadFunctionStatic(void *data)
{
ThreadDesc* pDesc = (ThreadDesc*)data;
pDesc->func(pDesc->data);
return 0;
}
//-----------------------------------------------------------------------------
void Thread::Sleep(unsigned mSec)
{
::Sleep(mSec);
}
//-----------------------------------------------------------------------------
// threading class (Static functions)
unsigned int Thread::GetNumCPUCores()
{
_SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
return systemInfo.dwNumberOfProcessors;
}
//-----------------------------------------------------------------------------
ThreadHandle CreateThread(ThreadDesc *desc)
{
ThreadHandle handle = ::CreateThread(0, 0, ThreadFunctionStatic, desc, 0, 0);
__assume(handle != NULL);
return handle;
}
//-----------------------------------------------------------------------------
void DestroyThread(ThreadHandle handle)
{
__assume(handle != NULL);
WaitForSingleObject((HANDLE)handle, INFINITE);
CloseHandle((HANDLE)handle);
handle = 0;
}
//-----------------------------------------------------------------------------
void JoinThread(ThreadHandle handle)
{
WaitForSingleObject((HANDLE)handle, INFINITE);
}
//-----------------------------------------------------------------------------
void Sleep(uint32_t mSec)
{
::Sleep((DWORD)mSec);
}
//-----------------------------------------------------------------------------
#endif
SE_NAMESPACE_END
//============================================================================= | 33.524138 | 93 | 0.424193 | SapphireEngine |
6ef59d31bba551d565b1b536bdda1656c7381f6b | 1,871 | cpp | C++ | snippets/0x03/d_copyctor.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | snippets/0x03/d_copyctor.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | snippets/0x03/d_copyctor.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | // author: a.voss@fh-aachen.de
#include <iostream>
using std::cout;
using std::endl;
class address {
int id;
public:
address() : id{0} { // (A)
cout << "-a| ctor(), id=" << id << endl;
}
address(int id) : id{id} { // (B)
cout << "-b| ctor(int), id=" << id << endl;
}
address(const address& a) : id{a.id+1} { // (C)
cout << "-c| ctor(address&), id=" << id << endl;
}
~address() {
cout << "-d| dtor(), id=" << id << endl;
}
};
address a(-1); // (D)
int main()
{
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
cout << "01| start" << endl;
address a0;
address a1(1);
address a2(a1);
address a3=a2; // (E)
address a4{a3}; // (F)
cout << "02| ende" << endl;
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
return 0;
} // (G)
/* Kommentierung
*
* (A) Standard-ctor, Verwendung ohne Argumente (auch ohne Klammern),
* siehe 'a0' in 'main'.
*
* (B) ctor mit 'int'-Argument, siehe 'a1' in 'main'.
*
* (C) ctor mit 'address'-Argument, siehe 'a2' in 'main'. Dies ist der
* sogenannte Kopierkonstruktor (copy-ctor), er initialisiert die
* Instant anhand des Arguments, d.h. häufig kopiert er den Inhalt.
*
* (D) Eine globale Variable, man beachte den Zeitpunkt der Aufrufe
* ctor und dtor.
*
* (E) Das sieht aus wie eine Zuweisung, tatsächlich ist es aber der
* copy-ctor.
*
* (F) In diesem Fall wie (E), der copy-ctor.
*
* (G) dtor der globalen Variablen.
*
*/
| 26.352113 | 72 | 0.435061 | pblan |
6ef5b2a3c0f8f35b1905b88c47ef7a80e2cbb576 | 1,622 | cpp | C++ | test/perf/os/OSTimerTester.cpp | ORNL-Fusion/xolotl | 993434bea0d3bca439a733a12af78034c911690c | [
"BSD-3-Clause"
] | 13 | 2018-06-13T18:08:57.000Z | 2021-09-30T02:39:01.000Z | test/perf/os/OSTimerTester.cpp | ORNL-Fusion/xolotl | 993434bea0d3bca439a733a12af78034c911690c | [
"BSD-3-Clause"
] | 97 | 2018-02-14T15:24:08.000Z | 2022-03-29T16:29:48.000Z | test/perf/os/OSTimerTester.cpp | ORNL-Fusion/xolotl | 993434bea0d3bca439a733a12af78034c911690c | [
"BSD-3-Clause"
] | 18 | 2018-02-13T20:36:03.000Z | 2022-01-04T14:54:16.000Z | #define BOOST_TEST_MODULE Regression
#include <string>
#include <boost/test/included/unit_test.hpp>
#include <xolotl/perf/os/OSTimer.h>
using namespace std;
using namespace xolotl;
/**
* This suite is responsible for testing the OSTimer.
*/
BOOST_AUTO_TEST_SUITE(OSTimer_testSuite)
BOOST_AUTO_TEST_CASE(checkTiming)
{
auto tester = perf::os::OSTimer();
double sleepSeconds = 2.0;
// Simulate some computation/communication with a sleep of known duration.
// Time the duration of the operation.
tester.start();
sleep(sleepSeconds);
tester.stop();
// Require that the value of this Timer is within 3% of the
// duration of the sleep.
BOOST_REQUIRE_CLOSE(sleepSeconds, tester.getValue(), 0.03);
BOOST_REQUIRE_EQUAL("s", tester.getUnits());
}
BOOST_AUTO_TEST_CASE(accumulate)
{
auto tester = perf::os::OSTimer();
const unsigned int sleepSeconds = 2;
tester.start();
sleep(sleepSeconds);
tester.stop();
tester.start();
sleep(sleepSeconds);
tester.stop();
double timerValue = tester.getValue();
double expValue = 2 * sleepSeconds; // we had two sleep intervals
BOOST_REQUIRE_CLOSE(expValue, timerValue, 0.03);
}
BOOST_AUTO_TEST_CASE(reset)
{
auto tester = perf::os::OSTimer();
const unsigned int sleepSeconds = 2;
tester.start();
sleep(sleepSeconds);
tester.stop();
tester.reset();
BOOST_REQUIRE_EQUAL(tester.getValue(), 0.0);
tester.start();
sleep(sleepSeconds);
tester.stop();
double timerValue = tester.getValue();
double expValue = sleepSeconds; // should only represent last sleep interval
BOOST_REQUIRE_CLOSE(expValue, timerValue, 0.03);
}
BOOST_AUTO_TEST_SUITE_END()
| 22.219178 | 77 | 0.74291 | ORNL-Fusion |
6efc04af7e71c2c6aef92cce088b860c1b483427 | 17,430 | cpp | C++ | tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp | florianjacob/gpuocelot | fa63920ee7c5f9a86e264cd8acd4264657cbd190 | [
"BSD-3-Clause"
] | 221 | 2015-03-29T02:05:49.000Z | 2022-03-25T01:45:36.000Z | tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 106 | 2015-03-29T01:28:42.000Z | 2022-02-15T19:38:23.000Z | tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 83 | 2015-07-10T23:09:57.000Z | 2022-03-25T03:01:00.000Z | /*
* Copyright 1993-2009 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws. Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users. This source code is a "commercial item" as
* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
* "commercial computer software" and "commercial computer software
* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#if defined(__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <cuda_runtime.h>
#include <cutil_inline.h>
#include <cutil_gl_inline.h>
#include <cuda_gl_interop.h>
#include <rendercheck_gl.h>
#include "SobelFilter_kernels.h"
//
// Cuda example code that implements the Sobel edge detection
// filter. This code works for 8-bit monochrome images.
//
// Use the '-' and '=' keys to change the scale factor.
//
// Other keys:
// I: display image
// T: display Sobel edge detection (computed solely with texture)
// S: display Sobel edge detection (computed with texture and shared memory)
void cleanup(void);
void initializeData(char *file) ;
#define MAX_EPSILON_ERROR 5.0f
static char *sSDKsample = "CUDA Sobel Edge-Detection";
// Define the files that are to be save and the reference images for validation
const char *sOriginal[] =
{
"lena_orig.pgm",
"lena_shared.pgm",
"lena_shared_tex.pgm",
NULL
};
const char *sOriginal_ppm[] =
{
"lena_orig.ppm",
"lena_shared.ppm",
"lena_shared_tex.ppm",
NULL
};
const char *sReference[] =
{
"ref_orig.pgm",
"ref_shared.pgm",
"ref_shared_tex.pgm",
NULL
};
const char *sReference_ppm[] =
{
"ref_orig.ppm",
"ref_shared.ppm",
"ref_shared_tex.ppm",
NULL
};
static int wWidth = 512; // Window width
static int wHeight = 512; // Window height
static int imWidth = 0; // Image width
static int imHeight = 0; // Image height
// Code to handle Auto verification
const int frameCheckNumber = 4;
int fpsCount = 0; // FPS count for averaging
int fpsLimit = 8; // FPS limit for sampling
unsigned int frameCount = 0;
unsigned int g_TotalErrors = 0;
bool g_Verify = false, g_AutoQuit = false;
unsigned int timer;
unsigned int g_Bpp;
unsigned int g_Index = 0;
bool g_bQAReadback = false;
bool g_bOpenGLQA = false;
bool g_bFBODisplay = false;
// Display Data
static GLuint pbo_buffer = 0; // Front and back CA buffers
static GLuint texid = 0; // Texture for display
unsigned char * pixels = NULL; // Image pixel data on the host
float imageScale = 1.f; // Image exposure
enum SobelDisplayMode g_SobelDisplayMode;
// CheckFBO/BackBuffer class objects
CheckRender *g_CheckRender = NULL;
bool bQuit = false;
extern "C" void runAutoTest(int argc, char **argv);
#define OFFSET(i) ((char *)NULL + (i))
#define MAX(a,b) ((a > b) ? a : b)
void AutoQATest()
{
if (g_CheckRender && g_CheckRender->IsQAReadback()) {
char temp[256];
g_SobelDisplayMode = (SobelDisplayMode)g_Index;
sprintf(temp, "%s Cuda Edge Detection (%s)", "AutoTest:", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
g_Index++;
if (g_Index > 2) {
g_Index = 0;
printf("Summary: %d errors!\n", g_TotalErrors);
printf("Test %s!\n", (g_TotalErrors==0) ? "PASSED" : "FAILED");
exit(0);
}
}
}
void computeFPS()
{
frameCount++;
fpsCount++;
if (fpsCount == fpsLimit-1) {
g_Verify = true;
}
if (fpsCount == fpsLimit) {
char fps[256];
float ifps = 1.f / (cutGetAverageTimerValue(timer) / 1000.f);
sprintf(fps, "%s Cuda Edge Detection (%s): %3.1f fps",
((g_CheckRender && g_CheckRender->IsQAReadback()) ? "AutoTest:" : ""),
filterMode[g_SobelDisplayMode], ifps);
glutSetWindowTitle(fps);
fpsCount = 0;
if (g_CheckRender && !g_CheckRender->IsQAReadback()) fpsLimit = (int)MAX(ifps, 1.f);
cutilCheckError(cutResetTimer(timer));
AutoQATest();
}
}
// This is the normal display path
void display(void)
{
cutilCheckError(cutStartTimer(timer));
// Sobel operation
Pixel *data = NULL;
cutilSafeCall(cudaGLMapBufferObject((void**)&data, pbo_buffer));
sobelFilter(data, imWidth, imHeight, g_SobelDisplayMode, imageScale );
cutilSafeCall(cudaGLUnmapBufferObject(pbo_buffer));
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texid);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, imWidth, imHeight,
GL_LUMINANCE, GL_UNSIGNED_BYTE, OFFSET(0));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBegin(GL_QUADS);
glVertex2f(0, 0); glTexCoord2f(0, 0);
glVertex2f(0, 1); glTexCoord2f(1, 0);
glVertex2f(1, 1); glTexCoord2f(1, 1);
glVertex2f(1, 0); glTexCoord2f(0, 1);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
if (g_CheckRender && g_CheckRender->IsQAReadback() && g_Verify) {
printf("> (Frame %d) readback BackBuffer\n", frameCount);
g_CheckRender->readback( imWidth, imHeight );
g_CheckRender->savePPM ( sOriginal_ppm[g_Index], true, NULL );
if (!g_CheckRender->PPMvsPPM(sOriginal_ppm[g_Index], sReference_ppm[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
g_TotalErrors++;
}
g_Verify = false;
}
glutSwapBuffers();
cutilCheckError(cutStopTimer(timer));
computeFPS();
glutPostRedisplay();
}
void idle(void) {
glutPostRedisplay();
}
void keyboard( unsigned char key, int /*x*/, int /*y*/)
{
char temp[256];
switch( key) {
case 27:
exit (0);
break;
case '-':
imageScale -= 0.1f;
printf("brightness = %4.2f\n", imageScale);
break;
case '=':
imageScale += 0.1f;
printf("brightness = %4.2f\n", imageScale);
break;
case 'i':
case 'I':
g_SobelDisplayMode = SOBELDISPLAY_IMAGE;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
break;
case 's':
case 'S':
g_SobelDisplayMode = SOBELDISPLAY_SOBELSHARED;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
break;
case 't':
case 'T':
g_SobelDisplayMode = SOBELDISPLAY_SOBELTEX;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
default: break;
}
glutPostRedisplay();
}
void reshape(int x, int y) {
glViewport(0, 0, x, y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutPostRedisplay();
}
void cleanup(void) {
cutilSafeCall(cudaGLUnregisterBufferObject(pbo_buffer));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glDeleteBuffers(1, &pbo_buffer);
glDeleteTextures(1, &texid);
deleteTexture();
if (g_CheckRender) {
delete g_CheckRender; g_CheckRender = NULL;
}
cutilCheckError(cutDeleteTimer(timer));
}
void initializeData(char *file) {
GLint bsize;
unsigned int w, h;
size_t file_length= strlen(file);
if (!strcmp(&file[file_length-3], "pgm")) {
if (cutLoadPGMub(file, &pixels, &w, &h) != CUTTrue) {
printf("Failed to load image file: %s\n", file);
exit(-1);
}
g_Bpp = 1;
} else if (!strcmp(&file[file_length-3], "ppm")) {
if (cutLoadPPM4ub(file, &pixels, &w, &h) != CUTTrue) {
printf("Failed to load image file: %s\n", file);
exit(-1);
}
g_Bpp = 4;
} else {
cudaThreadExit();
exit(-1);
}
imWidth = (int)w; imHeight = (int)h;
setupTexture(imWidth, imHeight, pixels, g_Bpp);
memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * imWidth * imHeight);
if (!g_bQAReadback) {
// use OpenGL Path
glGenBuffers(1, &pbo_buffer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
glBufferData(GL_PIXEL_UNPACK_BUFFER,
g_Bpp * sizeof(Pixel) * imWidth * imHeight,
pixels, GL_STREAM_DRAW);
glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize);
if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * imWidth * imHeight)) {
printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);
cudaThreadExit();
exit(-1);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
cutilSafeCall(cudaGLRegisterBufferObject(pbo_buffer));
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA),
imWidth, imHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
}
}
void loadDefaultImage( char* loc_exec) {
printf("Reading image: lena.pgm\n");
const char* image_filename = "lena.pgm";
char* image_path = cutFindFilePath(image_filename, loc_exec);
if (image_path == 0) {
printf( "Reading image failed.\n");
exit(EXIT_FAILURE);
}
initializeData( image_path );
cutFree( image_path );
}
void printHelp()
{
printf("\nUsage: SobelFilter <options>\n");
printf("\t\t-fbo (render using FBO display path)\n");
printf("\t\t-qatest (automatic validation)\n");
printf("\t\t-file = filename.pgm (image files for input)\n\n");
bQuit = true;
}
void initGL(int argc, char** argv)
{
glutInit( &argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(wWidth, wHeight);
glutCreateWindow("Cuda Edge Detection");
glewInit();
if (g_bFBODisplay) {
if (!glewIsSupported( "GL_VERSION_2_0 GL_ARB_fragment_program GL_EXT_framebuffer_object" )) {
fprintf(stderr, "Error: failed to get minimal extensions for demo\n");
fprintf(stderr, "This sample requires:\n");
fprintf(stderr, " OpenGL version 2.0\n");
fprintf(stderr, " GL_ARB_fragment_program\n");
fprintf(stderr, " GL_EXT_framebuffer_object\n");
cudaThreadExit();
exit(-1);
}
} else {
if (!glewIsSupported( "GL_VERSION_1_5 GL_ARB_vertex_buffer_object GL_ARB_pixel_buffer_object" )) {
fprintf(stderr, "Error: failed to get minimal extensions for demo\n");
fprintf(stderr, "This sample requires:\n");
fprintf(stderr, " OpenGL version 1.5\n");
fprintf(stderr, " GL_ARB_vertex_buffer_object\n");
fprintf(stderr, " GL_ARB_pixel_buffer_object\n");
cudaThreadExit();
exit(-1);
}
}
}
void runAutoTest(int argc, char **argv)
{
printf("[%s] (automated testing w/ readback)\n", sSDKsample);
if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
cutilDeviceInit(argc, argv);
} else {
cudaSetDevice( cutGetMaxGflopsDeviceId() );
}
if (argc > 1) {
char *filename;
if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
initializeData(filename);
}
} else {
loadDefaultImage( argv[0]);
}
g_CheckRender = new CheckBackBuffer(imWidth, imHeight, sizeof(Pixel), false);
g_CheckRender->setExecPath(argv[0]);
Pixel *d_result;
cutilSafeCall( cudaMalloc( (void **)&d_result, imWidth*imHeight*sizeof(Pixel)) );
while (g_SobelDisplayMode <= 2)
{
printf("AutoTest: %s <%s>\n", sSDKsample, filterMode[g_SobelDisplayMode]);
sobelFilter(d_result, imWidth, imHeight, g_SobelDisplayMode, imageScale );
cutilSafeCall( cudaThreadSynchronize() );
cudaMemcpy(g_CheckRender->imageData(), d_result, imWidth*imHeight*sizeof(Pixel), cudaMemcpyDeviceToHost);
g_CheckRender->savePGM(sOriginal[g_Index], false, NULL);
if (!g_CheckRender->PGMvsPGM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
g_TotalErrors++;
}
g_Index++;
g_SobelDisplayMode = (SobelDisplayMode)g_Index;
}
cutilSafeCall( cudaFree( d_result ) );
delete g_CheckRender;
if (!g_TotalErrors)
printf("TEST PASSED!\n");
else
printf("TEST FAILED!\n");
}
int main(int argc, char** argv)
{
if (!cutCheckCmdLineFlag(argc, (const char **)argv, "noqatest") ||
cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt"))
{
g_bQAReadback = true;
fpsLimit = frameCheckNumber;
}
if (argc > 1) {
if (cutCheckCmdLineFlag(argc, (const char **)argv, "help")) {
printHelp();
}
if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify"))
{
g_bOpenGLQA = true;
fpsLimit = frameCheckNumber;
}
if (cutCheckCmdLineFlag(argc, (const char **)argv, "fbo")) {
g_bFBODisplay = true;
fpsLimit = frameCheckNumber;
}
}
if (g_bQAReadback)
{
runAutoTest(argc, argv);
} else {
// First initialize OpenGL context, so we can properly set the GL for CUDA.
// This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
initGL( argc, argv );
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
cutilGLDeviceInit(argc, argv);
} else {
cudaGLSetGLDevice (cutGetMaxGflopsDeviceId() );
}
int device;
struct cudaDeviceProp prop;
cudaGetDevice( &device );
cudaGetDeviceProperties( &prop, device );
if( !strncmp( "Tesla", prop.name, 5 ) ){
printf("This sample needs a card capable of OpenGL and display.\n");
printf("Please choose a different device with the -device=x argument.\n");
cudaThreadExit();
cutilExit(argc, argv);
}
cutilCheckError(cutCreateTimer(&timer));
cutilCheckError(cutResetTimer(timer));
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
if (g_bOpenGLQA) {
loadDefaultImage( argv[0] );
}
if (argc > 1) {
char *filename;
if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
initializeData(filename);
}
} else {
loadDefaultImage( argv[0]);
}
// If code is not printing the USage, then we execute this path.
if (!bQuit) {
if (g_bOpenGLQA) {
g_CheckRender = new CheckBackBuffer(wWidth, wHeight, 4);
g_CheckRender->setPixelFormat(GL_BGRA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
}
printf("I: display image\n");
printf("T: display Sobel edge detection (computed with tex)\n");
printf("S: display Sobel edge detection (computed with tex+shared memory)\n");
printf("Use the '-' and '=' keys to change the brightness.\n");
fflush(stdout);
atexit(cleanup);
glutMainLoop();
}
}
cudaThreadExit();
cutilExit(argc, argv);
}
| 31.014235 | 114 | 0.635571 | florianjacob |
6efc5d7fe01f241b9c0715c28e342bdbc9a6e094 | 9,872 | hpp | C++ | Source/Math/Matrix4.hpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | Source/Math/Matrix4.hpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | Source/Math/Matrix4.hpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | // Copyright 2020, Nathan Blane
#pragma once
#include "Math/Vector4.hpp"
#include "Math/MathDefinitions.hpp"
#include "Math/MathAPI.hpp"
struct Quat;
// TODO - Make the set and constructor methods be free floating methods that
// return a constructed matrix of that type
class MATH_API Matrix4
{
public:
static const Matrix4 Identity;
public:
Matrix4();
explicit Matrix4(const Vector4& row0, const Vector4& row1, const Vector4& row2, const Vector4& row3);
explicit Matrix4(MatrixSpecialType specialEnum);
explicit Matrix4(MatrixTransType transEnum, const Vector4& transVec);
explicit Matrix4(MatrixTransType transEnum, f32 x, f32 y, f32 z);
explicit Matrix4(RotType rotationEnum, f32 angle);
explicit Matrix4(Rot3AxisType multiAxisEnum, f32 xAngleRad, f32 yAngleRad, f32 zAngleRad);
explicit Matrix4(RotAxisAngleType axisEnum, const Vector4& vect, f32 angleRads);
explicit Matrix4(RotOrientType orientEnum, const Vector4& dof, const Vector4& up);
explicit Matrix4(MatrixScaleType scaleEnum, const Vector4& scaleVec);
explicit Matrix4(MatrixScaleType scaleEnum, f32 sx, f32 sy, f32 sz);
Matrix4(const Quat& q);
// Setting specific matrix types
void Set(MatrixTransType transEnum, const Vector4& transVec);
void Set(MatrixTransType transEnum, f32 x, f32 y, f32 z);
void Set(RotType rotationEnum, f32 angle);
void Set(Rot3AxisType axisEnum, f32 xRad, f32 yRad, f32 zRad);
void Set(RotAxisAngleType axisEnum, const Vector4& vect, f32 angleRads);
void Set(RotOrientType orientEnum, const Vector4& dof, const Vector4& up);
void Set(const struct Quat& q);
void Set(MatrixScaleType scaleEnum, const Vector4& scaleVec);
void Set(MatrixScaleType scaleEnum, f32 sx, f32 sy, f32 sz);
void Set(MatrixSpecialType specialEnum);
void Set(const Vector4 &axis, f32 angle);
// Setting matrix
void Set(const Vector4& row0, const Vector4& row1, const Vector4& row2, const Vector4& row3);
void Set(MatrixRowType rowEnum, const Vector4& rowVec);
// Get row of matrix
Vector4 Get(MatrixRowType rowEnum) const;
// Matrix operations
// Determinant
f32 Determinant() const;
// Inverse
void Inverse();
Matrix4 GetInverse() const;
// Transpose
void Transpose();
Matrix4 GetTranspose() const;
bool IsIdentity(f32 epsilon = Math::InternalTolerence) const;
bool IsEqual(const Matrix4& m, f32 epsilon = Math::InternalTolerence) const;
Matrix4 operator+() const;
Matrix4 operator-() const;
Matrix4 operator+(const Matrix4& m) const;
Matrix4 operator-(const Matrix4& m) const;
Matrix4 operator*(const Matrix4& m) const;
Matrix4 operator*(f32 s) const;
Matrix4& operator+=(const Matrix4& m);
Matrix4& operator-=(const Matrix4& m);
Matrix4& operator*=(const Matrix4& m);
Matrix4& operator*=(f32 s);
//friend MATH_API Vector3 operator*(const Vector3& v, const Matrix4& m);
friend MATH_API Vector4 operator*(const Vector4& v, const Matrix4& m);
friend MATH_API Matrix4 operator*(f32 s, const Matrix4& m);
friend MATH_API Vector4& operator*=(Vector4& v, const Matrix4& m);
friend MATH_API bool operator==(const Matrix4& lhs, const Matrix4& rhs)
{
return lhs.IsEqual(rhs);
}
friend MATH_API bool operator!=(const Matrix4& lhs, const Matrix4& rhs)
{
return !lhs.IsEqual(rhs);
}
forceinline f32& m0();
forceinline f32& m1();
forceinline f32& m2();
forceinline f32& m3();
forceinline f32& m4();
forceinline f32& m6();
forceinline f32& m7();
forceinline f32& m8();
forceinline f32& m9();
forceinline f32& m5();
forceinline f32& m10();
forceinline f32& m11();
forceinline f32& m12();
forceinline f32& m13();
forceinline f32& m14();
forceinline f32& m15();
forceinline const f32& m0() const;
forceinline const f32& m1() const;
forceinline const f32& m2() const;
forceinline const f32& m3() const;
forceinline const f32& m4() const;
forceinline const f32& m5() const;
forceinline const f32& m6() const;
forceinline const f32& m7() const;
forceinline const f32& m8() const;
forceinline const f32& m9() const;
forceinline const f32& m10() const;
forceinline const f32& m11() const;
forceinline const f32& m12() const;
forceinline const f32& m13() const;
forceinline const f32& m14() const;
forceinline const f32& m15() const;
forceinline f32& operator[](m0_enum);
forceinline f32& operator[](m1_enum);
forceinline f32& operator[](m2_enum);
forceinline f32& operator[](m3_enum);
forceinline f32& operator[](m4_enum);
forceinline f32& operator[](m5_enum);
forceinline f32& operator[](m6_enum);
forceinline f32& operator[](m7_enum);
forceinline f32& operator[](m8_enum);
forceinline f32& operator[](m9_enum);
forceinline f32& operator[](m10_enum);
forceinline f32& operator[](m11_enum);
forceinline f32& operator[](m12_enum);
forceinline f32& operator[](m13_enum);
forceinline f32& operator[](m14_enum);
forceinline f32& operator[](m15_enum);
forceinline const f32& operator[](m0_enum) const;
forceinline const f32& operator[](m1_enum) const;
forceinline const f32& operator[](m2_enum) const;
forceinline const f32& operator[](m3_enum) const;
forceinline const f32& operator[](m4_enum) const;
forceinline const f32& operator[](m5_enum) const;
forceinline const f32& operator[](m6_enum) const;
forceinline const f32& operator[](m7_enum) const;
forceinline const f32& operator[](m8_enum) const;
forceinline const f32& operator[](m9_enum) const;
forceinline const f32& operator[](m10_enum) const;
forceinline const f32& operator[](m11_enum) const;
forceinline const f32& operator[](m12_enum) const;
forceinline const f32& operator[](m13_enum) const;
forceinline const f32& operator[](m14_enum) const;
forceinline const f32& operator[](m15_enum) const;
private:
// 00, 01, 02, 03
Vector4 v0;
// 10, 11, 12, 13
Vector4 v1;
// 20, 21, 22, 23
Vector4 v2;
// 30, 31, 32, 33
Vector4 v3;
};
f32& Matrix4::m0()
{
return v0.x;
}
forceinline f32& Matrix4::m1()
{
return v0.y;
}
forceinline f32& Matrix4::m2()
{
return v0.z;
}
forceinline f32& Matrix4::m3()
{
return v0.w;
}
forceinline f32& Matrix4::m4()
{
return v1.x;
}
forceinline f32& Matrix4::m5()
{
return v1.y;
}
forceinline f32& Matrix4::m6()
{
return v1.z;
}
forceinline f32& Matrix4::m7()
{
return v1.w;
}
forceinline f32& Matrix4::m8()
{
return v2.x;
}
forceinline f32& Matrix4::m9()
{
return v2.y;
}
forceinline f32& Matrix4::m10()
{
return v2.z;
}
forceinline f32& Matrix4::m11()
{
return v2.w;
}
forceinline f32& Matrix4::m12()
{
return v3.x;
}
forceinline f32& Matrix4::m13()
{
return v3.y;
}
forceinline f32& Matrix4::m14()
{
return v3.z;
}
forceinline f32& Matrix4::m15()
{
return v3.w;
}
forceinline const f32& Matrix4::m0() const
{
return v0.x;
}
forceinline const f32& Matrix4::m1() const
{
return v0.y;
}
forceinline const f32& Matrix4::m2() const
{
return v0.z;
}
forceinline const f32& Matrix4::m3() const
{
return v0.w;
}
forceinline const f32& Matrix4::m4() const
{
return v1.x;
}
forceinline const f32& Matrix4::m5() const
{
return v1.y;
}
forceinline const f32& Matrix4::m6() const
{
return v1.z;
}
forceinline const f32& Matrix4::m7() const
{
return v1.w;
}
forceinline const f32& Matrix4::m8() const
{
return v2.x;
}
forceinline const f32& Matrix4::m9() const
{
return v2.y;
}
forceinline const f32& Matrix4::m10() const
{
return v2.z;
}
forceinline const f32& Matrix4::m11() const
{
return v2.w;
}
forceinline const f32& Matrix4::m12() const
{
return v3.x;
}
forceinline const f32& Matrix4::m13() const
{
return v3.y;
}
forceinline const f32& Matrix4::m14() const
{
return v3.z;
}
forceinline const f32& Matrix4::m15() const
{
return v3.w;
}
forceinline f32& Matrix4::operator[](m0_enum)
{
return v0.x;
}
forceinline f32& Matrix4::operator[](m1_enum)
{
return v0.y;
}
forceinline f32& Matrix4::operator[](m2_enum)
{
return v0.z;
}
forceinline f32& Matrix4::operator[](m3_enum)
{
return v0.w;
}
forceinline f32& Matrix4::operator[](m4_enum)
{
return v1.x;
}
forceinline f32& Matrix4::operator[](m5_enum)
{
return v1.y;
}
forceinline f32& Matrix4::operator[](m6_enum)
{
return v1.z;
}
forceinline f32& Matrix4::operator[](m7_enum)
{
return v1.w;
}
forceinline f32& Matrix4::operator[](m8_enum)
{
return v2.x;
}
forceinline f32& Matrix4::operator[](m9_enum)
{
return v2.y;
}
forceinline f32& Matrix4::operator[](m10_enum)
{
return v2.z;
}
forceinline f32& Matrix4::operator[](m11_enum)
{
return v2.w;
}
forceinline f32& Matrix4::operator[](m12_enum)
{
return v3.x;
}
forceinline f32& Matrix4::operator[](m13_enum)
{
return v3.y;
}
forceinline f32& Matrix4::operator[](m14_enum)
{
return v3.z;
}
forceinline f32& Matrix4::operator[](m15_enum)
{
return v3.w;
}
forceinline const f32& Matrix4::operator[](m0_enum) const
{
return v0.x;
}
forceinline const f32& Matrix4::operator[](m1_enum) const
{
return v0.y;
}
forceinline const f32& Matrix4::operator[](m2_enum) const
{
return v0.z;
}
forceinline const f32& Matrix4::operator[](m3_enum) const
{
return v0.w;
}
forceinline const f32& Matrix4::operator[](m4_enum) const
{
return v1.x;
}
forceinline const f32& Matrix4::operator[](m5_enum) const
{
return v1.y;
}
forceinline const f32& Matrix4::operator[](m6_enum) const
{
return v1.z;
}
forceinline const f32& Matrix4::operator[](m7_enum) const
{
return v1.w;
}
forceinline const f32& Matrix4::operator[](m8_enum) const
{
return v2.x;
}
forceinline const f32& Matrix4::operator[](m9_enum) const
{
return v2.y;
}
forceinline const f32& Matrix4::operator[](m10_enum) const
{
return v2.z;
}
forceinline const f32& Matrix4::operator[](m11_enum) const
{
return v2.w;
}
forceinline const f32& Matrix4::operator[](m12_enum) const
{
return v3.x;
}
forceinline const f32& Matrix4::operator[](m13_enum) const
{
return v3.y;
}
forceinline const f32& Matrix4::operator[](m14_enum) const
{
return v3.z;
}
forceinline const f32& Matrix4::operator[](m15_enum) const
{
return v3.w;
}
| 19.863179 | 102 | 0.718395 | frobro98 |
6efdcea60d391d0bcd0a884c7455856be6b274e6 | 522 | cpp | C++ | KM/03code/book/Thinking-In-C-resource-master/C03/c0316.cpp | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 10 | 2019-03-17T10:13:04.000Z | 2021-03-03T03:23:34.000Z | KM/03code/book/Thinking-In-C-resource-master/C03/c0316.cpp | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 44 | 2018-12-14T02:35:47.000Z | 2021-02-06T09:12:10.000Z | KM/03code/book/Thinking-In-C-resource-master/C03/c0316.cpp | wangcy6/weekly | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
enum Color
{
blue = 1,
red = 2,
black = 3,
white = 4,
yellow = 5,
};
int main()
{
Color mcolor = blue;
for(int i = blue ; i <= yellow; i++)
{
switch(i)
{
case blue:
cout<<"blue color is: "<<blue<<endl;
break;
case red:
cout<<"red color is: "<<red<<endl;
break;
case black:
cout<<"black color is: "<<black<<endl;
break;
case white:
cout<<"white color is: "<<white<<endl;
break;
case yellow:
cout<<"yellow color is: "<<yellow<<endl;
break;
}
}
return 0;
}
| 11.6 | 40 | 0.599617 | wangcy6 |
6efe513761ea1954ddbf39cedcbdab45bba6b1bb | 63 | hpp | C++ | making coffee/coffee.hpp | mattersievers/cpp_basics | 53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc | [
"Apache-2.0"
] | null | null | null | making coffee/coffee.hpp | mattersievers/cpp_basics | 53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc | [
"Apache-2.0"
] | null | null | null | making coffee/coffee.hpp | mattersievers/cpp_basics | 53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc | [
"Apache-2.0"
] | null | null | null | std::string make_coffee(bool milk = false, bool sugar = false); | 63 | 63 | 0.746032 | mattersievers |
6efe6a2198b44083901f948149b2f993ef00259b | 5,537 | cc | C++ | mesh_estimate/src/stereo/inverse_depth_meas_model.cc | pangfumin/okvis_depth_mesh | a6c95a723796b3d9f14db7ec925bb7c046c81039 | [
"BSD-3-Clause"
] | 3 | 2018-09-20T01:41:27.000Z | 2020-06-03T15:13:20.000Z | mesh_estimate/src/stereo/inverse_depth_meas_model.cc | pangfumin/okvis_depth_mesh | a6c95a723796b3d9f14db7ec925bb7c046c81039 | [
"BSD-3-Clause"
] | null | null | null | mesh_estimate/src/stereo/inverse_depth_meas_model.cc | pangfumin/okvis_depth_mesh | a6c95a723796b3d9f14db7ec925bb7c046c81039 | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of FLaME.
* Copyright (C) 2017 W. Nicholas Greene (wng@csail.mit.edu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*
* @file inverse_depth_meas_model.cc
* @author W. Nicholas Greene
* @date 2016-07-19 21:03:02 (Tue)
*/
#include "flame/stereo/inverse_depth_meas_model.h"
#include <stdio.h>
#include "flame/utils/assert.h"
#include "flame/utils/image_utils.h"
namespace flame {
namespace stereo {
InverseDepthMeasModel::InverseDepthMeasModel(const Eigen::Matrix3f& K0,
const Eigen::Matrix3f& K0inv,
const Eigen::Matrix3f& K1,
const Eigen::Matrix3f& K1inv,
const Params& params) :
inited_geo_(false),
inited_imgs_(false),
params_(params),
img_ref_(),
img_cmp_(),
gradx_ref_(),
grady_ref_(),
gradx_cmp_(),
grady_cmp_(),
T_ref_to_cmp_(),
epigeo_(K0, K0inv, K1, K1inv) {}
bool InverseDepthMeasModel::idepth(const cv::Point2f& u_ref,
const cv::Point2f& u_cmp,
float* mu, float* var) const {
FLAME_ASSERT(inited_geo_ && inited_imgs_);
// Compute the inverse depth mean.
cv::Point2f u_inf, epi;
float disp = epigeo_.disparity(u_ref, u_cmp, &u_inf, &epi);
// printf("epi = %f, %f\n", epi.x, epi.y);
// printf("disp = %f\n", disp);
if (disp < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NegativeDisparity: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp);
}
// No dispariy = idepth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
*mu = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp);
if (*mu < 0.0f) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NegativeIDepth: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
// Get the image gradient.
cv::Point2f offset(params_.win_size/2+1, params_.win_size/2+1);
float gx = utils::bilinearInterp<float, float>(gradx_cmp_,
u_cmp.x + offset.x,
u_cmp.y + offset.y);
float gy = utils::bilinearInterp<float, float>(grady_cmp_,
u_cmp.x + offset.x,
u_cmp.y + offset.y);
float gnorm = sqrt(gx * gx + gy * gy);
if (gnorm < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NoGradient: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f, grad = (%f, %f)\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu, gx, gy);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
float ngx = gx / gnorm;
float ngy = gy / gnorm;
// printf("grad = %f, %f\n", gx, gy);
// Compute geometry disparity variance.
float epi_dot_ngrad = ngx * epi.x + ngy * epi.y;
float geo_var = params_.epipolar_line_var / (epi_dot_ngrad * epi_dot_ngrad);
if (utils::fast_abs(epi_dot_ngrad) < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NoEpiDotGradient: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f, grad = (%f, %f), epi = (%f, %f)\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu, gx, gy, epi.x, epi.y);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
// Compute photometric disparity variance.
float epi_dot_grad = gx * epi.x + gy * epi.y;
float photo_var = 2 * params_.pixel_var / (epi_dot_grad * epi_dot_grad);
// Compute disparity to inverse depth scaling factor.
float disp_min = disp - disp / 10;
float disp_max = disp + disp / 10;
float idepth_min = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp_min);
float idepth_max = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp_max);
float alpha = (idepth_max - idepth_min) / (disp_max - disp_min);
float meas_var = alpha * alpha * (geo_var + photo_var);
FLAME_ASSERT(!std::isnan(meas_var));
FLAME_ASSERT(!std::isinf(meas_var));
// printf("var1 = %f\n", meas_var);
// float angle = Eigen::AngleAxisf(T_ref_to_cmp_.unit_quaternion()).angle();
// float baseline = T_ref_to_cmp_.translation().squaredNorm();
// meas_var = 0.000001f / baseline + 0.0001f / cos(angle);
*var = meas_var;
// printf("var2 = %f\n", meas_var);
return true;
}
} // namespace stereo
} // namespace flame
| 33.969325 | 178 | 0.590392 | pangfumin |
3e01ac8d1067bf9c01e97f36acbc934061ca3af3 | 160 | hxx | C++ | src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_TRU64
#ifndef __UNIX_SOFTWAREFEATURESAPIMPLEMENTATION_PRIVATE_H
#define __UNIX_SOFTWAREFEATURESAPIMPLEMENTATION_PRIVATE_H
#endif
#endif
| 13.333333 | 57 | 0.88125 | brunolauze |
3e026e598383d4eb052638fb6a25a51b3efd37d1 | 787 | hpp | C++ | includes/Graphics/DebugInfoManager.hpp | razerx100/Gaia | 4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b | [
"MIT"
] | null | null | null | includes/Graphics/DebugInfoManager.hpp | razerx100/Gaia | 4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b | [
"MIT"
] | null | null | null | includes/Graphics/DebugInfoManager.hpp | razerx100/Gaia | 4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b | [
"MIT"
] | null | null | null | #ifndef __DXGI_INFO_MANAGER_HPP__
#define __DXGI_INFO_MANAGER_HPP__
#include <CleanWin.hpp>
#include <wrl.h>
#include <vector>
#include <string>
#include <d3d12.h>
using Microsoft::WRL::ComPtr;
class DebugInfoManager {
public:
DebugInfoManager();
~DebugInfoManager() = default;
DebugInfoManager(const DebugInfoManager&) = delete;
DebugInfoManager& operator=(const DebugInfoManager&) = delete;
void Set() noexcept;
std::vector<std::string> GetMessages() const;
ComPtr<ID3D12InfoQueue> m_pInfoQueue;
private:
std::uint64_t m_next;
#ifdef _DEBUG
public:
static void SetDebugInfoManager(ID3D12Device5* device) noexcept;
static DebugInfoManager& GetDebugInfoManager() noexcept;
private:
static DebugInfoManager s_InfoManager;
#endif
};
#endif | 23.147059 | 66 | 0.753494 | razerx100 |
3e03d0985df695dacaabfaf01baafb51955e176a | 30,372 | cpp | C++ | SparCraft/bwapidata/include/UpgradeType.cpp | iali17/TheDon | f21cae2357835e7a21ebf351abb6bb175f67540c | [
"MIT"
] | null | null | null | SparCraft/bwapidata/include/UpgradeType.cpp | iali17/TheDon | f21cae2357835e7a21ebf351abb6bb175f67540c | [
"MIT"
] | null | null | null | SparCraft/bwapidata/include/UpgradeType.cpp | iali17/TheDon | f21cae2357835e7a21ebf351abb6bb175f67540c | [
"MIT"
] | null | null | null | #include <string>
#include <map>
#include <set>
#include <BWAPI/UpgradeType.h>
#include <BWAPI/Race.h>
#include <BWAPI/UnitType.h>
#include <Util/Foreach.h>
#include "Common.h"
namespace BWAPI
{
bool initializingUpgradeType = true;
class UpgradeTypeInternal
{
public:
UpgradeTypeInternal() {valid = false;}
void set(const char* name, int mineralPriceBase, int mineralPriceFactor, int gasPriceBase, int gasPriceFactor, int upgradeTimeBase, int upgradeTimeFactor, BWAPI::UnitType whatUpgrades, Race race, BWAPI::UnitType whatUses, int maxRepeats)
{
if (initializingUpgradeType)
{
this->name = name;
this->mineralPriceBase = mineralPriceBase;
this->mineralPriceFactor = mineralPriceFactor;
this->gasPriceBase = gasPriceBase;
this->gasPriceFactor = gasPriceFactor;
this->upgradeTimeBase = upgradeTimeBase;
this->upgradeTimeFactor = upgradeTimeFactor;
this->whatUpgrades = whatUpgrades;
this->race = race;
if (whatUses != UnitTypes::None)
this->whatUses.insert(whatUses);
this->maxRepeats = maxRepeats;
this->valid = true;
}
}
std::string name;
int mineralPriceBase;
int mineralPriceFactor;
int gasPriceBase;
int gasPriceFactor;
int upgradeTimeBase;
int upgradeTimeFactor;
BWAPI::UnitType whatUpgrades;
Race race;
int maxRepeats;
std::set<BWAPI::UnitType> whatUses;
bool valid;
};
UpgradeTypeInternal upgradeTypeData[63];
std::map<std::string, UpgradeType> upgradeTypeMap;
std::set< UpgradeType > upgradeTypeSet;
namespace UpgradeTypes
{
const UpgradeType Terran_Infantry_Armor(0);
const UpgradeType Terran_Vehicle_Plating(1);
const UpgradeType Terran_Ship_Plating(2);
const UpgradeType Zerg_Carapace(3);
const UpgradeType Zerg_Flyer_Carapace(4);
const UpgradeType Protoss_Ground_Armor(5);
const UpgradeType Protoss_Air_Armor(6);
const UpgradeType Terran_Infantry_Weapons(7);
const UpgradeType Terran_Vehicle_Weapons(8);
const UpgradeType Terran_Ship_Weapons(9);
const UpgradeType Zerg_Melee_Attacks(10);
const UpgradeType Zerg_Missile_Attacks(11);
const UpgradeType Zerg_Flyer_Attacks(12);
const UpgradeType Protoss_Ground_Weapons(13);
const UpgradeType Protoss_Air_Weapons(14);
const UpgradeType Protoss_Plasma_Shields(15);
const UpgradeType U_238_Shells(16);
const UpgradeType Ion_Thrusters(17);
const UpgradeType Titan_Reactor(19);
const UpgradeType Ocular_Implants(20);
const UpgradeType Moebius_Reactor(21);
const UpgradeType Apollo_Reactor(22);
const UpgradeType Colossus_Reactor(23);
const UpgradeType Ventral_Sacs(24);
const UpgradeType Antennae(25);
const UpgradeType Pneumatized_Carapace(26);
const UpgradeType Metabolic_Boost(27);
const UpgradeType Adrenal_Glands(28);
const UpgradeType Muscular_Augments(29);
const UpgradeType Grooved_Spines(30);
const UpgradeType Gamete_Meiosis(31);
const UpgradeType Metasynaptic_Node(32);
const UpgradeType Singularity_Charge(33);
const UpgradeType Leg_Enhancements(34);
const UpgradeType Scarab_Damage(35);
const UpgradeType Reaver_Capacity(36);
const UpgradeType Gravitic_Drive(37);
const UpgradeType Sensor_Array(38);
const UpgradeType Gravitic_Boosters(39);
const UpgradeType Khaydarin_Amulet(40);
const UpgradeType Apial_Sensors(41);
const UpgradeType Gravitic_Thrusters(42);
const UpgradeType Carrier_Capacity(43);
const UpgradeType Khaydarin_Core(44);
const UpgradeType Argus_Jewel(47);
const UpgradeType Argus_Talisman(49);
const UpgradeType Caduceus_Reactor(51);
const UpgradeType Chitinous_Plating(52);
const UpgradeType Anabolic_Synthesis(53);
const UpgradeType Charon_Boosters(54);
const UpgradeType None(61);
const UpgradeType Unknown(62);
void init()
{
upgradeTypeData[Terran_Infantry_Armor.getID()].set("Terran Infantry Armor" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Engineering_Bay , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Vehicle_Plating.getID()].set("Terran Vehicle Plating" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Ship_Plating.getID()].set("Terran Ship Plating" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Zerg_Carapace.getID()].set("Zerg Carapace" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].set("Zerg Flyer Carapace" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Zerg_Spire , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Protoss_Ground_Armor.getID()].set("Protoss Ground Armor" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Air_Armor.getID()].set("Protoss Air Armor" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Terran_Infantry_Weapons.getID()].set("Terran Infantry Weapons", 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Engineering_Bay , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].set("Terran Vehicle Weapons" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Ship_Weapons.getID()].set("Terran Ship Weapons" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Zerg_Melee_Attacks.getID()].set("Zerg Melee Attacks" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Missile_Attacks.getID()].set("Zerg Missile Attacks" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].set("Zerg Flyer Attacks" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Zerg_Spire , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Protoss_Ground_Weapons.getID()].set("Protoss Ground Weapons" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Air_Weapons.getID()].set("Protoss Air Weapons" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Plasma_Shields.getID()].set("Protoss Plasma Shields" , 200, 100, 200, 100, 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[U_238_Shells.getID()].set("U-238 Shells" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Terran_Academy , Races::Terran , UnitTypes::Terran_Marine , 1);
upgradeTypeData[Ion_Thrusters.getID()].set("Ion Thrusters" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Terran_Machine_Shop , Races::Terran , UnitTypes::Terran_Vulture , 1);
upgradeTypeData[Titan_Reactor.getID()].set("Titan Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Science_Facility , Races::Terran , UnitTypes::Terran_Science_Vessel, 1);
upgradeTypeData[Ocular_Implants.getID()].set("Ocular Implants" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Terran_Covert_Ops , Races::Terran , UnitTypes::Terran_Ghost , 1);
upgradeTypeData[Moebius_Reactor.getID()].set("Moebius Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Covert_Ops , Races::Terran , UnitTypes::Terran_Ghost , 1);
upgradeTypeData[Apollo_Reactor.getID()].set("Apollo Reactor" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Terran_Control_Tower , Races::Terran , UnitTypes::Terran_Wraith , 1);
upgradeTypeData[Colossus_Reactor.getID()].set("Colossus Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Physics_Lab , Races::Terran , UnitTypes::Terran_Battlecruiser , 1);
upgradeTypeData[Ventral_Sacs.getID()].set("Ventral Sacs" , 200, 0 , 200, 0 , 2400, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Antennae.getID()].set("Antennae" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Pneumatized_Carapace.getID()].set("Pneumatized Carapace" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Metabolic_Boost.getID()].set("Metabolic Boost" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Zerg_Spawning_Pool , Races::Zerg , UnitTypes::Zerg_Zergling , 1);
upgradeTypeData[Adrenal_Glands.getID()].set("Adrenal Glands" , 200, 0 , 200, 0 , 1500, 0 , UnitTypes::Zerg_Spawning_Pool , Races::Zerg , UnitTypes::Zerg_Zergling , 1);
upgradeTypeData[Muscular_Augments.getID()].set("Muscular Augments" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Zerg_Hydralisk_Den , Races::Zerg , UnitTypes::Zerg_Hydralisk , 1);
upgradeTypeData[Grooved_Spines.getID()].set("Grooved Spines" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Zerg_Hydralisk_Den , Races::Zerg , UnitTypes::Zerg_Hydralisk , 1);
upgradeTypeData[Gamete_Meiosis.getID()].set("Gamete Meiosis" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Zerg_Queens_Nest , Races::Zerg , UnitTypes::Zerg_Queen , 1);
upgradeTypeData[Metasynaptic_Node.getID()].set("Metasynaptic Node" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Zerg_Defiler_Mound , Races::Zerg , UnitTypes::Zerg_Defiler , 1);
upgradeTypeData[Singularity_Charge.getID()].set("Singularity Charge" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::Protoss_Dragoon , 1);
upgradeTypeData[Leg_Enhancements.getID()].set("Leg Enhancements" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Citadel_of_Adun , Races::Protoss, UnitTypes::Protoss_Zealot , 1);
upgradeTypeData[Scarab_Damage.getID()].set("Scarab Damage" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Scarab , 1);
upgradeTypeData[Reaver_Capacity.getID()].set("Reaver Capacity" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Reaver , 1);
upgradeTypeData[Gravitic_Drive.getID()].set("Gravitic Drive" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Shuttle , 1);
upgradeTypeData[Sensor_Array.getID()].set("Sensor Array" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Observatory , Races::Protoss, UnitTypes::Protoss_Observer , 1);
upgradeTypeData[Gravitic_Boosters.getID()].set("Gravitic Boosters" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Observatory , Races::Protoss, UnitTypes::Protoss_Observer , 1);
upgradeTypeData[Khaydarin_Amulet.getID()].set("Khaydarin Amulet" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Templar_Archives , Races::Protoss, UnitTypes::Protoss_High_Templar , 1);
upgradeTypeData[Apial_Sensors.getID()].set("Apial Sensors" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Scout , 1);
upgradeTypeData[Gravitic_Thrusters.getID()].set("Gravitic Thrusters" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Scout , 1);
upgradeTypeData[Carrier_Capacity.getID()].set("Carrier Capacity" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Carrier , 1);
upgradeTypeData[Khaydarin_Core.getID()].set("Khaydarin Core" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Arbiter_Tribunal , Races::Protoss, UnitTypes::Protoss_Arbiter , 1);
upgradeTypeData[Argus_Jewel.getID()].set("Argus Jewel" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Corsair , 1);
upgradeTypeData[Argus_Talisman.getID()].set("Argus Talisman" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Templar_Archives , Races::Protoss, UnitTypes::Protoss_Dark_Archon , 1);
upgradeTypeData[Caduceus_Reactor.getID()].set("Caduceus Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Academy , Races::Terran , UnitTypes::Terran_Medic , 1);
upgradeTypeData[Chitinous_Plating.getID()].set("Chitinous Plating" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Ultralisk_Cavern , Races::Zerg , UnitTypes::Zerg_Ultralisk , 1);
upgradeTypeData[Anabolic_Synthesis.getID()].set("Anabolic Synthesis" , 200, 0 , 200, 0 , 2000, 0 , UnitTypes::Zerg_Ultralisk_Cavern , Races::Zerg , UnitTypes::Zerg_Ultralisk , 1);
upgradeTypeData[Charon_Boosters.getID()].set("Charon Boosters" , 100, 0 , 100, 0 , 2000, 0 , UnitTypes::Terran_Machine_Shop , Races::Terran , UnitTypes::Terran_Goliath , 1);
upgradeTypeData[None.getID()].set("None" , 0 , 0 , 0 , 0 , 0 , 0 , UnitTypes::None , Races::None , UnitTypes::None , 0);
upgradeTypeData[Unknown.getID()].set("Unknown" , 0 , 0 , 0 , 0 , 0 , 0 , UnitTypes::None , Races::Unknown, UnitTypes::None , 0);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Firebat);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Ghost);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Marine);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Medic);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_SCV);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Goliath);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Vulture);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Battlecruiser);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Dropship);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Science_Vessel);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Valkyrie);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Wraith);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Broodling);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Defiler);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Drone);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Hydralisk);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Infested_Terran);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Larva);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Lurker);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Ultralisk);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Zergling);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Devourer);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Guardian);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Mutalisk);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Overlord);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Queen);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Scourge);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Archon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Archon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_High_Templar);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Probe);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Reaver);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Carrier);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Observer);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Shuttle);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Firebat);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Ghost);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Marine);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Goliath);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Vulture);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Battlecruiser);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Valkyrie);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Wraith);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Broodling);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Ultralisk);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Zergling);
upgradeTypeData[Zerg_Missile_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Hydralisk);
upgradeTypeData[Zerg_Missile_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Lurker);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Devourer);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Guardian);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Mutalisk);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter_Tribunal);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Archon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Assimilator);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Carrier);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Citadel_of_Adun);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Cybernetics_Core);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Archon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Fleet_Beacon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Forge);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Gateway);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_High_Templar);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Nexus);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Observatory);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Observer);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Photon_Cannon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Probe);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Pylon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Reaver);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Robotics_Facility);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Robotics_Support_Bay);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Scarab);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Shield_Battery);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Shuttle);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Stargate);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Templar_Archives);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeSet.insert(Terran_Infantry_Armor);
upgradeTypeSet.insert(Terran_Vehicle_Plating);
upgradeTypeSet.insert(Terran_Ship_Plating);
upgradeTypeSet.insert(Zerg_Carapace);
upgradeTypeSet.insert(Zerg_Flyer_Carapace);
upgradeTypeSet.insert(Protoss_Ground_Armor);
upgradeTypeSet.insert(Protoss_Air_Armor);
upgradeTypeSet.insert(Terran_Infantry_Weapons);
upgradeTypeSet.insert(Terran_Vehicle_Weapons);
upgradeTypeSet.insert(Terran_Ship_Weapons);
upgradeTypeSet.insert(Zerg_Melee_Attacks);
upgradeTypeSet.insert(Zerg_Missile_Attacks);
upgradeTypeSet.insert(Zerg_Flyer_Attacks);
upgradeTypeSet.insert(Protoss_Ground_Weapons);
upgradeTypeSet.insert(Protoss_Air_Weapons);
upgradeTypeSet.insert(Protoss_Plasma_Shields);
upgradeTypeSet.insert(U_238_Shells);
upgradeTypeSet.insert(Ion_Thrusters);
upgradeTypeSet.insert(Titan_Reactor);
upgradeTypeSet.insert(Ocular_Implants);
upgradeTypeSet.insert(Moebius_Reactor);
upgradeTypeSet.insert(Apollo_Reactor);
upgradeTypeSet.insert(Colossus_Reactor);
upgradeTypeSet.insert(Ventral_Sacs);
upgradeTypeSet.insert(Antennae);
upgradeTypeSet.insert(Pneumatized_Carapace);
upgradeTypeSet.insert(Metabolic_Boost);
upgradeTypeSet.insert(Adrenal_Glands);
upgradeTypeSet.insert(Muscular_Augments);
upgradeTypeSet.insert(Grooved_Spines);
upgradeTypeSet.insert(Gamete_Meiosis);
upgradeTypeSet.insert(Metasynaptic_Node);
upgradeTypeSet.insert(Singularity_Charge);
upgradeTypeSet.insert(Leg_Enhancements);
upgradeTypeSet.insert(Scarab_Damage);
upgradeTypeSet.insert(Reaver_Capacity);
upgradeTypeSet.insert(Gravitic_Drive);
upgradeTypeSet.insert(Sensor_Array);
upgradeTypeSet.insert(Gravitic_Boosters);
upgradeTypeSet.insert(Khaydarin_Amulet);
upgradeTypeSet.insert(Apial_Sensors);
upgradeTypeSet.insert(Gravitic_Thrusters);
upgradeTypeSet.insert(Carrier_Capacity);
upgradeTypeSet.insert(Khaydarin_Core);
upgradeTypeSet.insert(Argus_Jewel);
upgradeTypeSet.insert(Argus_Talisman);
upgradeTypeSet.insert(Caduceus_Reactor);
upgradeTypeSet.insert(Chitinous_Plating);
upgradeTypeSet.insert(Anabolic_Synthesis);
upgradeTypeSet.insert(Charon_Boosters);
upgradeTypeSet.insert(None);
upgradeTypeSet.insert(Unknown);
foreach(UpgradeType i, upgradeTypeSet)
{
std::string name = i.getName();
fixName(&name);
upgradeTypeMap.insert(std::make_pair(name, i));
}
initializingUpgradeType = false;
}
}
UpgradeType::UpgradeType()
{
this->id = UpgradeTypes::None.id;
}
UpgradeType::UpgradeType(int id)
{
this->id = id;
if (!initializingUpgradeType && (id < 0 || id >= 63 || !upgradeTypeData[id].valid) )
this->id = UpgradeTypes::Unknown.id;
}
UpgradeType::UpgradeType(const UpgradeType& other)
{
this->id = other.id;
}
UpgradeType& UpgradeType::operator=(const UpgradeType& other)
{
this->id = other.id;
return *this;
}
bool UpgradeType::operator==(const UpgradeType& other) const
{
return this->id == other.id;
}
bool UpgradeType::operator!=(const UpgradeType& other) const
{
return this->id != other.id;
}
bool UpgradeType::operator<(const UpgradeType& other) const
{
return this->id < other.id;
}
int UpgradeType::getID() const
{
return this->id;
}
std::string UpgradeType::getName() const
{
return upgradeTypeData[this->id].name;
}
Race UpgradeType::getRace() const
{
return upgradeTypeData[this->id].race;
}
int UpgradeType::mineralPrice() const
{
return upgradeTypeData[this->id].mineralPriceBase;
}
int UpgradeType::mineralPriceFactor() const
{
return upgradeTypeData[this->id].mineralPriceFactor;
}
int UpgradeType::gasPrice() const
{
return upgradeTypeData[this->id].gasPriceBase;
}
int UpgradeType::gasPriceFactor() const
{
return upgradeTypeData[this->id].gasPriceFactor;
}
int UpgradeType::upgradeTime() const
{
return upgradeTypeData[this->id].upgradeTimeBase;
}
int UpgradeType::upgradeTimeFactor() const
{
return upgradeTypeData[this->id].upgradeTimeFactor;
}
UnitType UpgradeType::whatUpgrades() const
{
return upgradeTypeData[this->id].whatUpgrades;
}
const std::set<UnitType>& UpgradeType::whatUses() const
{
return upgradeTypeData[this->id].whatUses;
}
int UpgradeType::maxRepeats() const
{
return upgradeTypeData[this->id].maxRepeats;
}
UpgradeType UpgradeTypes::getUpgradeType(std::string name)
{
fixName(&name);
std::map<std::string, UpgradeType>::iterator i = upgradeTypeMap.find(name);
if (i == upgradeTypeMap.end())
return UpgradeTypes::Unknown;
return (*i).second;
}
std::set<UpgradeType>& UpgradeTypes::allUpgradeTypes()
{
return upgradeTypeSet;
}
}
| 72.314286 | 244 | 0.690307 | iali17 |
3e086ad85c6c673c77ac740a029a3b6fabc19c7c | 3,327 | cpp | C++ | ImageVis3D/UI/BrowseData.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | ImageVis3D/UI/BrowseData.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | ImageVis3D/UI/BrowseData.cpp | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : BrowseData.cpp
//! Author : Jens Krueger
//! SCI Institute
//! University of Utah
//! Date : September 2008
//
//! Copyright (C) 2008 SCI Institute
#include "BrowseData.h"
#include <QtCore/QFileInfo>
#include <ui_SettingsDlg.h>
#include "../Tuvok/LuaScripting/LuaScripting.h"
using namespace std;
BrowseData::BrowseData(MasterController& masterController, QDialog* pleaseWaitDialog, QString strDir, QWidget* parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
m_MasterController(masterController),
m_bDataFound(false),
m_strDir(strDir),
m_iSelected(0)
{
setupUi(this);
m_bDataFound = FillTable(pleaseWaitDialog);
}
BrowseData::~BrowseData() {
this->m_dirInfo.clear();
}
void BrowseData::showEvent ( QShowEvent * ) {
}
void BrowseData::accept() {
// find out which dataset is selected
for (size_t i = 0;i < m_vRadioButtons.size();i++) {
if (m_vRadioButtons[i]->isChecked()) {
m_iSelected = i;
break;
}
}
QDialog::accept();
}
void BrowseData::SetBrightness(int iScale) {
for (size_t i = 0;i < m_vRadioButtons.size();i++)
m_vRadioButtons[i]->SetBrightness(float(iScale));
}
bool BrowseData::FillTable(QDialog* pleaseWaitDialog)
{
shared_ptr<LuaScripting> ss(m_MasterController.LuaScript());
m_dirInfo = ss->cexecRet<vector<shared_ptr<FileStackInfo>>>(
"tuvok.io.scanDirectory", m_strDir.toStdWString());
m_vRadioButtons.clear();
for (size_t iStackID = 0;iStackID < m_dirInfo.size();iStackID++) {
QDataRadioButton *pStackElement;
pStackElement = new QDataRadioButton(m_dirInfo[iStackID],frame);
pStackElement->setMinimumSize(QSize(0, 80));
pStackElement->setChecked(iStackID==0);
pStackElement->setIconSize(QSize(80, 80));
verticalLayout_DICOM->addWidget(pStackElement);
m_vRadioButtons.push_back(pStackElement);
}
if (pleaseWaitDialog != NULL) pleaseWaitDialog->close();
return !m_dirInfo.empty();
}
| 31.386792 | 144 | 0.701232 | JensDerKrueger |
3e08930efc20de47c9396c39506d8dccc4004ebc | 20,741 | cpp | C++ | net/tapi/skywalker/hidtsp/phonemgr/phonemgr.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/tapi/skywalker/hidtsp/phonemgr/phonemgr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/tapi/skywalker/hidtsp/phonemgr/phonemgr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
/* Copyright (c) 1999 Microsoft Corporation */
#include "phonemgr.h"
#include <stdlib.h>
#include <stdio.h>
#include <wxdebug.h>
#ifdef _DBG
#define DEBUG(_x_) OutputDebugString(_x_)
#else
#define DEBUG(_x_)
#endif
ITRequest * g_pITRequest = NULL;
HRESULT InitAssistedTelephony(void)
{
HRESULT hr;
//
// Initialize COM.
//
printf("Initializing COM...\n");
hr = CoInitializeEx(
NULL,
COINIT_MULTITHREADED
);
if ( FAILED(hr) )
{
printf("CoInitialize failed - 0x%08x\n", hr);
return hr;
}
//
// Cocreate the assisted telephony object.
//
printf("Creating RequestMakeCall object...\n");
hr = CoCreateInstance(
CLSID_RequestMakeCall,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITRequest,
(void **) & g_pITRequest
);
if ( FAILED(hr) )
{
printf("CoCreateInstance failed - 0x%08x\n", hr);
return hr;
}
return S_OK;
}
HRESULT MakeAssistedTelephonyCall(WCHAR * wszDestAddress)
{
HRESULT hr;
BSTR bstrDestAddress = NULL;
BSTR bstrAppName = NULL;
BSTR bstrCalledParty = NULL;
BSTR bstrComment = NULL;
bstrDestAddress = SysAllocString(
wszDestAddress
);
if ( bstrDestAddress == NULL )
{
printf("SysAllocString failed");
return E_OUTOFMEMORY;
}
//
// Make a call.
//
printf("Calling ITRequest::MakeCall...\n");
hr = g_pITRequest->MakeCall(
bstrDestAddress,
bstrAppName,
bstrCalledParty,
bstrComment
);
SysFreeString(
bstrDestAddress
);
if ( FAILED(hr) )
{
printf("ITRequest::MakeCall failed - 0x%08x\n", hr);
return hr;
}
return S_OK;
}
int
WINAPI
WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
MSG msg;
HWND hwnd, hwndEdit;
ghInst = hInstance;
DialogBox(
ghInst,
MAKEINTRESOURCE(IDD_MAINDLG),
NULL,
MainWndProc
);
return 0;
}
INT_PTR
CALLBACK
MainWndProc(
HWND hDlg,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
LPCTSTR lszAppName = _T("Generate DialTone");
DWORD dwNumDevs, i;
LONG lResult;
PHONEINITIALIZEEXPARAMS initExParams;
PMYPHONE pNextPhone;
PWCHAR szAddressToCall;
ghDlg = hDlg;
switch (uMsg)
{
case WM_INITDIALOG:
initExParams.dwTotalSize = sizeof (PHONEINITIALIZEEXPARAMS);
initExParams.dwOptions = (DWORD) PHONEINITIALIZEEXOPTION_USEHIDDENWINDOW;
lResult = phoneInitializeEx(
(LPHPHONEAPP) &ghPhoneApp,
(HINSTANCE) ghInst,
(PHONECALLBACK) tapiCallback,
lszAppName,
(LPDWORD) &dwNumDevs,
(LPDWORD) &gdwAPIVersion,
(LPPHONEINITIALIZEEXPARAMS) &initExParams
);
if (lResult == 0)
{
gdwNumPhoneDevs = dwNumDevs;
}
gpPhone = (PMYPHONE) LocalAlloc(LPTR,gdwNumPhoneDevs * sizeof(MYPHONE));
g_wszMsg = (LPWSTR) LocalAlloc(LPTR, sizeof(WCHAR) * 100 );
g_wszDest = (LPWSTR) LocalAlloc(LPTR, sizeof(WCHAR) * 100 );
// Opening all the phones
for(i = 0, pNextPhone = gpPhone; i < gdwNumPhoneDevs; i++, pNextPhone++)
{
CreatePhone(pNextPhone, i);
}
SetStatusMessage(TEXT("Waiting for input from Phones"));
g_szDialStr = (LPWSTR) LocalAlloc(LPTR, 20 * sizeof(WCHAR));
lstrcpy(g_szDialStr, TEXT("Dial Number: "));
break;
case WM_COMMAND:
if ( LOWORD(wParam) == IDCANCEL )
{
//
// The close box or Exit button was pressed.
//
SetStatusMessage(TEXT("End Application"));
if(ghPhoneApp)
{
phoneShutdown(ghPhoneApp);
}
EndDialog( hDlg, 0 );
LocalFree(g_szDialStr);
LocalFree(g_wszMsg);
LocalFree(g_wszDest);
for( i=0; i<gdwNumPhoneDevs; i++ )
{
FreePhone(&gpPhone[i]);
}
LocalFree(gpPhone);
}
else if ( LOWORD(wParam) == IDC_MAKECALL )
{
//
// The Make Call button was pressed.
//
//
// Stop dialtone.
// this only works for one phone.
// Should be fine as we don't have
// the window visible unless you have the phone off hook.
//
gpPhone[0].pTonePlayer->StopDialtone();
//
// Dial the dest address in the edit box.
//
const int ciMaxPhoneNumberSize = 400;
WCHAR wszPhoneNumber[ciMaxPhoneNumberSize];
UINT uiResult;
uiResult = GetDlgItemText(
ghDlg, // handle to dialog box
IDC_DESTADDRESS, // identifier of control
wszPhoneNumber, // pointer to buffer for text (unicode)
ciMaxPhoneNumberSize // maximum size of string (in our buffer)
);
if ( uiResult == 0 )
{
DoMessage(L"Could not get dialog item text; not making call");
}
else
{
MakeAssistedTelephonyCall(wszPhoneNumber);
}
}
break;
default:
break;
}
return 0;
}
VOID
CALLBACK
tapiCallback(
DWORD hDevice,
DWORD dwMsg,
ULONG_PTR CallbackInstance,
ULONG_PTR Param1,
ULONG_PTR Param2,
ULONG_PTR Param3
)
{
PMYPHONE pPhone;
DWORD i;
BOOL bDialtone = FALSE;
if (hDevice != NULL)
{
pPhone = GetPhone((HPHONE) hDevice);
if (pPhone == NULL)
{
DEBUG(L"tapiCallback - phone not found\n");
return;
}
}
switch (dwMsg)
{
case PHONE_STATE:
DEBUG(L"PHONE_STATE\n");
if (pPhone != NULL)
{
EnterCriticalSection(&pPhone->csdial);
if ( Param1 == PHONESTATE_HANDSETHOOKSWITCH )
{
if ( Param2 != PHONEHOOKSWITCHMODE_ONHOOK ) // if off hook
{
if ( FAILED(pPhone->pTonePlayer->StartDialtone()) )
{
DoMessage(L"StartDialTone Failed");
}
// ZoltanS: show the window now
ShowWindow(ghDlg, SW_SHOWNORMAL);
pPhone->dwHandsetMode = PHONEHOOKSWITCHMODE_MICSPEAKER;
lstrcpy(pPhone->wszDialStr,TEXT(""));
lstrcpy(g_wszMsg,TEXT("Generating Dialtone for phones: "));
for( i=0 ; i < gdwNumPhoneDevs; i++)
{
if ( gpPhone[i].pTonePlayer->IsInUse() )
{
wsprintf(g_wszDest,TEXT("%d"),i);
lstrcat(g_wszMsg,g_wszDest);
}
}
SetStatusMessage(g_wszMsg);
}
else // on hook
{
pPhone->dwHandsetMode = PHONEHOOKSWITCHMODE_ONHOOK;
lstrcpy(pPhone->wszDialStr,TEXT(""));
if ( pPhone->pTonePlayer->IsInUse() )
{
pPhone->pTonePlayer->StopDialtone();
}
// ZoltanS: hide the window now
ShowWindow(ghDlg, SW_HIDE);
bDialtone = FALSE;
lstrcpy(g_wszMsg,TEXT("Generating Dialtone for phones: "));
for( i = 0 ; i < gdwNumPhoneDevs; i++ )
{
if ( gpPhone[i].pTonePlayer->DialtonePlaying() )
{
wsprintf(g_wszDest,TEXT("%d"),i);
lstrcat(g_wszMsg,g_wszDest);
bDialtone = TRUE;
}
}
if(!bDialtone)
{
SetStatusMessage(TEXT("Waiting for input from Phones"));
}
else
{
SetStatusMessage(g_wszMsg);
}
}
}
LeaveCriticalSection(&pPhone->csdial);
}
break;
case PHONE_BUTTON:
DEBUG(L"PHONE_BUTTON\n");
if (pPhone != NULL)
{
EnterCriticalSection(&pPhone->csdial);
if ( Param2 == PHONEBUTTONMODE_KEYPAD )
{
if (pPhone->dwHandsetMode != PHONEHOOKSWITCHMODE_ONHOOK)
{
if ( Param3 == PHONEBUTTONSTATE_DOWN )
{
if ( pPhone->pTonePlayer->IsInUse() )
{
if ( ( (int)Param1 >= 0 ) && ( (int)Param1 <= 9 ) )
{
//
// We have a dialed digit. Append it to the phone
// number we have so far.
//
wsprintf(g_wszDest, TEXT("%d"), Param1);
lstrcat(pPhone->wszDialStr, g_wszDest);
//
// Append the phone number so far to a standard prefix
// ("Phone number: ") and update the UI.
//
lstrcpy(g_wszMsg, g_szDialStr);
lstrcat(g_wszMsg,pPhone->wszDialStr);
SetStatusMessage(g_wszMsg);
//
// Generate a DTMF tone for this digit.
//
pPhone->pTonePlayer->GenerateDTMF( (long)Param1 );
}
else if ( Param1 == 10 )
{
//
// Generate a DTMF tone for "*". This will not count
// as part of the dialed number.
//
pPhone->pTonePlayer->GenerateDTMF( (long)Param1 );
}
else if ( Param1 == 11 )
{
//
// Generate a DTMF tone for "#". This will not count
// as part of the dialed number but it will tell us
// to make the call immediately.
//
pPhone->pTonePlayer->GenerateDTMF( (long)Param1 );
//
// Make the call.
//
if ( S_OK == MakeAssistedTelephonyCall(pPhone->wszDialStr) )
{
SetStatusMessage(L"Call created");
}
else
{
SetStatusMessage(L"Failed to create the call");
}
}
} // if in use
} // if button down
} // if off hook
} // if keypad
LeaveCriticalSection(&pPhone->csdial);
}
break; // case phone_button
case PHONE_CLOSE:
DEBUG(L"PHONE_CLOSE\n");
if (pPhone != NULL)
{
EnterCriticalSection(&pPhone->csdial);
phoneClose(pPhone->hPhone);
LeaveCriticalSection(&pPhone->csdial);
}
break;
case PHONE_REMOVE:
DEBUG(L"PHONE_REMOVE\n");
pPhone = GetPhoneByID( (DWORD)Param1);
if (pPhone != NULL)
{
FreePhone(pPhone);
RemovePhone(pPhone);
}
break;
case PHONE_CREATE:
DEBUG(L"PHONE_CREATE\n");
pPhone = AddPhone();
CreatePhone(pPhone, (DWORD)Param1);
break;
default:
break;
}
}
//////////////////////////////////////////////////////////////////
// SetStatusMessage
//////////////////////////////////////////////////////////////////
void
SetStatusMessage(
LPWSTR pszMessage
)
{
SetDlgItemText(
ghDlg,
IDC_STATUS,
pszMessage
);
}
//////////////////////////////////////////////////////////////////
// CreatePhone
//////////////////////////////////////////////////////////////////
void
CreatePhone(
PMYPHONE pPhone,
DWORD dwDevID
)
{
LRESULT lResult;
pPhone->hPhoneApp = ghPhoneApp;
InitializeCriticalSection(&pPhone->csdial);
// won't detect overrun if dialing more than 100 digits
pPhone->wszDialStr = (LPWSTR) LocalAlloc(LPTR, 100 * sizeof(WCHAR));
pPhone->dwHandsetMode = PHONEHOOKSWITCHMODE_ONHOOK;
lResult = phoneOpen(
ghPhoneApp,
dwDevID,
&pPhone->hPhone,
gdwAPIVersion,
0,
(DWORD_PTR) NULL,
PHONEPRIVILEGE_OWNER
);
//
// Save info about this phone that we can display later
//
pPhone->dwDevID = dwDevID;
pPhone->dwAPIVersion = gdwAPIVersion;
pPhone->dwPrivilege = PHONEPRIVILEGE_OWNER;
DWORD dwBigBuffSize = sizeof(VARSTRING) +
sizeof(DWORD) * 5;
LPVOID pBuffer = LocalAlloc(LPTR,dwBigBuffSize);
LPVARSTRING lpDeviceID = (LPVARSTRING) pBuffer;
lpDeviceID->dwTotalSize = dwBigBuffSize;
LPWSTR lpszDeviceClass;
lpszDeviceClass = (LPWSTR) LocalAlloc(LPTR, sizeof(WCHAR) * 20);
lstrcpy(lpszDeviceClass, TEXT("wave/in"));
lResult = phoneGetID(
pPhone->hPhone,
lpDeviceID,
lpszDeviceClass
);
if(lResult != 0)
{
pPhone->lCaptureID = WAVE_MAPPER;
}
else
{
CopyMemory(
&pPhone->lCaptureID,
(LPBYTE) lpDeviceID + lpDeviceID->dwStringOffset,
lpDeviceID->dwStringSize
);
}
lstrcpy(lpszDeviceClass, TEXT("wave/out"));
lResult = phoneGetID(
pPhone->hPhone,
lpDeviceID,
lpszDeviceClass
);
if(lResult != 0)
{
pPhone->lRenderID = WAVE_MAPPER;
}
else
{
CopyMemory(
&pPhone->lRenderID,
(LPBYTE) lpDeviceID + lpDeviceID->dwStringOffset,
lpDeviceID->dwStringSize
);
}
LocalFree(lpszDeviceClass);
LocalFree(pBuffer);
lResult = phoneSetStatusMessages(
pPhone->hPhone,
PHONESTATE_HANDSETHOOKSWITCH,
PHONEBUTTONMODE_FEATURE | PHONEBUTTONMODE_KEYPAD,
PHONEBUTTONSTATE_UP | PHONEBUTTONSTATE_DOWN
);
pPhone->pTonePlayer = new CTonePlayer;
if ( (pPhone->pTonePlayer == NULL) ||
FAILED(pPhone->pTonePlayer->Initialize()) )
{
DoMessage(L"Tone Player Initialization Failed");
}
else if ( FAILED(pPhone->pTonePlayer->OpenWaveDevice( pPhone->lRenderID )) )
{
DoMessage(L"OpenWaveDevice Failed");
}
if ( FAILED( InitAssistedTelephony() ) )
{
DoMessage(L"InitAssistedTelephony Failed");
}
}
//////////////////////////////////////////////////////////////////
// FreePhone
//////////////////////////////////////////////////////////////////
void
FreePhone(
PMYPHONE pPhone
)
{
EnterCriticalSection(&pPhone->csdial);
if ( pPhone->pTonePlayer->IsInUse() )
{
pPhone->pTonePlayer->StopDialtone();
pPhone->pTonePlayer->CloseWaveDevice();
}
LocalFree(pPhone->wszDialStr);
LeaveCriticalSection(&pPhone->csdial);
DeleteCriticalSection(&pPhone->csdial);
}
///////////////////////////////////////////////////////////////////
// GetPhone
///////////////////////////////////////////////////////////////////
PMYPHONE
GetPhone (HPHONE hPhone )
{
DWORD i;
for(i = 0; i < gdwNumPhoneDevs; i++)
{
if(gpPhone[i].hPhone == hPhone)
{
return &gpPhone[i];
}
}
return (PMYPHONE) NULL;
}
///////////////////////////////////////////////////////////////////
// GetPhoneByID
///////////////////////////////////////////////////////////////////
PMYPHONE
GetPhoneByID (DWORD dwDevID )
{
DWORD i;
for(i = 0; i < gdwNumPhoneDevs; i++)
{
if(gpPhone[i].dwDevID == dwDevID)
{
return &gpPhone[i];
}
}
return (PMYPHONE) NULL;
}
///////////////////////////////////////////////////////////////////
// RemovePhone
///////////////////////////////////////////////////////////////////
void
RemovePhone (PMYPHONE pPhone)
{
DWORD i,j;
PMYPHONE pNewPhones;
pNewPhones = (PMYPHONE) LocalAlloc(LPTR,(gdwNumPhoneDevs-1) * sizeof(MYPHONE));
for(i = 0, j = 0; i < gdwNumPhoneDevs; i++)
{
if(&gpPhone[i] != pPhone)
{
CopyMemory( &pNewPhones[j], &gpPhone[i], sizeof(MYPHONE));
j++;
}
}
LocalFree(gpPhone);
gpPhone = pNewPhones;
gdwNumPhoneDevs--;
}
///////////////////////////////////////////////////////////////////
// AddPhone
///////////////////////////////////////////////////////////////////
PMYPHONE
AddPhone ()
{
PMYPHONE pNewPhones;
pNewPhones = (PMYPHONE) LocalAlloc(LPTR,(gdwNumPhoneDevs+1) * sizeof(MYPHONE));
CopyMemory( pNewPhones, gpPhone, gdwNumPhoneDevs * sizeof(MYPHONE));
LocalFree(gpPhone);
gpPhone = pNewPhones;
gdwNumPhoneDevs++;
return &gpPhone[gdwNumPhoneDevs-1];
}
///////////////////////////////////////////////////////////////////
// DoMessage
///////////////////////////////////////////////////////////////////
void
DoMessage(
LPWSTR pszMessage
)
{
MessageBox(
ghDlg,
pszMessage,
gszTapi30,
MB_OK
);
}
| 27.112418 | 103 | 0.405091 | npocmaka |