blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
dd164aab9ea1cb99d6d68af0972393d5d8b84f4c
97700a9b339dcd15e4f17b4ce57db19a7ff25082
/conn/FakeTcp.cpp
3622e8a9d70fc600470b5850a2807dfd5bb1e57b
[]
no_license
iceonsun/rsock
468ad4efa058fc4cd2f26de3e91e6a16d5a982b8
9f2f7248df11952a73f1ff6529083b56d76960a9
refs/heads/master
2022-09-11T09:44:13.881848
2020-11-09T10:44:59
2020-11-09T10:44:59
123,566,088
262
41
null
null
null
null
UTF-8
C++
false
false
2,546
cpp
// // Created by System Administrator on 1/16/18. // #include <cassert> #include <plog/Log.h> #include "FakeTcp.h" #include "RConn.h" #include "../util/rsutil.h" #include "../src/util/KeyGenerator.h" #include "../src/util/TcpUtil.h" // If send 1 bytes for a specific interval to check if alive. This will severely slow down speed FakeTcp::FakeTcp(uv_tcp_t *tcp, IntKeyType key, const TcpInfo &info) : INetConn(key), mInfo(info) { assert(tcp); mTcp = (uv_stream_t *) tcp; TcpInfo anInfo; GetTcpInfo(anInfo, reinterpret_cast<uv_tcp_t *>(mTcp)); assert(anInfo.src == info.src && anInfo.dst == info.dst && anInfo.sp == info.sp && anInfo.dp == info.dp); } int FakeTcp::Init() { INetConn::Init(); assert(mTcp); TcpUtil::SetISN(this, mInfo); TcpUtil::SetAckISN(this, mInfo); mTcp->data = this; return uv_read_start(mTcp, alloc_buf, read_cb); } int FakeTcp::Close() { INetConn::Close(); if (mTcp) { uv_close(reinterpret_cast<uv_handle_t *>(mTcp), close_cb); mTcp = nullptr; } return 0; } int FakeTcp::Output(ssize_t nread, const rbuf_t &rbuf) { int n = INetConn::Output(nread, rbuf); if (n >= 0) { // todo: when add aes or encrpytion, here need to change mInfo.UpdateSeq((int) nread + mInfo.seq + RConn::HEAD_SIZE); } return n; } int FakeTcp::OnRecv(ssize_t nread, const rbuf_t &buf) { TcpInfo *info = static_cast<TcpInfo *>(buf.data); assert(info); EncHead *hd = info->head; assert(hd); int n = INetConn::OnRecv(nread, buf); if (n >= 0) { if (mInfo.ack < info->seq) { mInfo.UpdateAck(info->seq); } } return n; } void FakeTcp::read_cb(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { // this may never receive any packets. if (nread < 0 && nread != UV_ECANCELED) { FakeTcp *conn = static_cast<FakeTcp *>(stream->data); LOGE << "conn " << conn->ToStr() << " err: " << uv_strerror(nread); conn->onTcpError(conn, nread); } free(buf->base); } void FakeTcp::onTcpError(FakeTcp *conn, int err) { NotifyErr(ERR_FIN_RST); } void FakeTcp::SetISN(uint32_t isn) { mInfo.UpdateSeq(isn); } void FakeTcp::SetAckISN(uint32_t isn) { mInfo.UpdateAck(isn); } // The server will send keepalive now, so the alive state is determined by keepalive and tcp rst/fin if received any //bool FakeTcp::Alive() { // return mAlive; //} ConnInfo *FakeTcp::GetInfo() { return &mInfo; } bool FakeTcp::IsUdp() { return false; }
[ "nmq@example.com" ]
nmq@example.com
f39b9de409a45e3b0fe18d7408de363cae87100a
d9dedff83f5ce38294450b3be1ba42dd094aa842
/lib/eulerlib.cpp
bd65374f698c696c740958e94051f402f48f7e45
[]
no_license
conditionZebra/Algorithms
47466b5ed5895f0d0cf265c323b91bfd98c113f9
006bb8198586a2a15119b992870b74f9c815f3f6
refs/heads/master
2021-12-31T03:37:41.755868
2021-12-27T12:05:36
2021-12-27T12:05:36
80,654,944
0
0
null
null
null
null
UTF-8
C++
false
false
2,944
cpp
#include "eulerlib.h" #include <string> #include <sstream> // std::istringstream #include <fstream> #include <iostream> namespace eulerlib { std::shared_ptr<stringVector> getAllStringFromCSV(const char* fileName) { std::shared_ptr<stringVector> returnList(new stringVector); std::ifstream data(fileName); std::string line; while(std::getline(data,line)) { std::stringstream lineStream(line); std::string cell; while(std::getline(lineStream,cell,',')) { returnList->push_back(cell); } } return returnList; } int getFactorial(int num) { if(num == 1 || num == 0) return 1; else return num * getFactorial(num - 1); } bool isPrime(long num) { if(num <= 1) return false; for(long i = 2; i <= sqrt(num); i++) if(num%i == 0) return false; // std::cout << num << std::endl; return true; } bool isPalindrome(long num) { int length = numberOfDigits(num); if(length == 1) return true; int upperDigit = 0; int lowerDigit = 0; if(length % 2) { lowerDigit = length / 2; upperDigit = lowerDigit + 2; } else { upperDigit = length / 2 + 1; lowerDigit = length / 2; } while(lowerDigit > 0) { if(getDigitFromPosition(num, upperDigit) != getDigitFromPosition(num, lowerDigit)) return false; lowerDigit--; upperDigit++; } return true; } int getDigitFromPosition(long long int num, int pos) { long long int tenPower = 1; for(int i = 0; i < pos; i++) tenPower *= 10; num /= tenPower; return num % 10; } int numberOfDigits(long num) { int result = 0; while(num != 0) { num /= 10; result++; } return result; } long long int stringToInt( const std::string& string) { long long int numb; std::istringstream(string) >> numb; return numb; } divisorMap* getDivisors(long long int num) { divisorMap* returnMap = new divisorMap; if(isPrime(num)) { (*returnMap)[num] = 1; return returnMap; } int counter; for(long long int i = 2; i <= sqrt(num) + 1; i++) { if(num%i == 0) { counter = 0; while(num%i == 0) { counter++; num = num / i; } (*returnMap)[i] = counter; if(isPrime(num)) { (*returnMap)[num] = 1; return returnMap; } } } return returnMap; } allDivisorList* getAllDivisors(int num) { allDivisorList* returnList = new allDivisorList; for(int i = 1; i <= num /2; i++) { if(num % i == 0) returnList->push_back(i); } return returnList; } int getNumOfDivisors(int num) { divisorMap* divisors; int numOfDivisors = 1; divisors = getDivisors(num); for (std::map<long long int,int>::iterator it=(*divisors).begin(); it!=(*divisors).end(); ++it) { numOfDivisors = numOfDivisors * (it->second + 1); } delete divisors; return numOfDivisors; } }
[ "zltn.csaszar@gmail.com" ]
zltn.csaszar@gmail.com
bc6e1e1cbff328da17b200c150bfdd5cd22004fb
61314f889041b72d98e233a28e4e79c06167d1b4
/target/qnx6/usr/include/c++/4.4.2/tr1/memory
73a4e26c3d4484eefb7a225479250fc2536766db
[]
no_license
CyberSys/qnx650
37867847dacf9331926736e97009bc0af83850bd
a10a0e62384d0a6a24cc3879dee3b7bacf6d4601
refs/heads/master
2021-05-27T03:46:05.775523
2014-05-02T00:15:16
2014-05-02T00:15:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,332
// <tr1/memory> -*- C++ -*- // Copyright (C) 2005, 2006, 2007, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** * @file tr1/memory * This is a TR1 C++ Library header. */ #ifndef _GLIBCXX_TR1_MEMORY #define _GLIBCXX_TR1_MEMORY 1 #pragma GCC system_header #if defined(_GLIBCXX_INCLUDE_AS_CXX0X) # error TR1 header cannot be included from C++0x header #endif #include <memory> #include <exception> // std::exception #include <typeinfo> // std::type_info in get_deleter #include <bits/stl_algobase.h> // std::swap #include <iosfwd> // std::basic_ostream #include <ext/atomicity.h> #include <ext/concurrence.h> #include <bits/functexcept.h> #include <bits/stl_function.h> // std::less #include <debug/debug.h> #include <tr1/type_traits> #if defined(_GLIBCXX_INCLUDE_AS_TR1) # include <tr1_impl/boost_sp_counted_base.h> # include <tr1/shared_ptr.h> #else # define _GLIBCXX_INCLUDE_AS_TR1 # define _GLIBCXX_BEGIN_NAMESPACE_TR1 namespace tr1 { # define _GLIBCXX_END_NAMESPACE_TR1 } # define _GLIBCXX_TR1 tr1:: # include <tr1_impl/boost_sp_counted_base.h> # include <tr1/shared_ptr.h> # undef _GLIBCXX_TR1 # undef _GLIBCXX_END_NAMESPACE_TR1 # undef _GLIBCXX_BEGIN_NAMESPACE_TR1 # undef _GLIBCXX_INCLUDE_AS_TR1 #endif #endif // _GLIBCXX_TR1_MEMORY
[ "acklinr@us.panasonic.com" ]
acklinr@us.panasonic.com
645641d5aeef89d963a451ecb0c485f4a1500d1c
d06cd58541ca76818977ff9dc2375a2c66d21aab
/plugins/midiplayer/midiplayerplugin.cpp
2cd95462c95c4a1ecc790c9c6e9f80f8b4f198e6
[]
no_license
c-base/c_nancy-plugins
bd14d5fa72dbbdba41357a11055b9f3821faef74
146f195f2c15490f9b53aac203e7eb2a9a03fffb
refs/heads/master
2021-05-07T18:50:35.263465
2017-12-17T04:55:12
2017-12-17T04:55:12
108,839,120
0
0
null
null
null
null
UTF-8
C++
false
false
3,235
cpp
#include "midiplayerplugin.h" bool UccncPlugin::create() { return UccncPlugin::_create<MidiPlayer>(); } MidiPlayer::MidiPlayer() : UccncPlugin(AUTHOR, PLUGIN_NAME, PLUGIN_VERSION) { trace(); } MidiPlayer::~MidiPlayer() { trace(); } void MidiPlayer::onFirstCycle() { trace(); auto onNoteOn = [](int32_t track, int32_t tick, int32_t channel, int32_t note, int32_t velocity) -> void { dbg("NoteOn: [%i] %d\n", channel, note); auto midiNoteToFrequency = [](int note) -> double { return 8.17575 * pow(2.0, note / 12.0); }; double f = midiNoteToFrequency(note); double feedRate = (f / 80.0) * 60.0; char pCode[256]; sprintf_s(pCode, sizeof(pCode), "G1 X900 F%.3f", feedRate); dbg("%s\n", pCode); MidiPlayer::_instance()->UC.code(pCode); }; auto onNoteOff = [](int32_t track, int32_t tick, int32_t channel, int32_t note) -> void { dbg("NoteOff: [%i] %d\n", channel, note); }; auto onMetaTrackNameEvent = [](int32_t track, int32_t tick, char *pText) -> void { dbg("onMetaTrackNameEvent: %s\n", pText); }; auto onMetaTextEvent = [](int32_t track, int32_t tick, char* pText) -> void { dbg("onMetaTextEvent: %s\n", pText); }; auto onMetaCopyrightEvent = [](int32_t track, int32_t tick, char* pText) -> void { dbg("onMetaTextEvent: %s\n", pText); }; auto onEndOfSequenceEvent = [](int32_t track, int32_t tick) -> void { dbg("onEndOfSequenceEvent: [%i]\n", track); }; MidiPlayerCallbacks_t callbacks = {0}; callbacks.pOnNoteOnCb = onNoteOn; callbacks.pOnNoteOffCb = onNoteOff; callbacks.pOnMetaTextEventCb = onMetaTextEvent; callbacks.pOnMetaCopyrightCb = onMetaCopyrightEvent; callbacks.pOnMetaTrackNameCb = onMetaTrackNameEvent; callbacks.pOnMetaEndSequenceCb = onEndOfSequenceEvent; midiplayer_init(&mpl_, callbacks); } void MidiPlayer::onTick() { // trace(); midiPlayerTick(&mpl_); } void MidiPlayer::onShutdown() { trace(); } void MidiPlayer::buttonPressEvent(UccncButton button, bool onScreen) { trace(); if (onScreen) { if (button == UccncButton::Cyclestart) { // TODO: implement } } } void MidiPlayer::textFieldClickEvent(UccncField label, bool isMainScreen) { const char* pLabel; switch (label) { case UccncField::Mdi: pLabel = "Mdi"; break; case UccncField::Setnextlinefield: pLabel = "Setnextlinefield"; break; default: pLabel = "Unknown"; } dbg("textFieldClickEvent; label=%s, isMainScreen=%d\n", pLabel, isMainScreen); } void MidiPlayer::textFieldTextTypedEvent(UccncField label, bool isMainScreen, const char* pText) { trace(); string text = pText; if (isMainScreen) { if (label == UccncField::Mdi) { if (text == "play") { char pExePath[256]; GetModuleFileName(NULL, pExePath, sizeof(pExePath)); string exePath = pExePath; string midiPath = exePath.substr(0, exePath.find_last_of("\\") + 1); midiPath += "Plugins\\cpp\\"; midiPath += "midi.mid"; if (!playMidiFile(&mpl_, midiPath.c_str())) dbg("Failed opening midi file!\n"); else dbg("Midi file opened successfully!\n"); } } } }
[ "coon@c-base.org" ]
coon@c-base.org
ffb5fd37f00a3b801a8a3708daf601342095cf39
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/chrome/browser/ui/webui/options/font_settings_handler.cc
245d844f4941b8b6b735bf2bee685b38c17f7825
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
9,519
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/font_settings_handler.h" #include <string> #include "base/basictypes.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/i18n/rtl.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/options/font_settings_utils.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "content/public/browser/font_list_async.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/web_ui.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_WIN) #include "ui/gfx/font.h" #include "ui/gfx/platform_font_win.h" #endif namespace { // Returns the localized name of a font so that settings can find it within the // list of system fonts. On Windows, the list of system fonts has names only // for the system locale, but the pref value may be in the English name. std::string MaybeGetLocalizedFontName(const std::string& font_name) { #if defined(OS_WIN) gfx::Font font(font_name, 12); // dummy font size return static_cast<gfx::PlatformFontWin*>(font.platform_font())-> GetLocalizedFontName(); #else return font_name; #endif } } // namespace namespace options { FontSettingsHandler::FontSettingsHandler() { } FontSettingsHandler::~FontSettingsHandler() { } void FontSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); static OptionsStringResource resources[] = { { "fontSettingsStandard", IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_STANDARD_LABEL }, { "fontSettingsSerif", IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SERIF_LABEL }, { "fontSettingsSansSerif", IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SANS_SERIF_LABEL }, { "fontSettingsFixedWidth", IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_FIXED_WIDTH_LABEL }, { "fontSettingsMinimumSize", IDS_FONT_LANGUAGE_SETTING_MINIMUM_FONT_SIZE_TITLE }, { "fontSettingsEncoding", IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_ENCODING_TITLE }, { "fontSettingsSizeTiny", IDS_FONT_LANGUAGE_SETTING_FONT_SIZE_TINY }, { "fontSettingsSizeHuge", IDS_FONT_LANGUAGE_SETTING_FONT_SIZE_HUGE }, { "fontSettingsLoremIpsum", IDS_FONT_LANGUAGE_SETTING_LOREM_IPSUM }, }; RegisterStrings(localized_strings, resources, arraysize(resources)); RegisterTitle(localized_strings, "fontSettingsPage", IDS_FONT_LANGUAGE_SETTING_FONT_TAB_TITLE); localized_strings->SetString("fontSettingsPlaceholder", l10n_util::GetStringUTF16( IDS_FONT_LANGUAGE_SETTING_PLACEHOLDER)); } void FontSettingsHandler::InitializePage() { DCHECK(web_ui()); SetUpStandardFontSample(); SetUpSerifFontSample(); SetUpSansSerifFontSample(); SetUpFixedFontSample(); SetUpMinimumFontSample(); } void FontSettingsHandler::RegisterMessages() { // Perform validation for saved fonts. PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); FontSettingsUtilities::ValidateSavedFonts(pref_service); // Register for preferences that we need to observe manually. font_encoding_.Init(prefs::kDefaultCharset, pref_service); standard_font_.Init(prefs::kWebKitStandardFontFamily, pref_service, base::Bind(&FontSettingsHandler::SetUpStandardFontSample, base::Unretained(this))); serif_font_.Init(prefs::kWebKitSerifFontFamily, pref_service, base::Bind(&FontSettingsHandler::SetUpSerifFontSample, base::Unretained(this))); sans_serif_font_.Init( prefs::kWebKitSansSerifFontFamily, pref_service, base::Bind(&FontSettingsHandler::SetUpSansSerifFontSample, base::Unretained(this))); base::Closure callback = base::Bind( &FontSettingsHandler::SetUpFixedFontSample, base::Unretained(this)); fixed_font_.Init(prefs::kWebKitFixedFontFamily, pref_service, callback); default_fixed_font_size_.Init(prefs::kWebKitDefaultFixedFontSize, pref_service, callback); default_font_size_.Init( prefs::kWebKitDefaultFontSize, pref_service, base::Bind(&FontSettingsHandler::OnWebKitDefaultFontSizeChanged, base::Unretained(this))); minimum_font_size_.Init( prefs::kWebKitMinimumFontSize, pref_service, base::Bind(&FontSettingsHandler::SetUpMinimumFontSample, base::Unretained(this))); web_ui()->RegisterMessageCallback("fetchFontsData", base::Bind(&FontSettingsHandler::HandleFetchFontsData, base::Unretained(this))); } void FontSettingsHandler::HandleFetchFontsData(const ListValue* args) { content::GetFontListAsync( base::Bind(&FontSettingsHandler::FontsListHasLoaded, base::Unretained(this))); } void FontSettingsHandler::FontsListHasLoaded( scoped_ptr<base::ListValue> list) { // Selects the directionality for the fonts in the given list. for (size_t i = 0; i < list->GetSize(); i++) { ListValue* font; bool has_font = list->GetList(i, &font); DCHECK(has_font); string16 value; bool has_value = font->GetString(1, &value); DCHECK(has_value); bool has_rtl_chars = base::i18n::StringContainsStrongRTLChars(value); font->Append(new base::StringValue(has_rtl_chars ? "rtl" : "ltr")); } ListValue encoding_list; const std::vector<CharacterEncoding::EncodingInfo>* encodings; PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); encodings = CharacterEncoding::GetCurrentDisplayEncodings( g_browser_process->GetApplicationLocale(), pref_service->GetString(prefs::kStaticEncodings), pref_service->GetString(prefs::kRecentlySelectedEncoding)); DCHECK(encodings); DCHECK(!encodings->empty()); std::vector<CharacterEncoding::EncodingInfo>::const_iterator it; for (it = encodings->begin(); it != encodings->end(); ++it) { ListValue* option = new ListValue(); if (it->encoding_id) { int cmd_id = it->encoding_id; std::string encoding = CharacterEncoding::GetCanonicalEncodingNameByCommandId(cmd_id); string16 name = it->encoding_display_name; bool has_rtl_chars = base::i18n::StringContainsStrongRTLChars(name); option->Append(new base::StringValue(encoding)); option->Append(new base::StringValue(name)); option->Append(new base::StringValue(has_rtl_chars ? "rtl" : "ltr")); } else { // Add empty name/value to indicate a separator item. option->Append(new base::StringValue("")); option->Append(new base::StringValue("")); } encoding_list.Append(option); } ListValue selected_values; selected_values.Append(new base::StringValue(MaybeGetLocalizedFontName( standard_font_.GetValue()))); selected_values.Append(new base::StringValue(MaybeGetLocalizedFontName( serif_font_.GetValue()))); selected_values.Append(new base::StringValue(MaybeGetLocalizedFontName( sans_serif_font_.GetValue()))); selected_values.Append(new base::StringValue(MaybeGetLocalizedFontName( fixed_font_.GetValue()))); selected_values.Append(new base::StringValue(font_encoding_.GetValue())); web_ui()->CallJavascriptFunction("FontSettings.setFontsData", *list.get(), encoding_list, selected_values); } void FontSettingsHandler::SetUpStandardFontSample() { base::StringValue font_value(standard_font_.GetValue()); base::FundamentalValue size_value(default_font_size_.GetValue()); web_ui()->CallJavascriptFunction( "FontSettings.setUpStandardFontSample", font_value, size_value); } void FontSettingsHandler::SetUpSerifFontSample() { base::StringValue font_value(serif_font_.GetValue()); base::FundamentalValue size_value(default_font_size_.GetValue()); web_ui()->CallJavascriptFunction( "FontSettings.setUpSerifFontSample", font_value, size_value); } void FontSettingsHandler::SetUpSansSerifFontSample() { base::StringValue font_value(sans_serif_font_.GetValue()); base::FundamentalValue size_value(default_font_size_.GetValue()); web_ui()->CallJavascriptFunction( "FontSettings.setUpSansSerifFontSample", font_value, size_value); } void FontSettingsHandler::SetUpFixedFontSample() { base::StringValue font_value(fixed_font_.GetValue()); base::FundamentalValue size_value(default_fixed_font_size_.GetValue()); web_ui()->CallJavascriptFunction( "FontSettings.setUpFixedFontSample", font_value, size_value); } void FontSettingsHandler::SetUpMinimumFontSample() { base::FundamentalValue size_value(minimum_font_size_.GetValue()); web_ui()->CallJavascriptFunction("FontSettings.setUpMinimumFontSample", size_value); } void FontSettingsHandler::OnWebKitDefaultFontSizeChanged() { SetUpStandardFontSample(); SetUpSerifFontSample(); SetUpSansSerifFontSample(); } } // namespace options
[ "rjogrady@google.com" ]
rjogrady@google.com
58512757e6b45846f9ea893da363ac8cf8fc7270
1b22a1152258911bfe569afae9922be643bbeea5
/validateStackSequences.cpp
ed96742dcd052cf2eac976f6e491f0e4cf9cc40a
[]
no_license
Ambition111/-
c14bb5a439fa5028e4abe9f0d7c629c001f429e5
4a0e0c958a78a7d0903e1b2190ddbf3edd0c11d1
refs/heads/master
2023-04-16T11:01:38.044545
2021-04-15T16:00:00
2021-04-15T16:00:00
304,906,672
3
1
null
null
null
null
GB18030
C++
false
false
866
cpp
/* 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。 假设压入栈的所有数字均不相等。 例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列, 但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。 */ class Solution { public: bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { stack<int> st; int i = 0, j = 0; while (j < popped.size()) { while (st.empty() || st.top() != popped[j]) { if (i < pushed.size()) st.push(pushed[i++]); else return false; } st.pop(); j++; } return true; } };
[ "2460819991@qq.com" ]
2460819991@qq.com
3249a7475a9e1f5c278cc07d1c82a54dde1a7774
15c181b916b8bc55f3e180c0017a0d05dbaa6194
/src/demo.hpp
23be6cb03ffc8b0e5e4fe4e8e41d14acbb798fcd
[]
no_license
meleneth/rygen
e0fc3232b92311885308825b82cf597c664f526b
633a471f9811da782b64b3a87e156dadd671410e
refs/heads/master
2020-06-04T05:35:19.145511
2015-06-10T19:24:30
2015-06-10T19:24:30
27,327,671
1
0
null
null
null
null
UTF-8
C++
false
false
553
hpp
#ifndef DEMO_HPP #define DEMO_HPP #include "mel_opengl.hpp" #include "rygen_types.hpp" namespace Rygen { class Demo { public: Demo(const Video &video); void render_frame(Video &video); GLuint texid; GLuint entity_vbo; std::shared_ptr<ShaderProgram> entity_shader; glm::mat4 View; glm::mat4 Projection; GLuint widget_vbo; std::shared_ptr<ShaderProgram> widget_shader; GLuint texture_vbo; std::shared_ptr<ShaderProgram> texture_shader; GLuint widget_partial_texture_vbo; std::shared_ptr<Texture> texture; }; } #endif
[ "meleneth@answer.sectorfour" ]
meleneth@answer.sectorfour
2d5617c55d35956315cc2638b08ac255b33bb8f3
8e50c4abd5874d17f92ea74eca344787a893606b
/src/ex_finger.h
b7c42d3217326f3bd2de8292fd19bc23afc551de
[ "MIT" ]
permissive
HustDsy/DashTest
d953fea4ef407fd9dfc0be83acda027fc2f850f4
c30eb6e9c7a8db65156eb625836859c15f7fe382
refs/heads/main
2023-04-19T23:20:12.002840
2021-05-06T01:03:04
2021-05-06T01:03:04
360,755,758
0
0
null
null
null
null
GB18030
C++
false
false
87,558
h
// Copyright (c) Simon Fraser University & The Chinese University of Hong Kong. All rights reserved. // Licensed under the MIT license. // // Dash Extendible Hashing // Authors: // Baotong Lu <btlu@cse.cuhk.edu.hk> // Xiangpeng Hao <xiangpeng_hao@sfu.ca> // Tianzheng Wang <tzwang@sfu.ca> #pragma once #include <immintrin.h> #include <omp.h> #include <bitset> #include <cassert> #include <cmath> #include <cstring> #include <iostream> #include <shared_mutex> #include <thread> #include <tuple> #include <unordered_map> #include <vector> #include "../util/hash.h" #include "../util/pair.h" #include "Hash.h" #include "allocator.h" #ifdef PMEM #include <libpmemobj.h> #endif uint64_t merge_time; namespace extendible { //#define COUNTING 1 //#define PREALLOC 1 template <class T> struct _Pair { T key; Value_t value; }; const uint32_t lockSet = ((uint32_t)1 << 31); const uint32_t lockMask = ((uint32_t)1 << 31) - 1; const int overflowSet = 1 << 4; const int countMask = (1 << 4) - 1; const uint64_t tailMask = (1UL << 56) - 1; const uint64_t headerMask = ((1UL << 8) - 1) << 56; const uint8_t overflowBitmapMask = (1 << 4) - 1; constexpr size_t k_PairSize = 16; // a k-v _Pair with a bit constexpr size_t kNumPairPerBucket = 14; /* it is determined by the usage of the fingerprint*/ constexpr size_t kFingerBits = 8; constexpr size_t kMask = (1 << kFingerBits) - 1; const constexpr size_t kNumBucket = 64; /* the number of normal buckets in one segment*/ constexpr size_t stashBucket = 2; /* the number of stash buckets in one segment*/ constexpr int allocMask = (1 << kNumPairPerBucket) - 1; size_t bucketMask = ((1 << (int)log2(kNumBucket)) - 1); size_t stashMask = (1 << (int)log2(stashBucket)) - 1; uint8_t stashHighMask = ~((uint8_t)stashMask); #define BUCKET_INDEX(hash) ((hash >> kFingerBits) & bucketMask) #define GET_COUNT(var) ((var)&countMask) #define GET_MEMBER(var) (((var) >> 4) & allocMask) #define GET_INVERSE_MEMBER(var) ((~((var) >> 4)) & allocMask) #define GET_BITMAP(var) ((var) >> 18) inline bool var_compare(char *str1, char *str2, int len1, int len2) { if (len1 != len2) return false; return !memcmp(str1, str2, len1); } template <class T> struct Bucket { inline int find_empty_slot() { if (GET_COUNT(bitmap) == kNumPairPerBucket) { return -1; } auto mask = ~(GET_BITMAP(bitmap)); return __builtin_ctz(mask); } /*true indicates overflow, needs extra check in the stash*/ inline bool test_overflow() { return overflowCount; } inline bool test_stash_check() { return (overflowBitmap & overflowSet); } inline void clear_stash_check() { overflowBitmap = overflowBitmap & (~overflowSet); } inline void set_indicator(uint8_t meta_hash, Bucket<T> *neighbor, uint8_t pos) { int mask = overflowBitmap & overflowBitmapMask; mask = ~mask; auto index = __builtin_ctz(mask); if (index < 4) { finger_array[14 + index] = meta_hash; overflowBitmap = ((uint8_t)(1 << index) | overflowBitmap); overflowIndex = (overflowIndex & (~(3 << (index * 2)))) | (pos << (index * 2)); } else { mask = neighbor->overflowBitmap & overflowBitmapMask; mask = ~mask; index = __builtin_ctz(mask); if (index < 4) { neighbor->finger_array[14 + index] = meta_hash; neighbor->overflowBitmap = ((uint8_t)(1 << index) | neighbor->overflowBitmap); neighbor->overflowMember = ((uint8_t)(1 << index) | neighbor->overflowMember); neighbor->overflowIndex = (neighbor->overflowIndex & (~(3 << (index * 2)))) | (pos << (index * 2)); } else { /*overflow, increase count*/ overflowCount++; } } overflowBitmap = overflowBitmap | overflowSet; } /*both clear this bucket and its neighbor bucket*/ inline void unset_indicator(uint8_t meta_hash, Bucket<T> *neighbor, T key, uint64_t pos) { /*also needs to ensure that this meta_hash must belongs to other bucket*/ bool clear_success = false; int mask1 = overflowBitmap & overflowBitmapMask; for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask1, i) && (finger_array[14 + i] == meta_hash) && (((1 << i) & overflowMember) == 0) && (((overflowIndex >> (2 * i)) & stashMask) == pos)) { overflowBitmap = overflowBitmap & ((uint8_t)(~(1 << i))); overflowIndex = overflowIndex & (~(3 << (i * 2))); assert(((overflowIndex >> (i * 2)) & stashMask) == 0); clear_success = true; break; } } int mask2 = neighbor->overflowBitmap & overflowBitmapMask; if (!clear_success) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask2, i) && (neighbor->finger_array[14 + i] == meta_hash) && (((1 << i) & neighbor->overflowMember) != 0) && (((neighbor->overflowIndex >> (2 * i)) & stashMask) == pos)) { neighbor->overflowBitmap = neighbor->overflowBitmap & ((uint8_t)(~(1 << i))); neighbor->overflowMember = neighbor->overflowMember & ((uint8_t)(~(1 << i))); neighbor->overflowIndex = neighbor->overflowIndex & (~(3 << (i * 2))); assert(((neighbor->overflowIndex >> (i * 2)) & stashMask) == 0); clear_success = true; break; } } } if (!clear_success) { overflowCount--; } mask1 = overflowBitmap & overflowBitmapMask; mask2 = neighbor->overflowBitmap & overflowBitmapMask; if (((mask1 & (~overflowMember)) == 0) && (overflowCount == 0) && ((mask2 & neighbor->overflowMember) == 0)) { clear_stash_check(); } } int unique_check(uint8_t meta_hash, T key, Bucket<T> *neighbor, Bucket<T> *stash) { Value_t var=check_and_get(meta_hash, key, false); if(var!=NONE) { //Delete(key,meta_hash, false); // Insert(key,var,meta_hash,false); return -1; } var=neighbor->check_and_get(meta_hash, key, true); if(var!=NONE) { // neighbor->Delete(key,meta_hash, true); //neighbor->Insert(key,var,meta_hash,true); return -1; } if (test_stash_check()) { auto test_stash = false; if (test_overflow()) { test_stash = true; } else { int mask = overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (finger_array[14 + i] == meta_hash) && (((1 << i) & overflowMember) == 0)) { test_stash = true; goto STASH_CHECK; } } } mask = neighbor->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (neighbor->finger_array[14 + i] == meta_hash) && (((1 << i) & neighbor->overflowMember) != 0)) { test_stash = true; break; } } } } STASH_CHECK: if (test_stash == true) { for (int i = 0; i < stashBucket; ++i) { Bucket *curr_bucket = stash + i; var=curr_bucket->check_and_get(meta_hash, key, false); if(var!= NONE) { //curr_bucket->Delete(key,meta_hash, false); //curr_bucket->Insert(key,var,meta_hash,false); return -1; } } } } return 0; } inline int get_current_mask() { int mask = GET_BITMAP(bitmap) & GET_INVERSE_MEMBER(bitmap); return mask; } Value_t check_and_get(uint8_t meta_hash, T key, bool probe) { int mask = 0; SSE_CMP8(finger_array, meta_hash); int dul=_mm_popcnt_u32(mask); if (!probe) { mask = mask & GET_BITMAP(bitmap) & (~GET_MEMBER(bitmap)); } else { mask = mask & GET_BITMAP(bitmap) & GET_MEMBER(bitmap); } if (mask == 0) { return NONE; } if constexpr (std::is_pointer_v<T>) { /* variable-length key*/ string_key *_key = reinterpret_cast<string_key *>(key); for (int i = 0; i < 14; i += 1) { if (CHECK_BIT(mask, i) && (var_compare((reinterpret_cast<string_key *>(_[i].key))->key, _key->key, (reinterpret_cast<string_key *>(_[i].key))->length, _key->length))) { return _[i].value; } } } else { /*fixed-length key*/ /*loop unrolling*/ for (int i = 0; i < 12; i += 4) { if (CHECK_BIT(mask, i) && (_[i].key == key)) { return _[i].value; } if (CHECK_BIT(mask, i + 1) && (_[i + 1].key == key)) { return _[i + 1].value; } if (CHECK_BIT(mask, i + 2) && (_[i + 2].key == key)) { return _[i + 2].value; } if (CHECK_BIT(mask, i + 3) && (_[i + 3].key == key)) { return _[i + 3].value; } } if (CHECK_BIT(mask, 12) && (_[12].key == key)) { return _[12].value; } if (CHECK_BIT(mask, 13) && (_[13].key == key)) { return _[13].value; } } return NONE; } inline void set_hash(int index, uint8_t meta_hash, bool probe) { finger_array[index] = meta_hash; uint32_t new_bitmap = bitmap | (1 << (index + 18)); if (probe) { new_bitmap = new_bitmap | (1 << (index + 4)); } new_bitmap += 1; bitmap = new_bitmap; } inline uint8_t get_hash(int index) { return finger_array[index]; } inline void unset_hash(int index, bool nt_flush = false) { uint32_t new_bitmap = bitmap & (~(1 << (index + 18))) & (~(1 << (index + 4))); assert(GET_COUNT(bitmap) <= kNumPairPerBucket); assert(GET_COUNT(bitmap) > 0); new_bitmap -= 1; #ifdef PMEM if (nt_flush) { Allocator::NTWrite32(reinterpret_cast<uint32_t *>(&bitmap), new_bitmap); } else { bitmap = new_bitmap; } #else bitmap = new_bitmap; #endif } inline void get_lock() { uint32_t new_value = 0; uint32_t old_value = 0; do { while (true) { old_value = __atomic_load_n(&version_lock, __ATOMIC_ACQUIRE); if (!(old_value & lockSet)) { old_value &= lockMask; break; } } new_value = old_value | lockSet; } while (!CAS(&version_lock, &old_value, new_value)); } inline bool try_get_lock() { uint32_t v = __atomic_load_n(&version_lock, __ATOMIC_ACQUIRE); if (v & lockSet) { return false; } auto old_value = v & lockMask; auto new_value = v | lockSet; return CAS(&version_lock, &old_value, new_value); } inline void release_lock() { uint32_t v = version_lock; __atomic_store_n(&version_lock, v + 1 - lockSet, __ATOMIC_RELEASE); } /*if the lock is set, return true*/ inline bool test_lock_set(uint32_t &version) { version = __atomic_load_n(&version_lock, __ATOMIC_ACQUIRE); return (version & lockSet) != 0; } // test whether the version has change, if change, return true inline bool test_lock_version_change(uint32_t old_version) { auto value = __atomic_load_n(&version_lock, __ATOMIC_ACQUIRE); return (old_version != value); } int insert_with_slot(int index,T key, Value_t value, uint8_t meta_hash, bool probe) { _[index].value = value; _[index].key = key; #ifdef PMEM Allocator::Persist(&_[index], sizeof(_[index])); #endif set_hash(index, meta_hash, probe); return 0; } int Insert(T key, Value_t value, uint8_t meta_hash, bool probe) { auto slot = find_empty_slot(); assert(slot < kNumPairPerBucket); if (slot == -1) { return -1; } _[slot].value = value; _[slot].key = key; #ifdef PMEM Allocator::Persist(&_[slot], sizeof(_[slot])); #endif set_hash(slot, meta_hash, probe); return 0; } void delete_with_index(int index) { unset_hash(index, false); } //新增函数,根据位置插入数据一定会成功,probe一定是true void insert_with_index(T key,Value_t value,uint8_t meta_hash,int index) { _[index].value = value; _[index].key = key; #ifdef PMEM Allocator::Persist(&_[index], sizeof(_[index])); #endif set_hash(index, meta_hash, false); } /*if delete success, then return 0, else return -1*/ int Delete(T key, uint8_t meta_hash, bool probe) { /*do the simd and check the key, then do the delete operation*/ int mask = 0; SSE_CMP8(finger_array, meta_hash); if (!probe) { mask = mask & GET_BITMAP(bitmap) & (~GET_MEMBER(bitmap)); } else { mask = mask & GET_BITMAP(bitmap) & GET_MEMBER(bitmap); } /*loop unrolling*/ if constexpr (std::is_pointer_v<T>) { string_key *_key = reinterpret_cast<string_key *>(key); /*loop unrolling*/ if (mask != 0) { for (int i = 0; i < 12; i += 4) { if (CHECK_BIT(mask, i) && (var_compare((reinterpret_cast<string_key *>(_[i].key))->key, _key->key, (reinterpret_cast<string_key *>(_[i].key))->length, _key->length))) { unset_hash(i, false); return 0; } if (CHECK_BIT(mask, i + 1) && (var_compare( reinterpret_cast<string_key *>(_[i + 1].key)->key, _key->key, (reinterpret_cast<string_key *>(_[i + 1].key))->length, _key->length))) { unset_hash(i + 1, false); return 0; } if (CHECK_BIT(mask, i + 2) && (var_compare( reinterpret_cast<string_key *>(_[i + 2].key)->key, _key->key, (reinterpret_cast<string_key *>(_[i + 2].key))->length, _key->length))) { unset_hash(i + 2, false); return 0; } if (CHECK_BIT(mask, i + 3) && (var_compare( reinterpret_cast<string_key *>(_[i + 3].key)->key, _key->key, (reinterpret_cast<string_key *>(_[i + 3].key))->length, _key->length))) { unset_hash(i + 3, false); return 0; } } if (CHECK_BIT(mask, 12) && (var_compare(reinterpret_cast<string_key *>(_[12].key)->key, _key->key, (reinterpret_cast<string_key *>(_[12].key))->length, _key->length))) { unset_hash(12, false); return 0; } if (CHECK_BIT(mask, 13) && (var_compare(reinterpret_cast<string_key *>(_[13].key)->key, _key->key, (reinterpret_cast<string_key *>(_[13].key))->length, _key->length))) { unset_hash(13, false); return 0; } } } else { if (mask != 0) { for (int i = 0; i < 12; i += 4) { if (CHECK_BIT(mask, i) && (_[i].key == key)) { unset_hash(i, false); return 0; } if (CHECK_BIT(mask, i + 1) && (_[i + 1].key == key)) { unset_hash(i + 1, false); return 0; } if (CHECK_BIT(mask, i + 2) && (_[i + 2].key == key)) { unset_hash(i + 2, false); return 0; } if (CHECK_BIT(mask, i + 3) && (_[i + 3].key == key)) { unset_hash(i + 3, false); return 0; } } if (CHECK_BIT(mask, 12) && (_[12].key == key)) { unset_hash(12, false); return 0; } if (CHECK_BIT(mask, 13) && (_[13].key == key)) { unset_hash(13, false); return 0; } } } return -1; } int Insert_with_noflush(T key, Value_t value, uint8_t meta_hash, bool probe) { auto slot = find_empty_slot(); /* this branch can be removed*/ assert(slot < kNumPairPerBucket); if (slot == -1) { std::cout << "Cannot find the empty slot, for key " << key << std::endl; return -1; } _[slot].value = value; _[slot].key = key; set_hash(slot, meta_hash, probe); return 0; } void Insert_displace(T key, Value_t value, uint8_t meta_hash, int slot, bool probe) { _[slot].value = value; _[slot].key = key; #ifdef PMEM Allocator::Persist(&_[slot], sizeof(_Pair<T>)); #endif set_hash(slot, meta_hash, probe); } void Insert_displace_with_noflush(T key, Value_t value, uint8_t meta_hash, int slot, bool probe) { _[slot].value = value; _[slot].key = key; set_hash(slot, meta_hash, probe); } /* Find the displacment element in this bucket*/ inline int Find_org_displacement() { uint32_t mask = GET_INVERSE_MEMBER(bitmap); if (mask == 0) { return -1; } return __builtin_ctz(mask); } /*find element that it is in the probe*/ inline int Find_probe_displacement() { uint32_t mask = GET_MEMBER(bitmap); if (mask == 0) { return -1; } return __builtin_ctz(mask); } inline void resetLock() { version_lock = 0; } inline void resetOverflowFP() { overflowBitmap = 0; overflowIndex = 0; overflowMember = 0; overflowCount = 0; clear_stash_check(); } uint32_t version_lock; uint32_t bitmap; // allocation bitmap + pointer bitmap + counter uint8_t finger_array[18]; /*only use the first 14 bytes, can be accelerated by SSE instruction,0-13 for finger, 14-17 for overflowed*/ uint8_t overflowBitmap; uint8_t overflowIndex; uint8_t overflowMember; /*overflowmember indicates membership of the overflow fingerprint*/ uint8_t overflowCount; uint8_t unused[2]; _Pair<T> _[kNumPairPerBucket]; }; template <class T> struct Table; template <class T> struct Directory { typedef Table<T> *table_p; uint32_t global_depth; uint32_t version; uint32_t depth_count; table_p _[0]; Directory(size_t capacity, size_t _version) { version = _version; global_depth = static_cast<size_t>(log2(capacity)); depth_count = 0; } static void New(PMEMoid *dir, size_t capacity, size_t version) { #ifdef PMEM auto callback = [](PMEMobjpool *pool, void *ptr, void *arg) { auto value_ptr = reinterpret_cast<std::tuple<size_t, size_t> *>(arg); auto dir_ptr = reinterpret_cast<Directory *>(ptr); dir_ptr->version = std::get<1>(*value_ptr); dir_ptr->global_depth = static_cast<size_t>(log2(std::get<0>(*value_ptr))); size_t cap = std::get<0>(*value_ptr); pmemobj_persist(pool, dir_ptr, sizeof(Directory<T>) + sizeof(uint64_t) * cap); return 0; }; std::tuple callback_args = {capacity, version}; Allocator::Allocate(dir, kCacheLineSize, sizeof(Directory<T>) + sizeof(table_p) * capacity, callback, reinterpret_cast<void *>(&callback_args)); #else Allocator::Allocate((void **)dir, kCacheLineSize, sizeof(Directory<T>)); new (*dir) Directory(capacity, version, tables); #endif } }; /*thread local table allcoation pool*/ template <class T> struct TlsTablePool { static Table<T> *all_tables; static PMEMoid p_all_tables; static std::atomic<uint32_t> all_allocated; static const uint32_t kAllTables = 327680; static void AllocateMore() { auto callback = [](PMEMobjpool *pool, void *ptr, void *arg) { return 0; }; std::pair callback_para(0, nullptr); Allocator::Allocate(&p_all_tables, kCacheLineSize, sizeof(Table<T>) * kAllTables, callback, reinterpret_cast<void *>(&callback_para)); all_tables = reinterpret_cast<Table<T> *>(pmemobj_direct(p_all_tables)); memset((void *)all_tables, 0, sizeof(Table<T>) * kAllTables); all_allocated = 0; printf("MORE "); } TlsTablePool() {} static void Initialize() { AllocateMore(); } Table<T> *tables = nullptr; static const uint32_t kTables = 128; uint32_t allocated = kTables; void TlsPrepare() { retry: uint32_t n = all_allocated.fetch_add(kTables); if (n == kAllTables) { AllocateMore(); abort(); goto retry; } tables = all_tables + n; allocated = 0; } Table<T> *Get() { if (allocated == kTables) { TlsPrepare(); } return &tables[allocated++]; } }; template <class T> std::atomic<uint32_t> TlsTablePool<T>::all_allocated(0); template <class T> Table<T> *TlsTablePool<T>::all_tables = nullptr; template <class T> PMEMoid TlsTablePool<T>::p_all_tables = OID_NULL; /* the segment class*/ template <class T> struct Table { static void New(PMEMoid *tbl, size_t depth, PMEMoid pp) { #ifdef PMEM #ifdef PREALLOC thread_local TlsTablePool<T> tls_pool; auto ptr = tls_pool.Get(); ptr->local_depth = depth; ptr->next = pp; *tbl = pmemobj_oid(ptr); #else auto callback = [](PMEMobjpool *pool, void *ptr, void *arg) { auto value_ptr = reinterpret_cast<std::pair<size_t, PMEMoid> *>(arg); auto table_ptr = reinterpret_cast<Table<T> *>(ptr); table_ptr->local_depth = value_ptr->first; table_ptr->next = value_ptr->second; table_ptr->state = -3; /*NEW*/ memset(&table_ptr->lock_bit, 0, sizeof(PMEMmutex) * 2); int sumBucket = kNumBucket + stashBucket; for (int i = 0; i < sumBucket; ++i) { auto curr_bucket = table_ptr->bucket + i; memset(curr_bucket, 0, 64); } pmemobj_persist(pool, table_ptr, sizeof(Table<T>)); return 0; }; std::pair callback_para(depth, pp); Allocator::Allocate(tbl, kCacheLineSize, sizeof(Table<T>), callback, reinterpret_cast<void *>(&callback_para)); #endif #else Allocator::ZAllocate((void **)tbl, kCacheLineSize, sizeof(Table<T>)); (*tbl)->local_depth = depth; (*tbl)->next = pp; #endif }; ~Table(void) {} bool Acquire_and_verify(size_t _pattern) { bucket->get_lock(); if (pattern != _pattern) { bucket->release_lock(); return false; } else { return true; } } void Acquire_remaining_locks() { for (int i = 1; i < kNumBucket; ++i) { auto curr_bucket = bucket + i; curr_bucket->get_lock(); } } void Release_all_locks() { for (int i = 0; i < kNumBucket; ++i) { auto curr_bucket = bucket + i; curr_bucket->release_lock(); } } int Insert(T key, Value_t value, size_t key_hash, uint8_t meta_hash, Directory<T> **); void Insert4split(T key, Value_t value, size_t key_hash, uint8_t meta_hash); void Insert4splitWithCheck(T key, Value_t value, size_t key_hash, uint8_t meta_hash); /*with uniqueness check*/ void Insert4merge(T key, Value_t value, size_t key_hash, uint8_t meta_hash, bool flag = false); Table<T> *Split(size_t); void HelpSplit(Table<T> *); void Merge(Table<T> *, bool flag = false); int Delete(T key, size_t key_hash, uint8_t meta_hash, Directory<T> **_dir); int Next_displace(Bucket<T> *target, Bucket<T> *neighbor, Bucket<T> *next_neighbor, T key, Value_t value, uint8_t meta_hash) { int displace_index = neighbor->Find_org_displacement(); if ((GET_COUNT(next_neighbor->bitmap) != kNumPairPerBucket) && (displace_index != -1)) { next_neighbor->Insert(neighbor->_[displace_index].key, neighbor->_[displace_index].value, neighbor->finger_array[displace_index], true); next_neighbor->release_lock(); #ifdef PMEM Allocator::Persist(&next_neighbor->bitmap, sizeof(next_neighbor->bitmap)); #endif neighbor->unset_hash(displace_index); neighbor->Insert_displace(key, value, meta_hash, displace_index, true); neighbor->release_lock(); #ifdef PMEM Allocator::Persist(&neighbor->bitmap, sizeof(neighbor->bitmap)); #endif target->release_lock(); #ifdef COUNTING __sync_fetch_and_add(&number, 1); #endif return 0; } return -1; } int Prev_displace(Bucket<T> *target, Bucket<T> *prev_neighbor, Bucket<T> *neighbor, T key, Value_t value, uint8_t meta_hash) { int displace_index = target->Find_probe_displacement(); if ((GET_COUNT(prev_neighbor->bitmap) != kNumPairPerBucket) && (displace_index != -1)) { prev_neighbor->Insert(target->_[displace_index].key, target->_[displace_index].value, target->finger_array[displace_index], false); prev_neighbor->release_lock(); #ifdef PMEM Allocator::Persist(&prev_neighbor->bitmap, sizeof(prev_neighbor->bitmap)); #endif target->unset_hash(displace_index); target->Insert_displace(key, value, meta_hash, displace_index, false); target->release_lock(); #ifdef PMEM Allocator::Persist(&target->bitmap, sizeof(target->bitmap)); #endif neighbor->release_lock(); #ifdef COUNTING __sync_fetch_and_add(&number, 1); #endif return 0; } return -1; } int Stash_insert(Bucket<T> *target, Bucket<T> *neighbor, T key, Value_t value, uint8_t meta_hash, int stash_pos) { for (int i = 0; i < stashBucket; ++i) { Bucket<T> *curr_bucket = bucket + kNumBucket + ((stash_pos + i) & stashMask); if (GET_COUNT(curr_bucket->bitmap) < kNumPairPerBucket) { curr_bucket->Insert(key, value, meta_hash, false); #ifdef PMEM Allocator::Persist(&curr_bucket->bitmap, sizeof(curr_bucket->bitmap)); #endif target->set_indicator(meta_hash, neighbor, (stash_pos + i) & stashMask); #ifdef COUNTING __sync_fetch_and_add(&number, 1); #endif return 0; } } return -1; } void recoverMetadata() { Bucket<T> *curr_bucket, *neighbor_bucket; /*reset the lock and overflow meta-data*/ uint64_t knumber = 0; for (int i = 0; i < kNumBucket; ++i) { curr_bucket = bucket + i; curr_bucket->resetLock(); curr_bucket->resetOverflowFP(); neighbor_bucket = bucket + ((i + 1) & bucketMask); for (int j = 0; j < kNumPairPerBucket; ++j) { int mask = curr_bucket->get_current_mask(); if (CHECK_BIT(mask, j) && (neighbor_bucket->check_and_get( curr_bucket->finger_array[j], curr_bucket->_[j].key, true) != NONE)) { curr_bucket->unset_hash(j); } } #ifdef COUNTING knumber += __builtin_popcount(GET_BITMAP(curr_bucket->bitmap)); #endif } /*scan the stash buckets and re-insert the overflow FP to initial buckets*/ for (int i = 0; i < stashBucket; ++i) { curr_bucket = bucket + kNumBucket + i; curr_bucket->resetLock(); #ifdef COUNTING knumber += __builtin_popcount(GET_BITMAP(curr_bucket->bitmap)); #endif uint64_t key_hash; auto mask = GET_BITMAP(curr_bucket->bitmap); for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } /*compute the initial bucket*/ auto bucket_ix = BUCKET_INDEX(key_hash); auto meta_hash = ((uint8_t)(key_hash & kMask)); // the last 8 bits auto org_bucket = bucket + bucket_ix; auto neighbor_bucket = bucket + ((bucket_ix + 1) & bucketMask); org_bucket->set_indicator(meta_hash, neighbor_bucket, i); } } } #ifdef COUNTING number = knumber; #endif /* No need to flush these meta-data because persistent or not does not * influence the correctness*/ } char dummy[48]; Bucket<T> bucket[kNumBucket + stashBucket]; size_t local_depth; size_t pattern; int number; PMEMoid next; int state; /*-1 means this bucket is merging, -2 means this bucket is splitting (SPLITTING), 0 meanning normal bucket, -3 means new bucket (NEW)*/ PMEMmutex lock_bit; /* for the synchronization of the lazy recovery in one segment*/ }; /* it needs to verify whether this bucket has been deleted...*/ template <class T> int Table<T>::Insert(T key, Value_t value, size_t key_hash, uint8_t meta_hash, Directory<T> **_dir) { RETRY: /*we need to first do the locking and then do the verify*/ auto y = BUCKET_INDEX(key_hash); Bucket<T> *target = bucket + y; Bucket<T> *neighbor = bucket + ((y + 1) & bucketMask); target->get_lock(); if (!neighbor->try_get_lock()) { target->release_lock(); return -2; } auto old_sa = *_dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); if (reinterpret_cast<Table<T> *>(reinterpret_cast<uint64_t>(old_sa->_[x]) & tailMask) != this) { neighbor->release_lock(); target->release_lock(); return -2; } /*unique check, needs to check 2 hash table*/ auto ret = target->unique_check(meta_hash, key, neighbor, bucket + kNumBucket); if (ret == -1) { neighbor->release_lock(); target->release_lock(); return -3; /* duplicate insert*/ } if (((GET_COUNT(target->bitmap)) == kNumPairPerBucket) && ((GET_COUNT(neighbor->bitmap)) == kNumPairPerBucket)) { Bucket<T> *next_neighbor = bucket + ((y + 2) & bucketMask); // Next displacement if (!next_neighbor->try_get_lock()) { neighbor->release_lock(); target->release_lock(); return -2; } auto ret = Next_displace(target, neighbor, next_neighbor, key, value, meta_hash); if (ret == 0) { return 0; } next_neighbor->release_lock(); Bucket<T> *prev_neighbor; int prev_index; if (y == 0) { prev_neighbor = bucket + kNumBucket - 1; prev_index = kNumBucket - 1; } else { prev_neighbor = bucket + y - 1; prev_index = y - 1; } if (!prev_neighbor->try_get_lock()) { target->release_lock(); neighbor->release_lock(); return -2; } ret = Prev_displace(target, prev_neighbor, neighbor, key, value, meta_hash); if (ret == 0) { return 0; } Bucket<T> *stash = bucket + kNumBucket; if (!stash->try_get_lock()) { neighbor->release_lock(); target->release_lock(); prev_neighbor->release_lock(); return -2; } ret = Stash_insert(target, neighbor, key, value, meta_hash, y & stashMask); //if(ret==-1)表示这个stash也插不进去了 if(ret==-1) { //在insert中随便删一个数据,然后再进行插入 if(GET_COUNT(target->bitmap)>14||GET_COUNT(target->bitmap)==0) { int error=1; } target->delete_with_index(0); target->insert_with_slot(0,key,value,meta_hash,false); } stash->release_lock(); neighbor->release_lock(); target->release_lock(); prev_neighbor->release_lock(); return ret; } /* the fp+bitmap are persisted after releasing the lock of one bucket but * still guarantee the correctness of avoidance of "use-before-flush" since * the search operation could only proceed only if both target bucket and * probe bucket are released */ if (GET_COUNT(target->bitmap) <= GET_COUNT(neighbor->bitmap)) { target->Insert(key, value, meta_hash, false); target->release_lock(); #ifdef PMEM Allocator::Persist(&target->bitmap, sizeof(target->bitmap)); #endif neighbor->release_lock(); } else { neighbor->Insert(key, value, meta_hash, true); neighbor->release_lock(); #ifdef PMEM Allocator::Persist(&neighbor->bitmap, sizeof(neighbor->bitmap)); #endif target->release_lock(); } #ifdef COUNTING __sync_fetch_and_add(&number, 1); #endif return 0; } template <class T> void Table<T>::Insert4splitWithCheck(T key, Value_t value, size_t key_hash, uint8_t meta_hash) { auto y = BUCKET_INDEX(key_hash); Bucket<T> *target = bucket + y; Bucket<T> *neighbor = bucket + ((y + 1) & bucketMask); auto ret = target->unique_check(meta_hash, key, neighbor, bucket + kNumBucket); if (ret == -1) return; Bucket<T> *insert_target; bool probe = false; if (GET_COUNT(target->bitmap) <= GET_COUNT(neighbor->bitmap)) { insert_target = target; } else { insert_target = neighbor; probe = true; } /*some bucket may be overflowed?*/ if (GET_COUNT(insert_target->bitmap) < kNumPairPerBucket) { insert_target->_[GET_COUNT(insert_target->bitmap)].key = key; insert_target->_[GET_COUNT(insert_target->bitmap)].value = value; insert_target->set_hash(GET_COUNT(insert_target->bitmap), meta_hash, probe); #ifdef COUNTING ++number; #endif } else { /*do the displacement or insertion in the stash*/ Bucket<T> *next_neighbor = bucket + ((y + 2) & bucketMask); int displace_index; displace_index = neighbor->Find_org_displacement(); if (((GET_COUNT(next_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { next_neighbor->Insert_with_noflush( neighbor->_[displace_index].key, neighbor->_[displace_index].value, neighbor->finger_array[displace_index], true); neighbor->unset_hash(displace_index); neighbor->Insert_displace_with_noflush(key, value, meta_hash, displace_index, true); #ifdef COUNTING ++number; #endif return; } Bucket<T> *prev_neighbor; int prev_index; if (y == 0) { prev_neighbor = bucket + kNumBucket - 1; prev_index = kNumBucket - 1; } else { prev_neighbor = bucket + y - 1; prev_index = y - 1; } displace_index = target->Find_probe_displacement(); if (((GET_COUNT(prev_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { prev_neighbor->Insert_with_noflush( target->_[displace_index].key, target->_[displace_index].value, target->finger_array[displace_index], false); target->unset_hash(displace_index); target->Insert_displace_with_noflush(key, value, meta_hash, displace_index, false); #ifdef COUNTING ++number; #endif return; } Stash_insert(target, neighbor, key, value, meta_hash, y & stashMask); } } /*the insert needs to be perfectly balanced, not destory the power of balance*/ template <class T> void Table<T>::Insert4split(T key, Value_t value, size_t key_hash, uint8_t meta_hash) { auto y = BUCKET_INDEX(key_hash); Bucket<T> *target = bucket + y; Bucket<T> *neighbor = bucket + ((y + 1) & bucketMask); Bucket<T> *insert_target; bool probe = false; if (GET_COUNT(target->bitmap) <= GET_COUNT(neighbor->bitmap)) { insert_target = target; } else { insert_target = neighbor; probe = true; } /*some bucket may be overflowed?*/ if (GET_COUNT(insert_target->bitmap) < kNumPairPerBucket) { insert_target->_[GET_COUNT(insert_target->bitmap)].key = key; insert_target->_[GET_COUNT(insert_target->bitmap)].value = value; insert_target->set_hash(GET_COUNT(insert_target->bitmap), meta_hash, probe); #ifdef COUNTING ++number; #endif } else { /*do the displacement or insertion in the stash*/ Bucket<T> *next_neighbor = bucket + ((y + 2) & bucketMask); int displace_index; displace_index = neighbor->Find_org_displacement(); if (((GET_COUNT(next_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { next_neighbor->Insert_with_noflush( neighbor->_[displace_index].key, neighbor->_[displace_index].value, neighbor->finger_array[displace_index], true); neighbor->unset_hash(displace_index); neighbor->Insert_displace_with_noflush(key, value, meta_hash, displace_index, true); #ifdef COUNTING ++number; #endif return; } Bucket<T> *prev_neighbor; int prev_index; if (y == 0) { prev_neighbor = bucket + kNumBucket - 1; prev_index = kNumBucket - 1; } else { prev_neighbor = bucket + y - 1; prev_index = y - 1; } displace_index = target->Find_probe_displacement(); if (((GET_COUNT(prev_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { prev_neighbor->Insert_with_noflush( target->_[displace_index].key, target->_[displace_index].value, target->finger_array[displace_index], false); target->unset_hash(displace_index); target->Insert_displace_with_noflush(key, value, meta_hash, displace_index, false); #ifdef COUNTING ++number; #endif return; } Stash_insert(target, neighbor, key, value, meta_hash, y & stashMask); } } template <class T> void Table<T>::Insert4merge(T key, Value_t value, size_t key_hash, uint8_t meta_hash, bool unique_check_flag) { auto y = BUCKET_INDEX(key_hash); Bucket<T> *target = bucket + y; Bucket<T> *neighbor = bucket + ((y + 1) & bucketMask); if (unique_check_flag) { auto ret = target->unique_check(meta_hash, key, neighbor, bucket + kNumBucket); if (ret == -1) return; } Bucket<T> *insert_target; bool probe = false; if (GET_COUNT(target->bitmap) <= GET_COUNT(neighbor->bitmap)) { insert_target = target; } else { insert_target = neighbor; probe = true; } /*some bucket may be overflowed?*/ if (GET_COUNT(insert_target->bitmap) < kNumPairPerBucket) { insert_target->Insert(key, value, meta_hash, probe); #ifdef COUNTING ++number; #endif } else { /*do the displacement or insertion in the stash*/ Bucket<T> *next_neighbor = bucket + ((y + 2) & bucketMask); int displace_index; displace_index = neighbor->Find_org_displacement(); if (((GET_COUNT(next_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { next_neighbor->Insert_with_noflush( neighbor->_[displace_index].key, neighbor->_[displace_index].value, neighbor->finger_array[displace_index], true); neighbor->unset_hash(displace_index); neighbor->Insert_displace_with_noflush(key, value, meta_hash, displace_index, true); #ifdef COUNTING ++number; #endif return; } Bucket<T> *prev_neighbor; int prev_index; if (y == 0) { prev_neighbor = bucket + kNumBucket - 1; prev_index = kNumBucket - 1; } else { prev_neighbor = bucket + y - 1; prev_index = y - 1; } displace_index = target->Find_probe_displacement(); if (((GET_COUNT(prev_neighbor->bitmap)) != kNumPairPerBucket) && (displace_index != -1)) { prev_neighbor->Insert_with_noflush( target->_[displace_index].key, target->_[displace_index].value, target->finger_array[displace_index], false); target->unset_hash(displace_index); target->Insert_displace_with_noflush(key, value, meta_hash, displace_index, false); #ifdef COUNTING ++number; #endif return; } Stash_insert(target, neighbor, key, value, meta_hash, y & stashMask); } } template <class T> void Table<T>::HelpSplit(Table<T> *next_table) { size_t new_pattern = (pattern << 1) + 1; size_t old_pattern = pattern << 1; size_t key_hash; uint32_t invalid_array[kNumBucket + stashBucket]; for (int i = 0; i < kNumBucket; ++i) { auto *curr_bucket = bucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); uint32_t invalid_mask = 0; for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } if ((key_hash >> (64 - local_depth - 1)) == new_pattern) { invalid_mask = invalid_mask | (1 << j); next_table->Insert4splitWithCheck(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); #ifdef COUNTING number--; #endif } } } invalid_array[i] = invalid_mask; } for (int i = 0; i < stashBucket; ++i) { auto *curr_bucket = bucket + kNumBucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); uint32_t invalid_mask = 0; for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } if ((key_hash >> (64 - local_depth - 1)) == new_pattern) { invalid_mask = invalid_mask | (1 << j); next_table->Insert4splitWithCheck(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); auto bucket_ix = BUCKET_INDEX(key_hash); auto org_bucket = bucket + bucket_ix; auto neighbor_bucket = bucket + ((bucket_ix + 1) & bucketMask); org_bucket->unset_indicator(curr_bucket->finger_array[j], neighbor_bucket, curr_bucket->_[j].key, i); #ifdef COUNTING number--; #endif } } } invalid_array[kNumBucket + i] = invalid_mask; } next_table->pattern = new_pattern; Allocator::Persist(&next_table->pattern, sizeof(next_table->pattern)); pattern = old_pattern; Allocator::Persist(&pattern, sizeof(pattern)); #ifdef PMEM Allocator::Persist(next_table, sizeof(Table)); size_t sumBucket = kNumBucket + stashBucket; for (int i = 0; i < sumBucket; ++i) { auto curr_bucket = bucket + i; curr_bucket->bitmap = curr_bucket->bitmap & (~(invalid_array[i] << 18)) & (~(invalid_array[i] << 4)); uint32_t count = __builtin_popcount(invalid_array[i]); curr_bucket->bitmap = curr_bucket->bitmap - count; } Allocator::Persist(this, sizeof(Table)); #endif } template <class T> Table<T> *Table<T>::Split(size_t _key_hash) { size_t new_pattern = (pattern << 1) + 1; size_t old_pattern = pattern << 1; for (int i = 1; i < kNumBucket; ++i) { (bucket + i)->get_lock(); } state = -2; /*means the start of the split process*/ Allocator::Persist(&state, sizeof(state)); Table<T>::New(&next, local_depth + 1, next); Table<T> *next_table = reinterpret_cast<Table<T> *>(pmemobj_direct(next)); next_table->state = -2; Allocator::Persist(&next_table->state, sizeof(next_table->state)); next_table->bucket ->get_lock(); /* get the first lock of the new bucket to avoid it is operated(split or merge) by other threads*/ size_t key_hash; uint32_t invalid_array[kNumBucket + stashBucket]; for (int i = 0; i < kNumBucket; ++i) { auto *curr_bucket = bucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); uint32_t invalid_mask = 0; for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } if ((key_hash >> (64 - local_depth - 1)) == new_pattern) { invalid_mask = invalid_mask | (1 << j); next_table->Insert4split( curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); /*this shceme may destory the balanced segment*/ // curr_bucket->unset_hash(j); #ifdef COUNTING number--; #endif } } } invalid_array[i] = invalid_mask; } for (int i = 0; i < stashBucket; ++i) { auto *curr_bucket = bucket + kNumBucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); uint32_t invalid_mask = 0; for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } if ((key_hash >> (64 - local_depth - 1)) == new_pattern) { invalid_mask = invalid_mask | (1 << j); next_table->Insert4split( curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); /*this shceme may destory the balanced segment*/ auto bucket_ix = BUCKET_INDEX(key_hash); auto org_bucket = bucket + bucket_ix; auto neighbor_bucket = bucket + ((bucket_ix + 1) & bucketMask); org_bucket->unset_indicator(curr_bucket->finger_array[j], neighbor_bucket, curr_bucket->_[j].key, i); #ifdef COUNTING number--; #endif } } } invalid_array[kNumBucket + i] = invalid_mask; } next_table->pattern = new_pattern; Allocator::Persist(&next_table->pattern, sizeof(next_table->pattern)); pattern = old_pattern; Allocator::Persist(&pattern, sizeof(pattern)); #ifdef PMEM Allocator::Persist(next_table, sizeof(Table)); size_t sumBucket = kNumBucket + stashBucket; for (int i = 0; i < sumBucket; ++i) { auto curr_bucket = bucket + i; curr_bucket->bitmap = curr_bucket->bitmap & (~(invalid_array[i] << 18)) & (~(invalid_array[i] << 4)); uint32_t count = __builtin_popcount(invalid_array[i]); curr_bucket->bitmap = curr_bucket->bitmap - count; } Allocator::Persist(this, sizeof(Table)); #endif return next_table; } template <class T> void Table<T>::Merge(Table<T> *neighbor, bool unique_check_flag) { /*Restore the split/merge procedure*/ if (unique_check_flag) { size_t key_hash; for (int i = 0; i < kNumBucket; ++i) { auto *curr_bucket = neighbor->bucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } Insert4merge(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j], true); /*this shceme may destory the balanced segment*/ } } } for (int i = 0; i < stashBucket; ++i) { auto *curr_bucket = neighbor->bucket + kNumBucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } Insert4merge(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); /*this shceme may destory the balanced segment*/ } } } } else { size_t key_hash; for (int i = 0; i < kNumBucket; ++i) { auto *curr_bucket = neighbor->bucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } Insert4merge(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); /*this shceme may destory the balanced segment*/ } } } /*split the stash bucket, the stash must be full, right?*/ for (int i = 0; i < stashBucket; ++i) { auto *curr_bucket = neighbor->bucket + kNumBucket + i; auto mask = GET_BITMAP(curr_bucket->bitmap); for (int j = 0; j < kNumPairPerBucket; ++j) { if (CHECK_BIT(mask, j)) { if constexpr (std::is_pointer_v<T>) { auto curr_key = curr_bucket->_[j].key; key_hash = h(curr_key->key, curr_key->length); } else { key_hash = h(&(curr_bucket->_[j].key), sizeof(Key_t)); } Insert4merge(curr_bucket->_[j].key, curr_bucket->_[j].value, key_hash, curr_bucket->finger_array[j]); /*this shceme may destory the balanced segment*/ } } } } } template <class T> class Finger_EH : public Hash<T> { public: Finger_EH(void); Finger_EH(size_t, PMEMobjpool *_pool); ~Finger_EH(void); inline int Insert(T key, Value_t value); int Insert(T key, Value_t value, bool); inline bool Delete(T); bool Delete(T, bool); inline Value_t Get(T); Value_t Get(T key, bool is_in_epoch); void TryMerge(uint64_t); void Directory_Doubling(int x, Table<T> *new_b, Table<T> *old_b); void Directory_Merge_Update(Directory<T> *_sa, uint64_t key_hash, Table<T> *left_seg); void Directory_Update(Directory<T> *_sa, int x, Table<T> *new_b, Table<T> *old_b); void Halve_Directory(); int FindAnyway(T key); void ShutDown() { clean = true; Allocator::Persist(&clean, sizeof(clean)); } void getNumber() { std::cout << "The size of the bucket is " << sizeof(struct Bucket<T>) << std::endl; size_t _count = 0; size_t seg_count = 0; Directory<T> *seg = dir; Table<T> **dir_entry = seg->_; Table<T> *ss; auto global_depth = seg->global_depth; size_t depth_diff; int capacity = pow(2, global_depth); for (int i = 0; i < capacity;) { ss = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(dir_entry[i]) & tailMask); depth_diff = global_depth - ss->local_depth; _count += ss->number; seg_count++; i += pow(2, depth_diff); } ss = reinterpret_cast<Table<T> *>(reinterpret_cast<uint64_t>(dir_entry[0]) & tailMask); uint64_t verify_seg_count = 1; while (!OID_IS_NULL(ss->next)) { verify_seg_count++; ss = reinterpret_cast<Table<T> *>(pmemobj_direct(ss->next)); } std::cout << "seg_count = " << seg_count << std::endl; std::cout << "verify_seg_count = " << verify_seg_count << std::endl; #ifdef COUNTING std::cout << "#items = " << _count << std::endl; std::cout << "load_factor = " << (double)_count / (seg_count * kNumPairPerBucket * (kNumBucket + 2)) << std::endl; std::cout << "Raw_Space: ", (double)(_count * 16) / (seg_count * sizeof(Table<T>)) << std::endl; #endif } void recoverTable(Table<T> **target_table, size_t, size_t, Directory<T> *); void Recovery(); inline int Test_Directory_Lock_Set(void) { uint32_t v = __atomic_load_n(&lock, __ATOMIC_ACQUIRE); return v & lockSet; } inline bool try_get_directory_read_lock(){ uint32_t v = __atomic_load_n(&lock, __ATOMIC_ACQUIRE); uint32_t old_value = v & lockMask; auto new_value = ((v & lockMask) + 1) & lockMask; return CAS(&lock, &old_value, new_value); } inline void release_directory_read_lock(){ SUB(&lock, 1); } void Lock_Directory(){ uint32_t v = __atomic_load_n(&lock, __ATOMIC_ACQUIRE); uint32_t old_value = v & lockMask; uint32_t new_value = old_value | lockSet; while (!CAS(&lock, &old_value, new_value)) { old_value = old_value & lockMask; new_value = old_value | lockSet; } //wait until the readers all exit the critical section v = __atomic_load_n(&lock, __ATOMIC_ACQUIRE); while(v & lockMask){ v = __atomic_load_n(&lock, __ATOMIC_ACQUIRE); } } // just set the lock as 0 void Unlock_Directory(){ __atomic_store_n(&lock, 0, __ATOMIC_RELEASE); } Directory<T> *dir; uint32_t lock; // the MSB is the lock bit; remaining bits are used as the counter uint64_t crash_version; /*when the crash version equals to 0Xff => set the crash version as 0, set the version of all entries as 1*/ bool clean; PMEMobjpool *pool_addr; /* directory allocation will write to here first, * in oder to perform safe directory allocation * */ PMEMoid back_dir; }; template <class T> Finger_EH<T>::Finger_EH(size_t initCap, PMEMobjpool *_pool) { pool_addr = _pool; Directory<T>::New(&back_dir, initCap, 0); dir = reinterpret_cast<Directory<T> *>(pmemobj_direct(back_dir)); back_dir = OID_NULL; lock = 0; crash_version = 0; clean = false; PMEMoid ptr; /*FIXME: make the process of initialization crash consistent*/ Table<T>::New(&ptr, dir->global_depth, OID_NULL); dir->_[initCap - 1] = (Table<T> *)pmemobj_direct(ptr); dir->_[initCap - 1]->pattern = initCap - 1; dir->_[initCap - 1]->state = 0; /* Initilize the Directory*/ for (int i = initCap - 2; i >= 0; --i) { Table<T>::New(&ptr, dir->global_depth, ptr); dir->_[i] = (Table<T> *)pmemobj_direct(ptr); dir->_[i]->pattern = i; dir->_[i]->state = 0; } dir->depth_count = initCap; } template <class T> Finger_EH<T>::Finger_EH() { std::cout << "Reinitialize up" << std::endl; } template <class T> Finger_EH<T>::~Finger_EH(void) { // TO-DO } template <class T> void Finger_EH<T>::Halve_Directory() { std::cout << "Begin::Directory_Halving towards " << dir->global_depth << std::endl; auto d = dir->_; Directory<T> *new_dir; #ifdef PMEM Directory<T>::New(&back_dir, pow(2, dir->global_depth - 1), dir->version + 1); new_dir = reinterpret_cast<Directory<T> *>(pmemobj_direct(back_dir)); #else Directory<T>::New(&new_dir, pow(2, dir->global_depth - 1), dir->version + 1); #endif auto _dir = new_dir->_; new_dir->depth_count = 0; auto capacity = pow(2, new_dir->global_depth); bool skip = false; for (int i = 0; i < capacity; ++i) { _dir[i] = d[2 * i]; assert(d[2 * i] == d[2 * i + 1]); if (!skip) { if ((_dir[i]->local_depth == (dir->global_depth - 1)) && (_dir[i]->state != -2)) { if (_dir[i]->state != -1) { new_dir->depth_count += 1; } else { skip = true; } } } else { skip = false; } } #ifdef PMEM Allocator::Persist(new_dir, sizeof(Directory<T>) + sizeof(uint64_t) * capacity); auto reserve_item = Allocator::ReserveItem(); TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(reserve_item, sizeof(*reserve_item)); pmemobj_tx_add_range_direct(&dir, sizeof(dir)); pmemobj_tx_add_range_direct(&back_dir, sizeof(back_dir)); Allocator::Free(reserve_item, dir); dir = new_dir; back_dir = OID_NULL; } TX_ONABORT { std::cout << "TXN fails during halvling directory" << std::endl; } TX_END #else dir = new_dir; #endif std::cout << "End::Directory_Halving towards " << dir->global_depth << std::endl; } template <class T> void Finger_EH<T>::Directory_Doubling(int x, Table<T> *new_b, Table<T> *old_b) { Table<T> **d = dir->_; auto global_depth = dir->global_depth; std::cout << "Directory_Doubling towards " << global_depth + 1 << std::endl; auto capacity = pow(2, global_depth); Directory<T>::New(&back_dir, 2 * capacity, dir->version + 1); Directory<T> *new_sa = reinterpret_cast<Directory<T> *>(pmemobj_direct(back_dir)); auto dd = new_sa->_; for (unsigned i = 0; i < capacity; ++i) { dd[2 * i] = d[i]; dd[2 * i + 1] = d[i]; } dd[2 * x + 1] = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(new_b) | crash_version); new_sa->depth_count = 2; #ifdef PMEM Allocator::Persist(new_sa, sizeof(Directory<T>) + sizeof(uint64_t) * 2 * capacity); auto reserve_item = Allocator::ReserveItem(); ++merge_time; auto old_dir = dir; TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(reserve_item, sizeof(*reserve_item)); pmemobj_tx_add_range_direct(&dir, sizeof(dir)); pmemobj_tx_add_range_direct(&back_dir, sizeof(back_dir)); pmemobj_tx_add_range_direct(&old_b->local_depth, sizeof(old_b->local_depth)); old_b->local_depth += 1; Allocator::Free(reserve_item, dir); /*Swap the memory addr between new directory and old directory*/ dir = new_sa; back_dir = OID_NULL; } TX_ONABORT { std::cout << "TXN fails during doubling directory" << std::endl; } TX_END #else dir = new_sa; #endif } template <class T> void Finger_EH<T>::Directory_Update(Directory<T> *_sa, int x, Table<T> *new_b, Table<T> *old_b) { Table<T> **dir_entry = _sa->_; auto global_depth = _sa->global_depth; unsigned depth_diff = global_depth - new_b->local_depth; if (depth_diff == 0) { if (x % 2 == 0) { TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(&dir_entry[x + 1], sizeof(Table<T> *)); pmemobj_tx_add_range_direct(&old_b->local_depth, sizeof(old_b->local_depth)); dir_entry[x + 1] = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(new_b) | crash_version); old_b->local_depth += 1; } TX_ONABORT { std::cout << "Error for update txn" << std::endl; } TX_END } else { TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(&dir_entry[x], sizeof(Table<T> *)); pmemobj_tx_add_range_direct(&old_b->local_depth, sizeof(old_b->local_depth)); dir_entry[x] = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(new_b) | crash_version); old_b->local_depth += 1; } TX_ONABORT { std::cout << "Error for update txn" << std::endl; } TX_END } #ifdef COUNTING __sync_fetch_and_add(&_sa->depth_count, 2); #endif } else { int chunk_size = pow(2, global_depth - (new_b->local_depth - 1)); x = x - (x % chunk_size); int base = chunk_size / 2; TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(&dir_entry[x + base], sizeof(Table<T> *) * base); pmemobj_tx_add_range_direct(&old_b->local_depth, sizeof(old_b->local_depth)); for (int i = base - 1; i >= 0; --i) { dir_entry[x + base + i] = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(new_b) | crash_version); } old_b->local_depth += 1; } TX_ONABORT { std::cout << "Error for update txn" << std::endl; } TX_END } // printf("Done!directory update for %d\n", x); } template <class T> void Finger_EH<T>::Directory_Merge_Update(Directory<T> *_sa, uint64_t key_hash, Table<T> *left_seg) { Table<T> **dir_entry = _sa->_; auto global_depth = _sa->global_depth; auto x = (key_hash >> (8 * sizeof(key_hash) - global_depth)); uint64_t chunk_size = pow(2, global_depth - (left_seg->local_depth)); auto left = x - (x % chunk_size); auto right = left + chunk_size / 2; for (int i = right; i < right + chunk_size / 2; ++i) { dir_entry[i] = left_seg; Allocator::Persist(&dir_entry[i], sizeof(uint64_t)); } if ((left_seg->local_depth + 1) == global_depth) { SUB(&_sa->depth_count, 2); } } template <class T> void Finger_EH<T>::recoverTable(Table<T> **target_table, size_t key_hash, size_t x, Directory<T> *old_sa) { /*Set the lockBit to ahieve the mutal exclusion of the recover process*/ auto dir_entry = old_sa->_; uint64_t snapshot = (uint64_t)*target_table; Table<T> *target = (Table<T> *)(snapshot & tailMask); if (pmemobj_mutex_trylock(pool_addr, &target->lock_bit) != 0) { return; } target->recoverMetadata(); if (target->state != 0) { target->pattern = key_hash >> (8 * sizeof(key_hash) - target->local_depth); Allocator::Persist(&target->pattern, sizeof(target->pattern)); Table<T> *next_table = (Table<T> *)pmemobj_direct(target->next); if (target->state == -2) { if (next_table->state == -3) { /*Help finish the split operation*/ next_table->recoverMetadata(); target->HelpSplit(next_table); Lock_Directory(); auto x = (key_hash >> (8 * sizeof(key_hash) - dir->global_depth)); if (target->local_depth < dir->global_depth) { Directory_Update(dir, x, next_table, target); } else { Directory_Doubling(x, next_table, target); } Unlock_Directory(); /*release the lock for the target bucket and the new bucket*/ next_table->state = 0; Allocator::Persist(&next_table->state, sizeof(int)); } } else if (target->state == -1) { if (next_table->pattern == ((target->pattern << 1) + 1)) { target->Merge(next_table, true); Allocator::Persist(target, sizeof(Table<T>)); target->next = next_table->next; Allocator::Free(next_table); } } target->state = 0; Allocator::Persist(&target->state, sizeof(int)); } /*Compute for all entries and clear the dirty bit*/ int chunk_size = pow(2, old_sa->global_depth - target->local_depth); x = x - (x % chunk_size); for (int i = x; i < (x + chunk_size); ++i) { dir_entry[i] = reinterpret_cast<Table<T> *>( (reinterpret_cast<uint64_t>(dir_entry[i]) & tailMask) | crash_version); } *target_table = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(target) | crash_version); } template <class T> void Finger_EH<T>::Recovery() { /*scan the directory, set the clear bit, and also set the dirty bit in the * segment to indicate that this segment is clean*/ if (clean) { clean = false; return; } Allocator::EpochRecovery(); lock = 0; /*first check the back_dir log*/ if (!OID_IS_NULL(back_dir)) { pmemobj_free(&back_dir); } auto dir_entry = dir->_; int length = pow(2, dir->global_depth); crash_version = ((crash_version >> 56) + 1) << 56; if (crash_version == 0) { uint64_t set_one = 1UL << 56; for (int i = 0; i < length; ++i) { uint64_t snapshot = (uint64_t)dir_entry[i]; dir_entry[i] = reinterpret_cast<Table<T> *>((snapshot & tailMask) | set_one); } Allocator::Persist(dir_entry, sizeof(uint64_t) * length); } } template <class T> int Finger_EH<T>::Insert(T key, Value_t value, bool is_in_epoch) { if (!is_in_epoch) { auto epoch_guard = Allocator::AquireEpochGuard(); return Insert(key, value); } return Insert(key, value); } template <class T> int Finger_EH<T>::Insert(T key, Value_t value) { uint64_t key_hash; if constexpr (std::is_pointer_v<T>) { key_hash = h(key->key, key->length); } else { key_hash = h(&key, sizeof(key)); } auto meta_hash = ((uint8_t)(key_hash & kMask)); // the last 8 bits RETRY: auto old_sa = dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); auto dir_entry = old_sa->_; Table<T> *target = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(dir_entry[x]) & tailMask); if ((reinterpret_cast<uint64_t>(dir_entry[x]) & headerMask) != crash_version) { recoverTable(&dir_entry[x], key_hash, x, old_sa); goto RETRY; } auto ret = target->Insert(key, value, key_hash, meta_hash, &dir); if(ret == -3){ /*duplicate insert, insertion failure*/ return -1; } if(ret==-2) { goto RETRY; } //等于-1的话 直接在那边就处理了 //ret=-1表示需要进行扩容,我们这里直接避免这个问题! // if (ret == -1) { // if (!target->bucket->try_get_lock()) { // goto RETRY; // } // // /*verify procedure*/ // auto old_sa = dir; // auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); // if (reinterpret_cast<Table<T> *>(reinterpret_cast<uint64_t>(old_sa->_[x]) & // tailMask) != target) /* verify process*/ // { // target->bucket->release_lock(); // goto RETRY; // } // // auto new_b = // target->Split(key_hash); /* also needs the verify..., and we use try // lock for this rather than the spin lock*/ // /* update directory*/ // REINSERT: // old_sa = dir; // dir_entry = old_sa->_; // x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); // if (target->local_depth < old_sa->global_depth) { // if(!try_get_directory_read_lock()){ // goto REINSERT; // } // // if (old_sa->version != dir->version) { // // The directory has changed, thus need retry this update // release_directory_read_lock(); // goto REINSERT; // } // // Directory_Update(old_sa, x, new_b, target); // release_directory_read_lock(); // } else { // Lock_Directory(); // if (old_sa->version != dir->version) { // Unlock_Directory(); // goto REINSERT; // } // Directory_Doubling(x, new_b, target); // Unlock_Directory(); // } // // /*release the lock for the target bucket and the new bucket*/ // new_b->state = 0; // Allocator::Persist(&new_b->state, sizeof(int)); // target->state = 0; // Allocator::Persist(&target->state, sizeof(int)); // // Bucket<T> *curr_bucket; // for (int i = 0; i < kNumBucket; ++i) { // curr_bucket = target->bucket + i; // curr_bucket->release_lock(); // } // curr_bucket = new_b->bucket; // curr_bucket->release_lock(); // goto RETRY; // } else if (ret == -2) { // goto RETRY; // } return 0; } template <class T> Value_t Finger_EH<T>::Get(T key, bool is_in_epoch) { if (!is_in_epoch) { auto epoch_guard = Allocator::AquireEpochGuard(); return Get(key); } uint64_t key_hash; if constexpr (std::is_pointer_v<T>) { key_hash = h(key->key, key->length); } else { key_hash = h(&key, sizeof(key)); } auto meta_hash = ((uint8_t)(key_hash & kMask)); // the last 8 bits RETRY: auto old_sa = dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); auto y = BUCKET_INDEX(key_hash); auto dir_entry = old_sa->_; auto old_entry = dir_entry[x]; Table<T> *target = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(old_entry) & tailMask); if ((reinterpret_cast<uint64_t>(old_entry) & headerMask) != crash_version) { recoverTable(&dir_entry[x], key_hash, x, old_sa); goto RETRY; } Bucket<T> *target_bucket = target->bucket + y; Bucket<T> *neighbor_bucket = target->bucket + ((y + 1) & bucketMask); uint32_t old_version = __atomic_load_n(&target_bucket->version_lock, __ATOMIC_ACQUIRE); uint32_t old_neighbor_version = __atomic_load_n(&neighbor_bucket->version_lock, __ATOMIC_ACQUIRE); if ((old_version & lockSet) || (old_neighbor_version & lockSet)) { goto RETRY; } /*verification procedure*/ old_sa = dir; x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); if (old_sa->_[x] != old_entry) { goto RETRY; } auto ret = target_bucket->check_and_get(meta_hash, key, false); if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } if (ret != NONE) { return ret; } /*no need for verification procedure, we use the version number of * target_bucket to test whether the bucket has ben spliteted*/ ret = neighbor_bucket->check_and_get(meta_hash, key, true); if (neighbor_bucket->test_lock_version_change(old_neighbor_version)) { goto RETRY; } if (ret != NONE) { return ret; } if (target_bucket->test_stash_check()) { auto test_stash = false; if (target_bucket->test_overflow()) { /*this only occur when the bucket has more key-values than 10 that are * overfloed int he shared bucket area, therefore it needs to search in * the extra bucket*/ test_stash = true; } else { /*search in the original bucket*/ int mask = target_bucket->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (target_bucket->finger_array[14 + i] == meta_hash) && (((1 << i) & target_bucket->overflowMember) == 0)) { Bucket<T> *stash = target->bucket + kNumBucket + ((target_bucket->overflowIndex >> (i * 2)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } mask = neighbor_bucket->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (neighbor_bucket->finger_array[14 + i] == meta_hash) && (((1 << i) & neighbor_bucket->overflowMember) != 0)) { Bucket<T> *stash = target->bucket + kNumBucket + ((neighbor_bucket->overflowIndex >> (i * 2)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } goto FINAL; } TEST_STASH: if (test_stash == true) { for (int i = 0; i < stashBucket; ++i) { Bucket<T> *stash = target->bucket + kNumBucket + ((i + (y & stashMask)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } FINAL: return NONE; } template <class T> Value_t Finger_EH<T>::Get(T key) { uint64_t key_hash; if constexpr (std::is_pointer_v<T>) { key_hash = h(key->key, key->length); } else { key_hash = h(&key, sizeof(key)); } auto meta_hash = ((uint8_t)(key_hash & kMask)); // the last 8 bits RETRY: auto old_sa = dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); auto y = BUCKET_INDEX(key_hash); auto dir_entry = old_sa->_; auto old_entry = dir_entry[x]; Table<T> *target = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(old_entry) & tailMask); if ((reinterpret_cast<uint64_t>(old_entry) & headerMask) != crash_version) { recoverTable(&dir_entry[x], key_hash, x, old_sa); goto RETRY; } Bucket<T> *target_bucket = target->bucket + y; Bucket<T> *neighbor_bucket = target->bucket + ((y + 1) & bucketMask); uint32_t old_version = __atomic_load_n(&target_bucket->version_lock, __ATOMIC_ACQUIRE); uint32_t old_neighbor_version = __atomic_load_n(&neighbor_bucket->version_lock, __ATOMIC_ACQUIRE); if ((old_version & lockSet) || (old_neighbor_version & lockSet)) { goto RETRY; } /*verification procedure*/ old_sa = dir; x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); if (old_sa->_[x] != old_entry) { goto RETRY; } auto ret = target_bucket->check_and_get(meta_hash, key, false); if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } if (ret != NONE) { return ret; } ret = neighbor_bucket->check_and_get(meta_hash, key, true); if (neighbor_bucket->test_lock_version_change(old_neighbor_version)) { goto RETRY; } if (ret != NONE) { return ret; } if (target_bucket->test_stash_check()) { auto test_stash = false; if (target_bucket->test_overflow()) { /*this only occur when the bucket has more key-values than 10 that are * overfloed int he shared bucket area, therefore it needs to search in * the extra bucket*/ test_stash = true; } else { /*search in the original bucket*/ int mask = target_bucket->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (target_bucket->finger_array[14 + i] == meta_hash) && (((1 << i) & target_bucket->overflowMember) == 0)) { Bucket<T> *stash = target->bucket + kNumBucket + ((target_bucket->overflowIndex >> (i * 2)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } mask = neighbor_bucket->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (neighbor_bucket->finger_array[14 + i] == meta_hash) && (((1 << i) & neighbor_bucket->overflowMember) != 0)) { Bucket<T> *stash = target->bucket + kNumBucket + ((neighbor_bucket->overflowIndex >> (i * 2)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } goto FINAL; } TEST_STASH: if (test_stash == true) { for (int i = 0; i < stashBucket; ++i) { Bucket<T> *stash = target->bucket + kNumBucket + ((i + (y & stashMask)) & stashMask); auto ret = stash->check_and_get(meta_hash, key, false); if (ret != NONE) { if (target_bucket->test_lock_version_change(old_version)) { goto RETRY; } return ret; } } } } FINAL: return NONE; } template <class T> void Finger_EH<T>::TryMerge(size_t key_hash) { /*Compute the left segment and right segment*/ do { auto old_dir = dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_dir->global_depth)); auto target = old_dir->_[x]; int chunk_size = pow(2, old_dir->global_depth - (target->local_depth - 1)); assert(chunk_size >= 2); int left = x - (x % chunk_size); int right = left + chunk_size / 2; auto left_seg = old_dir->_[left]; auto right_seg = old_dir->_[right]; if ((reinterpret_cast<uint64_t>(left_seg) & headerMask) != crash_version) { recoverTable(&old_dir->_[left], key_hash, left, old_dir); continue; } if ((reinterpret_cast<uint64_t>(right_seg) & headerMask) != crash_version) { recoverTable(&old_dir->_[right], key_hash, right, old_dir); continue; } size_t _pattern0 = ((key_hash >> (8 * sizeof(key_hash) - target->local_depth + 1)) << 1); size_t _pattern1 = ((key_hash >> (8 * sizeof(key_hash) - target->local_depth + 1)) << 1) + 1; /* Get the lock from left to right*/ if (left_seg->Acquire_and_verify(_pattern0)) { if (right_seg->Acquire_and_verify(_pattern1)) { if (left_seg->local_depth != right_seg->local_depth) { left_seg->bucket->release_lock(); right_seg->bucket->release_lock(); return; } if ((left_seg->number != 0) && (right_seg->number != 0)) { left_seg->bucket->release_lock(); right_seg->bucket->release_lock(); return; } left_seg->Acquire_remaining_locks(); right_seg->Acquire_remaining_locks(); /*First improve the local depth, */ left_seg->local_depth = left_seg->local_depth - 1; Allocator::Persist(&left_seg->local_depth, sizeof(uint64_t)); left_seg->state = -1; Allocator::Persist(&left_seg->state, sizeof(int)); right_seg->state = -1; Allocator::Persist(&right_seg->state, sizeof(int)); REINSERT: old_dir = dir; /*Update the directory from left to right*/ while (Test_Directory_Lock_Set()) { asm("nop"); } /*start the merge operation*/ Directory_Merge_Update(old_dir, key_hash, left_seg); if (Test_Directory_Lock_Set() || old_dir->version != dir->version) { goto REINSERT; } if (right_seg->number != 0) { left_seg->Merge(right_seg); } auto reserve_item = Allocator::ReserveItem(); TX_BEGIN(pool_addr) { pmemobj_tx_add_range_direct(reserve_item, sizeof(*reserve_item)); pmemobj_tx_add_range_direct(&left_seg->next, sizeof(left_seg->next)); Allocator::Free(reserve_item, right_seg); left_seg->next = right_seg->next; } TX_ONABORT { std::cout << "Error for merge txn" << std::endl; } TX_END left_seg->pattern = left_seg->pattern >> 1; Allocator::Persist(&left_seg->pattern, sizeof(uint64_t)); left_seg->state = 0; Allocator::Persist(&left_seg->state, sizeof(int)); right_seg->Release_all_locks(); left_seg->Release_all_locks(); /*Try to halve directory?*/ if ((dir->depth_count == 0) && (dir->global_depth > 2)) { Lock_Directory(); if (dir->depth_count == 0) { Halve_Directory(); } Unlock_Directory(); } } else { left_seg->bucket->release_lock(); if (old_dir == dir) { return; } } } else { if (old_dir == dir) { /* If the directory itself does not change, directly return*/ return; } } } while (true); } template <class T> bool Finger_EH<T>::Delete(T key, bool is_in_epoch) { if (!is_in_epoch) { auto epoch_guard = Allocator::AquireEpochGuard(); return Delete(key); } return Delete(key); } /*By default, the merge operation is disabled*/ template <class T> bool Finger_EH<T>::Delete(T key) { /*Basic delete operation and merge operation*/ uint64_t key_hash; if constexpr (std::is_pointer_v<T>) { key_hash = h(key->key, key->length); } else { key_hash = h(&key, sizeof(key)); } auto meta_hash = ((uint8_t)(key_hash & kMask)); // the last 8 bits RETRY: auto old_sa = dir; auto x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); auto dir_entry = old_sa->_; Table<T> *target_table = reinterpret_cast<Table<T> *>( reinterpret_cast<uint64_t>(dir_entry[x]) & tailMask); if ((reinterpret_cast<uint64_t>(dir_entry[x]) & headerMask) != crash_version) { recoverTable(&dir_entry[x], key_hash, x, old_sa); goto RETRY; } /*we need to first do the locking and then do the verify*/ auto y = BUCKET_INDEX(key_hash); Bucket<T> *target = target_table->bucket + y; Bucket<T> *neighbor = target_table->bucket + ((y + 1) & bucketMask); target->get_lock(); if (!neighbor->try_get_lock()) { target->release_lock(); goto RETRY; } old_sa = dir; x = (key_hash >> (8 * sizeof(key_hash) - old_sa->global_depth)); if (reinterpret_cast<Table<T> *>(reinterpret_cast<uint64_t>(old_sa->_[x]) & tailMask) != target_table) { target->release_lock(); neighbor->release_lock(); goto RETRY; } auto ret = target->Delete(key, meta_hash, false); if (ret == 0) { #ifdef COUNTING auto num = SUB(&target_table->number, 1); #endif target->release_lock(); #ifdef PMEM Allocator::Persist(&target->bitmap, sizeof(target->bitmap)); #endif neighbor->release_lock(); #ifdef COUNTING if (num == 0) { TryMerge(key_hash); } #endif return true; } ret = neighbor->Delete(key, meta_hash, true); if (ret == 0) { #ifdef COUNTING auto num = SUB(&target_table->number, 1); #endif neighbor->release_lock(); #ifdef PMEM Allocator::Persist(&neighbor->bitmap, sizeof(neighbor->bitmap)); #endif target->release_lock(); #ifdef COUNTING if (num == 0) { TryMerge(key_hash); } #endif return true; } if (target->test_stash_check()) { auto test_stash = false; if (target->test_overflow()) { /*this only occur when the bucket has more key-values than 10 that are * overfloed int he shared bucket area, therefore it needs to search in * the extra bucket*/ test_stash = true; } else { /*search in the original bucket*/ int mask = target->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (target->finger_array[14 + i] == meta_hash) && (((1 << i) & target->overflowMember) == 0)) { test_stash = true; goto TEST_STASH; } } } mask = neighbor->overflowBitmap & overflowBitmapMask; if (mask != 0) { for (int i = 0; i < 4; ++i) { if (CHECK_BIT(mask, i) && (neighbor->finger_array[14 + i] == meta_hash) && (((1 << i) & neighbor->overflowMember) != 0)) { test_stash = true; break; } } } } TEST_STASH: if (test_stash == true) { Bucket<T> *stash = target_table->bucket + kNumBucket; stash->get_lock(); for (int i = 0; i < stashBucket; ++i) { int index = ((i + (y & stashMask)) & stashMask); Bucket<T> *curr_stash = target_table->bucket + kNumBucket + index; auto ret = curr_stash->Delete(key, meta_hash, false); if (ret == 0) { /*need to unset indicator in original bucket*/ stash->release_lock(); #ifdef PMEM Allocator::Persist(&curr_stash->bitmap, sizeof(curr_stash->bitmap)); #endif auto bucket_ix = BUCKET_INDEX(key_hash); auto org_bucket = target_table->bucket + bucket_ix; assert(org_bucket == target); target->unset_indicator(meta_hash, neighbor, key, index); #ifdef COUNTING auto num = SUB(&target_table->number, 1); #endif neighbor->release_lock(); target->release_lock(); #ifdef COUNTING if (num == 0) { TryMerge(key_hash); } #endif return true; } } stash->release_lock(); } } neighbor->release_lock(); target->release_lock(); return false; } /*DEBUG FUNCTION: search the position of the key in this table and print * correspongdign informantion in this table, to test whether it is correct*/ template <class T> int Finger_EH<T>::FindAnyway(T key) { uint64_t key_hash; if constexpr (std::is_pointer_v<T>) { // key_hash = h(key, (reinterpret_cast<string_key *>(key))->length); key_hash = h(key->key, key->length); } else { key_hash = h(&key, sizeof(key)); } auto meta_hash = ((uint8_t)(key_hash & kMask)); auto x = (key_hash >> (8 * sizeof(key_hash) - dir->global_depth)); size_t _count = 0; size_t seg_count = 0; Directory<T> *seg = dir; Table<T> **dir_entry = seg->_; Table<T> *ss; auto global_depth = seg->global_depth; size_t depth_diff; int capacity = pow(2, global_depth); for (int i = 0; i < capacity;) { ss = dir_entry[i]; Bucket<T> *curr_bucket; for (int j = 0; j < kNumBucket; ++j) { curr_bucket = ss->bucket + j; auto ret = curr_bucket->check_and_get(meta_hash, key, false); if (ret != NONE) { printf("successfully find in the normal bucket with false\n"); printf( "the segment is %d, the bucket is %d, the local depth = %lld, the " "pattern is %lld\n", i, j, ss->local_depth, ss->pattern); return 0; } ret = curr_bucket->check_and_get(meta_hash, key, true); if (ret != NONE) { printf("successfully find in the normal bucket with true\n"); printf( "the segment is %d, the bucket is %d, the local depth is %lld, the " "pattern is %lld\n", i, j, ss->local_depth, ss->pattern); return 0; } } for (int i = 0; i < stashBucket; ++i) { curr_bucket = ss->bucket + kNumBucket + i; auto ret = curr_bucket->check_and_get(meta_hash, key, false); if (ret != NONE) { printf("successfully find in the stash bucket\n"); auto bucket_ix = BUCKET_INDEX(key_hash); auto org_bucket = ss->bucket + bucket_ix; auto neighbor_bucket = ss->bucket + ((bucket_ix + 1) & bucketMask); printf("the segment number is %d, the bucket_ix is %d\n", x, bucket_ix); printf("the image of org_bucket\n"); int mask = org_bucket->overflowBitmap & overflowBitmapMask; for (int j = 0; j < 4; ++j) { printf( "the hash is %d, the pos bit is %d, the alloc bit is %d, the " "stash bucket info is %d, the real stash bucket info is %d\n", org_bucket->finger_array[14 + j], (org_bucket->overflowMember >> (j)) & 1, (org_bucket->overflowBitmap >> j) & 1, (org_bucket->overflowIndex >> (j * 2)) & stashMask, i); } printf("the image of the neighbor bucket\n"); printf("the stash check is %d\n", neighbor_bucket->test_stash_check()); mask = neighbor_bucket->overflowBitmap & overflowBitmapMask; for (int j = 0; j < 4; ++j) { printf( "the hash is %d, the pos bit is %d, the alloc bit is %d, the " "stash bucket info is %d, the real stash bucket info is %d\n", neighbor_bucket->finger_array[14 + j], (neighbor_bucket->overflowMember >> (j)) & 1, (neighbor_bucket->overflowBitmap >> j) & 1, (neighbor_bucket->overflowIndex >> (j * 2)) & stashMask, i); } if (org_bucket->test_overflow()) { printf("the org bucket has overflowed\n"); } return 0; } } depth_diff = global_depth - ss->local_depth; _count += ss->number; seg_count++; i += pow(2, depth_diff); } return -1; } #undef BUCKET_INDEX #undef GET_COUNT #undef GET_BITMAP #undef GET_MEMBER #undef GET_INVERSE_MEMBER } // namespace extendible
[ "379644606@qq.com" ]
379644606@qq.com
2b6359fee366c925c1c92132e422d7d2a0a6cc39
899d501c231c5ee2f5f496cce8e839a66ac3391c
/src/relay/transforms/device_aware_visitors.h
3f4c5c24481e72c65b25608682dff24d92e1d91a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "Zlib", "Unlicense", "BSD-3-Clause", "MIT", "BSD-2-Clause" ]
permissive
xintin/tvm
45376a741581ebd07a36030cf0d180c8235543b2
4087e72b657eae484bb647cbd8ef86b9acf11748
refs/heads/main
2021-12-02T20:46:48.445562
2021-10-30T04:50:27
2021-10-30T04:50:27
212,755,770
1
0
Apache-2.0
2019-10-04T07:07:29
2019-10-04T07:07:25
null
UTF-8
C++
false
false
12,723
h
/* * 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. */ /*! * \file src/relay/transforms/device_aware_visitors.h * \brief Visitors which track the device for the current Relay expression and Relay Vars. */ #ifndef TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_ #define TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_ #include <dlpack/dlpack.h> #include <tvm/relay/expr.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/function.h> #include <unordered_map> #include <utility> #include <vector> #include "../op/annotation/annotation.h" namespace tvm { namespace relay { namespace transform { /*! * \brief Helper class for expression transformers which need to keep track of the device * holding the results of expressions. This is recovered from function attributes and "on_device" * CallNodes added by the PlanDevices pass. * * \sa \p DeviceAwareExpr{Functor,Visitor,Mutator}. */ class LexicalOnDeviceMixin { protected: explicit LexicalOnDeviceMixin(const Optional<IRModule>& maybe_mod); /*! * \brief Returns the device type on which the result of \p expr should/will be stored, assuming * Push/Pop DeviceType/BoundVar have been correctly called. May return \p kInvalidDeviceType if * the device planning pass has not been run. */ DLDeviceType GetInScopeDeviceType(const Expr& expr) const; /*! \brief Indicate a function body is being entered. */ void EnterFunctionBody(); /*! \brief Indicate a function body has been processed. */ void ExitFunctionBody(); /*! \brief Push a device type onto the lexical device stack. Ignore if \p kInvalidDeviceType. */ void PushDeviceType(DLDeviceType device_type); /*! \brief Pop a device type from the lexical device stack. Ignore if stack is empty. */ void PopDeviceType(); /*! \brief Remember that \p var will be stored on \p device_type. Ignore if \p kInvalidDeviceType. * * CAUTION: Despite the name we don't support re-entering the same function body. */ void PushBoundVar(Var var, DLDeviceType device_type); /*! \brief Remove the binding for \p var to it's device type. Ignore if var is not bound. */ void PopBoundVar(const Var& var); /*! * \brief Returns the number of function definitions wrapping the currently visited expression. */ int function_nesting() const { return function_nesting_; } private: /*! * \brief The number of function bodies entered. Since many transforms need to distinguish global * functions from local functions this supports the mixin's \p is_global() helper method. */ int function_nesting_ = 0; /*! * \brief The stack of lexically enclosing "on_device" devices types, from outermost to innermost. * When visiting an expression other than a variable we can assume the expression's result is to * be stored on device_type_.back(). */ std::vector<DLDeviceType> expr_device_types_; /*! * \brief A map from in-scope local variables to their device types. We may assume the variable is * only ever bound to a value stored on this device at runtime. * * Note: We're playing it safe and keying by object refs here just in case the Relay expression * being rewritten has no module or other global to keep it alive. */ std::unordered_map<Var, DLDeviceType, runtime::ObjectPtrHash, runtime::ObjectPtrEqual> var_device_types_; /*! * \brief A map from global variables to their device types, ie the "result_device_type" of the * function they are bound to in the module we are working on. We calculate this explicitly so * that we don't neeed to hold on to any module, which is often in the process of being rewritten. */ std::unordered_map<GlobalVar, DLDeviceType, runtime::ObjectPtrHash, runtime::ObjectPtrEqual> global_var_device_types_; }; template <typename FType> class DeviceAwareExprFunctor; /*! * \brief ExprFunctor which tracks devices. We only support 'visitor' style implementation * with no additional arguments, thus this is equivalent to \p DeviceAwareExprVisitor without * any memoization. */ template <> class DeviceAwareExprFunctor<void(const Expr& n)> : public ExprFunctor<void(const Expr& n)>, public LexicalOnDeviceMixin { private: using TSuper = ExprFunctor<void(const Expr& n)>; public: explicit DeviceAwareExprFunctor(const Optional<IRModule>& maybe_mod) : LexicalOnDeviceMixin(maybe_mod) {} void VisitExpr_(const FunctionNode* function_node) { if (function_node->HasNonzeroAttr(attr::kPrimitive)) { // No tracking inside primitive functions. return DeviceAwareVisitExpr_(function_node); } else { // Function parameters come into scope. for (size_t i = 0; i < function_node->params.size(); ++i) { PushBoundVar(function_node->params[i], GetFunctionParamDeviceType(function_node, i)); } // Entering scope of function body. PushDeviceType(GetFunctionResultDeviceType(function_node)); EnterFunctionBody(); DeviceAwareVisitExpr_(function_node); // Leaving scope of function body. ExitFunctionBody(); PopDeviceType(); // Function parameters go out of scope. for (size_t i = 0; i < function_node->params.size(); ++i) { PopBoundVar(function_node->params[i]); } } } void VisitExpr_(const LetNode* let_node) { PreVisitLetBlock_(let_node); std::vector<const LetNode*> bindings; Expr expr = GetRef<Expr>(let_node); while (const auto* inner_let_node = expr.as<LetNode>()) { // Let-bound var (in pre visited version) goes into scope. // (We'll just assume this is a letrec.) PushBoundVar(inner_let_node->var, GetInScopeDeviceType(inner_let_node->value)); PreVisitLetBinding_(inner_let_node->var, inner_let_node->value); bindings.emplace_back(inner_let_node); expr = inner_let_node->body; } VisitExpr(expr); for (auto itr = bindings.rbegin(); itr != bindings.rend(); ++itr) { // Let-bound var goes out of scope. const LetNode* visited_let_node = *itr; PopBoundVar(visited_let_node->var); PostVisitLet_(visited_let_node); } PostVisitLetBlock_(let_node); } void VisitExpr_(const CallNode* call_node) { auto props = GetOnDeviceProps(call_node); if (props.body.defined() && props.is_fixed) { // Entering lexical scope of fixed "on_device" call. PushDeviceType(props.device_type); VisitExpr(props.body); // Leaving lexical scope of "on_device" call. PopDeviceType(); } else { DeviceAwareVisitExpr_(call_node); } } /*! * \brief These are as for VisitExpr_. Devices for expressions and function parameters will be * tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For * functions the function_nesting count will already include that of \p function_node. */ virtual void DeviceAwareVisitExpr_(const FunctionNode* function_node) { return TSuper::VisitExpr_(function_node); } virtual void DeviceAwareVisitExpr_(const CallNode* call_node) { return TSuper::VisitExpr_(call_node); } /*! * \brief Visit the first let in a chain of let expressions before any let bindings or final * body has been visited. Default implementation is a no-op. */ virtual void PreVisitLetBlock_(const LetNode* let_node) { /* no-op */ } /*! * \brief Visit a let-bound expression before the let body has been visited. Devices for the * let-bound variable will be tracked automatically. Default implementation just visits var and * value. */ virtual void PreVisitLetBinding_(const Var& var, const Expr& value) { VisitExpr(var); VisitExpr(value); } /*! * \brief Visit a let expression after the let-bound value and body have been visited. * Default implementation is a no-op. */ virtual void PostVisitLet_(const LetNode* let_node) { /* no-op */ } /*! * \brief Visit the first let in a chain of let expressions after it has been visited. * Default implementation is a no-op. */ virtual void PostVisitLetBlock_(const LetNode* let_node) {} }; /*! \brief ExprVisitor which tracks devices. */ class DeviceAwareExprVisitor : public ExprVisitor, public LexicalOnDeviceMixin { public: explicit DeviceAwareExprVisitor(const Optional<IRModule>& maybe_mod) : LexicalOnDeviceMixin(maybe_mod) {} using ExprVisitor::VisitExpr_; void VisitExpr_(const FunctionNode* function_node) final; void VisitExpr_(const LetNode* let_node) final; void VisitExpr_(const CallNode* call_node) final; /*! * \brief These are as for VisitExpr_. Devices for expressions and function parameters will be * tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For * functions the function_nesting count will already include that of \p function_node. */ virtual void DeviceAwareVisitExpr_(const FunctionNode* function_node); virtual void DeviceAwareVisitExpr_(const CallNode* call_node); /*! * \brief Visit the first let in a chain of let expressions before any let bindings or final * body has been visited. Default implementation is a no-op. */ virtual void PreVisitLetBlock_(const LetNode* let_node); /*! * \brief Visit a let-bound expression before the let body has been visited. Devices for the * let-bound variable will be tracked automatically. Default implementation just visits var and * value. */ virtual void PreVisitLetBinding_(const Var& var, const Expr& value); /*! * \brief Visit a let expression after the let-bound value and body have been visited. * Default implementation is a no-op. */ virtual void PostVisitLet_(const LetNode* let_node); /*! * \brief Visit the first let in a chain of let expressions after it has been visited. * Default implementation is a no-op. */ virtual void PostVisitLetBlock_(const LetNode* let_node); }; /*! \brief ExprMutator which tracks devices. */ class DeviceAwareExprMutator : public ExprMutator, public LexicalOnDeviceMixin { public: explicit DeviceAwareExprMutator(const Optional<IRModule>& maybe_mod) : LexicalOnDeviceMixin(maybe_mod) {} Expr VisitExpr_(const FunctionNode* function_node) final; Expr VisitExpr_(const LetNode* let_node) final; Expr VisitExpr_(const CallNode* call_node) final; /*! * \brief These are as for VisitExpr_. Devices for expressions and function parameters will be * tracked automatically. Default implementation defers to ExprMutator::VisitExpr_. For * functions the function_nesting count will already include that of \p function_node. */ virtual Expr DeviceAwareVisitExpr_(const FunctionNode* function_node); virtual Expr DeviceAwareVisitExpr_(const CallNode* call_node); /*! * \brief Visit the first let in a chain of let expressions before any let bindings or final * body has been visited. Default implementation is a no-op. */ virtual void PreVisitLetBlock_(const LetNode* let_node); /*! * \brief Visit a let-bound expression before the let body has been visited. Devices for the * let-bound variable will be tracked automatically. Default implementation just visits var and * value. */ virtual std::pair<Var, Expr> PreVisitLetBinding_(const Var& var, const Expr& value); /*! * \brief Visit a let expression after the let-bound value and body have been visited. * Default implementation just returns a reference to the post-visited node. */ virtual Expr PostVisitLet_(const LetNode* pre_let_node, const LetNode* post_let_node); /*! * \brief Visit the first let in a chain of let expressions after it has been visited. * Default implementation returns reference to let node. */ virtual Expr PostVisitLetBlock_(const LetNode* pre_let_node, const LetNode* post_let_node); }; } // namespace transform } // namespace relay } // namespace tvm #endif // TVM_RELAY_TRANSFORMS_DEVICE_AWARE_VISITORS_H_
[ "noreply@github.com" ]
xintin.noreply@github.com
702da32cddc7009aa206b8469ead69dda12e33d8
958b3bcdcf8f9de013323bdc35ba419cffa246cb
/examples/OpenHAK_Firmware/BLE_Stuff.ino
ed6276319cb8468321413514f3350b3777c0ee6f
[ "MIT" ]
permissive
OpenHAK/OpenHAK_Playground
b607d53b411ed9715ffe5d5f2129885ecabb7154
de2a707e8e83a3996536f431769df9afe4dd1e56
refs/heads/master
2022-03-22T23:46:24.763336
2019-12-01T00:38:12
2019-12-01T00:38:12
198,309,889
1
2
null
null
null
null
UTF-8
C++
false
false
2,337
ino
void SimbleeBLE_onConnect() { bConnected = true; analogWrite(BLU, 100); Lazarus.ariseLazarus(); // Tell Lazarus to arise. #ifdef SERIAL_LOG Serial.println("ble connected"); #endif delay(100); analogWrite(BLU,255); } void SimbleeBLE_onDisconnect() { bConnected = false; modeNum = 2; analogWrite(GRN,100); #ifdef SERIAL_LOG Serial.println("ble disconnected"); #endif delay(100); analogWrite(GRN,255); } void SimbleeBLE_onReceive(char *data, int len) { Lazarus.ariseLazarus(); #ifdef SERIAL_LOG Serial.print("Received data over BLE "); Serial.print(len); Serial.println(" bytes"); #endif // the first byte says what mode to be in modeNum = data[0]; switch (modeNum){ case 10: if (len >= 5) { unsigned long thyme = (data[1] << 24) | (data[2] << 16) | (data[3] << 8) | data[4]; setTime(thyme); //timeZoneOffset = 0xE2; //(data[5]); // Phone sends UTC offset timeZoneOffset = (data[5]); minutesOffset = timeZoneOffset; minutesOffset *= 10; TimeChangeRule localCR = {"TCR", First, Sun, Nov, 2, minutesOffset}; Timezone localZone(localCR, localCR); utc = now(); //current time from the Time Library localTime = localZone.toLocal(utc); setTime(utc); // modeNum = 0; } break; case 3: if(currentSample < 1){ // if we are just starting out modeNum = 0; } break; default: break; } } void transferSamples() { #ifdef SERIAL_LOG Serial.println("Starting History transfer"); #endif for (int i = 0; i < currentSample; i++) { if (bConnected) { sendSamples(samples[i]); } } modeNum = 2; // WHAT TO DO HERE? } void sendSamples(Payload sample) { char data[20]; data[0] = (sample.epoch >> 24) & 0xFF; data[1] = (sample.epoch >> 16) & 0xFF; data[2] = (sample.epoch >> 8) & 0xFF; data[3] = sample.epoch & 0xFF; data[4] = (sample.steps >> 8) & 0xFF; data[5] = sample.steps & 0xFF; data[6] = sample.hr; data[7] = sample.hrDev; data[8] = sample.battery; data[9] = sample.aux1; data[10] = sample.aux2; data[11] = sample.aux3; // send is queued (the ble stack delays send to the start of the next tx window) while (!SimbleeBLE.send(data, 12)) ; // all tx buffers in use (can't send - try again later) }
[ "biomurph@gmail.com" ]
biomurph@gmail.com
ec41abfa0eeef9447edd1bc4a600f98e67c34b10
5d2445f14a9a3505ffe5700e484982f420863886
/DirectX_Frame/DirectX_Frame/cGrid.cpp
620c6ae2817f7c8e487cb3694dc1f128bfe9b6f9
[]
no_license
MinHyukKim/Mojak3
ee705c02d5261aa0f35a9f2a09cfb68ad92ec4b5
e6c9090256fb6b25a1880fe9854a069ee45896b6
refs/heads/master
2021-01-21T12:16:39.762585
2018-11-02T07:27:53
2018-11-02T07:27:53
102,059,162
1
0
null
null
null
null
UTF-8
C++
false
false
3,032
cpp
#include "StdAfx.h" #include "cGrid.h" #include "cPyramid.h" cGrid::cGrid(void) { } cGrid::~cGrid(void) { for each(auto p in m_vecPyramid) { SAFE_RELEASE(p); } } void cGrid::Setup( int nNumLine, float fInterval ) { int nHalfNumLine = nNumLine / 2; float fMax = fabs(nHalfNumLine * fInterval); D3DCOLOR c = D3DCOLOR_XRGB(255, 255, 255); for (int i = 1; i <= nHalfNumLine; ++i) { if( i % 5 == 0 ) c = D3DCOLOR_XRGB(255, 255, 255); else c = D3DCOLOR_XRGB(155, 155, 155); m_vecVertex.reserve(16); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3(-fMax, 0, i * fInterval), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( fMax, 0, i * fInterval), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3(-fMax, 0, -i * fInterval), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( fMax, 0, -i * fInterval), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( i * fInterval, 0, -fMax), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( i * fInterval, 0, fMax), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3(-i * fInterval, 0, -fMax), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3(-i * fInterval, 0, fMax), c)); } c = D3DCOLOR_XRGB(255, 0, 0); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3(-fMax, 0, 0), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( fMax, 0, 0), c)); c = D3DCOLOR_XRGB(0, 255, 0); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( 0,-fMax, 0), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( 0, fMax, 0), c)); c = D3DCOLOR_XRGB(0, 0, 255); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( 0, 0,-fMax), c)); m_vecVertex.push_back(ST_PC_VERTEX(D3DXVECTOR3( 0, 0, fMax), c)); D3DXMATRIX matS, matR, mat; D3DXMatrixScaling(&matS, 0.1f, 2.0f, 0.1f); cPyramid* pPyramid = cPyramid::Create(); D3DXMatrixRotationZ(&matR, D3DX_PI / 2.0f); mat = matS * matR; pPyramid->Setup(&mat, D3DCOLOR_XRGB(255, 0, 0)); m_vecPyramid.push_back(pPyramid); pPyramid = cPyramid::Create(); D3DXMatrixRotationZ(&matR, D3DX_PI); mat = matS * matR; pPyramid->Setup(&mat, D3DCOLOR_XRGB(0, 255, 0)); m_vecPyramid.push_back(pPyramid); pPyramid = cPyramid::Create(); D3DXMatrixRotationX(&matR, -D3DX_PI / 2.0f); mat = matS * matR; pPyramid->Setup(&mat, D3DCOLOR_XRGB(0, 0, 255)); m_vecPyramid.push_back(pPyramid); } void cGrid::Render() { DWORD dwPrev; g_pD3DDevice->GetRenderState(D3DRS_LIGHTING, &dwPrev); g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, false); D3DXMATRIX matWorld; D3DXMatrixIdentity(&matWorld); g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); g_pD3DDevice->SetTexture(0, NULL); g_pD3DDevice->SetFVF(ST_PC_VERTEX::FVF); g_pD3DDevice->DrawPrimitiveUP(D3DPT_LINELIST, m_vecVertex.size() / 2, &m_vecVertex[0], sizeof(ST_PC_VERTEX)); g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, true); for each(auto p in m_vecPyramid) { p->Render(); } g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, (bool)dwPrev); } cGrid* cGrid::Create(void) { cGrid* newClass = new cGrid; newClass->AddRef(); return newClass; }
[ "rlaalsgur05@naver.com" ]
rlaalsgur05@naver.com
fc4eb71a5586ca1723b1110bdb2975ea859d7ab7
145a8f3ffd94b119425899a4bc318ea41bf702c6
/src/MRT.cpp
85b2db15c5bdb1693c9972ba0b17201d64490ecd
[]
no_license
andrewthomasjones/RRMM
68dfb4f45bcf3262ab4299775cfaea2af7d6abe4
f641f3d89ef98dbc2f077120561c16ae8f876511
refs/heads/master
2021-07-25T22:25:23.179778
2017-11-08T07:04:14
2017-11-08T07:04:14
108,078,764
0
0
null
null
null
null
UTF-8
C++
false
false
8,531
cpp
// [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(BH)]] // [[Rcpp::plugins(cpp11)]] //'@importFrom Rcpp sourceCpp //'@useDynLib MRT #include "RcppArmadillo.h" //BOOST #include "boost/math/distributions/students_t.hpp" #include "boost/program_options.hpp" #include "boost/math/tools/roots.hpp" #include "boost/math/special_functions/digamma.hpp" #include <algorithm> using namespace Rcpp; Rcpp::NumericVector export_vec(arma::vec y) { Rcpp::NumericVector tmp = Rcpp::wrap(y); tmp.attr("dim") = R_NilValue; return tmp; } template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } double phi(double d){ double c = 1.345; double temp = 1.0; if(std::abs(d) >= c) { temp= c/std::abs(d); } return temp; } double phi2(double d){ double c = 4.685; double temp = 0.0; if(std::abs(d) < c) { temp = std::pow(1-std::pow(d/c,2.0),2.0); } return temp; } double phi3(double d){ double c = 3; double temp = 0.0; if(std::abs(d) < c) { temp = std::pow(1-std::pow(d/c,2.0),1.0); } return temp; } // [[Rcpp::export]] double mahalanobis_c(double y, double mu, double sigma) { double delta = (y-mu)*(1./sigma)*(y-mu); return delta; } // [[Rcpp::export]] double mahalanobis_HD(arma::vec y, arma::vec mu, arma::mat sigma) { arma::vec d = y-mu; double delta = std::sqrt(as_scalar(d.t()*pinv(sigma)*d)); return delta; } // [[Rcpp::export]] double norm_HD(arma::vec y, arma::vec mu, arma::mat sigma) { int dim = y.n_elem; double f1 = std::sqrt(std::pow(arma::datum::pi*2.0, dim)*det(sigma)); double f2 = std::exp(-0.5*mahalanobis_HD(y, mu, sigma)); double f = f1/f2; return f; } // [[Rcpp::export]] double norm_c(double y, double mu, double sigma) { double f = (1/(std::sqrt(arma::datum::pi*2.0*sigma))) * std::exp(-0.5*mahalanobis_c(y,mu,std::sqrt(sigma))); // return(f <= std::pow(1, -100)) ? 0.0 : f; return f; } arma::mat start_kmeans(arma::vec dat, int g){ arma::mat params(g,3, arma::fill::zeros); arma::vec weights(1, arma::fill::ones); arma::uvec alloc(dat.n_elem, arma::fill::zeros); arma::uvec cluster_sizes(g, arma::fill::zeros); Rcpp::Environment base("package:stats"); Rcpp::Function kmeans = base["kmeans"]; Rcpp::List res = kmeans(Rcpp::_["x"] = dat, Rcpp::_["centers"] = g); arma::vec tmp_mu = res["centers"]; params.col(1) = tmp_mu; for(int i=0; i<dat.n_elem;i++){ arma::vec temp = abs(params.col(1)- dat(i)); alloc.at(i) = arma::index_min(temp); } //cluster size and variance for(int i =0; i<g;i++){ arma::uvec tmp1 = find(alloc == i); cluster_sizes.at(i) = tmp1.n_elem; params(i,2) = sum(pow(dat(tmp1)-params(i,1),2.0))/dat.n_elem; } params.col(0) = arma::conv_to< arma::vec >::from(cluster_sizes)/dat.n_elem; return(params); } arma::mat start_random(arma::vec dat, int g){ arma::mat params(g,3, arma::fill::zeros); arma::vec weights(1, arma::fill::ones); arma::uvec alloc(dat.n_elem, arma::fill::zeros); arma::uvec cluster_sizes(g, arma::fill::zeros); return(params); } arma::mat start_kmeans2(arma::mat dat, int g){ arma::mat params(g,3, arma::fill::zeros); arma::vec weights(1, arma::fill::ones); arma::uvec alloc(dat.n_elem, arma::fill::zeros); arma::uvec cluster_sizes(g, arma::fill::zeros); Rcpp::Environment base("package:stats"); Rcpp::Function kmeans = base["kmeans"]; Rcpp::List res = kmeans(Rcpp::_["x"] = dat, Rcpp::_["centers"] = g); arma::vec tmp_mu = res["centers"]; params.col(1) = tmp_mu; for(int i=0; i<dat.n_elem;i++){ arma::vec temp = abs(params.col(1)- dat(i)); alloc.at(i) = arma::index_min(temp); } //cluster size and variance for(int i =0; i<g;i++){ arma::uvec tmp1 = find(alloc == i); cluster_sizes.at(i) = tmp1.n_elem; params(i,2) = sum(pow(dat(tmp1)-params(i,1),2.0))/dat.n_elem; } params.col(0) = arma::conv_to< arma::vec >::from(cluster_sizes)/dat.n_elem; return(params); } arma::mat start_random2(arma::vec dat, int g){ arma::mat params(g,3, arma::fill::zeros); arma::vec weights(1, arma::fill::ones); arma::uvec alloc(dat.n_elem, arma::fill::zeros); arma::uvec cluster_sizes(g, arma::fill::zeros); return(params); } //'@export // [[Rcpp::export]] Rcpp::List MMEst(const arma::mat& y, int g = 1, double tol = 0.00001, int max_iter = 100) { int dim = y.n_cols; Rcpp::List temp_list; if(dim == 1){ int n = y.n_elem; arma::mat d = arma::zeros(g,n); arma::mat u = arma::zeros(g,n); arma::mat w = arma::ones(g,n); arma::mat tau = arma::zeros(g,n); //allocate double arma::vec mu = arma::zeros(g); arma::vec sigma = arma::zeros(g); arma::vec pi = arma::zeros(g); double diff = 1.0; arma::mat init_mat = arma::zeros(g,3); init_mat = start_kmeans(y,g); pi = init_mat.col(0); mu = init_mat.col(1); sigma = init_mat.col(2); //allocated int int k =0; //iterative fit for M-est while(diff>tol & k <max_iter ){ for(int i=0;i<g;i++){ double mu_i =mu(i); double sigma_i = sigma(i); arma::rowvec tmp = arma::zeros(1,n); std::transform(y.begin(), y.end(), tmp.begin(), [mu_i, sigma_i](double dat) { return mahalanobis_c(dat, mu_i, std::sqrt(sigma_i)); }); d.row(i) = tmp; std::transform(y.begin(), y.end(), tmp.begin(), [mu_i, sigma_i](double dat) {return norm_c(dat, mu_i, sigma_i);} ); tau.row(i) = pi(i)*tmp; } tau = tau.each_row() / sum(tau,0); std::transform(d.begin(), d.end(), w.begin(), [](double val) { return phi(val);} ); u = w; for(int i=0;i<g;i++){ mu(i) = sum(tau.row(i)%u.row(i)%y.t()) / sum(tau.row(i)%u.row(i)); double mu_i = mu(i); arma::rowvec tmp = y.t() - mu_i; sigma(i) = sum(tau.row(i)%u.row(i)%(tmp)%(tmp))/ sum(tau.row(i)); //sum(tau.row(i)); pi(i)= sum(tau.row(i))/accu(tau); } ++k; } temp_list = Rcpp::List::create( Rcpp::Named("mu")= export_vec(mu), Rcpp::Named("sigma") = export_vec(sigma), Rcpp::Named("pi") = export_vec(pi), Rcpp::Named("tau") = tau, Rcpp::Named("g") = g, Rcpp::Named("n_iter") =k ); }else{ int n = y.n_rows; arma::mat d = arma::zeros(g,n); arma::mat u = arma::zeros(g,n); arma::mat w = arma::ones(g,n); arma::mat tau = arma::zeros(g,n); //allocate double arma::mat mu = arma::zeros(g,dim); arma::cube sigma = arma::zeros(g,dim,dim); arma::vec pi = arma::zeros(g); double diff = 1.0; arma::mat init_mat = arma::zeros(g,3); init_mat = start_kmeans2(y,g); pi = init_mat.col(0); //sigma = init_mat.col(1); mu = init_mat.col(2); //allocated int int k =0; //iterative fit for M-est while(diff>tol & k <max_iter ){ for(int i=0;i<g;i++){ arma::vec mu_i = mu.row(i); arma::mat sigma_i = sigma.slice(i); arma::rowvec tmp = arma::zeros(1,n); for(int j=0;j<n;j++){ tmp(i) = mahalanobis_HD(y.row(i), mu_i, sigma_i); } d.row(i) = tmp; for(int j=0;j<n;j++){ tmp(i) = norm_HD(y.row(i), mu_i, sigma_i); } tau.row(i) = pi(i)*tmp; } tau = tau.each_row() / sum(tau,0); std::transform(d.begin(), d.end(), w.begin(), [](double val) { return phi(val);} ); u = w; for(int i=0;i<g;i++){ mu.row(i) = sum(tau.row(i)%u.row(i)%y.t()) / sum(tau.row(i)%u.row(i)); arma::vec mu_i = mu.row(i); arma::mat tmp = y.each_row() - mu_i; sigma.slice(i) = sum(tau.row(i)%u.row(i)%(tmp)%(tmp))/ sum(tau.row(i)); //sum(tau.row(i)); pi(i)= sum(tau.row(i))/accu(tau); } ++k; } temp_list = Rcpp::List::create( Rcpp::Named("mu")= (mu), Rcpp::Named("sigma") = sigma, Rcpp::Named("pi") = export_vec(pi), Rcpp::Named("tau") = tau, Rcpp::Named("g") = g, Rcpp::Named("n_iter") =k ); } return temp_list; }
[ "andrewthomasjones@gmail.com" ]
andrewthomasjones@gmail.com
1b8626716b259c740237280c9a0419edfb1e3033
42f39bcfb7418468ee9d6951fb1fea67b891c618
/Agony/LuaFunctions.cpp
a2244493baa3570c72e11894cbefa60651ac9df5
[]
no_license
normalzero/WoWBotV2
68d5207de2f887c97634f776278460e9354eb492
948d5ed92f709d33aad796c5870b6119627610c8
refs/heads/master
2022-06-13T04:47:33.095066
2020-05-07T00:40:55
2020-05-07T00:40:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,664
cpp
#include "LuaFunctions.h" #include "vector3.h" #include "Navigation.h" #include "Drawings.h" #include "ObjectManager.h" #include "Game.h" #include "LuaGlobals.h" #include <tuple> #include <sstream> namespace Agony { namespace Native { std::map<const char*, int64_t> LuaFunctions::FunctionsMap = { {"Unlock", reinterpret_cast<int64_t>(Unlock)}, {"GetUnitPosition", reinterpret_cast<int64_t>(GetUnitPosition)}, {"IsFacingTarget", reinterpret_cast<int64_t>(IsFacingTarget)}, {"CalculatePath", reinterpret_cast<int64_t>(CalculatePath)}, {"GoToPoint", reinterpret_cast<int64_t>(GoToPoint)}, {"WorldToScreen", reinterpret_cast<int64_t>(WorldToScreen)}, {"DrawLine3D", reinterpret_cast<int64_t>(DrawLine3D)}, {"GetCorpsePosition", reinterpret_cast<int64_t>(GetCorpsePosition)}, {"GetPlayerAngle", reinterpret_cast<int64_t>(GetPlayerAngle)}, {"NextPoint", reinterpret_cast<int64_t>(NextPoint)}, {"IsInGame", reinterpret_cast<int64_t>(IsInGame)}, {"Test", reinterpret_cast<int64_t>(Test)} }; WoWObject* LuaFunctions::GetUnitById(const char* unitid) { return reinterpret_cast<WoWObject * (__fastcall*)(const char*)>(Offsets::Base + Offsets::GetBaseFromToken)(unitid); } WoWObject* LuaFunctions::GetLocalPlayer() { return GetUnitById("player"); } WoWObject* LuaFunctions::GetTarget() { return GetUnitById("target"); } void LuaFunctions::Execute(const char* com) { reinterpret_cast<uintptr_t(__fastcall*)(const char*, const char*, int64_t)>(Offsets::Base + Offsets::FrameScript_Execute)(com, "KappaMorpher", 0); } void LuaFunctions::Execute(const std::string& com) { Execute(com.c_str()); } std::string LuaFunctions::ExecuteGetResult(const std::string& com, const std::string& arg) { reinterpret_cast<uintptr_t(__fastcall*)(const char*, const char*, int64_t)>(Offsets::Base + Offsets::FrameScript_Execute)(com.c_str(), "KappaMorpher", 0); return std::string(reinterpret_cast<const char*>(reinterpret_cast<uintptr_t(__fastcall*)(const char*, int64_t, int32_t, uint8_t)>(Offsets::Base + Offsets::FrameScript_GetText)(arg.c_str(), -1, 0, 0))); } bool LuaFunctions::FramescriptRegister(const char* command, const int64_t funcPointer) { const auto textSectionEnd = *reinterpret_cast<int64_t*>(Offsets::Base + Offsets::InvalidFunctionPtr); if (funcPointer >= textSectionEnd) { const auto dif = funcPointer - textSectionEnd; *reinterpret_cast<int64_t*>(Offsets::Base + Offsets::InvalidFunctionPtr) = textSectionEnd + dif + 1; } return reinterpret_cast<bool(__fastcall*)(const char*, int64_t)>(Offsets::Base + Offsets::FrameScript_RegisterFunction)(command, funcPointer); } int64_t LuaFunctions::LuaSetTop(uintptr_t* l, const int32_t a2) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, int32_t)>(Offsets::Base + Offsets::lua_settop)(l, a2); } int64_t LuaFunctions::LuaGetTop(uintptr_t* l) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*)>(Offsets::Base + Offsets::lua_gettop)(l); } int64_t LuaFunctions::LuaGetField(uintptr_t* l, int idx, const char* k) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, int idx, const char* k)>(Offsets::Base + Offsets::lua_getfield)(l, idx, k); } bool LuaFunctions::LuaIsNumber(uintptr_t* l, const int32_t stackPos) { return reinterpret_cast<bool(__fastcall*)(uintptr_t*, int32_t)>(Offsets::Base + Offsets::lua_isnumber)(l, stackPos); } double LuaFunctions::LuaToNumber(uintptr_t* l, const int32_t stackPos) { return reinterpret_cast<double(__fastcall*)(uintptr_t*, int32_t)>(Offsets::Base + Offsets::lua_tonumber)(l, stackPos); } int64_t LuaFunctions::LuaPushInteger(uintptr_t* l, const int32_t theInteger) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, int32_t)>(Offsets::Base + Offsets::lua_pushinteger)(l, theInteger); } int64_t LuaFunctions::LuaPushNumber(uintptr_t* l, const double theNumber) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, double)>(Offsets::Base + Offsets::lua_pushnumber)(l, theNumber); } int64_t LuaFunctions::LuaPushString(uintptr_t* l, const char* theString) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, const char*)>(Offsets::Base + Offsets::lua_pushstring)(l, theString); } bool LuaFunctions::LuaIsString(uintptr_t* l, const int32_t stackPos) { return reinterpret_cast<bool(__fastcall*)(uintptr_t*, int32_t)>(Offsets::Base + Offsets::lua_isstring)(l, stackPos); } const char* LuaFunctions::LuaToString(uintptr_t* l, const int32_t stackPos) { return reinterpret_cast<const char* (__fastcall*)(uintptr_t*, int32_t, uintptr_t*)>(Offsets::Base + Offsets::lua_tolstring)(l, stackPos, nullptr); } bool LuaFunctions::LuaPushBoolean(uintptr_t* l, const bool theBool) { return reinterpret_cast<bool(__fastcall*)(uintptr_t*, bool)>(Offsets::Base + Offsets::lua_pushboolean)(l, theBool); } int64_t LuaFunctions::LuaError(uintptr_t* l, const char* msg) { return reinterpret_cast<int64_t(__cdecl*)(uintptr_t*, const char*)>(Offsets::Base + Offsets::luaL_error)(l, msg); } int64_t LuaFunctions::LuaCreateTable(uintptr_t* l, const int32_t narr, const int32_t nrec) { return reinterpret_cast<int64_t(__fastcall*)(uintptr_t*, int32_t, int32_t)>(Offsets::Base + Offsets::lua_createtable)(l, narr, nrec); } void LuaFunctions::LuaRawSeti(uintptr_t* l, const int32_t narr, const int32_t nrec) { reinterpret_cast<void(__fastcall*)(uintptr_t*, int32_t, int32_t)>(Offsets::Base + Offsets::lua_rawseti)(l, narr, nrec); } int32_t LuaFunctions::LuaPCall(uintptr_t* l, const int32_t nargs, const int32_t nresults, const int32_t errfunc) { return reinterpret_cast<int32_t(__fastcall*)(uintptr_t*, int32_t, int32_t, int32_t)>(Offsets::Base + Offsets::lua_pcall)(l, nargs, nresults, errfunc); } //the first param will be sent by wow when u call this function and its the lua_state pointer aka stack basically int32_t LuaFunctions::Unlock(uintptr_t* l) //ok so ur return value here is how many returns ur lua function will return we aernt returning anything so will be 0 { //so to run protected function from addon we need to call execute in our dll so the first thing we need to do is get the number of arguments on the lua stack when this is called //num args sent to this command we expect 1 and we expect it to be a string auto numArgs = LuaGetTop(l); //if we have 1 arg passed to function like we expect if (numArgs == 1) { //check if that arg is a string like we expect //if we have 1 arg then its pos on stack is 1 if (LuaIsString(l, 1)) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); if ((currentState >> 4) & 1) { //if we are here the 1 arg on the stack is a string now we need to convert it to a string type for lua > c++ auto s = LuaToString(l, 1); Execute(s); } return 0; } LuaError(l, "Invalid Argument: string expected."); } LuaError(l, "Invalid # of Arguments: 1 expected."); return 0; } //another function so u know how to return results //lets make it add 2 user supplied numbers and return a string and the number //so we know already we need 2 args passed to the function int32_t LuaFunctions::GetUnitPosition(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 1) { if (LuaIsString(l, 1)) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); if ((currentState >> 4) & 1) { auto unitId = LuaToString(l, 1); auto unit = GetUnitById(unitId); if (unit == nullptr) { LuaPushNumber(l, 0); LuaPushNumber(l, 0); LuaPushNumber(l, 0); } else { LuaPushNumber(l, unit->pos.y); LuaPushNumber(l, unit->pos.x); LuaPushNumber(l, unit->pos.z); } } else { LuaPushNumber(l, 0); LuaPushNumber(l, 0); LuaPushNumber(l, 0); } return 3; } LuaError(l, "Invalid Argument: string expected."); //err die return 0; } LuaError(l, "Invalid # of Arguments: 1 expected."); return 0; } int32_t LuaFunctions::IsFacingTarget(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { auto player = GetLocalPlayer(); auto target = GetTarget(); if (target == nullptr) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); if ((currentState >> 4) & 1) { auto Object1Facing = player->fAngle; auto Angle = ((player->pos.x - target->pos.x) * std::cos(-Object1Facing)) - ((player->pos.y - target->pos.y) * std::sin(-Object1Facing)); bool isFacing = Angle < 0; LuaPushBoolean(l, isFacing); } else { LuaPushBoolean(l, true); } } else { LuaPushBoolean(l, false); } //err die return 1; } return 0; } int32_t LuaFunctions::CalculatePath(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 4) { if (LuaIsNumber(l, 1) && LuaIsNumber(l, 2) && LuaIsNumber(l, 3) && LuaIsNumber(l, 4)) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); if ((currentState >> 4) & 1) { auto player = GetLocalPlayer(); Navigation* navigation = Navigation::GetInstance(); Vector3 start = Vector3(player->pos.x, player->pos.y, player->pos.z); Vector3 end = Vector3(LuaToNumber(l, 1), LuaToNumber(l, 2), LuaToNumber(l, 3)); //XYZ start = XYZ(-8949.95f, -132.493f, 83.5312f); //XYZ end = XYZ(-9046.507f, -45.71962f, 88.33186f); int instanceId = LuaToNumber(l, 4); Navigation::GetInstance()->Initialize(instanceId); if (Drawings::Waypoints) { Navigation::GetInstance()->FreePathArr(Drawings::Waypoints); } Drawings::CurrentWaypoint = 0; Drawings::Waypoints = Navigation::GetInstance()->CalculatePath(instanceId, start, end, false, &Drawings::WaypointsLenght, false); LuaCreateTable(l, Drawings::WaypointsLenght, 0); for (int i = 0; i < Drawings::WaypointsLenght; i++) { LuaCreateTable(l, 3, 0); LuaPushNumber(l, Drawings::Waypoints[i].x); LuaRawSeti(l, -2, 1); LuaPushNumber(l, Drawings::Waypoints[i].y); LuaRawSeti(l, -2, 2); LuaPushNumber(l, Drawings::Waypoints[i].z); LuaRawSeti(l, -2, 3); LuaRawSeti(l, -2, i + 1); } return 1; } else { if (Drawings::Waypoints) { Navigation::GetInstance()->FreePathArr(Drawings::Waypoints); } Drawings::Waypoints = new Vector3[0]; Drawings::WaypointsLenght = 0; LuaCreateTable(l, Drawings::WaypointsLenght, 0); return 1; } } else { if (Drawings::Waypoints) { Navigation::GetInstance()->FreePathArr(Drawings::Waypoints); } Drawings::Waypoints = new Vector3[0]; Drawings::WaypointsLenght = 0; LuaCreateTable(l, Drawings::WaypointsLenght, 0); return 1; } } return 0; } int32_t LuaFunctions::NextPoint(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { Drawings::CurrentWaypoint++; if (Drawings::CurrentWaypoint == Drawings::WaypointsLenght) Drawings::CurrentWaypoint = Drawings::WaypointsLenght - 1; } return 0; } int32_t LuaFunctions::GoToPoint(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 3) { if (LuaIsNumber(l, 1) && LuaIsNumber(l, 2) && LuaIsNumber(l, 3)) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); if ((currentState >> 4) & 1) { auto player = GetLocalPlayer(); Vector3 point = Vector3(LuaToNumber(l, 1), LuaToNumber(l, 2), LuaToNumber(l, 3)); reinterpret_cast<void(__fastcall*)(WoWObject*, Vector3*)>(Offsets::Base + Offsets::TerrainClick)(player, &point);//same shit XD } } } return 0; } int32_t LuaFunctions::WorldToScreen(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 3) { if (LuaIsNumber(l, 1) && LuaIsNumber(l, 2) && LuaIsNumber(l, 3)) { Vector2 screenLoc; if (Drawings::WorldToScreen(Vector3(LuaToNumber(l, 1), LuaToNumber(l, 2), LuaToNumber(l, 3)), &screenLoc)) { LuaPushNumber(l, screenLoc.x); LuaPushNumber(l, screenLoc.y); } else { LuaPushNumber(l, 0); LuaPushNumber(l, 0); } //auto screenPos = Drawings::WorldToScreen(point); return 2; } return 0; } // } int32_t LuaFunctions::DrawLine3D(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 6) { if (LuaIsNumber(l, 1) && LuaIsNumber(l, 2) && LuaIsNumber(l, 3) && LuaIsNumber(l, 4) && LuaIsNumber(l, 5) && LuaIsNumber(l, 6)) { Vector3 from = Vector3(LuaToNumber(l, 1), LuaToNumber(l, 2), LuaToNumber(l, 3)); Vector3 to = Vector3(LuaToNumber(l, 4), LuaToNumber(l, 5), LuaToNumber(l, 6)); Drawings::DrawLine(from, to); return 0; } return 0; } // } int32_t LuaFunctions::GetCorpsePosition(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { auto corpseBase = reinterpret_cast<CorpseBase*>(Offsets::Base + Offsets::CorpseBase); if (corpseBase == nullptr) { LuaPushNumber(l, 0); LuaPushNumber(l, 0); LuaPushNumber(l, 0); } else { LuaPushNumber(l, corpseBase->pos.x); LuaPushNumber(l, corpseBase->pos.y); LuaPushNumber(l, corpseBase->pos.z); } return 3; } return 0; } int32_t LuaFunctions::GetPlayerAngle(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { auto player = GetLocalPlayer(); LuaPushNumber(l, player->fAngle); return 1; } return 0; } int32_t LuaFunctions::IsInGame(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { const auto currentState = *reinterpret_cast<unsigned __int16*>(Offsets::Base + Offsets::InGame); LuaPushBoolean(l, (currentState >> 4) & 1); return 1; } return 0; } int32_t LuaFunctions::Test(uintptr_t* l) { auto numArgs = LuaGetTop(l); if (numArgs == 0) { //auto player = Agony::Native::Game::Me(); //uintptr_t* L = *(uintptr_t**)(Offsets::Base + Offsets::lua_state); //auto v4 = 0;// reinterpret_cast<uintptr_t* (__thiscall*)(void*)>(Offsets::Base + 0xD08BE0)(L); //auto result = LuaFunctions::Call("GetProfessionInfo", {2, 2, 1, 1, 1, 1, 1, 1, 1, 1}, 5); //std::cout << "v4 = " << std::dec << std::any_cast<int>(result[2]) << "/" << std::any_cast<int>(result[3]) << std::endl; auto result = LuaFunctions::Call("UnitHealth", {1}, "player"); std::cout << "Test = " << std::dec << std::any_cast<int>(result[0]) << std::endl; /*ObjectGuid* guid2 = reinterpret_cast<ObjectGuid*>(Offsets::Base + Offsets::CGGameUI__m_currentObjectTrack); if (guid2 != nullptr && !(guid2->HiWord == 0 && guid2->LoWord)) { //std::cout << "guid1 type " << std::dec << guid1.Type() << std::endl; std::cout << "guid2 type " << std::dec << guid2->Type() << std::endl; auto obj = ObjectManager::GetObjectFromGuid(guid2); if (obj != nullptr) { std::cout << "Obj address 0x" << std::hex << obj << std::endl; if (obj->GetType() == WoWObjectType::Unit) { std::cout << obj->GetName() << std::endl; } else if (obj->GetType() == WoWObjectType::GameObject) { std::cout << obj->GetName() << std::endl; //This even check if it is called from Unlock or not : this one? reinterpret_cast<bool(__fastcall*)(ObjectGuid*)>(Offsets::Base + Offsets::CGGameUI__OnSpriteRightClick)(&obj->GetGuid()); } } }*/ /*THIS ALSO WORKS: auto gameObjects = ObjectManager::GetVisibleObjects(); for (std::size_t i = 0; i < gameObjects.size(); ++i) { auto gameObject = gameObjects[i]; if (gameObject->GetType() == WoWObjectType::GameObject) { //std::cout << gameObject->GetName() << std::endl; reinterpret_cast<bool(__fastcall*)(ObjectGuid*)>(Offsets::Base + Offsets::CGGameUI__OnSpriteRightClick)(&gameObject->GetGuid()); } }*/ } return 0; } const char* LuaFunctions::GetMainScriptCode() { int32_t dummy = 0; #include "main.lua"//This include the file and return it.... how nice :D } inline void PrintLuaResults(const sol::variadic_results& results) { for (const auto& result : results) { switch (result.get_type()) { case sol::type::nil: { std::cout << "nil\n"; break; } case sol::type::function: { std::cout << "function: 0x" << std::hex << result.as<uintptr_t>() << "\n"; break; } case sol::type::string: { std::cout << result.as<std::string>() << "\n"; break; } case sol::type::number: { std::cout << std::to_string(result.as<double>()) << "\n"; break; } case sol::type::boolean: { std::cout << (result.as<bool>() ? "true" : "false") << "\n"; break; } case sol::type::table: { std::cout << "table: 0x" << std::hex << result.as<uintptr_t>() << "\n"; break; } case sol::type::userdata: { std::cout << "userdata: 0x" << std::hex << result.as<uintptr_t>() << "\n"; break; } default: { std::cout << "Type value is either unknown or doesn't matter\n"; break; } } } } //create var to bind only once later void LuaFunctions::BindLua() { const auto l = *reinterpret_cast<lua_State**>(Offsets::Base + Offsets::lua_state); LuaGlobals::MainEnvironment = std::make_unique<sol::state_view>(l); auto& lua = *LuaGlobals::MainEnvironment; //empty scope, i dont get it, doesnt that same as after method call ? no { lua.new_usertype<void>("AgonyLuaEvents", sol::no_constructor, "OnEvent", [](const sol::variadic_args& results) { std::string eventName; std::cout << "Received event in core: " << eventName << std::endl; std::vector<std::any> args = std::vector<std::any>(); int i = 0; for (const auto& result : results) { switch (result.get_type()) { case sol::type::nil: { args.push_back(std::nullptr_t()); break; } case sol::type::function: { args.push_back(result.as<uintptr_t>()); break; } case sol::type::string: { if (i == 0) { eventName = result.as<std::string>(); } else { args.push_back(result.as<std::string>()); } break; } case sol::type::number: { args.push_back(result.as<double>()); break; } case sol::type::boolean: { args.push_back(result.as<bool>()); break; } case sol::type::table: { args.push_back(result.as<uintptr_t>()); break; } case sol::type::userdata: { args.push_back(result.as<uintptr_t>()); break; } default: { std::cout << "Type value is either unknown or doesn't matter\n"; break; } } i++; } Game::GetInstance()->OnLuaEvent.Trigger(eventName, args); } ); std::cout << "Finished binding functions.\n"; } //thats basically it SEE IF WORKS const auto badCodeResult = lua.safe_script( GetMainScriptCode(), [](lua_State*, const sol::protected_function_result& pfr) { const auto errObj = pfr.get<sol::error>(); const auto errMsg = errObj.what(); std::cout << errMsg << "\n"; return pfr; } ); //////ok now u can call lua anywhere but we do here for example //////let start simple unithealth //int health = lua["UnitHealth"]("player"); //std::cout << "Player health = " << health << std::endl; //try //{ // sol::variadic_results result2 = lua["GetBattlefieldStatus"](1);//Guess it will work // PrintLuaResults(result2); // /*for (auto arg : result2) // { // if (arg.valid()) // { // if (arg.is<std::string>()) // std::cout << "Got arg: " << arg.as<std::string>() << std::endl; // else if (arg.is<float>()) // std::cout << "Got arg: " << arg.as<float>() << std::endl; // else if (arg.is<int>()) // std::cout << "Got arg: " << arg.as<int>() << std::endl; // else if (arg.is<bool>()) // std::cout << "Got arg: " << arg.as<bool>() << std::endl; // } // }*/ // /*if (result2.size() == 8) // { // std::cout << "status: " << result2.at(0).as<std::string>() << " mapName: " << result2.at(1).as<std::string>() << std::endl; // }*/ //} //catch (...) {} } void LuaFunctions::DropLua() { if (LuaGlobals::MainEnvironment) LuaGlobals::MainEnvironment.reset();//Not release ? //reset sets to null } bool LuaFunctions::RegisterEvent(std::string eventName) { if (!Game::IsInGame()) return false; auto& lua = *LuaGlobals::MainEnvironment; sol::table AgonyLuaEvents = lua["AgonyCoreFrame"]; return AgonyLuaEvents["RegisterEvent"](AgonyLuaEvents, eventName).get<bool>(); //return true; } void LuaFunctions::UnregisterEvent(std::string eventName) { if (!Game::IsInGame()) return; auto& lua = *LuaGlobals::MainEnvironment; sol::table AgonyLuaEvents = lua["AgonyCoreFrame"]; AgonyLuaEvents["UnregisterEvent"](AgonyLuaEvents, eventName); } } }
[ "sylvainmartens@gmail.com" ]
sylvainmartens@gmail.com
19fd005e87f1ca65b4739bbb44dac76678bd8bf6
8f2dc5e7afc79f4dede1d9f91a57c353913eda56
/ResectionPlanning/MRML/vtkMRMLLRPModelNode.h
63e96f94d9ca91ddc3f0dc6124efc0bdca2396b6
[]
no_license
TheInterventionCentre/NorMIT-Plan
f09ff653184caf1381fdd925c003f61f2099689e
b841da7b959d9299da3480ad41182ac271794c91
refs/heads/development
2021-01-20T11:17:47.596583
2018-04-24T07:49:58
2018-04-24T07:49:58
77,453,850
11
1
null
2018-04-24T07:49:59
2016-12-27T12:27:58
C++
UTF-8
C++
false
false
3,668
h
/*========================================================================= Program: NorMIT-Plan Module: vtkMRMLLRPModelNode.h Copyright (c) 2017, The Intervention Centre, Oslo University Hospital All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #ifndef __vtkMRMLLRPModelNode_h #define __vtkMRMLLRPModelNode_h // This module includes #include "vtkSlicerResectionPlanningModuleMRMLExport.h" //MRML #include <vtkMRMLModelNode.h> //------------------------------------------------------------------------------ /** * \ingroup ResectionPlanning * * This is a support class to distinguish between regular 3D Slicer models * and 3D models corresponding to organs in the resection planning systems. */ class VTK_SLICER_RESECTIONPLANNING_MODULE_MRML_EXPORT vtkMRMLLRPModelNode: public vtkMRMLModelNode { public: enum AnatomicalStructure { Unknown = 0, Parenchyma = 1, PortalSystem = 2, HepaticSystem = 3, Tumor = 4, }; /** * Standard VTK object instantiation methods * * @return a pointer to a newly created vtkMRMLLRPModelNode. */ static vtkMRMLLRPModelNode* New(); vtkTypeMacro(vtkMRMLLRPModelNode, vtkMRMLModelNode); /** * Standard print object information method. * * @param os output stream to print the information to. * @param indent intdent value. */ void PrintSelf(ostream &os, vtkIndent indent); /** * Standard MRML method to create the node instance. * * * @return a pointer to the newly created vtkMRMLNode. */ virtual vtkMRMLNode* CreateNodeInstance(); /** * Get the tag name of the node. * * * @return string with the tag name of the node. */ virtual const char* GetNodeTagName() {return "LRPModelNode";} /** * Get the icon associated to the node. * * * @return string pointing to the resource where the icon is located. */ virtual const char* GetIcon() {return "";} vtkSetClampMacro(TypeOfAnatomicalStructure, int, 0, 4); vtkGetMacro(TypeOfAnatomicalStructure, int); protected: vtkMRMLLRPModelNode(); ~vtkMRMLLRPModelNode(); private: int TypeOfAnatomicalStructure; }; #endif
[ "rafael.palomar@rr-research.no" ]
rafael.palomar@rr-research.no
da1e4db8d4a922d052a4baaae8df02983484596c
521bee76566df1fe7a00b7e0fd88b19eb0b91802
/Super Mario Bros/Collision.hpp
5a10d2db83789780fc1156de58e56dbaa9210708
[]
no_license
roccosec/Super-Mario-Bros
d7bc9085d07e5e9df99ee55c4b08c45f39de368f
80b469d2e8554109012f85e2f4d992cb6d668f05
refs/heads/master
2022-01-16T09:21:38.418139
2019-06-21T00:42:17
2019-06-21T00:42:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
738
hpp
#pragma once #include <SFML/Graphics.hpp> namespace Game { class Collision { public: static bool checkSpriteCollision(const sf::Sprite& sprite1, const sf::Sprite& sprite2); static bool checkSpriteCollision(const sf::FloatRect& sprite1, const sf::Sprite& sprite2); static bool checkSpriteCollision(const sf::Sprite& sprite1, const float& scale1, const sf::Sprite& sprite2, const float& scale2); static bool checkSpriteCollision(const sf::Sprite& sprite1, const float& scaleX, const float& scaleY, const sf::Sprite& sprite2); static float distanceBetween(const float& x1, const float& y1, const float& x2, const float& y2); static float distanceBetween(const sf::Vector2f& vector1, const sf::Vector2f& vector2); }; }
[ "kaikkonen.jaakko@gmail.com" ]
kaikkonen.jaakko@gmail.com
c0fd238da255e5706c39b0efbfa69689416b652c
3d801968b2a83496d711075b8c39d45f5c1cfc00
/Arrays/Subarray/Maximum sum subarray.cpp
cd1639b59d2e6441d693690078ba35e96db4bc21
[]
no_license
hemalhansda/ds_algo
74fa462843aed9f48fd3518a0db8664d724bfc88
f038190e647a70dbecfcb42239abb4c679b56e04
refs/heads/master
2020-09-18T05:31:22.975399
2019-10-09T07:04:09
2019-10-09T07:04:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
/*ind the contiguous subarray within an array (containing at least one number) which has the largest sum. For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. For this problem, return the maximum sum.*/ int Solution::maxSubArray(const vector<int> &A) { int n = A.size(); int pos = 0; int prefix = 0; int mx = INT_MIN; for (int i = 0; i < n; ++i) { prefix += A[i]; mx = max(mx, prefix); if (prefix < 0) prefix = 0; if (A[i] >= 0) pos = 1; } if (!pos) { mx = *max_element(A.begin(), A.end()); } return mx; }
[ "avinash.kumar@seenit.in" ]
avinash.kumar@seenit.in
77e11392dcecfe3a8c7eef9b924b79f8d6a4b5dd
040dcdde3fc8c465f0ed6b913f3ceb8717306840
/Binary Tree.cpp
3f9d3e7df3f0b6f651ea327863688fb3293a9488
[]
no_license
shreygupta2101/HackerRank-CPP
6cf41b968de7e5950dfd4b61e1d8d4772b09ba1f
73a54b4107cefa5bff6ca0973ba2b0442d8e7129
refs/heads/main
2023-08-29T13:31:09.909012
2021-10-30T19:17:08
2021-10-30T19:17:08
422,969,980
0
0
null
2021-10-30T19:14:17
2021-10-30T19:14:17
null
UTF-8
C++
false
false
69
cpp
struct node { int data; struct node* left; struct node* right; };
[ "noreply@github.com" ]
shreygupta2101.noreply@github.com
b65d5c32e16702e2a89a1977e11534974671324a
9f6ac63e81535daeb55611d66560ab2a87fc9d8c
/libs/vislib/net/include/vislib/DNS.h
ae7806af468e744daf99adcad80f8a4678b6a1ef
[]
no_license
ComputationalRadiationPhysics/rivlib
68e4de9cc98f62112ec21a05d68c406ef580a32d
1a838630400892a53ff7eb120aec4282fc9967ac
refs/heads/master
2021-01-21T05:00:23.480426
2016-05-23T07:29:51
2016-05-23T07:29:51
29,530,946
3
1
null
2016-05-23T07:29:51
2015-01-20T13:27:18
C++
ISO-8859-3
C++
false
false
14,944
h
/* * DNS.h * * Copyright (C) 2009 by Christoph Müller. Alle Rechte vorbehalten. * Copyright (C) 2006 - 2008 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #ifndef VISLIB_DNS_H_INCLUDED #define VISLIB_DNS_H_INCLUDED #if (defined(_MSC_VER) && (_MSC_VER > 1000)) #pragma once #endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */ #if defined(_WIN32) && defined(_MANAGED) #pragma managed(push, off) #endif /* defined(_WIN32) && defined(_MANAGED) */ #include "vislib/IPAddress.h" #include "vislib/IPAddress6.h" #include "vislib/IPAgnosticAddress.h" #include "vislib/IPHostEntry.h" #include "vislib/String.h" namespace vislib { namespace net { /** * This class povides DNS queries via static methods. */ class DNS { public: /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * The method first tries to retrieve the address by using the rather * new getaddrinfo function. If this fails, it tries to recover using * the older gethostbyname function. If this fails either, the exception * raised by the first try is rethrown. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAddress& outAddress, const char *hostNameOrAddress); /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * The method first tries to retrieve the address by using the rather * new getaddrinfo function. If this fails, it tries to recover using * the older gethostbyname function. If this fails either, the exception * raised by the first try is rethrown. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAddress& outAddress, const wchar_t *hostNameOrAddress); /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAddress6& outAddress, const char *hostNameOrAddress); /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAddress6& outAddress, const wchar_t *hostNameOrAddress); /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * @param inCaseOfDoubt The address family to be used if it is not * clear from the 'hostNameOrAddress' * parameter. This parameter defaults to * FAMILY_INET6. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAgnosticAddress& outAddress, const char *hostNameOrAddress, const IPAgnosticAddress::AddressFamily inCaseOfDoubt = IPAgnosticAddress::FAMILY_INET6); /** * Answer any of the IP addresses of the host identified by the given * host name or human readable IP address. * * @param outAddress Receives the IP address. * @param hostNameOrAddress The host name or stringised IP address to * search. * @param inCaseOfDoubt The address family to be used if it is not * clear from the 'hostNameOrAddress' * parameter. This parameter defaults to * FAMILY_INET6. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static void GetHostAddress(IPAgnosticAddress& outAddress, const wchar_t *hostNameOrAddress, const IPAgnosticAddress::AddressFamily inCaseOfDoubt = IPAgnosticAddress::FAMILY_INET6); //static void GetHostAddresses(vislib::Array<IPAddress>& outAddresses, // const char *hostNameOrAddress); //static void GetHostAddresses(vislib::Array<IPAddress>& outAddresses, // const wchar_t *hostNameOrAddress); //static void GetHostAddresses(vislib::Array<IPAddress6>& outAddresses, // const char *hostNameOrAddress); //static void GetHostAddresses(vislib::Array<IPAddress6>& outAddresses, // const wchar_t *hostNameOrAddress); //static void GetHostEntry(IPHostEntryA& outEntry, // const IPAddress& hostAddress); //static void GetHostEntry(IPHostEntryA& outEntry, // const IPAddress6& hostAddress); //static void GetHostEntry(IPHostEntryW& outEntry, // const IPAddress& hostAddress); //static void GetHostEntry(IPHostEntryW& outEntry, // const IPAddress6& hostAddress); /** * Answer the IPHostEntry for the specified host name or IP address * string. * * @param outEntry Receives the host entry. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryA& outEntry, const char *hostNameOrAddress); /** * Answer the IPHostEntry for the specified host name or IP address * string. * * @param outEntry Receives the host entry. * @param hostNameOrAddress The host name or stringised IP address to * search. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryW& outEntry, const wchar_t *hostNameOrAddress); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryA& outEntry, const IPAgnosticAddress& address); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryW& outEntry, const IPAgnosticAddress& address); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryA& outEntry, const IPAddress& address); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryW& outEntry, const IPAddress& address); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryA& outEntry, const IPAddress6& address); /** * Answer the IPHostEntry for the specified IP address. * * @param outEntry Receives the host entry. * @param addrress The reference IP address to search. * * @throws SocketException In case the operation fails, e.g. the * host could not be found. * @throws IllegalParamException If the specified host does not use * IPv4 or IPv6. */ static void GetHostEntry(IPHostEntryW& outEntry, const IPAddress6& address); /** Dtor. */ ~DNS(void); private: /** * Retrieve the addrinfo list for the specified host name of IP address * string. * * The caller takes the ownership of the returned list and must release * it using the appropriate API function. * * @param hostNameOrAddress The host name or stringised IP address to * search. * @param addressFamily The address familiy to limit the search to. * * @returns The addrinfo list if the host was found. The caller must * free this list. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ static struct addrinfo *getAddrInfo(const char *hostNameOrAddress, const int addressFamily); /** * Retrieve the addrinfo list for the specified host name of IP address * string. * * The caller takes the ownership of the returned list and must release * it using the appropriate API function. * * @param hostNameOrAddress The host name or stringised IP address to * search. * @param addressFamily The address familiy to limit the search to. * * @returns The addrinfo list if the host was found. The caller must * free this list. * * @throws SocketException In case the operation fails, e.g. the host * could not be found. */ #if (defined(_WIN32) && defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0502)) static ADDRINFOW *getAddrInfo(const wchar_t *hostNameOrAddress, const int addressFamily); #else /* (defined(_WIN32) && defined(_WIN32_WINNT) && ... */ static struct addrinfo *getAddrInfo(const wchar_t *hostNameOrAddress, const int addressFamily); #endif /* (defined(_WIN32) && defined(_WIN32_WINNT) && ... */ /** * Disallow instances. */ DNS(void); /** * Forbidden copy ctor. * * @param rhs The object to be cloned. * * @throws UnsupportedOperationException Unconditionally. */ DNS(const DNS& rhs); /** * Forbidden assignment. * * @param rhs The right hand side operand. * * @return *this. * * @throws IllegalParamException If (this != &rhs). */ DNS& operator =(const DNS& rhs); }; } /* end namespace net */ } /* end namespace vislib */ #if defined(_WIN32) && defined(_MANAGED) #pragma managed(pop) #endif /* defined(_WIN32) && defined(_MANAGED) */ #endif /* VISLIB_DNS_H_INCLUDED */
[ "axel.huebl@web.de" ]
axel.huebl@web.de
c66eecd0773907166afcb28eeb504bc0d474204c
84afdf38689005f299aa311c9597cf547d0e83d3
/library/Tree/treap.cpp
5f3a54673a328e7cb9087bb4746ce7959e1c2e60
[]
no_license
Endered/library
84509207d201dbc34f9af8f7f31285ab15a3c817
fbd16b09e3498baaebcceadcc974b25d3b720277
refs/heads/master
2022-12-22T03:15:09.612016
2022-12-10T04:25:17
2022-12-10T04:25:17
213,359,443
1
0
null
null
null
null
UTF-8
C++
false
false
3,767
cpp
#include<bits/stdc++.h> #define ll long long #define rep(i, n) for(int i=0;i<(n);++i) #define per(i, n) for(int i=(n)-1;i>=0;--i) #define repa(i, n) for(int i=1;i<(n);++i) #define foreach(i, n) for(auto &i:(n)) #define pii pair<int, int> #define pll pair<long long, long long> #define all(x) (x).begin(), (x).end() #define bit(x) (1ll << (x)) const ll MOD = (ll)1e9+7; const int INF = (ll)1e9+7; const ll INFLL = (ll)1e18; using namespace std; template<class t> using vvector = vector<vector<t>>; template<class t> using vvvector = vector<vector<vector<t>>>; template<class t> using priority_queuer = priority_queue<t, vector<t>, greater<t>>; template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;} template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;} ll modpow(ll x, ll b){ ll res = 1; while(b){ if(b&1)res = res * x % MOD; x = x * x % MOD; b>>=1; } return res; } ll modinv(ll x){ return modpow(x, MOD-2); } class treap{ public: class node{ public: int key; int priority; node *right; node *left; node():right(NULL), left(NULL){} node(int k, int p):key(k), priority(p), right(NULL), left(NULL){} }; node *root; treap():root(NULL){} node* insert(int key, int priority){ return root = insert(root, key, priority); } node* insert(node* t, int key, int priority){ if(t == NULL){ return new node(key, priority); } if(key == t->key){ return t; } if(key < t->key){ t->left = insert(t->left, key, priority); if(t->priority < t->left->priority){ t = right_rotate(t); } }else{ t->right = insert(t->right, key, priority); if(t->priority < t->right->priority){ t = left_rotate(t); } } return t; } node* right_rotate(node *t){ node *s = t->left; t->left = s->right; s->right = t; return s; } node* left_rotate(node *t){ node *s = t->right; t->right = s->left; s->left = t; return s; } node* erase(int key){ root = erase(root, key); } node* erase(node *t, int key){ if(t == NULL){ return NULL; } if(key < t->key){ t->left = erase(t->left, key); }else if(key > t->key){ t->right = erase(t->right, key); }else{ return _erase(t, key); } return t; } node* _erase(node* t, int key){ if(t->left == NULL && t->right == NULL){ delete t; return NULL; }else if(t->left == NULL){ t = left_rotate(t); }else if(t->right == NULL){ t = right_rotate(t); }else{ if(t->left->priority > t->right->priority){ t = right_rotate(t); }else{ t = left_rotate(t); } } return erase(t, key); } bool find(int key){ return find(root, key); } bool find(node *t, int key){ if(t==NULL){ return false; } if(t->key==key){ return true; } if(key < t->key){ return find(t->left, key); }else{ return find(t->right, key); } return false; } void print_inorder(){ print_inorder(root); } void print_inorder(node *t){ if(t==NULL){ return; } print_inorder(t->left); cout << " " << t->key; print_inorder(t->right); } void print_preorder(){ print_preorder(root); } void print_preorder(node *t){ if(t==NULL){ return; } cout << " " << t->key; print_preorder(t->left); print_preorder(t->right); } }; int main(){ int time; cin >> time; treap tr; rep(i, time){ string op; cin >> op; if(op=="insert"){ int key, priority; cin >> key >> priority; tr.insert(key, priority); }else if(op=="print"){ tr.print_inorder(); cout << endl; tr.print_preorder(); cout << endl; }else if(op=="delete"){ int key; cin >> key; tr.erase(key); }else{ int key; cin >> key; bool flag = tr.find(key); cout << (flag?"yes":"no") << endl; } } return 0; }
[ "yy56ga10ve@gmail.com" ]
yy56ga10ve@gmail.com
db07f381cffee39c81e902e7ac4de346f7429170
c51febc209233a9160f41913d895415704d2391f
/library/ATF/CRadarItemMgrDetail.hpp
12d2d8c854f75987959fbebf07b563a85471d8f0
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
351
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CRadarItemMgrInfo.hpp> START_ATF_NAMESPACE namespace Detail { extern ::std::array<hook_record, 14> CRadarItemMgr_functions; }; // end namespace Detail END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
182f37c7bdd3ec2afc8dbbf6e8c3232225ff20bd
399b5e377fdd741fe6e7b845b70491b9ce2cccfd
/LLVM_src/libcxx/test/std/utilities/allocator.adaptor/allocator.adaptor.cnstr/copy.pass.cpp
38878e234e9217ca6ca81da2d23ff44eb7c36178
[ "NCSA", "LLVM-exception", "MIT", "Apache-2.0" ]
permissive
zslwyuan/LLVM-9-for-Light-HLS
6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab
ec6973122a0e65d963356e0fb2bff7488150087c
refs/heads/master
2021-06-30T20:12:46.289053
2020-12-07T07:52:19
2020-12-07T07:52:19
203,967,206
1
3
null
2019-10-29T14:45:36
2019-08-23T09:25:42
C++
UTF-8
C++
false
false
2,160
cpp
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <memory> // template <class OuterAlloc, class... InnerAllocs> // class scoped_allocator_adaptor // scoped_allocator_adaptor(const scoped_allocator_adaptor& other); #include <scoped_allocator> #include <cassert> #include "allocators.h" int main() { { typedef std::scoped_allocator_adaptor<A1<int>> A; A a1(A1<int>(3)); A1<int>::copy_called = false; A1<int>::move_called = false; A a2 = a1; assert(A1<int>::copy_called == true); assert(A1<int>::move_called == false); assert(a2 == a1); } { typedef std::scoped_allocator_adaptor<A1<int>, A2<int>> A; A a1(A1<int>(4), A2<int>(5)); A1<int>::copy_called = false; A1<int>::move_called = false; A2<int>::copy_called = false; A2<int>::move_called = false; A a2 = a1; assert(A1<int>::copy_called == true); assert(A1<int>::move_called == false); assert(A2<int>::copy_called == true); assert(A2<int>::move_called == false); assert(a2 == a1); } { typedef std::scoped_allocator_adaptor<A1<int>, A2<int>, A3<int>> A; A a1(A1<int>(4), A2<int>(5), A3<int>(6)); A1<int>::copy_called = false; A1<int>::move_called = false; A2<int>::copy_called = false; A2<int>::move_called = false; A3<int>::copy_called = false; A3<int>::move_called = false; A a2 = a1; assert(A1<int>::copy_called == true); assert(A1<int>::move_called == false); assert(A2<int>::copy_called == true); assert(A2<int>::move_called == false); assert(A3<int>::copy_called == true); assert(A3<int>::move_called == false); assert(a2 == a1); } }
[ "tliang@connect.ust.hk" ]
tliang@connect.ust.hk
15e8997687bf9c2c8f1b77f34779c43842ad258e
2b210288fb83c773c7a2afa4d874d35f6a000699
/chromium-webcl/src/chromeos/dbus/mock_dbus_thread_manager_without_gmock.h
ff1e7365cd6d879af34199d4da01bba4ea62cfda
[ "BSD-3-Clause" ]
permissive
mychangle123/Chromium-WebCL
3462ff60a6ef3144729763167be6308921e4195d
2b25f42a0a239127ed39a159c377be58b3102b17
HEAD
2016-09-16T10:47:58.247722
2013-10-31T05:48:50
2013-10-31T05:48:50
14,553,669
1
2
null
null
null
null
UTF-8
C++
false
false
7,682
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_DBUS_MOCK_DBUS_THREAD_MANAGER_WITHOUT_GMOCK_H_ #define CHROMEOS_DBUS_MOCK_DBUS_THREAD_MANAGER_WITHOUT_GMOCK_H_ #include <string> #include "base/logging.h" #include "base/observer_list.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace dbus { class Bus; class ObjectPath; } // namespace dbus namespace chromeos { class DBusThreadManagerObserver; class FakeBluetoothAdapterClient; class FakeBluetoothAgentManagerClient; class FakeBluetoothDeviceClient; class FakeBluetoothInputClient; class FakeBluetoothProfileManagerClient; class FakeCrosDisksClient; class FakeCryptohomeClient; class FakeShillManagerClient; class FakeImageBurnerClient; class FakeSystemClockClient; class MockIBusClient; class MockIBusConfigClient; class MockIBusEngineFactoryService; class MockIBusEngineService; class MockIBusInputContextClient; class MockIBusPanelService; // This class provides an another mock DBusThreadManager without gmock // dependency. This class is used for places where GMock is not allowed // (ex. ui/) or is not used. // TODO(haruki): Along with crbug.com/223061, we can rename this class to // clarify that this can also provides fakes and stubs. class MockDBusThreadManagerWithoutGMock : public DBusThreadManager { public: MockDBusThreadManagerWithoutGMock(); virtual ~MockDBusThreadManagerWithoutGMock(); virtual void AddObserver(DBusThreadManagerObserver* observer) OVERRIDE; virtual void RemoveObserver(DBusThreadManagerObserver* observer) OVERRIDE; virtual void InitIBusBus(const std::string& ibus_address, const base::Closure& closure) OVERRIDE; virtual dbus::Bus* GetSystemBus() OVERRIDE; virtual dbus::Bus* GetIBusBus() OVERRIDE; virtual BluetoothAdapterClient* GetBluetoothAdapterClient() OVERRIDE; virtual BluetoothDeviceClient* GetBluetoothDeviceClient() OVERRIDE; virtual BluetoothInputClient* GetBluetoothInputClient() OVERRIDE; virtual BluetoothManagerClient* GetBluetoothManagerClient() OVERRIDE; virtual BluetoothNodeClient* GetBluetoothNodeClient() OVERRIDE; virtual CrasAudioClient* GetCrasAudioClient() OVERRIDE; virtual CrosDisksClient* GetCrosDisksClient() OVERRIDE; virtual CryptohomeClient* GetCryptohomeClient() OVERRIDE; virtual DebugDaemonClient* GetDebugDaemonClient() OVERRIDE; virtual ExperimentalBluetoothAdapterClient* GetExperimentalBluetoothAdapterClient() OVERRIDE; virtual ExperimentalBluetoothAgentManagerClient* GetExperimentalBluetoothAgentManagerClient() OVERRIDE; virtual ExperimentalBluetoothDeviceClient* GetExperimentalBluetoothDeviceClient() OVERRIDE; virtual ExperimentalBluetoothInputClient* GetExperimentalBluetoothInputClient() OVERRIDE; virtual ExperimentalBluetoothProfileManagerClient* GetExperimentalBluetoothProfileManagerClient() OVERRIDE; virtual ShillDeviceClient* GetShillDeviceClient() OVERRIDE; virtual ShillIPConfigClient* GetShillIPConfigClient() OVERRIDE; virtual ShillManagerClient* GetShillManagerClient() OVERRIDE; virtual ShillProfileClient* GetShillProfileClient() OVERRIDE; virtual ShillServiceClient* GetShillServiceClient() OVERRIDE; virtual GsmSMSClient* GetGsmSMSClient() OVERRIDE; virtual ImageBurnerClient* GetImageBurnerClient() OVERRIDE; virtual IntrospectableClient* GetIntrospectableClient() OVERRIDE; virtual ModemMessagingClient* GetModemMessagingClient() OVERRIDE; virtual PermissionBrokerClient* GetPermissionBrokerClient() OVERRIDE; virtual PowerManagerClient* GetPowerManagerClient() OVERRIDE; virtual PowerPolicyController* GetPowerPolicyController() OVERRIDE; virtual SessionManagerClient* GetSessionManagerClient() OVERRIDE; virtual SMSClient* GetSMSClient() OVERRIDE; virtual SystemClockClient* GetSystemClockClient() OVERRIDE; virtual UpdateEngineClient* GetUpdateEngineClient() OVERRIDE; virtual BluetoothOutOfBandClient* GetBluetoothOutOfBandClient() OVERRIDE; virtual IBusClient* GetIBusClient() OVERRIDE; virtual IBusConfigClient* GetIBusConfigClient() OVERRIDE; virtual IBusInputContextClient* GetIBusInputContextClient() OVERRIDE; virtual IBusEngineFactoryService* GetIBusEngineFactoryService() OVERRIDE; virtual IBusEngineService* GetIBusEngineService( const dbus::ObjectPath& object_path) OVERRIDE; virtual void RemoveIBusEngineService( const dbus::ObjectPath& object_path) OVERRIDE; virtual IBusPanelService* GetIBusPanelService() OVERRIDE; FakeBluetoothAdapterClient* fake_bluetooth_adapter_client() { return fake_bluetooth_adapter_client_.get(); } FakeBluetoothAgentManagerClient* fake_bluetooth_agent_manager_client() { return fake_bluetooth_agent_manager_client_.get(); } FakeBluetoothDeviceClient* fake_bluetooth_device_client() { return fake_bluetooth_device_client_.get(); } FakeBluetoothInputClient* fake_bluetooth_input_client() { return fake_bluetooth_input_client_.get(); } FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client() { return fake_bluetooth_profile_manager_client_.get(); } FakeCryptohomeClient* fake_cryptohome_client() { return fake_cryptohome_client_.get(); } FakeShillManagerClient* fake_shill_manager_client() { return fake_shill_manager_client_.get(); } FakeImageBurnerClient* fake_image_burner_client() { return fake_image_burner_client_.get(); } FakeSystemClockClient* fake_system_clock_client() { return fake_system_clock_client_.get(); } MockIBusClient* mock_ibus_client() { return mock_ibus_client_.get(); } MockIBusConfigClient* mock_ibus_config_client() { return mock_ibus_config_client_.get(); } MockIBusInputContextClient* mock_ibus_input_context_client() { return mock_ibus_input_context_client_.get(); } MockIBusEngineService* mock_ibus_engine_service() { return mock_ibus_engine_service_.get(); } MockIBusEngineFactoryService* mock_ibus_engine_factory_service() { return mock_ibus_engine_factory_service_.get(); } MockIBusPanelService* mock_ibus_panel_service() { return mock_ibus_panel_service_.get(); } void set_ibus_bus(dbus::Bus* ibus_bus) { ibus_bus_ = ibus_bus; } private: scoped_ptr<FakeBluetoothAdapterClient> fake_bluetooth_adapter_client_; scoped_ptr<FakeBluetoothAgentManagerClient> fake_bluetooth_agent_manager_client_; scoped_ptr<FakeBluetoothDeviceClient> fake_bluetooth_device_client_; scoped_ptr<FakeBluetoothInputClient> fake_bluetooth_input_client_; scoped_ptr<FakeBluetoothProfileManagerClient> fake_bluetooth_profile_manager_client_; scoped_ptr<FakeCrosDisksClient> fake_cros_disks_client_; scoped_ptr<FakeCryptohomeClient> fake_cryptohome_client_; scoped_ptr<FakeImageBurnerClient> fake_image_burner_client_; scoped_ptr<FakeShillManagerClient> fake_shill_manager_client_; scoped_ptr<FakeSystemClockClient> fake_system_clock_client_; scoped_ptr<MockIBusClient> mock_ibus_client_; scoped_ptr<MockIBusConfigClient> mock_ibus_config_client_; scoped_ptr<MockIBusInputContextClient> mock_ibus_input_context_client_; scoped_ptr<MockIBusEngineService> mock_ibus_engine_service_; scoped_ptr<MockIBusEngineFactoryService> mock_ibus_engine_factory_service_; scoped_ptr<MockIBusPanelService> mock_ibus_panel_service_; dbus::Bus* ibus_bus_; ObserverList<DBusThreadManagerObserver> observers_; DISALLOW_COPY_AND_ASSIGN(MockDBusThreadManagerWithoutGMock); }; } // namespace chromeos #endif // CHROMEOS_DBUS_MOCK_DBUS_THREAD_MANAGER_WITHOUT_GMOCK_H_
[ "ZhangPeiXuan.CN@Gmail.COM" ]
ZhangPeiXuan.CN@Gmail.COM
36f6aaf10d7e78c6d40d242e3d408a7a248b2316
e8472546fb8c9b0550d3b4a33a2f53623b035295
/Source/Toy/Common/PS_Utils.cpp
a40dc33a3ea0ff2be3641dc14ffd8773c27d5b77
[]
no_license
sungjin-bae/Toy
513d3ebcd7994ea11f8298626be24ca5e25cb72d
8ba1a6ca40910009a0fd0c926762e626bdfa8f9d
refs/heads/master
2021-09-17T22:10:31.116647
2018-07-05T21:23:16
2018-07-05T21:23:16
null
0
0
null
null
null
null
UHC
C++
false
false
2,989
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PS_Utils.h" #include "Engine.h" // 항상 해결해야하는 치명적인 오류에 대한 로깅 DECLARE_LOG_CATEGORY_EXTERN(AssertError, Log, All); DEFINE_LOG_CATEGORY(AssertError); using namespace std; FVector SJ_RotateUtills::ToRight(const FVector& _forward) { SJ_ASSERT(_forward.IsNormalized()); static const FRotator rotate_yaw = FRotator(0.0f, 90.0f, 0.0f); return rotate_yaw.RotateVector(_forward); } FVector2D SJ_RotateUtills::ToRight(const FVector2D& _forward) { SJ_ASSERT(_forward.Size() == 1.0f); static const float rotate_angle = 90.0f; float radian = FMath::DegreesToRadians(rotate_angle); float sin_value = FMath::Sin(radian); float cos_value = FMath::Cos(radian); // rotate point float x_new = _forward.X * cos_value - _forward.Y * sin_value; float y_new = _forward.X * sin_value + _forward.Y * cos_value; return FVector2D(x_new, y_new); } FVector2D SJ_VectorUtills::ToVector2D(const FVector& _vec3) { // z value ingnore // Z값이 필요없는 곳에서 만 사용되어야 한다. FVector2D ret(_vec3.X, _vec3.Y); return ret; } FVector SJ_VectorUtills::ToVector3D(const FVector2D& _vec2) { // z value set 0 // Z값이 필요없는 곳에서 만 사용되어야 한다. FVector ret(_vec2.X, _vec2.Y, 0); return ret; } FVector2D SJ_VectorUtills::ToProjection(const FVector2D& _pivot, const FVector2D& _projection_vec) { // 내적을 얻는다. float dot_scala = FVector2D::DotProduct(_pivot, _projection_vec); // 벡터의 길이를 구한다. float pivot_size = _pivot.SizeSquared(); float _projection_vector_size = _projection_vec.SizeSquared(); float cos_scala = dot_scala / (pivot_size * _projection_vector_size); // v1P의 길이는 float projectioned_size = cos_scala * _projection_vector_size; return FVector2D(projectioned_size * _pivot.X / pivot_size, (projectioned_size * _pivot.Y / pivot_size)); } bool SJ_VectorUtills::Normalize(FVector2D& _vec) { //TODO...size 가 1이 아닌경우가 있다. float size = _vec.Size(); _vec = _vec / size; return true; } bool SJ_VectorUtills::IsNormalized(const FVector2D& _vec) { //TODO 위랑 같음. if (_vec.Size() == 1) { return true; } return true; } void Shutdown(const TCHAR*_file, const int& _line, const TCHAR* _function) { #if WITH_EDITOR PrintLog(_file, _line, _function); QuitTheGame(); #endif } void PrintLog(const TCHAR*_file, const int& _line, const TCHAR*_function) { UE_LOG(AssertError, Error, TEXT("Assert [ File : %s Line : %d Function : %s]"), _file, _line, _function); } void QuitTheGame() { //check assert if (GWorld) { APlayerController *player_controller = GWorld->GetFirstPlayerController(); check(player_controller); //player_controller->IsLocalController(); player_controller->ConsoleCommand("quit"); } }
[ "baehun92@naver.com" ]
baehun92@naver.com
6af605d782825909152d5658b674c4d2151ff10b
93deffee902a42052d9f5fb01e516becafe45b34
/cf/0630/C.cpp
9558f4a1146c538121ce1efaee913edbf16426de
[]
no_license
kobortor/Competitive-Programming
1aca670bc37ea6254eeabbe33e1ee016174551cc
69197e664a71a492cb5b0311a9f7b00cf0b1ccba
refs/heads/master
2023-06-25T05:04:42.492243
2023-06-16T18:28:42
2023-06-16T18:28:42
95,998,328
10
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include<bits/stdc++.h> using namespace std; #define allof(x) (x).begin(), (x).end() typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; int main(){ cin.tie(0); cin.sync_with_stdio(0); ll n; cin >> n; cout << (2ll << n) - 2; }
[ "kobortor@gmail.com" ]
kobortor@gmail.com
08bd5ad5e4b558b583e02b421a9a9bc6690fa7c5
d089b97fa7a0137f95bb2049d0d50ca6b83384aa
/select_value_from_stream/main.cpp
67011366bf076f065c63753e9fbce944cfc3dc3d
[ "MIT" ]
permissive
mogers/fun-challenges
ef2eafce7eeb6103eeb8a0f110e82d3eb5894500
6ae31dae9e97bdcdc4e3bc2054191b2b4a8147a0
refs/heads/master
2021-01-21T13:56:39.847276
2015-10-23T23:05:54
2015-10-23T23:05:54
29,982,573
0
0
null
null
null
null
UTF-8
C++
false
false
1,566
cpp
#include "../data_structures/simple_stream.h" #include <cstdlib> #include <ctime> #include <iostream> using namespace std; // Given a stream of pairs <value, weight>, selects a random value from the // stream with probability proportional to its weight compared to the total // weight sums. Assumes the stream is not empty. template<typename T> T Select(ds::SimpleStream<pair<T, int>>& stream) { pair<T, int> p = stream.Next(); T selected_value = p.first; int sum = p.second; while (stream.HasNext()) { p = stream.Next(); sum += p.second; // We should use a better random number generator. if (rand() % sum < p.second) { selected_value = p.first; } } return selected_value; } void SimpleTest() { vector<pair<int, int>> pairs{{0, 2}, {1, 2}, {2, 4}, {3, 10}, {4, 4}, {5, 3}}; vector<int> times_selected(pairs.size(), 0); // Simulate 1 000 000 selections. int number_trials = 1000000; for (int t = 0; t < number_trials; ++t) { ds::SimpleStream<pair<int, int>> s(pairs); int id = Select<int>(s); ++times_selected[id]; } // Check if the selection match the expected probabilities. int total_weight = 0; for (const auto& p : pairs) { total_weight += p.second; } for (size_t i = 0; i < pairs.size(); i++) { double expected = static_cast<double>(pairs[i].second) / total_weight; double got = static_cast<double>(times_selected[i]) / number_trials; printf("id %lu expected %.4f got %.4f\n", i, expected, got); } } int main() { srand(time(0)); SimpleTest(); return 0; }
[ "mr.miguel.oliveira@gmail.com" ]
mr.miguel.oliveira@gmail.com
dc099d3018fa8b4ec71ce347e29295b29c389b30
aed2f0a60ae095da1d87e6d37d7b4f6e9e5863ca
/campaign/campaign.cpp
6ae2a0ac3326713d6c124bfc44d924411fdadc9f
[]
no_license
rambabuiitk/BigData
55e82f14082401a52bc065078c6463f495cb9879
ae2204986df052fd40453e4af731ff6c5532e947
refs/heads/master
2021-01-17T11:58:30.866112
2013-06-28T00:29:10
2013-06-28T00:29:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,168
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <time.h> using namespace std; typedef std::vector<std::string> StringVector; void Split( std::string sInput, const std::string& sChars, StringVector& vResult ) { std::string sTemp; size_t found; found = sInput.find_first_of( sChars ); while ( found != std::string::npos ) { sTemp = sInput.substr ( 0, found ); vResult.push_back( sTemp ); sInput.erase( 0, found + 1 ); found = sInput.find_first_of( sChars ); } } int StringToNum( const std::string& sInput ) { std::stringstream ss; ss << sInput; int nValue; ss >> nValue; return nValue; } int main(int argc, char *argv[]) { int count = 0; /* match count for each line */ int maxmatch = 0; /* max match for outout campaign */ string name; if (argc < 2) { cout << "Please enter a file path\n"; return -1; } std::ifstream ifsReadFile( argv[1] ); if( ifsReadFile ) { cout<<"Wait for user to type in the input data ..."<<endl; string input_line; getline(cin, input_line); StringVector vInput; StringVector vOutput; Split( input_line, " ", vInput ); std::string sFileLine; while( getline( ifsReadFile, sFileLine ) ) { StringVector vResult; Split( sFileLine, " ", vResult ); for(int i=1;i<vResult.size();i++) { for(int j=0;j<vInput.size();j++) { if(vResult[i].compare(vInput[j]) == 0) { count++; break; } } } if(count > maxmatch || (count == maxmatch && count!= 0)) { maxmatch = count; count = 0; vOutput.push_back( vResult[0] ); name = vResult[0]; } else { count = 0; } } if(maxmatch == 0) { cout<<"No campaign is matched "<<endl; } else { srand ( time(NULL) ); int index = rand() % vOutput.size(); cout<<"index"<<index<<"output size"<<vOutput.size()<<endl; cout<<"Output Campaign is : "<<vOutput[index]<<name<<endl; } } else { std::cerr << "Error: Cannot open the file." << std::endl; return -1; } return 0; }
[ "rambabu.iitk@gmail.com" ]
rambabu.iitk@gmail.com
739e347117ccadbc45d30a6099859f7e567fce7e
a84a232366d1a4fa6b7e81d01c12dd4dff38eb1d
/Text/Text/main.cpp
13b2e67f7acb6f53f7f2fe341eb4d7ad7f9b3368
[]
no_license
TheYoungSmile/caoyang
9c421210ee00109a8cd2750b14646ea449b3adb4
4186657cc959282e0cc6af3c138a1016d4673b82
refs/heads/master
2021-01-01T05:00:48.855463
2016-04-14T14:36:11
2016-04-14T14:36:11
56,241,907
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
// // main.cpp // Text // // Created by caoyang on 16/4/14. // Copyright © 2016年 neworigin. All rights reserved. // #include <iostream> using namespace std; #include "Point.hpp" int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; cout<<"23456789olkjhgf"<<endl; return 0; }
[ "1069230922@qq.com" ]
1069230922@qq.com
431910ab23467c6e5d280274f13ced60ffa20736
31b3fdd0ceb144bbf67b1ac1e67446eec4344fe1
/src/DSGRN/_dsgrn/DSGRN.cpp
326a2092fd9d4147a5c1c478cfb4f08ac85d34b2
[ "MIT" ]
permissive
skepley/DSGRN
13895b84e12253992dd344e5826e7327f51eceee
ea64bece3abee5e2495f3ea63abccc18c53ae25e
refs/heads/master
2020-03-11T00:09:42.932805
2018-03-30T23:58:07
2018-03-30T23:58:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
cpp
/// DSGRN.cpp /// Shaun Harker /// 2018-01-30 /// MIT LICENSE #include "DSGRN.hpp" #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; PYBIND11_MODULE( _dsgrn, m) { TypedObjectBinding(m); // Dynamics AnnotationBinding(m); MorseDecompositionBinding(m); MorseGraphBinding(m); // Graph DigraphBinding(m); PosetBinding(m); ComponentsBinding(m); StrongComponentsBinding(m); LabelledMultidigraphBinding(m); NFABinding(m); // Parameter LogicParameterBinding(m); NetworkBinding(m); OrderParameterBinding(m); ParameterBinding(m); ParameterGraphBinding(m); ConfigurationBinding(m); // Phase DomainBinding(m); DomainGraphBinding(m); // Pattern MatchingGraphBinding(m); MatchingRelationBinding(m); PatternBinding(m); PatternGraphBinding(m); PatternMatchBinding(m); SearchGraphBinding(m); }
[ "sharker81@gmail.com" ]
sharker81@gmail.com
16243b57a3bd490abba21e25234c5f3e329f9724
a5dd4f83e877214a0caa88f2b67d4d70c0d213e2
/9m.Insertion_sort.cpp
baeafb7e65273e8c1bdffac1551b4e20a11d9357
[]
no_license
khushi-kothari/Cplusplus
d9d1a6865a89fb5f094ad6becc0c7a0000a57b70
7c39727c6fec8cfd9f9297bbba0884f26231288f
refs/heads/main
2023-02-08T10:22:27.994995
2020-12-29T06:24:58
2020-12-29T06:24:58
320,293,431
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
//Insertion Sort in an array #include <iostream> #include <climits> using namespace std; int main() { int n; cout << "How many elements you want in an array?" <<endl; cin >> n; int arr[n]; cout << "Enter elements of array:" << endl; for(int i=0; i<n; i++) { cin >> arr[i]; } for(int i=1; i<n; i++) { int e = arr[i]; int j = i-1; while(j>=0 && arr[j] > e) { arr[j+1] = arr[j]; j--; } arr[j+1] = e; } for(int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
[ "noreply@github.com" ]
khushi-kothari.noreply@github.com
c5d87356d22d4ceda76922411591936d8792faea
140d78334109e02590f04769ec154180b2eaf78d
/aws-cpp-sdk-rekognition/include/aws/rekognition/RekognitionErrorMarshaller.h
b2d8e4793e0356e525327a74440e20d42ffc36dc
[ "Apache-2.0", "MIT", "JSON" ]
permissive
coderTong/aws-sdk-cpp
da140feb7e5495366a8d2a6a02cf8b28ba820ff6
5cd0c0a03b667c5a0bd17394924abe73d4b3754a
refs/heads/master
2021-07-08T07:04:40.181622
2017-08-22T21:50:00
2017-08-22T21:50:00
101,145,374
0
1
Apache-2.0
2021-05-04T21:06:36
2017-08-23T06:24:37
C++
UTF-8
C++
false
false
972
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/rekognition/Rekognition_EXPORTS.h> #include <aws/core/client/AWSErrorMarshaller.h> namespace Aws { namespace Client { class AWS_REKOGNITION_API RekognitionErrorMarshaller : public Client::JsonErrorMarshaller { public: Client::AWSError<Client::CoreErrors> FindErrorByName(const char* exceptionName) const override; }; } // namespace Rekognition } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
fe4d2293c0fe736bbb6843835b7240c5dce10d15
6b81e0615c558374b46503922c902bd1a529e92b
/58A - Chat room.cpp
eb3a767e1b745ce9010fb11c0895627854403373
[]
no_license
devfahad/Codeforces
74a77ebef2452357da917b7ef0910fcc53bbef81
7cbd60c5fedf223f38e483ea385ec7586fc45211
refs/heads/master
2021-08-19T01:48:04.775237
2017-11-24T11:44:16
2017-11-24T11:44:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
700
cpp
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; int j = 0, tot = 0; for(int i = j; i < s.length(); i++){ if(s[i] == 'h'){ j=i; tot++; break; } } for(int i = j+1; i < s.length(); i++){ if(s[i] == 'e'){ j=i; tot++; break; } } for(int i = j+1; i < s.length(); i++){ if(s[i] == 'l'){ j=i; tot++; break; } } for(int i = j+1; i < s.length(); i++){ if(s[i] == 'l'){ j=i; tot++; break; } } for(int i = j+1; i < s.length(); i++){ if(s[i] == 'o'){ j=i; tot++; break; } } if(tot == 5) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
[ "noreply@github.com" ]
devfahad.noreply@github.com
d5737395eb37bd2aa958a1a64bd64e60c10fcd76
dee52474971db4fcbc8696feab48ce63d141b2d3
/Base/BaseAnalysis/interface/StyleManager.h
6f854241e00e64922d9f3cb36e2b3cf89a4328d5
[]
no_license
nadjieh/work
7de0282f3ed107e25f596fd7d0a95f21793c8d29
3c9cc0319e1ab5cd240063f6dd940872b212ddce
refs/heads/master
2016-09-01T17:34:31.112603
2014-02-07T22:43:32
2014-02-07T22:43:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,884
h
/* * File: StyleManager.h * Author: hbakhshi * * Created on January 29, 2009, 7:45 PM */ #ifndef _STYLEMANAGER_H #define _STYLEMANAGER_H #include "TH1.h" #include "TStyle.h" #include "TRandom.h" class StyleManager { public: //option = 1 : fill ; 2 : line static TH1 * SetStyle(TH1* h, int k, short option = 1) { int fillStyle = -1; short fillColor = -1; h->SetLineWidth(1); switch (k) { case 0: h->SetLineWidth(2); fillStyle = 3454; fillColor = (short) 30; break; case 1: fillStyle = 3445; fillColor = (short) 46; break; case 2: fillColor = 38; goto def; case 3: fillColor = 40; goto def; case 4: fillColor = 47; goto def; case 5: fillColor = 14; goto def; case 6: fillColor = 32; goto def; case 7: fillColor = short(kBlack); goto def; def: default: break; } if (fillStyle < 0) fillStyle = (330 + k) *10 + k; if (fillColor < 0) fillColor = short(gRandom->Uniform(3, 50)); h->SetFillColor(kWhite); h->SetFillStyle(0); h->SetLineColor(kWhite); h->SetFillAttributes(); h->SetLineAttributes(); if (option == 1) { h->SetFillColor(fillColor); h->SetFillStyle(fillStyle); h->SetFillAttributes(); } else if (option == 2) { h->SetLineColor(fillColor); h->SetLineAttributes(); } return h; }; }; #endif /* _STYLEMANAGER_H */
[ "ajafari@cern.ch" ]
ajafari@cern.ch
20d6452f9c1f8dd7b5d6ebbcd17bc13a42624b62
312904f23d5aa152081ad66cd8f19c717f4e86a7
/Divisible/Divisible.h
b375dda98f944eff1dc36ce51693dd915434428a
[]
no_license
jesus2708/Divisible
ac651b173aaebb5b346032cd1b9b54d55800abf1
a6e20e4b8d3d9a47e1fb9e541644af118e1331e4
refs/heads/master
2020-07-10T00:29:47.178015
2017-06-13T23:57:15
2017-06-13T23:57:15
94,265,529
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
h
#pragma once //______________________________________ Divisible.h #include "Resource.h" class Divisible: public Win::Dialog { public: Divisible() { } ~Divisible() { } protected: //______ Wintempla GUI manager section begin: DO NOT EDIT AFTER THIS LINE Win::Label lb1; Win::Textbox tbxNumero1; Win::Label lb2; Win::Textbox tbxNumero2; Win::Textbox tbxResultado; Win::Button btCalcular; protected: Win::Gdi::Font fontArial009A; void GetDialogTemplate(DLGTEMPLATE& dlgTemplate) { dlgTemplate.cx=Sys::Convert::CentimetersToDlgUnitX(10.82146); dlgTemplate.cy=Sys::Convert::CentimetersToDlgUnitY(2.91042); dlgTemplate.style = WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | DS_CENTER | DS_MODALFRAME; } //_________________________________________________ void InitializeGui() { this->Text = L"Divisible"; lb1.CreateX(NULL, L"numero 1", WS_CHILD | WS_VISIBLE | SS_LEFT | SS_WINNORMAL, 0.58208, 0.37042, 2.22250, 0.60854, hWnd, 1000); tbxNumero1.CreateX(WS_EX_CLIENTEDGE, NULL, WS_CHILD | WS_TABSTOP | WS_VISIBLE | ES_AUTOHSCROLL | ES_LEFT | ES_WINNORMALCASE, 0.50271, 1.29646, 2.30187, 0.60854, hWnd, 1001); lb2.CreateX(NULL, L"Numero 2", WS_CHILD | WS_VISIBLE | SS_LEFT | SS_WINNORMAL, 4.49792, 0.44979, 2.43417, 0.60854, hWnd, 1002); tbxNumero2.CreateX(WS_EX_CLIENTEDGE, NULL, WS_CHILD | WS_TABSTOP | WS_VISIBLE | ES_AUTOHSCROLL | ES_LEFT | ES_WINNORMALCASE, 4.47146, 1.27000, 2.43417, 0.60854, hWnd, 1003); tbxResultado.CreateX(WS_EX_CLIENTEDGE, NULL, WS_CHILD | WS_TABSTOP | WS_VISIBLE | ES_AUTOHSCROLL | ES_READONLY | ES_LEFT | ES_WINNORMALCASE, 0.47625, 2.11667, 6.61458, 0.60854, hWnd, 1004); btCalcular.CreateX(NULL, L"Calcular", WS_CHILD | WS_TABSTOP | WS_VISIBLE | BS_PUSHBUTTON | BS_CENTER | BS_VCENTER, 7.93750, 0.92604, 2.69875, 0.68792, hWnd, 1005); fontArial009A.CreateX(L"Arial", 0.317500, false, false, false, false); lb1.Font = fontArial009A; tbxNumero1.Font = fontArial009A; lb2.Font = fontArial009A; tbxNumero2.Font = fontArial009A; tbxResultado.Font = fontArial009A; btCalcular.Font = fontArial009A; } //_________________________________________________ void btCalcular_Click(Win::Event& e); void Window_Open(Win::Event& e); //_________________________________________________ bool EventHandler(Win::Event& e) { if (btCalcular.IsEvent(e, BN_CLICKED)) {btCalcular_Click(e); return true;} return false; } };
[ "calderon3356@hotmail.com" ]
calderon3356@hotmail.com
2eaf6ea734f7d29880d51dce8d9e33b26184c26d
749d80a853776ea9d9fb61f329e187abc08cbcc1
/server/src/file_system.h
7e8297d1f264a0f511d712061c53ddd5d557fcf9
[]
no_license
iuvei/SimpleEngine
1b724dafdb9b4acd6dcbdd1657983ca3e49516c8
cebfe7132f001e04879c731889b9686ebc41abb2
refs/heads/master
2020-05-18T11:59:04.550843
2019-04-20T09:38:48
2019-04-20T09:38:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
#pragma once #include <string> #include <vector> using String = std::string; class FileSystem { public: FileSystem(); ~FileSystem(); static std::string GetPath(); static String GetTSVPath(String name); static String GetTablePath(String name); static std::string GetAbsPath(std::string localPath); static std::string GetResourcePath(std::string localPath); static std::string GetAssetsPath(std::string path); static std::string GetShaderPath(std::string path); static std::string GetLuaPath(std::string path); static std::string GetWDFPath(std::string path); static std::string GetMapPath(std::string path); static std::string GetFontPath(std::string path); static std::string GetIconPath(std::string path); static std::vector<std::string> ListFiles(std::string path); static std::vector<std::string> ListAllFiles(std::string path); };
[ "oceancx@gmail.com" ]
oceancx@gmail.com
ea472d6ca6f533b51722b2639e0b3139ca7a13ff
43f7d99daae7bde69fdd80605462560808b6de16
/inc/simple-win32/mfc/FlashCtrl.h
55c930bec523f055e338713531f86ff7ca84915d
[ "MIT" ]
permissive
brucezhang80/simple-cpp-win32
4e1238c700dd4b12a1d507c8a298c87c44e01ba3
06e3bf61f4c8c70ae9c2f285a6bf161c00468dcd
refs/heads/master
2021-05-11T04:23:58.662667
2017-05-26T09:06:31
2017-05-26T09:06:31
null
0
0
null
null
null
null
GB18030
C++
false
false
17,034
h
#pragma once // 计算机生成了由 Microsoft Visual C++ 创建的 IDispatch 包装类 // 注意: 不要修改此文件的内容。如果此类由 // Microsoft Visual C++ 重新生成,您的修改将被覆盖。 ///////////////////////////////////////////////////////////////////////////// // FlashCtrl 包装类 class FlashCtrl : public CWnd { protected: DECLARE_DYNCREATE(FlashCtrl) public: CLSID const& GetClsid() { static CLSID const clsid = { 0xD27CDB6E, 0xAE6D, 0x11CF, { 0x96, 0xB8, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } }; return clsid; } virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL) { return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); } BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CFile* pPersist = NULL, BOOL bStorage = FALSE, BSTR bstrLicKey = NULL) { return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID, pPersist, bStorage, bstrLicKey); } // 特性 public: // 操作 public: // IShockwaveFlash // Functions // long get_ReadyState() { long result; InvokeHelper(DISPID_READYSTATE, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long get_TotalFrames() { long result; InvokeHelper(0x7c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } BOOL get_Playing() { BOOL result; InvokeHelper(0x7d, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_Playing(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0x7d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_Quality() { long result; InvokeHelper(0x69, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_Quality(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x69, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_ScaleMode() { long result; InvokeHelper(0x78, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_ScaleMode(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x78, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_AlignMode() { long result; InvokeHelper(0x79, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_AlignMode(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x79, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_BackgroundColor() { long result; InvokeHelper(0x7b, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_BackgroundColor(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x7b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL get_Loop() { BOOL result; InvokeHelper(0x6a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_Loop(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0x6a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_Movie() { CString result; InvokeHelper(0x66, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_Movie(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x66, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_FrameNum() { long result; InvokeHelper(0x6b, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_FrameNum(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x6b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } void SetZoomRect(long left, long top, long right, long bottom) { static BYTE parms[] = VTS_I4 VTS_I4 VTS_I4 VTS_I4 ; InvokeHelper(0x6d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, left, top, right, bottom); } void Zoom(long factor) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x76, DISPATCH_METHOD, VT_EMPTY, NULL, parms, factor); } void Pan(long x, long y, long mode) { static BYTE parms[] = VTS_I4 VTS_I4 VTS_I4 ; InvokeHelper(0x77, DISPATCH_METHOD, VT_EMPTY, NULL, parms, x, y, mode); } void Play() { InvokeHelper(0x70, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Stop() { InvokeHelper(0x71, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Back() { InvokeHelper(0x72, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Forward() { InvokeHelper(0x73, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void Rewind() { InvokeHelper(0x74, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void StopPlay() { InvokeHelper(0x7e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void GotoFrame(long FrameNum) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x7f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, FrameNum); } long CurrentFrame() { long result; InvokeHelper(0x80, DISPATCH_METHOD, VT_I4, (void*)&result, NULL); return result; } BOOL IsPlaying() { BOOL result; InvokeHelper(0x81, DISPATCH_METHOD, VT_BOOL, (void*)&result, NULL); return result; } long PercentLoaded() { long result; InvokeHelper(0x82, DISPATCH_METHOD, VT_I4, (void*)&result, NULL); return result; } BOOL FrameLoaded(long FrameNum) { BOOL result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0x83, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, FrameNum); return result; } long FlashVersion() { long result; InvokeHelper(0x84, DISPATCH_METHOD, VT_I4, (void*)&result, NULL); return result; } CString get_WMode() { CString result; InvokeHelper(0x85, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_WMode(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x85, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_SAlign() { CString result; InvokeHelper(0x86, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_SAlign(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x86, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL get_Menu() { BOOL result; InvokeHelper(0x87, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_Menu(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0x87, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_Base() { CString result; InvokeHelper(0x88, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_Base(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x88, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_Scale() { CString result; InvokeHelper(0x89, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_Scale(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x89, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL get_DeviceFont() { BOOL result; InvokeHelper(0x8a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_DeviceFont(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0x8a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL get_EmbedMovie() { BOOL result; InvokeHelper(0x8b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_EmbedMovie(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0x8b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_BGColor() { CString result; InvokeHelper(0x8c, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_BGColor(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x8c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_Quality2() { CString result; InvokeHelper(0x8d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_Quality2(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x8d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } void LoadMovie(long layer, LPCTSTR url) { static BYTE parms[] = VTS_I4 VTS_BSTR ; InvokeHelper(0x8e, DISPATCH_METHOD, VT_EMPTY, NULL, parms, layer, url); } void TGotoFrame(LPCTSTR target, long FrameNum) { static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0x8f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, FrameNum); } void TGotoLabel(LPCTSTR target, LPCTSTR label) { static BYTE parms[] = VTS_BSTR VTS_BSTR ; InvokeHelper(0x90, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, label); } long TCurrentFrame(LPCTSTR target) { long result; static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x91, DISPATCH_METHOD, VT_I4, (void*)&result, parms, target); return result; } CString TCurrentLabel(LPCTSTR target) { CString result; static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x92, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, target); return result; } void TPlay(LPCTSTR target) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x93, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target); } void TStopPlay(LPCTSTR target) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x94, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target); } void SetVariable(LPCTSTR name, LPCTSTR value) { static BYTE parms[] = VTS_BSTR VTS_BSTR ; InvokeHelper(0x97, DISPATCH_METHOD, VT_EMPTY, NULL, parms, name, value); } CString GetVariable(LPCTSTR name) { CString result; static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x98, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, name); return result; } void TSetProperty(LPCTSTR target, long property, LPCTSTR value) { static BYTE parms[] = VTS_BSTR VTS_I4 VTS_BSTR ; InvokeHelper(0x99, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, property, value); } CString TGetProperty(LPCTSTR target, long property) { CString result; static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0x9a, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, target, property); return result; } void TCallFrame(LPCTSTR target, long FrameNum) { static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0x9b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, FrameNum); } void TCallLabel(LPCTSTR target, LPCTSTR label) { static BYTE parms[] = VTS_BSTR VTS_BSTR ; InvokeHelper(0x9c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, label); } void TSetPropertyNum(LPCTSTR target, long property, double value) { static BYTE parms[] = VTS_BSTR VTS_I4 VTS_R8 ; InvokeHelper(0x9d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, target, property, value); } double TGetPropertyNum(LPCTSTR target, long property) { double result; static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0x9e, DISPATCH_METHOD, VT_R8, (void*)&result, parms, target, property); return result; } double TGetPropertyAsNumber(LPCTSTR target, long property) { double result; static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0xac, DISPATCH_METHOD, VT_R8, (void*)&result, parms, target, property); return result; } CString get_SWRemote() { CString result; InvokeHelper(0x9f, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_SWRemote(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x9f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_FlashVars() { CString result; InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_FlashVars(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xaa, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_AllowScriptAccess() { CString result; InvokeHelper(0xab, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_AllowScriptAccess(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xab, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_MovieData() { CString result; InvokeHelper(0xbe, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_MovieData(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xbe, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } LPUNKNOWN get_InlineData() { LPUNKNOWN result; InvokeHelper(0xbf, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); return result; } void put_InlineData(LPUNKNOWN newValue) { static BYTE parms[] = VTS_UNKNOWN ; InvokeHelper(0xbf, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL get_SeamlessTabbing() { BOOL result; InvokeHelper(0xc0, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_SeamlessTabbing(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0xc0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } void EnforceLocalSecurity() { InvokeHelper(0xc1, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } BOOL get_Profile() { BOOL result; InvokeHelper(0xc2, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void put_Profile(BOOL newValue) { static BYTE parms[] = VTS_BOOL ; InvokeHelper(0xc2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_ProfileAddress() { CString result; InvokeHelper(0xc3, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_ProfileAddress(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xc3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long get_ProfilePort() { long result; InvokeHelper(0xc4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_ProfilePort(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0xc4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString CallFunction(LPCTSTR request) { CString result; static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xc6, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, request); return result; } void SetReturnValue(LPCTSTR returnValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xc7, DISPATCH_METHOD, VT_EMPTY, NULL, parms, returnValue); } void DisableLocalSecurity() { InvokeHelper(0xc8, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } CString get_AllowNetworking() { CString result; InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_AllowNetworking(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xc9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString get_AllowFullScreen() { CString result; InvokeHelper(0xca, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_AllowFullScreen(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0xca, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } // Properties // };
[ "ximenpo@jiandan.ren" ]
ximenpo@jiandan.ren
a1404883fd36934742adcbe850ee8fde511c23e5
7755086db5a0aa7b68883760867ba34057cf9ba0
/Practice_primer/test_static.cpp
eeda226c533150e711027da382b70ab7422d2a58
[]
no_license
huoxiaodan-kaihong/C-Plus-Plus
e87f68ff539399ac9b0ad9998525696d6f2a5ef5
a3ab82ae1fe215d13b6861b5e2e9213a7c6a038a
refs/heads/master
2023-03-17T23:05:46.631718
2019-06-10T07:54:43
2019-06-10T07:54:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
412
cpp
#include <iostream> using namespace std; class MyClass { public: MyClass() { ++count; } ~MyClass() { --count; } static int getCount() { return count; } private: static int count; }; int MyClass::count = 0; int main() { MyClass obj; cout << obj.getCount(); MyClass obj2; cout << MyClass::getCount(); cout << obj2.getCount(); return 0; }
[ "872575628@qq.com" ]
872575628@qq.com
9139a398865194d49a2d60ca2aa64713e32a214f
2a9cf39e8dd941bd9fb0c4fb5dcdb49897502318
/OpencvTutorial/Imgprocessing/MorphLineDetection/morph_line_detection.cpp
c3571a5d55cb03c22d46227cc97e3b0eaece1d4a
[]
no_license
spidervn/atom_it
4542e55d3c358cb673d8a767474df38d691219a4
5fe296410e2330c0677d7dbcb42553da15c5d1f2
refs/heads/master
2018-09-16T04:58:40.150441
2018-06-05T16:39:01
2018-06-05T16:39:01
92,168,496
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
cpp
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main(int argc, char const *argv[]) { if (argc != 2) { printf("Usage: %s image_file\n", argv[0]); return -1; } // Load the image Mat src = imread(argv[1]); if (!src.data) { cerr << "Problem loading page !!!" << endl; } imshow("src", src); // Transform source image to gray if it is not Mat gray; if (src.channels() == 3) { cvtColor(src, gray, CV_BGR2GRAY); } else { gray = src; } // Show gray image imshow("gray", gray); // Apply adaptiveThreshold at the bitwise_not of gray, notice the ~symbol Mat bw; adaptiveThreshold(~gray, bw, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2); // Show binary image imshow("binary", bw); // Create the images that will use to extract the horizontal and vertical lines Mat horizontal = bw.clone(); Mat vertical = bw.clone(); // Specify size on horizontal axis int horizontalsize = horizontal.cols / 30; // Create structure element for extracting horizontal lines through morpholog operations Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontalsize, 1)); // Apply morphology operations erode(horizontal, horizontal, horizontalStructure, Point(-1, -1)); dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1)); // Show extracted horizontal lines imshow("horizontal", horizontal); // Specific size of vertical axis int verticalsize = vertical.rows / 30; // Create structure element for extracting vertical lines through morphology operations Mat verticalStructure = getStructuringElement(MORPH_RECT, Size(1, verticalsize)); // Apply morphology operations erode(vertical, vertical, verticalStructure, Point(-1, -1)); dilate(vertical, vertical, verticalStructure, Point(-1, -1)); // Show extracted vertical lines imshow("vertical", vertical); // Inverse vertical image bitwise_not(vertical, vertical); imshow("vertical_bit", vertical); // Extract edges and smooth image according to the logic // 1. Extract edges // 2. Dilate (edges) // 3. src.copyTo(smooth) // 4. blur smooth img // 5. smooth.copyTo(src, edges) // Step 1 Mat edges; adaptiveThreshold(vertical, edges,255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, -2); imshow("edges", edges); // Step 2 Mat kernel = Mat::ones(2, 2, CV_8UC1); dilate(edges, edges, kernel); imshow("dilate", edges); // Step 3 Mat smooth; vertical.copyTo(smooth); // Step 4 blur(smooth, smooth, Size(2, 2)); // Step 5 smooth.copyTo(vertical, edges); // Show final result imshow("smooth", vertical); waitKey(0); return 0; }
[ "a@vnn.vn" ]
a@vnn.vn
8008ff21fa7e285c809390a02f5d41e5012bbaf0
ae9e2680ce3fbcc95f8ccec1be7cda52195f9c73
/camLasAlignment.h
cd54717bee239d455bee327e04753b862f7add2e
[]
no_license
OliverBJ01/alignment
00f3a5e4fd9082158712efb47f422a5c043e43d8
b1d127493fc09196cd36217625b6c741e04ff57d
refs/heads/master
2021-08-23T04:08:45.354195
2017-12-03T05:57:16
2017-12-03T05:57:16
112,903,666
0
0
null
null
null
null
UTF-8
C++
false
false
3,022
h
// // Created by bernard on 10/06/17. // #ifndef CAMLASALIGNMENT_CAMLASALIGNMENT_H #define CAMLASALIGNMENT_CAMLASALIGNMENT_H #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <unistd.h> // for usleep using namespace cv; using namespace std; // IP cam stream addresses //#define IPCAM_STREAMADDRESS "http://root:Isabel00@10.1.1.5/mjpg/video.mjpg" //Axis IP Camera @ Port 80 #define IPCAM_STREAMADDRESS "http://admin:Isabel00@10.1.1.5/video.cgi?.mjpg" // D-Link IP camera @ Port 80 int cameraCapture( VideoCapture &cap, string camType, int usbDeviceNo, string ipCamStreamAddress, int &frameWidth, int &frameHeight); // ------------- scanner defs ------------------ // scanner frame size is theoretically 0 to 65535 both x and y set by scanner DAC range // However, this is the practical frame size as scanner board trips outside these values #define DAC_X_MIN 512 #define DAC_X_MAX 65024 #define DAC_Y_MIN 512 #define DAC_Y_MAX 65024 // used only to reverse direction in sendScannerMssg() #define SCANNER_DAC_LIMIT 65535 #endif //CAMLASALIGNMENT_CAMLASALIGNMENT_H // mcuScanner server #define SCANNERPORT "1000" // scanner port No. #define SCANNERADDRESS "10.1.1.99" // scanner IP address //#define OPENCVPORT 9988 // port to receive UDP packets from openCV // ---------message details copied from mcuServer ----------- struct statusWord { ushort serverFault : 1; // server has fault ushort laserFault : 1; // server fault ushort scanXFault : 1; // server fault ushort scanYFault : 1; // server fault ushort unknownScannerFault : 1; // server fault ushort hwStartFail : 1; // server hardware didn't start ushort laserPower : 1; // client command ushort dacReset : 1; // client command ushort spiError : 1; // server sets on excessive spi errors ushort verbose : 1; // client command } ; // 1. ---- messages received by client from mcuServer struct serverMssg { // message sent to client ushort scanX; //scanner X value ushort scanY; ushort info; struct statusWord status; }; // 2. ----- message sent to mcuServer by client struct clientMssg { // message recvd. from client ushort scanX; //scanner X value ushort scanY; ushort info; // send data client to server & vice versa } ; // (this) client's commands to server enum cmdMssg {CMD_LASER_OFF, CMD_LASER_ON, CMD_SCANXPWR_OFF, CMD_SCANXPWR_ON, CMD_SCANYPWR_OFF, CMD_SCANYPWR_ON, CMD_SLEW, CMD_VERBOSE_ON, CMD_VERBOSE_OFF, CMD_NULL_MSSG, CMD_RESET } ; //void sendMssg(uint x, uint y, bool laserOn) ; int initQtSocket(void); void showCalRectangle(int state, void*); void disableEngagement(int state, void*); int initLaserEnableTimer(void) ; void Bresenham(long x1, long y1, long x2, long y2); int connectToServer(); void error(const char *msg); void sendMssgToScanner(uint x, uint y, uint laserOn); void *drawLaserExtents(void *arg); void *drawNbyNPoints(void *arg);
[ "bernard.j.oliver@gmail.com" ]
bernard.j.oliver@gmail.com
79316ebca81a5b967aa9ad9c84614b66b7b94a0a
cae23192da4ae19ed19140051bb427af8da5ffef
/src/pyHiChi/include/pyField.h
b5cbe39b12e863508bb4e3804e865342cc199132
[ "MIT" ]
permissive
AleksandrPanov/pyHiChi
9d8ca6fcd8ad7f9a3653e552351af47ad3e81fed
f9b0c4ec17ad1c9b5897770b86be9152b0ab29ca
refs/heads/master
2021-07-14T07:25:23.208457
2021-05-05T11:08:46
2021-05-05T11:08:46
247,687,495
0
0
MIT
2020-03-16T11:41:39
2020-03-16T11:41:38
null
UTF-8
C++
false
false
43,922
h
#pragma once #include <memory> #include "Grid.h" #include "FieldValue.h" #include "Mapping.h" #include "Fdtd.h" #include "Psatd.h" #include "Pstd.h" #include "Mapping.h" #include "pybind11/pybind11.h" namespace py = pybind11; using namespace pybind11::literals; namespace pfc { template <class TGrid, class TFieldSolver> class pyFieldEntity : public TGrid, public TFieldSolver { public: pyFieldEntity(const Int3 & numInternalCells, const FP3 & minCoords, const FP3 & steps, FP dt) : TGrid(Int3(numInternalCells), minCoords, steps, numInternalCells), TFieldSolver(static_cast<TGrid*>(this), dt) {} void refresh() { this->globalTime = 0.0; } }; template <class TGrid, class TFieldSolver, class TDerived, bool ifStraggered> class pyStraggeredFieldIntarface {}; // spatial straggered grids template <class TGrid, class TFieldSolver, class TDerived> class pyStraggeredFieldIntarface<TGrid, TFieldSolver, TDerived, true> { public: template <class FieldConfigurationType> void setFieldConfiguration(const FieldConfigurationType* fieldConf) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); const int chunkSize = 32; const int nChunks = fieldEntity->numCells.z / chunkSize; const int chunkRem = fieldEntity->numCells.z % chunkSize; const int nx = fieldEntity->numCells.x, ny = fieldEntity->numCells.y; #pragma omp parallel for collapse(2) for (int i = 0; i < nx; i++) for (int j = 0; j < ny; j++) for (int chunk = 0; chunk < nChunks + 1; chunk++) { FP3 cEx[chunkSize], cEy[chunkSize], cEz[chunkSize]; FP3 cBx[chunkSize], cBy[chunkSize], cBz[chunkSize]; int kLast = chunk == nChunks ? chunkRem : chunkSize; #pragma ivdep for (int k = 0; k < kLast; k++) { cEx[k] = derived->convertCoords(fieldEntity->ExPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftE); cEy[k] = derived->convertCoords(fieldEntity->EyPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftE); cEz[k] = derived->convertCoords(fieldEntity->EzPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftE); cBx[k] = derived->convertCoords(fieldEntity->BxPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftB); cBy[k] = derived->convertCoords(fieldEntity->ByPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftB); cBz[k] = derived->convertCoords(fieldEntity->BzPosition(i, j, chunk * chunkSize), fieldEntity->timeShiftB); } #pragma ivdep #pragma omp simd for (int k = 0; k < kLast; k++) { fieldEntity->Ex(i, j, k) = fieldConf->getE(cEx[k].x, cEx[k].y, cEx[k].z).x; fieldEntity->Ey(i, j, k) = fieldConf->getE(cEy[k].x, cEy[k].y, cEy[k].z).y; fieldEntity->Ez(i, j, k) = fieldConf->getE(cEz[k].x, cEz[k].y, cEz[k].z).z; fieldEntity->Bx(i, j, k) = fieldConf->getB(cBx[k].x, cBx[k].y, cBx[k].z).x; fieldEntity->By(i, j, k) = fieldConf->getB(cBy[k].x, cBy[k].y, cBy[k].z).y; fieldEntity->Bz(i, j, k) = fieldConf->getB(cBz[k].x, cBz[k].y, cBz[k].z).z; } } } }; // collocated grids template <class TGrid, class TFieldSolver, class TDerived> class pyStraggeredFieldIntarface<TGrid, TFieldSolver, TDerived, false> { public: template <class FieldConfigurationType> void setFieldConfiguration(const FieldConfigurationType* fieldConf) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); const int chunkSize = 32; const int nChunks = fieldEntity->numCells.z / chunkSize; const int chunkRem = fieldEntity->numCells.z % chunkSize; const int nx = fieldEntity->numCells.x, ny = fieldEntity->numCells.y; #pragma omp parallel for collapse(2) for (int i = 0; i < nx; i++) for (int j = 0; j < ny; j++) for (int chunk = 0; chunk < nChunks + 1; chunk++) { FP3 coords[chunkSize]; int kLast = chunk == nChunks ? chunkRem : chunkSize; FP3 startPosition = fieldEntity->ExPosition(i, j, chunk * chunkSize); #pragma ivdep for (int k = 0; k < kLast; k++) { FP3 position(startPosition.x, startPosition.y, startPosition.z + k * fieldEntity->steps.z); coords[k] = derived->convertCoords(position); } #pragma ivdep #pragma omp simd for (int k = 0; k < kLast; k++) { FP3 E, B; fieldConf->getEB(coords[k].x, coords[k].y, coords[k].z, &E, &B); fieldEntity->Ex(i, j, k + chunk * chunkSize) = E.x; fieldEntity->Ey(i, j, k + chunk * chunkSize) = E.y; fieldEntity->Ez(i, j, k + chunk * chunkSize) = E.z; fieldEntity->Bx(i, j, k + chunk * chunkSize) = B.x; fieldEntity->By(i, j, k + chunk * chunkSize) = B.y; fieldEntity->Bz(i, j, k + chunk * chunkSize) = B.z; } } } void pySetEMField(py::function fValueField) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 coords = derived->convertCoords(fieldEntity->ExPosition(i, j, k)); ValueField field = fValueField("x"_a = coords.x, "y"_a = coords.y, "z"_a = coords.z). template cast<ValueField>(); fieldEntity->Ex(i, j, k) = field.E.x; fieldEntity->Ey(i, j, k) = field.E.y; fieldEntity->Ez(i, j, k) = field.E.z; fieldEntity->Bx(i, j, k) = field.B.x; fieldEntity->By(i, j, k) = field.B.y; fieldEntity->Bz(i, j, k) = field.B.z; } } void setEMField(int64_t _fValueField) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); void(*fValueField)(FP, FP, FP, FP*) = (void(*)(FP, FP, FP, FP*))_fValueField; const int chunkSize = 32; const int nChunks = fieldEntity->numCells.z / chunkSize; const int chunkRem = fieldEntity->numCells.z % chunkSize; const int nx = fieldEntity->numCells.x, ny = fieldEntity->numCells.y; #pragma omp parallel for collapse(2) for (int i = 0; i < nx; i++) for (int j = 0; j < ny; j++) for (int chunk = 0; chunk < nChunks + 1; chunk++) { FP3 coords[chunkSize]; int kLast = chunk == nChunks ? chunkRem : chunkSize; FP3 startPosition = fieldEntity->ExPosition(i, j, chunk * chunkSize); #pragma ivdep for (int k = 0; k < kLast; k++) { FP3 position(startPosition.x, startPosition.y, startPosition.z + k * fieldEntity->steps.z); coords[k] = derived->convertCoords(position); } #pragma ivdep #pragma omp simd for (int k = 0; k < kLast; k++) { ValueField field(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); fValueField(coords[k].x, coords[k].y, coords[k].z, &(field.E.x)); fieldEntity->Ex(i, j, k + chunk * chunkSize) = field.E.x; fieldEntity->Ey(i, j, k + chunk * chunkSize) = field.E.y; fieldEntity->Ez(i, j, k + chunk * chunkSize) = field.E.z; fieldEntity->Bx(i, j, k + chunk * chunkSize) = field.B.x; fieldEntity->By(i, j, k + chunk * chunkSize) = field.B.y; fieldEntity->Bz(i, j, k + chunk * chunkSize) = field.B.z; } } } }; template<class TGrid, class TFieldSolver, class TDerived> class pyFieldGridInterface : public pyStraggeredFieldIntarface<TGrid, TFieldSolver, TDerived, TGrid::ifFieldsSpatialStraggered && TGrid::ifFieldsTimeStraggered> { public: pyFieldGridInterface() { fEt[0] = 0; fEt[1] = 0; fEt[2] = 0; fBt[0] = 0; fBt[1] = 0; fBt[2] = 0; isAnalytical = false; } void setAnalytical(int64_t _fEx, int64_t _fEy, int64_t _fEz, int64_t _fBx, int64_t _fBy, int64_t _fBz) { fEt[0] = _fEx; fEt[1] = _fEy; fEt[2] = _fEz; fBt[0] = _fBx; fBt[1] = _fBy; fBt[2] = _fBz; isAnalytical = true; } void analyticalUpdateFields(FP t) { if (isAnalytical) { setExyzt(fEt[0], fEt[1], fEt[2], t); setBxyzt(fBt[0], fBt[1], fBt[2], t); } } void pySetExyz(py::function fEx, py::function fEy, py::function fEz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cEx, cEy, cEz; cEx = derived->convertCoords(fieldEntity->ExPosition(i, j, k), fieldEntity->timeShiftE); cEy = derived->convertCoords(fieldEntity->EyPosition(i, j, k), fieldEntity->timeShiftE); cEz = derived->convertCoords(fieldEntity->EzPosition(i, j, k), fieldEntity->timeShiftE); fieldEntity->Ex(i, j, k) = fEx("x"_a = cEx.x, "y"_a = cEx.y, "z"_a = cEx.z).template cast<FP>(); fieldEntity->Ey(i, j, k) = fEy("x"_a = cEy.x, "y"_a = cEy.y, "z"_a = cEy.z).template cast<FP>(); fieldEntity->Ez(i, j, k) = fEz("x"_a = cEz.x, "y"_a = cEz.y, "z"_a = cEz.z).template cast<FP>(); } } void pySetE(py::function fE) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cEx, cEy, cEz; cEx = derived->convertCoords(fieldEntity->ExPosition(i, j, k), fieldEntity->timeShiftE); cEy = derived->convertCoords(fieldEntity->EyPosition(i, j, k), fieldEntity->timeShiftE); cEz = derived->convertCoords(fieldEntity->EzPosition(i, j, k), fieldEntity->timeShiftE); fieldEntity->Ex(i, j, k) = fE("x"_a = cEx.x, "y"_a = cEx.y, "z"_a = cEx.z).template cast<FP3>().x; fieldEntity->Ey(i, j, k) = fE("x"_a = cEy.x, "y"_a = cEy.y, "z"_a = cEy.z).template cast<FP3>().y; fieldEntity->Ez(i, j, k) = fE("x"_a = cEz.x, "y"_a = cEz.y, "z"_a = cEz.z).template cast<FP3>().z; } } void setExyz(int64_t _fEx, int64_t _fEy, int64_t _fEz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fEx)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fEx; FP(*fEy)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fEy; FP(*fEz)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fEz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cEx, cEy, cEz; cEx = derived->convertCoords(fieldEntity->ExPosition(i, j, k), fieldEntity->timeShiftE); cEy = derived->convertCoords(fieldEntity->EyPosition(i, j, k), fieldEntity->timeShiftE); cEz = derived->convertCoords(fieldEntity->EzPosition(i, j, k), fieldEntity->timeShiftE); fieldEntity->Ex(i, j, k) = fEx(cEx.x, cEx.y, cEx.z); fieldEntity->Ey(i, j, k) = fEy(cEy.x, cEy.y, cEy.z); fieldEntity->Ez(i, j, k) = fEz(cEz.x, cEz.y, cEz.z); } } void setExyzt(int64_t _fEx, int64_t _fEy, int64_t _fEz, FP t) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fEx)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fEx; FP(*fEy)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fEy; FP(*fEz)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fEz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cEx, cEy, cEz; cEx = derived->convertCoords(fieldEntity->ExPosition(i, j, k), fieldEntity->timeShiftE); cEy = derived->convertCoords(fieldEntity->EyPosition(i, j, k), fieldEntity->timeShiftE); cEz = derived->convertCoords(fieldEntity->EzPosition(i, j, k), fieldEntity->timeShiftE); fieldEntity->Ex(i, j, k) = fEx(cEx.x, cEx.y, cEx.z, t + fieldEntity->timeShiftE); fieldEntity->Ey(i, j, k) = fEy(cEy.x, cEy.y, cEy.z, t + fieldEntity->timeShiftE); fieldEntity->Ez(i, j, k) = fEz(cEz.x, cEz.y, cEz.z, t + fieldEntity->timeShiftE); } } void setE(int64_t _fE) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP3(*fE)(FP, FP, FP) = (FP3(*)(FP, FP, FP))_fE; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cEx, cEy, cEz; cEx = derived->convertCoords(fieldEntity->ExPosition(i, j, k), fieldEntity->timeShiftE); cEy = derived->convertCoords(fieldEntity->EyPosition(i, j, k), fieldEntity->timeShiftE); cEz = derived->convertCoords(fieldEntity->EzPosition(i, j, k), fieldEntity->timeShiftE); fieldEntity->Ex(i, j, k) = fE(cEx.x, cEx.y, cEx.z).x; fieldEntity->Ey(i, j, k) = fE(cEy.x, cEy.y, cEy.z).y; fieldEntity->Ez(i, j, k) = fE(cEz.x, cEz.y, cEz.z).z; } } void pySetBxyz(py::function fBx, py::function fBy, py::function fBz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cBx, cBy, cBz; cBx = derived->convertCoords(fieldEntity->BxPosition(i, j, k), fieldEntity->timeShiftB); cBy = derived->convertCoords(fieldEntity->ByPosition(i, j, k), fieldEntity->timeShiftB); cBz = derived->convertCoords(fieldEntity->BzPosition(i, j, k), fieldEntity->timeShiftB); fieldEntity->Bx(i, j, k) = fBx("x"_a = cBx.x, "y"_a = cBx.y, "z"_a = cBx.z).template cast<FP>(); fieldEntity->By(i, j, k) = fBy("x"_a = cBy.x, "y"_a = cBy.y, "z"_a = cBy.z).template cast<FP>(); fieldEntity->Bz(i, j, k) = fBz("x"_a = cBz.x, "y"_a = cBz.y, "z"_a = cBz.z).template cast<FP>(); } } void pySetB(py::function fB) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cBx, cBy, cBz; cBx = derived->convertCoords(fieldEntity->BxPosition(i, j, k), fieldEntity->timeShiftB); cBy = derived->convertCoords(fieldEntity->ByPosition(i, j, k), fieldEntity->timeShiftB); cBz = derived->convertCoords(fieldEntity->BzPosition(i, j, k), fieldEntity->timeShiftB); fieldEntity->Bx(i, j, k) = fB("x"_a = cBx.x, "y"_a = cBx.y, "z"_a = cBx.z).template cast<FP3>().x; fieldEntity->By(i, j, k) = fB("x"_a = cBy.x, "y"_a = cBy.y, "z"_a = cBy.z).template cast<FP3>().y; fieldEntity->Bz(i, j, k) = fB("x"_a = cBz.x, "y"_a = cBz.y, "z"_a = cBz.z).template cast<FP3>().z; } } void setBxyz(int64_t _fBx, int64_t _fBy, int64_t _fBz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fBx)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fBx; FP(*fBy)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fBy; FP(*fBz)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fBz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cBx, cBy, cBz; cBx = derived->convertCoords(fieldEntity->BxPosition(i, j, k), fieldEntity->timeShiftB); cBy = derived->convertCoords(fieldEntity->ByPosition(i, j, k), fieldEntity->timeShiftB); cBz = derived->convertCoords(fieldEntity->BzPosition(i, j, k), fieldEntity->timeShiftB); fieldEntity->Bx(i, j, k) = fBx(cBx.x, cBx.y, cBx.z); fieldEntity->By(i, j, k) = fBy(cBy.x, cBy.y, cBy.z); fieldEntity->Bz(i, j, k) = fBz(cBz.x, cBz.y, cBz.z); } } void setBxyzt(int64_t _fBx, int64_t _fBy, int64_t _fBz, FP t) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fBx)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fBx; FP(*fBy)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fBy; FP(*fBz)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fBz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cBx, cBy, cBz; cBx = derived->convertCoords(fieldEntity->BxPosition(i, j, k), fieldEntity->timeShiftB); cBy = derived->convertCoords(fieldEntity->ByPosition(i, j, k), fieldEntity->timeShiftB); cBz = derived->convertCoords(fieldEntity->BzPosition(i, j, k), fieldEntity->timeShiftB); fieldEntity->Bx(i, j, k) = fBx(cBx.x, cBx.y, cBx.z, t + fieldEntity->timeShiftB); fieldEntity->By(i, j, k) = fBy(cBy.x, cBy.y, cBy.z, t + fieldEntity->timeShiftB); fieldEntity->Bz(i, j, k) = fBz(cBz.x, cBz.y, cBz.z, t + fieldEntity->timeShiftB); } } void setB(int64_t _fB) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP3(*fB)(FP, FP, FP) = (FP3(*)(FP, FP, FP))_fB; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cBx, cBy, cBz; cBx = derived->convertCoords(fieldEntity->BxPosition(i, j, k), fieldEntity->timeShiftB); cBy = derived->convertCoords(fieldEntity->ByPosition(i, j, k), fieldEntity->timeShiftB); cBz = derived->convertCoords(fieldEntity->BzPosition(i, j, k), fieldEntity->timeShiftB); fieldEntity->Bx(i, j, k) = fB(cBx.x, cBx.y, cBx.z).x; fieldEntity->By(i, j, k) = fB(cBy.x, cBy.y, cBy.z).y; fieldEntity->Bz(i, j, k) = fB(cBz.x, cBz.y, cBz.z).z; } } void pySetJxyz(py::function fJx, py::function fJy, py::function fJz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cJx, cJy, cJz; cJx = derived->convertCoords(fieldEntity->JxPosition(i, j, k), fieldEntity->timeShiftJ); cJy = derived->convertCoords(fieldEntity->JyPosition(i, j, k), fieldEntity->timeShiftJ); cJz = derived->convertCoords(fieldEntity->JzPosition(i, j, k), fieldEntity->timeShiftJ); fieldEntity->Jx(i, j, k) = fJx("x"_a = cJx.x, "y"_a = cJx.y, "z"_a = cJx.z).template cast<FP>(); fieldEntity->Jy(i, j, k) = fJy("x"_a = cJy.x, "y"_a = cJy.y, "z"_a = cJy.z).template cast<FP>(); fieldEntity->Jz(i, j, k) = fJz("x"_a = cJz.x, "y"_a = cJz.y, "z"_a = cJz.z).template cast<FP>(); } } void pySetJ(py::function fJ) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cJx, cJy, cJz; cJx = derived->convertCoords(fieldEntity->JxPosition(i, j, k), fieldEntity->timeShiftJ); cJy = derived->convertCoords(fieldEntity->JyPosition(i, j, k), fieldEntity->timeShiftJ); cJz = derived->convertCoords(fieldEntity->JzPosition(i, j, k), fieldEntity->timeShiftJ); fieldEntity->Jx(i, j, k) = fJ("x"_a = cJx.x, "y"_a = cJx.y, "z"_a = cJx.z).template cast<FP3>().x; fieldEntity->Jy(i, j, k) = fJ("x"_a = cJy.x, "y"_a = cJy.y, "z"_a = cJy.z).template cast<FP3>().y; fieldEntity->Jz(i, j, k) = fJ("x"_a = cJz.x, "y"_a = cJz.y, "z"_a = cJz.z).template cast<FP3>().z; } } void setJxyz(int64_t _fJx, int64_t _fJy, int64_t _fJz) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fJx)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fJx; FP(*fJy)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fJy; FP(*fJz)(FP, FP, FP) = (FP(*)(FP, FP, FP))_fJz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cJx, cJy, cJz; cJx = derived->convertCoords(fieldEntity->JxPosition(i, j, k), fieldEntity->timeShiftJ); cJy = derived->convertCoords(fieldEntity->JyPosition(i, j, k), fieldEntity->timeShiftJ); cJz = derived->convertCoords(fieldEntity->JzPosition(i, j, k), fieldEntity->timeShiftJ); fieldEntity->Jx(i, j, k) = fJx(cJx.x, cJx.y, cJx.z); fieldEntity->Jy(i, j, k) = fJy(cJy.x, cJy.y, cJy.z); fieldEntity->Jz(i, j, k) = fJz(cJz.x, cJz.y, cJz.z); } } void setJxyzt(int64_t _fJx, int64_t _fJy, int64_t _fJz, FP t) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP(*fJx)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fJx; FP(*fJy)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fJy; FP(*fJz)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))_fJz; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cJx, cJy, cJz; cJx = derived->convertCoords(fieldEntity->JxPosition(i, j, k), fieldEntity->timeShiftJ); cJy = derived->convertCoords(fieldEntity->JyPosition(i, j, k), fieldEntity->timeShiftJ); cJz = derived->convertCoords(fieldEntity->JzPosition(i, j, k), fieldEntity->timeShiftJ); fieldEntity->Jx(i, j, k) = fJx(cJx.x, cJx.y, cJx.z, t + fieldEntity->timeShiftJ); fieldEntity->Jy(i, j, k) = fJy(cJy.x, cJy.y, cJy.z, t + fieldEntity->timeShiftJ); fieldEntity->Jz(i, j, k) = fJz(cJz.x, cJz.y, cJz.z, t + fieldEntity->timeShiftJ); } } void setJ(int64_t _fJ) { TDerived* derived = static_cast<TDerived*>(this); pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = derived->getFieldEntity(); FP3(*fJ)(FP, FP, FP) = (FP3(*)(FP, FP, FP))_fJ; #pragma omp parallel for for (int i = 0; i < fieldEntity->numCells.x; i++) for (int j = 0; j < fieldEntity->numCells.y; j++) for (int k = 0; k < fieldEntity->numCells.z; k++) { FP3 cJx, cJy, cJz; cJx = derived->convertCoords(fieldEntity->JxPosition(i, j, k), fieldEntity->timeShiftJ); cJy = derived->convertCoords(fieldEntity->JyPosition(i, j, k), fieldEntity->timeShiftJ); cJz = derived->convertCoords(fieldEntity->JzPosition(i, j, k), fieldEntity->timeShiftJ); fieldEntity->Jx(i, j, k) = fJ(cJx.x, cJx.y, cJx.z).x; fieldEntity->Jy(i, j, k) = fJ(cJy.x, cJy.y, cJy.z).y; fieldEntity->Jz(i, j, k) = fJ(cJz.x, cJz.y, cJz.z).z; } } FP3 getE(const FP3& coords) const { pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = static_cast<const TDerived*>(this)->getFieldEntity(); FP3 result; if (isAnalytical) { FP(*fx)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fEt[0]; FP(*fy)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fEt[1]; FP(*fz)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fEt[2]; FP time = fieldEntity->globalTime + fieldEntity->timeShiftE; result[0] = fx(coords.x, coords.y, coords.z, time); result[1] = fy(coords.x, coords.y, coords.z, time); result[2] = fz(coords.x, coords.y, coords.z, time); } else { result = fieldEntity->getE(coords); } return result; } FP3 getB(const FP3& coords) const { pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = static_cast<const TDerived*>(this)->getFieldEntity(); FP3 result; if (isAnalytical) { FP(*fx)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fBt[0]; FP(*fy)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fBt[1]; FP(*fz)(FP, FP, FP, FP) = (FP(*)(FP, FP, FP, FP))fBt[2]; FP time = fieldEntity->globalTime + fieldEntity->timeShiftB; result[0] = fx(coords.x, coords.y, coords.z, time); result[1] = fy(coords.x, coords.y, coords.z, time); result[2] = fz(coords.x, coords.y, coords.z, time); } else { result = fieldEntity->getB(coords); } return result; } FP3 getJ(const FP3& coords) const { return static_cast<const TDerived*>(this)->getFieldEntity()->getJ(coords); } void getFields(const FP3& coords, FP3& e, FP3& b) const { static_cast<const TDerived*>(this)->getFieldEntity()->getFields(coords, e, b); } private: int64_t fEt[3], fBt[3]; bool isAnalytical; }; template <class TGrid, class TFieldSolver, class TDerived, bool> class pyPoissonFieldSolverInterface {}; template <class TGrid, class TFieldSolver, class TDerived> class pyPoissonFieldSolverInterface<TGrid, TFieldSolver, TDerived, true> { public: void convertFieldsPoissonEquation() { static_cast<TDerived*>(this)->getFieldEntity()->convertFieldsPoissonEquation(); } }; template <class TGrid, class TFieldSolver, class TDerived> class pyPoissonFieldSolverInterface<TGrid, TFieldSolver, TDerived, false> { public: void convertFieldsPoissonEquation() { std::cout << "WARNING: the used field does not include the 'convertFieldsPoissonEquation' method" << std::endl; } }; template <class TGrid, class TFieldSolver, class TDerived, bool> class pyFieldGeneratorSolverInterface {}; template <class TGrid, class TFieldSolver, class TDerived> class pyFieldGeneratorSolverInterface<TGrid, TFieldSolver, TDerived, true> { public: void setFieldGenerator(FieldGenerator<TGrid::gridType>* generator) { static_cast<TDerived*>(this)->getFieldEntity()->setFieldGenerator(generator); } }; template <class TGrid, class TFieldSolver, class TDerived> class pyFieldGeneratorSolverInterface<TGrid, TFieldSolver, TDerived, false> { public: void setFieldGenerator(FieldGenerator<TGrid::gridType>* generator) { std::cout << "WARNING: the used field does not include the 'setFieldGenerator' method" << std::endl; } }; template<class TGrid, class TFieldSolver, class TDerived> class pyFieldSolverInterface : public pyPoissonFieldSolverInterface<TGrid, TFieldSolver, TDerived, std::is_same<TFieldSolver, PSATD>::value || std::is_same<TFieldSolver, PSATDPoisson>::value || std::is_same<TFieldSolver, PSATDTimeStraggered>::value || std::is_same<TFieldSolver, PSATDTimeStraggeredPoisson>::value>, public pyFieldGeneratorSolverInterface<TGrid, TFieldSolver, TDerived, std::is_same<TFieldSolver, FDTD>::value> { public: void setTime(FP time) { static_cast<TDerived*>(this)->getFieldEntity()->globalTime = time; } FP getTime() { return static_cast<TDerived*>(this)->getFieldEntity()->globalTime; } void setPML(int sizePMLx, int sizePMLy, int sizePMLz) { static_cast<TDerived*>(this)->getFieldEntity()->setPML(sizePMLx, sizePMLy, sizePMLz); } void changeTimeStep(double dt) { static_cast<TDerived*>(this)->getFieldEntity()->setTimeStep(dt); } void updateFields() { static_cast<TDerived*>(this)->getFieldEntity()->updateFields(); } void advance(FP dt) { pyFieldEntity<TGrid, TFieldSolver>* fieldEntity = static_cast<TDerived*>(this)->getFieldEntity(); FP oldDt = fieldEntity->dt; fieldEntity->setTimeStep(dt); fieldEntity->updateFields(); fieldEntity->setTimeStep(oldDt); } }; template<class TGrid, class TFieldSolver, class TDerived> class pyFieldInterface: public pyFieldGridInterface<TGrid, TFieldSolver, TDerived>, public pyFieldSolverInterface<TGrid, TFieldSolver, TDerived> { public: using BaseGridInterface = pyFieldGridInterface<TGrid, TFieldSolver, TDerived>; using BaseSolverInterface = pyFieldSolverInterface<TGrid, TFieldSolver, TDerived>; TGrid* getGrid() const { return static_cast<TGrid*>(static_cast<const TDerived*>(this)->getFieldEntity()); } TFieldSolver* getFieldSolver() const { return static_cast<TFieldSolver*>(static_cast<const TDerived*>(this)->getFieldEntity()); } void refresh() { static_cast<TDerived*>(this)->getFieldEntity()->refresh(); } }; class pyFieldBase { public: virtual FP3 getE(const FP3& coords) const = 0; virtual FP3 getB(const FP3& coords) const = 0; virtual FP3 getJ(const FP3& coords) const = 0; void getFields(const FP3& coords, FP3& e, FP3& b) const { e = getE(coords); b = getB(coords); } virtual void updateFields() = 0; virtual void advance(FP dt) = 0; virtual std::shared_ptr<pyFieldBase> applyMapping( const std::shared_ptr<pyFieldBase>& self, const std::shared_ptr<Mapping>& mapping) const = 0; }; template<class TGrid, class TFieldSolver> class pyField : public pyFieldInterface<TGrid, TFieldSolver, pyField<TGrid, TFieldSolver>>, public pyFieldBase { using BaseInterface = pyFieldInterface<TGrid, TFieldSolver, pyField<TGrid, TFieldSolver>>; public: pyField(const Int3 & numInternalCells, const FP3 & minCoords, const FP3 & steps, FP dt) : fieldEntity(new pyFieldEntity<TGrid, TFieldSolver>(numInternalCells, minCoords, steps, dt)) {} pyField(const std::shared_ptr<pyField<TGrid, TFieldSolver>>& other, const std::shared_ptr<Mapping>& mapping) : pyWrappedField(other), mapping(mapping) {} inline pyFieldEntity<TGrid, TFieldSolver>* getFieldEntity() const { if (fieldEntity) return fieldEntity.get(); return pyWrappedField->getFieldEntity(); } inline FP3 convertCoords(const FP3& coords, FP timeShift = 0.0) const { bool status = true; return getDirectCoords(coords, getFieldEntity()->globalTime + timeShift, &status); } std::shared_ptr<pyFieldBase> applyMapping( const std::shared_ptr<pyFieldBase>& self, const std::shared_ptr<Mapping>& mapping) const override { return std::static_pointer_cast<pyFieldBase>( std::make_shared<pyField<TGrid, TFieldSolver>>( std::static_pointer_cast<pyField<TGrid, TFieldSolver>>(self), mapping ) ); } inline FP3 getE(const FP3& coords) const override { bool status = true; FP time = getFieldEntity()->globalTime + getFieldEntity()->timeShiftE; FP3 inverseCoords = getInverseCoords(coords, time, &status); if (!status) return FP3(0, 0, 0); return BaseInterface::getE(inverseCoords); } inline FP3 getB(const FP3& coords) const override { bool status = true; FP time = getFieldEntity()->globalTime + getFieldEntity()->timeShiftB; FP3 inverseCoords = getInverseCoords(coords, time, &status); if (!status) return FP3(0, 0, 0); return BaseInterface::getB(inverseCoords); } FP3 getJ(const FP3& coords) const override { bool status = true; FP time = getFieldEntity()->globalTime + getFieldEntity()->timeShiftJ; FP3 inverseCoords = getInverseCoords(coords, time, &status); if (!status) return FP3(0, 0, 0); return BaseInterface::getJ(inverseCoords); } void updateFields() override { return BaseInterface::updateFields(); } void advance(FP dt) override { return BaseInterface::advance(dt); } protected: inline FP3 getDirectCoords(const FP3& coords, FP time, bool* status) const { FP3 coords_ = coords; *status = true; if (pyWrappedField) coords_ = pyWrappedField->getDirectCoords(coords_, time, status); bool status2 = true; if (mapping) coords_ = mapping->getDirectCoords(coords_, time, &status2); *status = *status && status2; return coords_; } inline FP3 getInverseCoords(const FP3& coords, FP time, bool* status) const { FP3 coords_ = coords; *status = true; if (pyWrappedField) coords_ = pyWrappedField->getInverseCoords(coords_, time, status); bool status2 = true; if (mapping) coords_ = mapping->getInverseCoords(coords_, time, &status2); *status = *status && status2; return coords_; } private: // the simple grid state // if fieldEntity!=0 then pyField is a memory owner std::unique_ptr<pyFieldEntity<TGrid, TFieldSolver>> fieldEntity; // the mapping grid state // if pyWrappedField!=0 then pyField is a wrapper std::shared_ptr<pyField<TGrid, TFieldSolver>> pyWrappedField; std::shared_ptr<Mapping> mapping; }; typedef pyField<YeeGrid, FDTD> pyYeeField; typedef pyField<PSTDGrid, PSTD> pyPSTDField; typedef pyField<PSATDGrid, PSATD> pyPSATDField; typedef pyField<PSATDGrid, PSATDPoisson> pyPSATDPoissonField; typedef pyField<PSATDTimeStraggeredGrid, PSATDTimeStraggered> pyPSATDTimeStraggeredField; typedef pyField<PSATDTimeStraggeredGrid, PSATDTimeStraggeredPoisson> pyPSATDTimeStraggeredPoissonField; class pySumField : public pyFieldBase { public: pySumField(const std::shared_ptr<pyFieldBase>& pyWrappedField1, const std::shared_ptr<pyFieldBase>& pyWrappedField2) : pyWrappedField1(pyWrappedField1), pyWrappedField2(pyWrappedField2) {} pySumField(const std::shared_ptr<pySumField>& other, const std::shared_ptr<Mapping>& mapping) : pyWrappedField1(other->pyWrappedField1->applyMapping(other->pyWrappedField1, mapping)), pyWrappedField2(other->pyWrappedField2->applyMapping(other->pyWrappedField2, mapping)) {} std::shared_ptr<pyFieldBase> applyMapping( const std::shared_ptr<pyFieldBase>& self, const std::shared_ptr<Mapping>& mapping) const override { return std::static_pointer_cast<pyFieldBase>( std::make_shared<pySumField>( std::static_pointer_cast<pySumField>(self), mapping ) ); } FP3 getE(const FP3& coords) const override { return pyWrappedField1->getE(coords) + pyWrappedField2->getE(coords); } FP3 getB(const FP3& coords) const override { return pyWrappedField1->getB(coords) + pyWrappedField2->getB(coords); } FP3 getJ(const FP3& coords) const override { return pyWrappedField1->getJ(coords) + pyWrappedField2->getJ(coords); } void updateFields() override { pyWrappedField1->updateFields(); pyWrappedField2->updateFields(); } void advance(FP dt) override { pyWrappedField1->advance(dt); pyWrappedField2->advance(dt); } private: std::shared_ptr<pyFieldBase> pyWrappedField1; std::shared_ptr<pyFieldBase> pyWrappedField2; }; class pyMulField : public pyFieldBase { public: pyMulField(const std::shared_ptr<pyFieldBase>& pyWrappedField, FP factor) : pyWrappedField(pyWrappedField), factor(factor) {} pyMulField(const std::shared_ptr<pyMulField>& other, const std::shared_ptr<Mapping>& mapping) : pyWrappedField(other->pyWrappedField->applyMapping(other->pyWrappedField, mapping)) {} std::shared_ptr<pyFieldBase> applyMapping( const std::shared_ptr<pyFieldBase>& self, const std::shared_ptr<Mapping>& mapping) const override { return std::static_pointer_cast<pyFieldBase>( std::make_shared<pyMulField>( std::static_pointer_cast<pyMulField>(self), mapping ) ); } FP3 getE(const FP3& coords) const override { return pyWrappedField->getE(coords) * factor; } FP3 getB(const FP3& coords) const override { return pyWrappedField->getB(coords) * factor; } FP3 getJ(const FP3& coords) const override { return pyWrappedField->getJ(coords) * factor; } void updateFields() override { pyWrappedField->updateFields(); } void advance(FP dt) override { pyWrappedField->advance(dt); } private: FP factor = 1.0; std::shared_ptr<pyFieldBase> pyWrappedField; }; }
[ "noreply@github.com" ]
AleksandrPanov.noreply@github.com
5634300376229d3bf3a2273499c5e69af01640f9
fa01f02ef9f7f5a008ace7dd020ea8c900c5758b
/SurroundedRegion.cpp
e504724d452e68bb0c727cb4f131acb6fc192199
[]
no_license
Codinator29/LeetCode
2c61143557b250b833c6b8628cd56e39b1b1b5f2
6e836ee08acba156fd0ae238a2ff731e2d7cc16e
refs/heads/main
2023-04-15T20:59:21.012521
2021-04-16T03:14:42
2021-04-16T03:14:42
344,186,177
0
0
null
null
null
null
UTF-8
C++
false
false
1,317
cpp
/* https://leetcode.com/problems/surrounded-regions/ Given an m x n matrix board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. */ class Solution { public: void expand(vector<vector<char>>& board, int i, int j) { if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size()) return; if (board[i][j] == 'O') { board[i][j] = 'A'; expand(board, i+1, j); expand(board, i-1, j); expand(board, i, j+1); expand(board, i, j-1); } } void solve(vector<vector<char>>& board) { if (board.empty()) return; for (int i = 0; i < board.size(); ++i) { expand(board, i, 0); expand(board, i, board[0].size()-1); } for (int j = 0; j < board[0].size(); ++j) { expand(board, 0, j); expand(board, board.size()-1, j); } for (int i = 0; i < board.size(); ++i) for (int j = 0; j < board[0].size(); ++j) { if (board[i][j] == 'O') board[i][j] = 'X'; if (board[i][j] == 'A') board[i][j] = 'O'; } } };
[ "noreply@github.com" ]
Codinator29.noreply@github.com
ef8c21c83b8d2f4f309cc223944f4a9a25c51168
5fcca1afa38349fc2a0ebbbaf7eb3e10b8741c99
/detectLoopLinkedList/detectLoopLinkedList.cpp
42e8e9bfd99c9866e9fe2c544c19f584b654b528
[]
no_license
MitCoder/CPlusPlus
0d01338d38323b3baf45e057e425636ae40eacf9
29c88762f0349135b065db34c243199314328e80
refs/heads/master
2020-06-13T22:57:34.288081
2018-02-01T15:19:13
2018-02-01T15:19:13
17,533,729
0
0
null
null
null
null
UTF-8
C++
false
false
2,462
cpp
#include <iostream> using namespace std; struct node { int data; node *next; }; node *head=NULL; void insert(node *list,int data); void printlist(node *list); void detectLoop(node *list); void removeLoop(node *slow,node *head); void insert(node *list, int data) { node *newNode = new node; newNode->data = data; newNode->next = head; head = newNode; } void printlist(node *list) { for (list = head; list != NULL;list = list->next) { cout << list->data << endl; cin.get(); } } void detectLoop(node *list) { node *fast = list; node *slow = list; while (fast != NULL && fast->next != NULL) { // cout << " slow " << slow->data << " fast " << fast->next->data << fast->next->next->data << endl; slow = slow->next; fast = fast->next->next; if (slow == fast) { cout << "loop"<<slow->data << endl; cin.get(); removeLoop(slow,head); } } } void removeLoop(node *slow, node *head) { /* node *ptr1=slow; node *ptr2=slow; int count=0; //how many items are there in loop while (ptr1->next != ptr2) { count++; ptr1 = ptr1->next; } //position both the pointers to head. ptr1 = head; ptr2 = head; for (int i = 0; i <= count;i++) { ptr2 = ptr2->next; } //place both the pointers in the same location. while (ptr2 != ptr1) { ptr1 = ptr1->next; ptr2 = ptr2->next; } //Once both the pointers meet at the same location, just traverse the ptr2 to the end of the list.This will let ptr2->next point to ptr1. ptr2 = ptr2->next; while (ptr2->next != ptr1) { ptr2 = ptr2->next; } ptr2->next = NULL; */ //below code also works node *fast = head; while (fast->next != slow->next) { fast = fast->next; slow = slow->next; } //get the start of the loop /* 50--->20---->15---->4---->10 ▲ | | ▼ -------------- 15 is start of the list. Once you know where the loop starts, it's easy to identify the last element in the list, since it's the element in the list following the start of the loop that ends up pointing back to the start of the loop.*/ node *start = fast->next; fast = start; while (fast->next != start) { fast = fast->next; } fast->next = NULL; } int main() { node *list = new node; insert(list, 10); insert(list, 4); insert(list, 15); insert(list, 20); insert(list, 50); head->next->next->next->next->next = head->next->next; detectLoop(head); printlist(head); }
[ "mithila_84@yahoo.com" ]
mithila_84@yahoo.com
48f1000a4d36a1fe6226718228d032f9a7bf90c6
a37626167f68b6608753f924001a48f3ab395d6e
/iitX/Programming_Basics/pps01_set1_q2.cpp
e7d2f3da05ae4d48ffd1b16522ab62674f3dc77e
[]
no_license
mxd369/cpp
020ae3e3d90df559369ac8ce54384db355fd6324
eb88e92f16b8e54d5265099e1c6716077b592b7f
refs/heads/master
2021-01-11T22:29:46.771673
2017-03-18T07:18:46
2017-03-18T07:18:46
78,972,533
0
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
/* i. Use locations A, B; ii. Output "Give A and B: "; iii. Input A; Input B; iv. A = A + B; v. B = A + B; vi. Output "B is: "; vii. Output B; */ #include <iostream> using namespace std; int main() { int A, B; cout << "Give A and B: " ; cin >> A >> B ; A = A + B; B = A + B; cout << "Output B is: " << B << '\n'; return 0; } /* Test A = 5 B = 4 A = 5 + 4; A is assigned 9 B = 9 + 4; B is assigned 13; Output B is 13 */
[ "mxd789@gmail.com" ]
mxd789@gmail.com
9153131d836962356efda66b883a74ed4ab28ad8
811ef2df7a0e831e8ac2e26721194012f1d8dcbf
/course/payment_service/payment_gateway_mock.h
0f13f0ad43b152e18f0201244c18b35cb1420f27
[]
no_license
wrightsg/sc-cpp
0edf1f0d3a41f49d5e329cdfe1de8f09fc4e0307
49fd801182071bbb0f3c376c96ce58dbc8b4f877
refs/heads/master
2020-05-03T09:15:39.246048
2019-03-30T11:18:08
2019-03-30T11:18:08
178,549,443
0
0
null
null
null
null
UTF-8
C++
false
false
298
h
#ifndef SC_CPP_PAYMENT_GATEWAY_MOCK_H #define SC_CPP_PAYMENT_GATEWAY_MOCK_H #include "gmock/gmock.h" #include "payment_gateway.h" class PaymentGatewayMock : public PaymentGateway { public: MOCK_METHOD1(processPayment, void(const PaymentDetails&)); }; #endif //SC_CPP_PAYMENT_GATEWAY_MOCK_H
[ "wrightsgdev@gmail.com" ]
wrightsgdev@gmail.com
61d531483d5853e7e402f2c3a951fe191d37f3c0
70f6aac788d5b06d33a935645065c029c519fa45
/2019-01-24/Master-AIP-PG-DCW-HV/AIPRelease/Out-Moc/moc_sqlproduct.cpp
2ec8fddabafa14bb3de75fe0261d122cb92682d2
[]
no_license
Bluce-Song/2019
dedf7f37c61ca40a33429c366256876dd12f2471
074a6e31566f35843959d52e68606f4fe9a21a92
refs/heads/master
2020-04-18T08:01:09.796128
2019-01-25T01:25:16
2019-01-25T01:25:16
167,381,182
1
0
null
null
null
null
UTF-8
C++
false
false
3,697
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'sqlproduct.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../AIPDebug/sql/sqlproduct.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'sqlproduct.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_SqlProduct[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 10, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 12, 11, 11, 11, 0x08, 21, 11, 11, 11, 0x08, 32, 11, 11, 11, 0x08, 43, 11, 11, 11, 0x08, 56, 11, 11, 11, 0x08, 71, 11, 11, 11, 0x08, 86, 11, 11, 11, 0x08, 101, 11, 11, 11, 0x08, 118, 116, 11, 11, 0x08, 145, 141, 11, 11, 0x08, 0 // eod }; static const char qt_meta_stringdata_SqlProduct[] = { "SqlProduct\0\0initUI()\0initView()\0" "initText()\0initLayout()\0createSqlite()\0" "updateSqlite()\0insertSqlite()\0" "selectSqlite()\0e\0showEvent(QShowEvent*)\0" "msg\0recvSqlMap(QVariantMap)\0" }; void SqlProduct::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); SqlProduct *_t = static_cast<SqlProduct *>(_o); switch (_id) { case 0: _t->initUI(); break; case 1: _t->initView(); break; case 2: _t->initText(); break; case 3: _t->initLayout(); break; case 4: _t->createSqlite(); break; case 5: _t->updateSqlite(); break; case 6: _t->insertSqlite(); break; case 7: _t->selectSqlite(); break; case 8: _t->showEvent((*reinterpret_cast< QShowEvent*(*)>(_a[1]))); break; case 9: _t->recvSqlMap((*reinterpret_cast< QVariantMap(*)>(_a[1]))); break; default: ; } } } const QMetaObjectExtraData SqlProduct::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject SqlProduct::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_SqlProduct, qt_meta_data_SqlProduct, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &SqlProduct::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *SqlProduct::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *SqlProduct::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_SqlProduct)) return static_cast<void*>(const_cast< SqlProduct*>(this)); return QWidget::qt_metacast(_clname); } int SqlProduct::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 10) qt_static_metacall(this, _c, _id, _a); _id -= 10; } return _id; } QT_END_MOC_NAMESPACE
[ "songliang008@163.com" ]
songliang008@163.com
af98769f6957a806c542d6af903f93d9215132aa
11bece4b4615e8640c21e759626b63294be7d314
/src/Camera.cpp
2e02841dddc8ce1a56269f676c96327ed6bb53de
[]
no_license
Attractadore/OpenGLTutorial
f0c94fcf51e6f634aa0299fac68b22b5a4f505ef
404436414e73b56d7d73ef49617276b7f6f87012
refs/heads/master
2023-05-01T08:11:09.100008
2020-08-14T11:56:34
2020-08-14T11:56:34
269,996,362
0
0
null
null
null
null
UTF-8
C++
false
false
2,320
cpp
#include "Camera.hpp" #include <glm/gtc/matrix_transform.hpp> #include <cstdio> Camera::Camera(glm::vec3 cameraPos, glm::vec3 cameraLookDirection, glm::vec3 worldUpDirection) { cameraLookDirection = glm::normalize(cameraLookDirection); worldUpDirection = glm::normalize(worldUpDirection); this->cameraPos = cameraPos; this->cameraDefaultUpVector = worldUpDirection; this->cameraDefaultRightVector = glm::normalize(glm::cross(cameraLookDirection, worldUpDirection)); this->cameraDefaultForwardVector = glm::cross(this->cameraDefaultUpVector, this->cameraDefaultRightVector); this->addPitch(glm::degrees(glm::asin(glm::dot(worldUpDirection, cameraLookDirection)))); this->updateCameraForwardVector(); this->updateCameraRightVector(); this->updateCameraUpVector(); } glm::vec3 Camera::getCameraPos() { return this->cameraPos; } glm::vec3 Camera::getCameraForwardVector() { return this->cameraForwardVector; } glm::vec3 Camera::getCameraRightVector() { return this->cameraRightVector; } glm::vec3 Camera::getCameraUpVector() { return this->cameraUpVector; } void Camera::addPitch(float degrees) { this->pitch += degrees; this->pitch = glm::clamp(this->pitch, -80.0f, 80.0f); this->pitchRotationMatrix = glm::rotate(glm::mat4(1.0f), glm::radians(this->pitch), this->cameraDefaultRightVector); this->updateCameraForwardVector(); this->updateCameraUpVector(); } void Camera::addYaw(float degrees) { this->yaw += degrees; this->yawRotationMatrix = glm::rotate(glm::mat4(1.0f), glm::radians(this->yaw), this->cameraDefaultUpVector); this->updateCameraRightVector(); this->updateCameraForwardVector(); this->updateCameraUpVector(); } void Camera::addLocationOffset(glm::vec3 offset) { this->cameraPos += offset; } void Camera::updateCameraForwardVector() { this->cameraForwardVector = this->yawRotationMatrix * this->pitchRotationMatrix * glm::vec4(this->cameraDefaultForwardVector, 0.0f); } void Camera::updateCameraRightVector() { this->cameraRightVector = this->yawRotationMatrix * glm::vec4(this->cameraDefaultRightVector, 0.0f); } void Camera::updateCameraUpVector() { this->cameraUpVector = this->yawRotationMatrix * this->pitchRotationMatrix * glm::vec4(this->cameraDefaultUpVector, 0.0f); }
[ "attractadore02@gmail.com@" ]
attractadore02@gmail.com@
d4761e02f5c533fed5e468eceed7e2f25b15ae66
dd6b6da760c32ac6830c52aa2f4d5cce17e4d408
/magma-2.5.0/testing/testing_ztrmm_batched.cpp
0c6833d8eb7d0721306a83c846dcb5e6df13a258
[]
no_license
uumami/hit_and_run
81584b4f68cf25a2a1140baa3ee88f9e1844b672
dfda812a52bbd65e02753b9abcb9f54aeb4e8184
refs/heads/master
2023-03-13T16:48:37.975390
2023-02-28T05:04:58
2023-02-28T05:04:58
139,909,134
1
0
null
null
null
null
UTF-8
C++
false
false
8,930
cpp
/* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @precisions normal z -> c d s @author Chongxiao Cao */ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // includes, project #include "flops.h" #include "magma_v2.h" #include "magma_lapack.h" #include "testings.h" #if defined(_OPENMP) #include <omp.h> #include "../control/magma_threadsetting.h" #endif /* //////////////////////////////////////////////////////////////////////////// -- Testing ztrmm_batched */ int main( int argc, char** argv) { TESTING_CHECK( magma_init() ); magma_print_environment(); real_Double_t gflops, magma_perf, magma_time, cpu_perf, cpu_time; double error, magma_error, normalize, work[1]; magma_int_t M, N, NN; magma_int_t Ak, Akk; magma_int_t sizeA, sizeB; magma_int_t lda, ldb, ldda, lddb; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; magmaDoubleComplex **dA_array, **dB_array; magmaDoubleComplex **hA_array, **hB_array; magmaDoubleComplex *h_A, *h_B, *h_Bmagma; magmaDoubleComplex_ptr d_A, d_B; magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE; magmaDoubleComplex alpha = MAGMA_Z_MAKE( 0.29, -0.86 ); int status = 0; magma_opts opts( MagmaOptsBatched ); opts.parse_opts( argc, argv ); opts.lapack |= opts.check; // check (-c) implies lapack (-l) magma_int_t batchCount = opts.batchcount; double *Anorm, *Bnorm; TESTING_CHECK( magma_dmalloc_cpu( &Anorm, batchCount )); TESTING_CHECK( magma_dmalloc_cpu( &Bnorm, batchCount )); TESTING_CHECK( magma_malloc_cpu((void**)&hA_array, batchCount*sizeof(magmaDoubleComplex*)) ); TESTING_CHECK( magma_malloc_cpu((void**)&hB_array, batchCount*sizeof(magmaDoubleComplex*)) ); TESTING_CHECK( magma_malloc((void**)&dA_array, batchCount*sizeof(magmaDoubleComplex*)) ); TESTING_CHECK( magma_malloc((void**)&dB_array, batchCount*sizeof(magmaDoubleComplex*)) ); // See testing_zgemm about tolerance. double eps = lapackf77_dlamch("E"); double tol = 3*eps; printf("%% If running lapack (option --lapack), MAGMA error is computed\n" "%% relative to CPU BLAS result.\n\n"); printf("%% side = %s, uplo = %s, transA = %s, diag = %s\n", lapack_side_const(opts.side), lapack_uplo_const(opts.uplo), lapack_trans_const(opts.transA), lapack_diag_const(opts.diag) ); printf("%% BatchCount M N MAGMA Gflop/s (ms) CPU Gflop/s (ms) MAGMA error\n"); printf("%%=============================================================================\n"); for( int itest = 0; itest < opts.ntest; ++itest ) { for( int iter = 0; iter < opts.niter; ++iter ) { M = opts.msize[itest]; N = opts.nsize[itest]; gflops = batchCount * FLOPS_ZTRMM(opts.side, M, N) / 1e9; if ( opts.side == MagmaLeft ) { lda = M; Ak = M; } else { lda = N; Ak = N; } ldb = M; Akk = Ak * batchCount; NN = N * batchCount; ldda = magma_roundup( lda, opts.align ); // multiple of 32 by default lddb = magma_roundup( ldb, opts.align ); // multiple of 32 by default sizeA = lda*Ak*batchCount; sizeB = ldb*N*batchCount; TESTING_CHECK( magma_zmalloc_cpu( &h_A, lda*Ak*batchCount ) ); TESTING_CHECK( magma_zmalloc_cpu( &h_B, ldb*N*batchCount ) ); TESTING_CHECK( magma_zmalloc_cpu( &h_Bmagma, ldb*N*batchCount ) ); TESTING_CHECK( magma_zmalloc( &d_A, ldda*Ak*batchCount ) ); TESTING_CHECK( magma_zmalloc( &d_B, lddb*N*batchCount ) ); /* Initialize the matrices */ lapackf77_zlarnv( &ione, ISEED, &sizeA, h_A ); lapackf77_zlarnv( &ione, ISEED, &sizeB, h_B ); // Compute norms for error for (int s = 0; s < batchCount; ++s) { Anorm[s] = lapackf77_zlantr( "F", lapack_uplo_const(opts.uplo), lapack_diag_const(opts.diag), &Ak, &Ak, &h_A[s*lda*Ak], &lda, work ); Bnorm[s] = lapackf77_zlange( "F", &M, &N, &h_B[s*ldb*N], &ldb, work ); } /* ===================================================================== Performs operation using CUBLAS =================================================================== */ magma_zsetmatrix( Ak, Akk, h_A, lda, d_A, ldda, opts.queue ); magma_zsetmatrix( M, NN, h_B, ldb, d_B, lddb, opts.queue ); magma_zset_pointer( dA_array, d_A, ldda, 0, 0, ldda*Ak, batchCount, opts.queue ); magma_zset_pointer( dB_array, d_B, lddb, 0, 0, lddb*N, batchCount, opts.queue ); magma_time = magma_sync_wtime( opts.queue ); magmablas_ztrmm_batched( opts.side, opts.uplo, opts.transA, opts.diag, M, N, alpha, dA_array, ldda, dB_array, lddb, batchCount, opts.queue ); magma_time = magma_sync_wtime( opts.queue ) - magma_time; magma_perf = gflops / magma_time; magma_zgetmatrix( M, NN, d_B, lddb, h_Bmagma, ldb, opts.queue ); /* ===================================================================== Performs operation using CPU BLAS =================================================================== */ if ( opts.lapack ) { // populate pointer arrays on the host for(int s = 0; s < batchCount; s++){ hA_array[s] = h_A+s*lda*Ak; hB_array[s] = h_B+s*ldb*N; } cpu_time = magma_wtime(); blas_ztrmm_batched( opts.side, opts.uplo, opts.transA, opts.diag, M, N, alpha, hA_array, lda, hB_array, ldb, batchCount ); cpu_time = magma_wtime() - cpu_time; cpu_perf = gflops / cpu_time; } /* ===================================================================== Check the result =================================================================== */ if ( opts.lapack ) { // compute error compared lapack // error = |dB - B| / (gamma_{k}|A||Bin|); k = Ak; no beta magma_error = 0; for (int s = 0; s < batchCount; s++) { normalize = sqrt(double(Ak))*Anorm[s]*Bnorm[s]; if (normalize == 0) normalize = 1; magma_int_t Bsize = ldb*N; blasf77_zaxpy( &Bsize, &c_neg_one, &h_B[s*ldb*N], &ione, &h_Bmagma[s*ldb*N], &ione ); error = lapackf77_zlange( "F", &M, &N, &h_Bmagma[s*ldb*N], &ldb, work ) / normalize; magma_error = magma_max_nan( error, magma_error ); } bool okay = (magma_error < tol); status += ! okay; printf(" %10lld %5lld %5lld %7.2f (%7.2f) %7.2f (%7.2f) %8.2e %s\n", (long long)batchCount, (long long)M, (long long)N, magma_perf, 1000.*magma_time, cpu_perf, 1000.*cpu_time, magma_error, (okay ? "ok" : "failed")); } else { printf(" %10lld %5lld %5lld %7.2f (%7.2f) --- ( --- ) ---\n", (long long)batchCount, (long long)M, (long long)N, magma_perf, 1000.*magma_time); } magma_free_cpu( h_A ); magma_free_cpu( h_B ); magma_free_cpu( h_Bmagma ); magma_free( d_A ); magma_free( d_B ); fflush( stdout ); } if ( opts.niter > 1 ) { printf( "\n" ); } } magma_free_cpu( hA_array ); magma_free_cpu( hB_array ); magma_free( dA_array ); magma_free( dB_array ); magma_free_cpu( Anorm ); magma_free_cpu( Bnorm ); opts.cleanup(); TESTING_CHECK( magma_finalize() ); return status; }
[ "vazcorm@gmail.com" ]
vazcorm@gmail.com
5d23fe5842e54feddbb315c39ba8f5b1b882329c
41db71010ff664ecd163710019dde3db9d8e2e09
/thrift/compiler/test/fixtures/includes/gen-cpp2/includes_metadata.cpp
f36aae3bac9bcf9e2ebf61f52918d1d5a4529b79
[ "Apache-2.0" ]
permissive
jahau/fbthrift
069c4203ccbe55f84b439b700f94cdd1f0d1311e
2c73323d9e31fc99ea7a3b73ce8a201b3b8715d0
refs/heads/master
2022-04-21T04:31:43.313556
2020-02-15T05:53:32
2020-02-15T05:55:05
240,657,490
1
0
null
2020-02-15T06:37:02
2020-02-15T06:37:01
null
UTF-8
C++
false
false
426
cpp
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "thrift/compiler/test/fixtures/includes/gen-cpp2/includes_metadata.h" namespace apache { namespace thrift { namespace detail { namespace md { using ThriftMetadata = ::apache::thrift::metadata::ThriftMetadata; } // namespace md } // namespace detail } // namespace thrift } // namespace apache
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
4cade68a1ba67350ae5a4ea3b9a557aae32364b9
383c3256e78d8536ba5b573d0244e19ac1832f95
/Link List/Reverse traverse/reverse.cpp
e6fb2e632c1443fce7c571e8c3162136ca5a0f54
[]
no_license
Mahibulhassan/Data-structure
d0ca537e690689212c0238a9902c5c2a7e133092
c55bffaad244ba0bbb8a46ece0ae920096fd291b
refs/heads/master
2020-12-09T17:02:39.862362
2020-06-20T13:17:46
2020-06-20T13:17:46
233,366,406
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
#include<cstdio> #include<cstdlib> struct Node { int data; Node* next; }; Node* head; void inserting(int d, int p); void del(int p); void print(); void fMem(); int traverse(); Node* rev(Node* head); int main() { head=NULL; int n,d,p; printf("How many numbers do you want in the list?\n"); scanf("%d", &n); while(n--) { stay: scanf("%d %d", &d, &p); if(p>=1&&p<=traverse()+1) { inserting(d,p); continue; } printf("Invalid position to insert!!! the next valid position is %d \n", traverse()+1); goto stay; } print(); head=rev(head); print(); fMem(); return 0; } void inserting(int d, int p) { Node* temp=new Node(); temp->data=d; temp->next=NULL; if(p==1) { temp->next=head; head=temp; return; } Node* temp2=head; for(int i=0; i<(p-2); i++) temp2=temp2->next; temp->next=temp2->next; temp2->next=temp; } void print() { Node* temp=head; printf("\nThe list is:\n"); while(temp!=NULL) { printf("%d ", temp->data); temp=temp->next; } printf("\n\n"); } int traverse() { int k=0; Node* temp=head; while(temp!=NULL) { temp=temp->next; k++; } return k; } Node* rev(Node* head) { Node* temp=head; Node* temp2=NULL; Node* prev=NULL; while(temp!=NULL) { temp2=temp->next; temp->next=prev; prev=temp; temp=temp2; } head=prev; return head; } void fMem() { Node* temp=head; Node* temp2=NULL; while(temp!=NULL) { temp2=head; head=temp->next; temp=temp->next; free(temp2); temp2=NULL; } printf("\nThe memory has been freed!\n"); }
[ "noreply@github.com" ]
Mahibulhassan.noreply@github.com
64b8b72e0ed0ffb7b54c6cad723dd9374c397597
24862dcb99a7da2050768212be89e91b9acb67b5
/UE_4.21/Engine/Intermediate/Build/Win32/UE4/Inc/Engine/OnlineEngineInterface.generated.h
2f283d382751a39ff0e9c972dbe48dd93d8e389e
[]
no_license
dadtaylo/makingchanges
3f8f1b4b4c7b2605d2736789445fcda693c92eea
3ea08eab63976feab82561a9355c4fc2d0f76362
refs/heads/master
2020-04-22T05:28:01.381983
2019-02-25T02:56:07
2019-02-25T02:56:07
170,160,587
0
0
null
null
null
null
UTF-8
C++
false
false
4,812
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef ENGINE_OnlineEngineInterface_generated_h #error "OnlineEngineInterface.generated.h already included, missing '#pragma once' in OnlineEngineInterface.h" #endif #define ENGINE_OnlineEngineInterface_generated_h #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_RPC_WRAPPERS #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_RPC_WRAPPERS_NO_PURE_DECLS #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUOnlineEngineInterface(); \ friend struct Z_Construct_UClass_UOnlineEngineInterface_Statics; \ public: \ DECLARE_CLASS(UOnlineEngineInterface, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \ DECLARE_SERIALIZER(UOnlineEngineInterface) \ static const TCHAR* StaticConfigName() {return TEXT("Engine");} \ #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_INCLASS \ private: \ static void StaticRegisterNativesUOnlineEngineInterface(); \ friend struct Z_Construct_UClass_UOnlineEngineInterface_Statics; \ public: \ DECLARE_CLASS(UOnlineEngineInterface, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \ DECLARE_SERIALIZER(UOnlineEngineInterface) \ static const TCHAR* StaticConfigName() {return TEXT("Engine");} \ #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UOnlineEngineInterface(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UOnlineEngineInterface) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UOnlineEngineInterface); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UOnlineEngineInterface); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UOnlineEngineInterface(UOnlineEngineInterface&&); \ NO_API UOnlineEngineInterface(const UOnlineEngineInterface&); \ public: #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UOnlineEngineInterface(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UOnlineEngineInterface(UOnlineEngineInterface&&); \ NO_API UOnlineEngineInterface(const UOnlineEngineInterface&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UOnlineEngineInterface); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UOnlineEngineInterface); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UOnlineEngineInterface) #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_PRIVATE_PROPERTY_OFFSET #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_40_PROLOG #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_RPC_WRAPPERS \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_INCLASS \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_RPC_WRAPPERS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_INCLASS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h_43_ENHANCED_CONSTRUCTORS \ static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class OnlineEngineInterface."); \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Public_Net_OnlineEngineInterface_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "dadtaylo@iu.edu" ]
dadtaylo@iu.edu
6c839c940cf2f82e7d2116d25b87e1bc3027e13c
7d52ba18a2625287b9ce088691ab85f225dbbe78
/algo/Cible.cpp
5bfa91bcdd045710c54b06615e8fe99b3e10803e
[]
no_license
Heabelix/algo
c32f132bd20e1310548a1517c733995ecd840035
65a3f40567add84cf83f5a63ed00eb4a6b4358dd
refs/heads/master
2023-01-19T17:23:16.203004
2020-11-23T20:52:28
2020-11-23T20:52:28
315,437,155
0
1
null
null
null
null
UTF-8
C++
false
false
60
cpp
#include "Cible.h" Cible::Cible(int id) { this->id = id; }
[ "valentin.lefloch35@gmail.com" ]
valentin.lefloch35@gmail.com
b1f0a5ef9e8c1cdc1c41ccf8db6a19efaf3487d6
48e9625fcc35e6bf790aa5d881151906280a3554
/Sources/Elastos/LibCore/src/org/apache/harmony/security/pkcs8/CPrivateKeyInfoHelper.cpp
4231c9cd22ff9484882de209feb3cec56b052d78
[ "Apache-2.0" ]
permissive
suchto/ElastosRT
f3d7e163d61fe25517846add777690891aa5da2f
8a542a1d70aebee3dbc31341b7e36d8526258849
refs/heads/master
2021-01-22T20:07:56.627811
2017-03-17T02:37:51
2017-03-17T02:37:51
85,281,630
4
2
null
2017-03-17T07:08:49
2017-03-17T07:08:49
null
UTF-8
C++
false
false
1,350
cpp
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "CPrivateKeyInfoHelper.h" #include <CPrivateKeyInfo.h> namespace Org { namespace Apache { namespace Harmony { namespace Security { namespace Pkcs8 { CAR_SINGLETON_IMPL(CPrivateKeyInfoHelper) CAR_INTERFACE_IMPL(CPrivateKeyInfoHelper, Singleton, IPrivateKeyInfoHelper) ECode CPrivateKeyInfoHelper::GetASN1( /* [out] */ IASN1Sequence** asn1) { VALIDATE_NOT_NULL(asn1) *asn1 = CPrivateKeyInfo::ASN1.Get(); REFCOUNT_ADD(*asn1) return NOERROR; } } // namespace Pkcs8 } // namespace Security } // namespace Harmony } // namespace Apache } // namespace Org
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
41957d73ba208d338736beb769e782437d9aa624
28d25f81c33fe772a6d5f740a1b36b8c8ba854b8
/UVA/11456/main.cpp
b01bee620a4450e0d759c09e68aa29602bc679e0
[]
no_license
ahmedibrahim404/CompetitiveProgramming
b59dcfef250818fb9f34797e432a75ef1507578e
7473064433f92ac8cf821b3b1d5cd2810f81c4ad
refs/heads/master
2021-12-26T01:18:35.882467
2021-11-11T20:43:08
2021-11-11T20:43:08
148,578,163
1
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include<algorithm> #include<cstdio> using namespace std; int A[2500], Ma[2500], Mb[2500]; int N, T; int main() { scanf("%d", &T); for(int t = 0; t < T; t++) { scanf("%d", &N); for(int i = 0; i < N; i++) scanf("%d", &A[i]); for(int i = N - 1; i >= 0; i--) { Ma[i] = 1; for(int j = i + 1; j < N; j++) { if(A[i] < A[j]) { Ma[i] = max(Ma[j] + 1, Ma[i]); } } } for(int i = N - 1; i >= 0; i--) { Mb[i] = 1; for(int j = i + 1; j < N; j++) { if(A[i] > A[j]) { Mb[i] = max(Mb[j] + 1, Mb[i]); } } } int ans = 0; for(int i = 0; i < N; i++) { ans = max(ans, Ma[i] + Mb[i] - 1); } printf("%d\n", ans); } }
[ "ahmedie20022011@gmail.com" ]
ahmedie20022011@gmail.com
973fabdd69d8863c9304a25131b5076a641a43ac
e2bb8568b21bb305de3b896cf81786650b1a11f9
/SDK/SCUM_1H_Brass_knuckles_classes.hpp
3da32b10a9a9659b6c30a01435618c5dba7c1236
[]
no_license
Buttars/SCUM-SDK
822e03fe04c30e04df0ba2cb4406fe2c18a6228e
954f0ab521b66577097a231dab2bdc1dd35861d3
refs/heads/master
2020-03-28T02:45:14.719920
2018-09-05T17:53:23
2018-09-05T17:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
931
hpp
#pragma once // SCUM (0.1.17) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SCUM_1H_Brass_knuckles_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass 1H_Brass_knuckles.1H_Brass_knuckles_C // 0x0008 (0x07D8 - 0x07D0) class A1H_Brass_knuckles_C : public AWeaponItem { public: class UMeleeAttackCollisionCapsule* MeleeAttackCollisionCapsule; // 0x07D0(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass 1H_Brass_knuckles.1H_Brass_knuckles_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
bc24cccb0cb9e066ec282fd201c3733953f3a461
ca4d238a1648d3fa1f38aa3845b2063e0b27643a
/12/graph_distanceTree/queue_distanceTree.cpp
36900303d3a626aa8c45da765da5f06452bd3f70
[]
no_license
LeafLu0315/CS_Programming
fee05c367f159e269fe94bd6ee7cbb03901c1579
4cd9f4b3d08181f058451959ad8a40833d993c32
refs/heads/master
2018-09-20T19:32:59.780279
2018-09-12T13:09:38
2018-09-12T13:09:38
114,989,772
0
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include<cstdio> #include<vector> #include<queue> #define N 5001 using namespace std; void sol(); int main(void){ int n; scanf("%d",&n); while(n--) sol(); return 0; } void sol(){ int ans=0,i,nodes; int parent[N],edge[N],node[N],degree[N]; queue<int> q; scanf("%d",&nodes); for(i=2;i<=nodes;i++) scanf("%d",&parent[i]); for(i=2;i<=nodes;i++) scanf("%d",&edge[i]); for(i=1;i<=nodes;i++){ degree[i]=0; node[i]=1; } for(i=2;i<=nodes;i++) degree[parent[i]]++; for(i=1;i<=nodes;i++) if(!degree[i]) q.push(i); while(!q.empty()){ int f = q.front(); q.pop(); node[parent[f]]+=node[f]; ans += 2*node[f]*(nodes-node[f])*edge[f]; degree[parent[f]]--; if(!degree[parent[f]]) q.push(parent[f]); } printf("%d\n",ans); }
[ "johnson7511333@gmail.com" ]
johnson7511333@gmail.com
cc37545d98455f8bbee66bab6b7039925210628c
fe7113121c8e628fdbb166a3daf7958a187f0eb9
/xfa/fxfa/parser/xfa_basic_data.cpp
d17baeed2b8c926e0c218a9948223d7f5b1ea6b8
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
tszirr/pdfium
f80704b6293e3d07fcc73f8368dc1710c6b19617
6ab909c1a31743b218455ce90d698463069bae79
refs/heads/master
2022-12-31T02:41:35.858154
2020-10-21T10:57:12
2020-10-21T10:57:12
272,494,987
0
0
NOASSERTION
2020-06-15T16:53:13
2020-06-15T16:53:12
null
UTF-8
C++
false
false
9,013
cpp
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/parser/xfa_basic_data.h" #include <iterator> #include <utility> #include "fxjs/xfa/cjx_boolean.h" #include "fxjs/xfa/cjx_container.h" #include "fxjs/xfa/cjx_datawindow.h" #include "fxjs/xfa/cjx_delta.h" #include "fxjs/xfa/cjx_desc.h" #include "fxjs/xfa/cjx_draw.h" #include "fxjs/xfa/cjx_encrypt.h" #include "fxjs/xfa/cjx_eventpseudomodel.h" #include "fxjs/xfa/cjx_exclgroup.h" #include "fxjs/xfa/cjx_extras.h" #include "fxjs/xfa/cjx_field.h" #include "fxjs/xfa/cjx_form.h" #include "fxjs/xfa/cjx_handler.h" #include "fxjs/xfa/cjx_hostpseudomodel.h" #include "fxjs/xfa/cjx_instancemanager.h" #include "fxjs/xfa/cjx_layoutpseudomodel.h" #include "fxjs/xfa/cjx_logpseudomodel.h" #include "fxjs/xfa/cjx_manifest.h" #include "fxjs/xfa/cjx_model.h" #include "fxjs/xfa/cjx_node.h" #include "fxjs/xfa/cjx_occur.h" #include "fxjs/xfa/cjx_packet.h" #include "fxjs/xfa/cjx_script.h" #include "fxjs/xfa/cjx_signaturepseudomodel.h" #include "fxjs/xfa/cjx_source.h" #include "fxjs/xfa/cjx_subform.h" #include "fxjs/xfa/cjx_textnode.h" #include "fxjs/xfa/cjx_tree.h" #include "fxjs/xfa/cjx_treelist.h" #include "fxjs/xfa/cjx_wsdlconnection.h" #include "fxjs/xfa/cjx_xfa.h" #include "third_party/base/stl_util.h" #include "xfa/fxfa/fxfa_basic.h" namespace { struct PacketRecord { XFA_PacketType packet_type; uint32_t hash; uint32_t flags; const wchar_t* name; const wchar_t* uri; }; const PacketRecord g_PacketTable[] = { #undef PCKT____ #define PCKT____(a, b, c, d, e, f) \ {XFA_PacketType::c, a, XFA_XDPPACKET_FLAGS_##e | XFA_XDPPACKET_FLAGS_##f, \ L##b, d}, #include "xfa/fxfa/parser/packets.inc" #undef PCKT____ }; struct ElementRecord { uint32_t hash; // Hashed as wide string. XFA_Element element; XFA_Element parent; }; // Contains read-only data that do not require relocation. // Parts that require relocation are in `kElementNames` below. constexpr ElementRecord kElementRecords[] = { #undef ELEM____ #define ELEM____(a, b, c, d) {a, XFA_Element::c, XFA_Element::d}, #include "xfa/fxfa/parser/elements.inc" #undef ELEM____ }; constexpr const char* kElementNames[] = { #undef ELEM____ #define ELEM____(a, b, c, d) b, #include "xfa/fxfa/parser/elements.inc" #undef ELEM____ }; static_assert(pdfium::size(kElementRecords) == pdfium::size(kElementNames), "Size mismatch"); struct AttributeRecord { uint32_t hash; // Hashed as wide string. XFA_Attribute attribute; XFA_ScriptType script_type; }; // Contains read-only data that do not require relocation. // Parts that require relocation are in `kAttributeNames` below. constexpr AttributeRecord kAttributeRecords[] = { #undef ATTR____ #define ATTR____(a, b, c, d) {a, XFA_Attribute::c, XFA_ScriptType::d}, #include "xfa/fxfa/parser/attributes.inc" #undef ATTR____ }; constexpr const char* kAttributeNames[] = { #undef ATTR____ #define ATTR____(a, b, c, d) b, #include "xfa/fxfa/parser/attributes.inc" #undef ATTR____ }; static_assert(pdfium::size(kAttributeRecords) == pdfium::size(kAttributeNames), "Size mismatch"); struct AttributeValueRecord { // Associated entry in `kAttributeValueNames` hashed as WideString. uint32_t uHash; XFA_AttributeValue eName; }; // Contains read-only data that do not require relocation. // Parts that require relocation are in `kAttributeValueNames` below. constexpr AttributeValueRecord kAttributeValueRecords[] = { #undef VALUE____ #define VALUE____(a, b, c) {a, XFA_AttributeValue::c}, #include "xfa/fxfa/parser/attribute_values.inc" #undef VALUE____ }; constexpr const char* kAttributeValueNames[] = { #undef VALUE____ #define VALUE____(a, b, c) b, #include "xfa/fxfa/parser/attribute_values.inc" #undef VALUE____ }; static_assert(pdfium::size(kAttributeValueRecords) == pdfium::size(kAttributeValueNames), "Size mismatch"); struct ElementAttributeRecord { XFA_Element element; XFA_Attribute attribute; }; // Contains read-only data that do not require relocation. // Parts that require relocation are in `kElementAttributeCallbacks` below. constexpr ElementAttributeRecord kElementAttributeRecords[] = { #undef ELEM_ATTR____ #define ELEM_ATTR____(a, b, c) {XFA_Element::a, XFA_Attribute::b}, #include "xfa/fxfa/parser/element_attributes.inc" #undef ELEM_ATTR____ }; constexpr XFA_ATTRIBUTE_CALLBACK kElementAttributeCallbacks[] = { #undef ELEM_ATTR____ #define ELEM_ATTR____(a, b, c) c##_static, #include "xfa/fxfa/parser/element_attributes.inc" #undef ELEM_ATTR____ }; static_assert(pdfium::size(kElementAttributeRecords) == pdfium::size(kElementAttributeCallbacks), "Size mismatch"); } // namespace XFA_PACKETINFO XFA_GetPacketByIndex(XFA_PacketType ePacket) { const PacketRecord* pRecord = &g_PacketTable[static_cast<uint8_t>(ePacket)]; return {pRecord->name, pRecord->packet_type, pRecord->uri, pRecord->flags}; } Optional<XFA_PACKETINFO> XFA_GetPacketByName(WideStringView wsName) { uint32_t hash = FX_HashCode_GetW(wsName, false); auto* elem = std::lower_bound( std::begin(g_PacketTable), std::end(g_PacketTable), hash, [](const PacketRecord& a, uint32_t hash) { return a.hash < hash; }); if (elem != std::end(g_PacketTable) && elem->name == wsName) return XFA_GetPacketByIndex(elem->packet_type); return {}; } ByteStringView XFA_ElementToName(XFA_Element elem) { return kElementNames[static_cast<size_t>(elem)]; } XFA_Element XFA_GetElementByName(WideStringView name) { uint32_t hash = FX_HashCode_GetW(name, false); auto* elem = std::lower_bound( std::begin(kElementRecords), std::end(kElementRecords), hash, [](const ElementRecord& a, uint32_t hash) { return a.hash < hash; }); if (elem == std::end(kElementRecords)) return XFA_Element::Unknown; size_t index = std::distance(std::begin(kElementRecords), elem); return name.EqualsASCII(kElementNames[index]) ? elem->element : XFA_Element::Unknown; } ByteStringView XFA_AttributeToName(XFA_Attribute attr) { return kAttributeNames[static_cast<size_t>(attr)]; } Optional<XFA_ATTRIBUTEINFO> XFA_GetAttributeByName(WideStringView name) { uint32_t hash = FX_HashCode_GetW(name, false); auto* elem = std::lower_bound( std::begin(kAttributeRecords), std::end(kAttributeRecords), hash, [](const AttributeRecord& a, uint32_t hash) { return a.hash < hash; }); if (elem == std::end(kAttributeRecords)) return pdfium::nullopt; size_t index = std::distance(std::begin(kAttributeRecords), elem); if (!name.EqualsASCII(kAttributeNames[index])) return pdfium::nullopt; XFA_ATTRIBUTEINFO result; result.attribute = elem->attribute; result.eValueType = elem->script_type; return result; } ByteStringView XFA_AttributeValueToName(XFA_AttributeValue item) { return kAttributeValueNames[static_cast<int32_t>(item)]; } Optional<XFA_AttributeValue> XFA_GetAttributeValueByName(WideStringView name) { auto* it = std::lower_bound(std::begin(kAttributeValueRecords), std::end(kAttributeValueRecords), FX_HashCode_GetW(name, false), [](const AttributeValueRecord& arg, uint32_t hash) { return arg.uHash < hash; }); if (it == std::end(kAttributeValueRecords)) return pdfium::nullopt; size_t index = std::distance(std::begin(kAttributeValueRecords), it); if (!name.EqualsASCII(kAttributeValueNames[index])) return pdfium::nullopt; return it->eName; } Optional<XFA_SCRIPTATTRIBUTEINFO> XFA_GetScriptAttributeByName( XFA_Element element, WideStringView attribute_name) { Optional<XFA_ATTRIBUTEINFO> attr = XFA_GetAttributeByName(attribute_name); if (!attr.has_value()) return {}; while (element != XFA_Element::Unknown) { auto compound_key = std::make_pair(element, attr.value().attribute); auto* it = std::lower_bound( std::begin(kElementAttributeRecords), std::end(kElementAttributeRecords), compound_key, [](const ElementAttributeRecord& arg, const std::pair<XFA_Element, XFA_Attribute>& key) { return std::make_pair(arg.element, arg.attribute) < key; }); if (it != std::end(kElementAttributeRecords) && compound_key == std::make_pair(it->element, it->attribute)) { XFA_SCRIPTATTRIBUTEINFO result; result.attribute = attr.value().attribute; result.eValueType = attr.value().eValueType; size_t index = std::distance(std::begin(kElementAttributeRecords), it); result.callback = kElementAttributeCallbacks[index]; return result; } element = kElementRecords[static_cast<size_t>(element)].parent; } return {}; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1a2ed7ea4fac8cf39f8aa9e18e7154facc139314
00e925fe9705dddd93c155667d71da861fb01772
/src/test/pmt_tests.cpp
c7178a7ead1206c9ebf3890b930d526ea0301211
[ "MIT" ]
permissive
Crowndev/crown
f017445d4cbc6b5dda4e6a57fec16d07febfdf92
7d8f35e5f1749b0b93e16fda5c45c800ba15f882
refs/heads/main
2022-12-28T08:08:51.649518
2022-12-25T19:59:36
2022-12-25T19:59:36
415,886,236
7
3
MIT
2022-12-25T19:59:37
2021-10-11T10:57:29
C++
UTF-8
C++
false
false
4,438
cpp
// Copyright (c) 2012-2020 The Crown Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <arith_uint256.h> #include <consensus/merkle.h> #include <merkleblock.h> #include <serialize.h> #include <streams.h> #include <test/util/setup_common.h> #include <uint256.h> #include <version.h> #include <vector> #include <boost/test/unit_test.hpp> class CPartialMerkleTreeTester : public CPartialMerkleTree { public: // flip one bit in one of the hashes - this should break the authentication void Damage() { unsigned int n = InsecureRandRange(vHash.size()); int bit = InsecureRandBits(8); *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7); } }; BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(pmt_test1) { static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095}; for (int i = 0; i < 12; i++) { unsigned int nTx = nTxCounts[i]; // build a block with some dummy transactions CBlock block; for (unsigned int j=0; j<nTx; j++) { CMutableTransaction tx; tx.nLockTime = j; // actual transaction data doesn't matter; just make the nLockTime's unique block.vtx.push_back(MakeTransactionRef(std::move(tx))); } // calculate actual merkle root and height uint256 merkleRoot1 = BlockMerkleRoot(block); std::vector<uint256> vTxid(nTx, uint256()); for (unsigned int j=0; j<nTx; j++) vTxid[j] = block.vtx[j]->GetHash(); int nHeight = 1, nTx_ = nTx; while (nTx_ > 1) { nTx_ = (nTx_+1)/2; nHeight++; } // check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128 for (int att = 1; att < 15; att++) { // build random subset of txid's std::vector<bool> vMatch(nTx, false); std::vector<uint256> vMatchTxid1; for (unsigned int j=0; j<nTx; j++) { bool fInclude = InsecureRandBits(att / 2) == 0; vMatch[j] = fInclude; if (fInclude) vMatchTxid1.push_back(vTxid[j]); } // build the partial merkle tree CPartialMerkleTree pmt1(vTxid, vMatch); // serialize CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pmt1; // verify CPartialMerkleTree's size guarantees unsigned int n = std::min<unsigned int>(nTx, 1 + vMatchTxid1.size()*nHeight); BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8); // deserialize into a tester copy CPartialMerkleTreeTester pmt2; ss >> pmt2; // extract merkle root and matched txids from copy std::vector<uint256> vMatchTxid2; std::vector<unsigned int> vIndex; uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex); // check that it has the same merkle root as the original, and a valid one BOOST_CHECK(merkleRoot1 == merkleRoot2); BOOST_CHECK(!merkleRoot2.IsNull()); // check that it contains the matched transactions (in the same order!) BOOST_CHECK(vMatchTxid1 == vMatchTxid2); // check that random bit flips break the authentication for (int j=0; j<4; j++) { CPartialMerkleTreeTester pmt3(pmt2); pmt3.Damage(); std::vector<uint256> vMatchTxid3; uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex); BOOST_CHECK(merkleRoot3 != merkleRoot1); } } } } BOOST_AUTO_TEST_CASE(pmt_malleability) { std::vector<uint256> vTxid = { ArithToUint256(1), ArithToUint256(2), ArithToUint256(3), ArithToUint256(4), ArithToUint256(5), ArithToUint256(6), ArithToUint256(7), ArithToUint256(8), ArithToUint256(9), ArithToUint256(10), ArithToUint256(9), ArithToUint256(10), }; std::vector<bool> vMatch = {false, false, false, false, false, false, false, false, false, true, true, false}; CPartialMerkleTree tree(vTxid, vMatch); std::vector<unsigned int> vIndex; BOOST_CHECK(tree.ExtractMatches(vTxid, vIndex).IsNull()); } BOOST_AUTO_TEST_SUITE_END()
[ "blockmecha@gmail.com" ]
blockmecha@gmail.com
bc4b4e067513cab3de47e4689bd8a5024e6eadab
07ca4af273d8d6d37eeab4242d6ef73c6e52cc12
/advance/1062.cpp
c3fdbb8857186070c6bc1e93ed2c0d4b29cbd066
[]
no_license
zffffw/pta
d2fb1c83e9b5435c2dfbd1179baf842c0426c7b1
c3bdf45602d0e8a382b5511723bcdd9cf498c558
refs/heads/master
2020-05-01T07:57:51.563963
2019-05-01T03:13:43
2019-05-01T03:13:43
177,365,318
2
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
#include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; typedef struct node { string idx; int a; int b; int s; bool operator < (const node &A) const { if(s != A.s) return s > A.s; else if(a != A.a) return a > A.a; else return idx < A.idx; } } node; vector <node> v[4]; int n, L, H; int main() { scanf("%d %d %d", &n, &L, &H); int total = 0; for(int i = 0; i < n; ++i) { char buf[128]; int a, b; scanf("%s %d %d", buf, &a, &b); string idx = buf; node tmp = {buf, a, b, a + b}; if(a >= H && b >= H) { v[0].push_back(tmp); total ++; } else if(a >= H && b >= L) { v[1].push_back(tmp); total ++; } else if(a >= b && a < H && b < H && a >= L && b >= L) { v[2].push_back(tmp); total ++; } else if(a >= L && b >= L) { v[3].push_back(tmp); total ++; } } printf("%d\n", total); for(int i = 0; i < 4; ++i) { sort(v[i].begin(), v[i].end()); for(int j = 0; j < v[i].size(); ++j) { printf("%s %d %d\n", v[i][j].idx.data(), v[i][j].a, v[i][j].b); } } }
[ "424533148@qq.com" ]
424533148@qq.com
061f663b5801ada16fc574acbc30efdeb8213e5d
5c77de87b42178964d736ef692e2589bf30c8224
/Source/CylandEditor/Public/CyLandToolInterface.h
ca9afc8aa2910999ee5421bae06ff83d39e67c68
[]
no_license
hanbim520/UnrealLandscapeCopy
7f5876584f0bbf31ad0da9a8516fd1db8ac29c82
209af4d0b2733d62ee42ab0133c51c2022d7e2df
refs/heads/master
2022-02-10T12:28:34.660178
2019-07-02T15:46:26
2019-07-02T15:46:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,930
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "InputCoreTypes.h" #include "UObject/GCObject.h" #include "UnrealWidget.h" #include "EdMode.h" class FEditorViewportClient; class FPrimitiveDrawInterface; class FSceneView; class FViewport; class UCyLandInfo; class UCyLandLayerInfoObject; class UMaterialInstance; class UMaterialInterface; class UViewportInteractor; struct FViewportClick; // FCyLandToolMousePosition - Struct to store mouse positions since the last time we applied the brush struct FCyLandToolInteractorPosition { // Stored in heightmap space. FVector2D Position; bool bModifierPressed; FCyLandToolInteractorPosition(FVector2D InPosition, const bool bInModifierPressed) : Position(InPosition) , bModifierPressed(bInModifierPressed) { } }; enum class ECyLandBrushType { Normal = 0, Alpha, Component, Gizmo, Splines }; class FCyLandBrushData { protected: FIntRect Bounds; TArray<float> BrushAlpha; public: FCyLandBrushData() : Bounds() { } FCyLandBrushData(FIntRect InBounds) : Bounds(InBounds) { BrushAlpha.SetNumZeroed(Bounds.Area()); } FIntRect GetBounds() const { return Bounds; } // For compatibility with older CyLand code that uses inclusive bounds in 4 int32s void GetInclusiveBounds(int32& X1, int32& Y1, int32& X2, int32& Y2) const { X1 = Bounds.Min.X; Y1 = Bounds.Min.Y; X2 = Bounds.Max.X - 1; Y2 = Bounds.Max.Y - 1; } float* GetDataPtr(FIntPoint Position) { return BrushAlpha.GetData() + (Position.Y - Bounds.Min.Y) * Bounds.Width() + (Position.X - Bounds.Min.X); } const float* GetDataPtr(FIntPoint Position) const { return BrushAlpha.GetData() + (Position.Y - Bounds.Min.Y) * Bounds.Width() + (Position.X - Bounds.Min.X); } FORCEINLINE explicit operator bool() const { return BrushAlpha.Num() != 0; } FORCEINLINE bool operator!() const { return !(bool)*this; } }; class FCyLandBrush : public FGCObject { public: virtual void MouseMove(float CyLandX, float CyLandY) = 0; virtual FCyLandBrushData ApplyBrush(const TArray<FCyLandToolInteractorPosition>& InteractorPositions) = 0; virtual TOptional<bool> InputKey(FEditorViewportClient* InViewportClient, FViewport* InViewport, FKey InKey, EInputEvent InEvent) { return TOptional<bool>(); } virtual void Tick(FEditorViewportClient* ViewportClient, float DeltaTime) {}; virtual void BeginStroke(float CyLandX, float CyLandY, class FCyLandTool* CurrentTool); virtual void EndStroke(); virtual void EnterBrush() {} virtual void LeaveBrush() {} virtual ~FCyLandBrush() {} virtual UMaterialInterface* GetBrushMaterial() { return NULL; } virtual const TCHAR* GetBrushName() = 0; virtual FText GetDisplayName() = 0; virtual ECyLandBrushType GetBrushType() { return ECyLandBrushType::Normal; } // FGCObject interface virtual void AddReferencedObjects(FReferenceCollector& Collector) override {} }; struct FCyLandBrushSet { FCyLandBrushSet(const TCHAR* InBrushSetName) : BrushSetName(InBrushSetName) , PreviousBrushIndex(0) { } const FName BrushSetName; TArray<FCyLandBrush*> Brushes; int32 PreviousBrushIndex; virtual ~FCyLandBrushSet() { for (int32 BrushIdx = 0; BrushIdx < Brushes.Num(); BrushIdx++) { delete Brushes[BrushIdx]; } } }; namespace ECyLandToolTargetType { enum Type : int8 { Heightmap = 0, Weightmap = 1, Visibility = 2, Invalid = -1, // only valid for CyLandEdMode->CurrentToolTarget.TargetType }; } namespace ECyLandToolTargetTypeMask { enum Type : uint8 { Heightmap = 1 << ECyLandToolTargetType::Heightmap, Weightmap = 1 << ECyLandToolTargetType::Weightmap, Visibility = 1 << ECyLandToolTargetType::Visibility, NA = 0, All = 0xFF, }; inline ECyLandToolTargetTypeMask::Type FromType(ECyLandToolTargetType::Type TargetType) { if (TargetType == ECyLandToolTargetType::Invalid) { return ECyLandToolTargetTypeMask::NA; } return (ECyLandToolTargetTypeMask::Type)(1 << TargetType); } } struct FCyLandToolTarget { TWeakObjectPtr<UCyLandInfo> CyLandInfo; ECyLandToolTargetType::Type TargetType; TWeakObjectPtr<UCyLandLayerInfoObject> LayerInfo; FName LayerName; int32 CurrentProceduralLayerIndex; FCyLandToolTarget() : CyLandInfo() , TargetType(ECyLandToolTargetType::Heightmap) , LayerInfo() , LayerName(NAME_None) , CurrentProceduralLayerIndex(INDEX_NONE) { } }; enum class ECyLandToolType { Normal = 0, Mask, }; /** * FCyLandTool */ class FCyLandTool : public FGCObject { public: virtual void EnterTool() {} virtual bool IsToolActive() const { return false; } virtual void ExitTool() {} virtual bool BeginTool(FEditorViewportClient* ViewportClient, const FCyLandToolTarget& Target, const FVector& InHitLocation) = 0; virtual void EndTool(FEditorViewportClient* ViewportClient) = 0; virtual void Tick(FEditorViewportClient* ViewportClient, float DeltaTime) {}; virtual bool MouseMove(FEditorViewportClient* ViewportClient, FViewport* Viewport, int32 x, int32 y) = 0; virtual bool HandleClick(HHitProxy* HitProxy, const FViewportClick& Click) { return false; } virtual bool InputKey(FEditorViewportClient* InViewportClient, FViewport* InViewport, FKey InKey, EInputEvent InEvent) { return false; } virtual bool InputDelta(FEditorViewportClient* InViewportClient, FViewport* InViewport, FVector& InDrag, FRotator& InRot, FVector& InScale) { return false; } virtual bool GetCursor(EMouseCursor::Type& OutCursor) const { return false; } FCyLandTool() : PreviousBrushIndex(-1) {} virtual ~FCyLandTool() {} virtual const TCHAR* GetToolName() = 0; virtual FText GetDisplayName() = 0; virtual void SetEditRenderType(); virtual void Render(const FSceneView* View, FViewport* Viewport, FPrimitiveDrawInterface* PDI) {} virtual bool SupportsMask() { return true; } virtual bool SupportsComponentSelection() { return false; } virtual bool OverrideSelection() const { return false; } virtual bool IsSelectionAllowed(AActor* InActor, bool bInSelection) const { return false; } virtual bool UsesTransformWidget() const { return false; } virtual EAxisList::Type GetWidgetAxisToDraw(FWidget::EWidgetMode InWidgetMode) const { return EAxisList::All; } virtual bool OverrideWidgetLocation() const { return true; } virtual bool OverrideWidgetRotation() const { return true; } virtual FVector GetWidgetLocation() const { return FVector::ZeroVector; } virtual FMatrix GetWidgetRotation() const { return FMatrix::Identity; } virtual bool DisallowMouseDeltaTracking() const { return false; } virtual void SetCanToolBeActivated(bool Value) { } virtual bool CanToolBeActivated() const { return true; } virtual void SetExternalModifierPressed(const bool bPressed) {}; virtual EEditAction::Type GetActionEditDuplicate() { return EEditAction::Skip; } virtual EEditAction::Type GetActionEditDelete() { return EEditAction::Skip; } virtual EEditAction::Type GetActionEditCut() { return EEditAction::Skip; } virtual EEditAction::Type GetActionEditCopy() { return EEditAction::Skip; } virtual EEditAction::Type GetActionEditPaste() { return EEditAction::Skip; } virtual bool ProcessEditDuplicate() { return false; } virtual bool ProcessEditDelete() { return false; } virtual bool ProcessEditCut() { return false; } virtual bool ProcessEditCopy() { return false; } virtual bool ProcessEditPaste() { return false; } // Functions which doesn't need Viewport data... virtual void Process(int32 Index, int32 Arg) {} virtual ECyLandToolType GetToolType() { return ECyLandToolType::Normal; } virtual ECyLandToolTargetTypeMask::Type GetSupportedTargetTypes() { return ECyLandToolTargetTypeMask::NA; }; // FGCObject interface virtual void AddReferencedObjects(FReferenceCollector& Collector) override {} public: int32 PreviousBrushIndex; TArray<FName> ValidBrushes; }; namespace CyLandTool { UMaterialInstance* CreateMaterialInstance(UMaterialInterface* BaseMaterial); }
[ "knziha@gmail.com" ]
knziha@gmail.com
fb007b1f0ed6bd17e41255a1fc882e9c9e58c3b4
900eeb54ac340c17f5921a1035248463046efe48
/SDK/PWND_EngineSettings_structs.hpp
d5ea5ced34c3daa2cb6c5de9d8a504df00376faf
[]
no_license
hinnie123/PWND_SDK
f94c5f8ebc99fd68aac02928550cf9401a7ac18d
b7cf225765a8083ba0a358ecb0067eb9ce1964d6
refs/heads/master
2020-04-02T04:44:07.654425
2018-10-21T17:01:00
2018-10-21T17:01:00
154,031,939
2
4
null
null
null
null
UTF-8
C++
false
false
1,844
hpp
#pragma once // PWND (4.17.2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Enums //--------------------------------------------------------------------------- // Enum EngineSettings.EThreePlayerSplitScreenType enum class EThreePlayerSplitScreenType : uint8_t { FavorTop = 0, FavorBottom = 1, EThreePlayerSplitScreenType_MAX = 2 }; // Enum EngineSettings.ETwoPlayerSplitScreenType enum class ETwoPlayerSplitScreenType : uint8_t { Horizontal = 0, Vertical = 1, ETwoPlayerSplitScreenType_MAX = 2 }; //--------------------------------------------------------------------------- //Script Structs //--------------------------------------------------------------------------- // ScriptStruct EngineSettings.AutoCompleteCommand // 0x0028 struct FAutoCompleteCommand { struct FString Command; // 0x0000(0x0010) (Edit, ZeroConstructor, Config) struct FString Desc; // 0x0010(0x0010) (Edit, ZeroConstructor, Config) unsigned char UnknownData00[0x8]; // 0x0020(0x0008) MISSED OFFSET }; // ScriptStruct EngineSettings.GameModeName // 0x0020 struct FGameModeName { struct FString Name; // 0x0000(0x0010) (Edit, ZeroConstructor) struct FStringClassReference GameMode; // 0x0010(0x0010) (Edit) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hindrik-sibma@hotmail.nl" ]
hindrik-sibma@hotmail.nl
49388d4d169e1c1309874ab77b74dc509237f012
323788cf746237167c70f38117d3fbd26e92c041
/sandbox/yajie/src/nnet/nnet-test.cc
36c211df6d574af1f800907185acafc7bb85b14d
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
zweiein/kaldi
3cfc5d1fc66c1ca32c74f71171d4af2e2512f15c
708448c693272af0d68c8e178c7b4ff836125acf
refs/heads/master
2020-12-26T00:45:36.907011
2015-10-23T21:17:02
2015-10-23T21:17:02
46,313,562
0
1
null
2015-11-17T00:57:57
2015-11-17T00:57:57
null
UTF-8
C++
false
false
1,196
cc
// nnet/nnet-test.cc // Copyright 2010 Brno University of Technology (author: Karel Vesely) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <iostream> #include "base/kaldi-common.h" #include "nnet/nnet-component.h" #include "nnet/nnet-nnet.h" using namespace kaldi; using namespace kaldi::nnet1; // :TODO: static void UnitTestSomething() { KALDI_ERR << "Unimeplemented"; } static void UnitTestNnet() { try { UnitTestSomething(); } catch (const std::exception &e) { std::cerr << e.what(); } } int main() { UnitTestNnet(); }
[ "danielpovey@5e6a8d80-dfce-4ca6-a32a-6e07a63d50c8" ]
danielpovey@5e6a8d80-dfce-4ca6-a32a-6e07a63d50c8
e75f6f36cdbc4a84299f4093c3653efcbfb0385a
e9cd4bb2814fffb908639af593f0c1b90923fe74
/util.h
596b2de5275085853e54047c2c95ddda835585a8
[]
no_license
MarcosChabolla/Cpp-Listmap
4ceb3c78f267184ad61509a04d3804e0abe4af07
028d0799d693401b65c92638e2c984a1b8e99892
refs/heads/master
2021-04-29T07:51:32.708018
2017-01-04T03:03:01
2017-01-04T03:03:01
77,975,201
0
0
null
null
null
null
UTF-8
C++
false
false
2,544
h
// $Id: util.h,v 1.5 2016/07/20 20:07:26 akhatri Exp $ // // util - // A utility class to provide various services not conveniently // associated with other modules. // #ifndef __UTIL_H__ #define __UTIL_H__ #include <iostream> #include <list> #include <stdexcept> #include <string> using namespace std; #include "trace.h" // // sys_info - // Keep track of execname and exit status. Must be initialized // as the first thing done inside main. Main should call: // sys_info::set_execname (argv[0]); // before anything else. // class sys_info { public: static const string& get_execname (); static void set_exit_status (int status); static int get_exit_status (); private: friend int main (int argc, char** argv); static void set_execname (const string& argv0); static string execname; static int exit_status; }; // // datestring - // Return the current date, as printed by date(1). // const string datestring (); // // split - // Split a string into a list<string>.. Any sequence // of chars in the delimiter string is used as a separator. To // Split a pathname, use "/". To split a shell command, use " ". // list<string> split (const string& line, const string& delimiter); // // complain - // Used for starting error messages. Sets the exit status to // EXIT_FAILURE, writes the program name to cerr, and then // returns the cerr ostream. Example: // complain() << filename << ": some problem" << endl; // ostream& complain(); // // syscall_error - // Complain about a failed system call. Argument is the name // of the object causing trouble. The extern errno must contain // the reason for the problem. // void syscall_error (const string&); // // operator<< (list) - // An overloaded template operator which allows lists to be // printed out as a single operator, each element separated from // the next with spaces. The item_t must have an output operator // defined for it. // template <typename item_t> ostream& operator<< (ostream& out, const list<item_t>& vec); // // string to_string (thing) - // Convert anything into a string if it has an ostream<< operator. // template <typename item_t> string to_string (const item_t&); // // thing from_string (cons string&) - // Scan a string for something if it has an istream>> operator. // template <typename item_t> item_t from_string (const string&); // // Put the RCS Id string in the object file. // #include "util.tcc" #endif
[ "Marcos.chabolla@gmail.com" ]
Marcos.chabolla@gmail.com
dc703b06e08936064158f5faaa8bffde5f7590ef
338f814b6e97001863042556f50b7c85d1ecae08
/3.1.2DObjects_GLSL/blockTileClass.cpp
1df2e81c3709d5b72ab7ece983b888f323566a98
[]
no_license
DaeunGod/Graphics-GLUT
bb0eede4ed51e663e4a23d96444fa40809962368
491e6044d4bfea067cedba04ee18f7719e1a0f67
refs/heads/master
2020-03-07T17:08:03.294362
2018-04-10T16:22:49
2018-04-10T16:22:49
127,603,215
0
0
null
null
null
null
UTF-8
C++
false
false
3,271
cpp
#include "stdafx.h" GLfloat blockTileBackGround[5][2] = { { -40.0, 20.0 },{ -40.0, -100.0 } ,{ 40.0, 20.0 },{ 40.0f, -100.0 },{ -40.0f, -100.0 } }; GLfloat blockTileline[4][2] = { { -40, 15.0 },{ -40.0, 20.0 } ,{ 40.0, 15.0 },{ 40.0f, 20.0 } }; GLfloat blockTileDeco1[3][2] = { { -28, 15.0 },{ -23.0, 10.0 },{ -20.0, 15.0 } }; GLfloat blockTileDeco2[3][2] = { { -10, 15.0 },{ -7.0, 12.0 },{ 3.0, 15.0 } }; GLfloat blockTileDeco3[4][2] = { { 12, 20.0 },{ 15.0, 23.0 },{ 21.0, 19.0 },{ 25.0, 22.0 } }; GLfloat blockTileDeco4[4][2] = { { 20, 12.0 },{ 25.0, 17.0 },{ 31.0, 10.0 },{ 33.0, 16.0 } }; GLfloat blockTile_color[2][3] = { { 110 / 255.0f, 67 / 255.0f, 42 / 255.0f }, { 14 / 255.0f, 209 / 255.0f, 69 / 255.0f }, }; void blockTileClass::initObject() { GLsizeiptr buffer_size = sizeof(blockTileBackGround) + sizeof(blockTileline) + sizeof(blockTileDeco1) + sizeof(blockTileDeco2) + sizeof(blockTileDeco3) + sizeof(blockTileDeco4); // Initialize vertex buffer object. glGenBuffers(1, &VBO_blockTile); glBindBuffer(GL_ARRAY_BUFFER, VBO_blockTile); glBufferData(GL_ARRAY_BUFFER, buffer_size, NULL, GL_STATIC_DRAW); // allocate buffer object memory glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(blockTileBackGround), blockTileBackGround); glBufferSubData(GL_ARRAY_BUFFER, sizeof(blockTileBackGround), sizeof(blockTileline), blockTileline); glBufferSubData(GL_ARRAY_BUFFER, sizeof(blockTileBackGround) + sizeof(blockTileline), sizeof(blockTileDeco1), blockTileDeco1); glBufferSubData(GL_ARRAY_BUFFER, sizeof(blockTileBackGround) + sizeof(blockTileline) + sizeof(blockTileDeco1) , sizeof(blockTileDeco2), blockTileDeco2); glBufferSubData(GL_ARRAY_BUFFER, sizeof(blockTileBackGround) + sizeof(blockTileline) + sizeof(blockTileDeco1) + sizeof(blockTileDeco2), sizeof(blockTileDeco3), blockTileDeco3); glBufferSubData(GL_ARRAY_BUFFER, sizeof(blockTileBackGround) + sizeof(blockTileline) + sizeof(blockTileDeco1) + sizeof(blockTileDeco2) + sizeof(blockTileDeco3), sizeof(blockTileDeco4), blockTileDeco4); // Initialize vertex array object. glGenVertexArrays(1, &VAO_blockTile); glBindVertexArray(VAO_blockTile); glBindBuffer(GL_ARRAY_BUFFER, VBO_blockTile); glVertexAttribPointer(LOC_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void blockTileClass::drawObject(glm::mat4 ViewProjectionMatrix) { calcUniforMat4(ViewProjectionMatrix); glBindVertexArray(VAO_blockTile); glUniform3fv(loc_primitive_color, 1, blockTile_color[0]); glDrawArrays(GL_TRIANGLE_STRIP, 0, 5); glUniform3fv(loc_primitive_color, 1, blockTile_color[1]); glDrawArrays(GL_TRIANGLE_STRIP, 5, 4); glUniform3fv(loc_primitive_color, 1, blockTile_color[1]); glDrawArrays(GL_TRIANGLE_FAN, 9, 3); glUniform3fv(loc_primitive_color, 1, blockTile_color[1]); glDrawArrays(GL_TRIANGLE_FAN, 12, 3); glUniform3fv(loc_primitive_color, 1, blockTile_color[1]); glDrawArrays(GL_TRIANGLE_FAN, 15, 4); glUniform3fv(loc_primitive_color, 1, blockTile_color[1]); glDrawArrays(GL_TRIANGLE_FAN, 19, 4); glBindVertexArray(0); } void blockTileClass::updateObjcet() { } void blockTileClass::cleanup() { glDeleteVertexArrays(1, &VAO_blockTile); glDeleteBuffers(1, &VBO_blockTile); }
[ "dcj4655@naver.com" ]
dcj4655@naver.com
25368cadc04e1c0df62d4c9391add67fb3a649fb
d4433d8c51e9dc6e0c2904def0a524c9125555de
/Battle/AffectArea/AffectFrontArea.cpp
25bd94b70661c44d4dcec77149cd4a5e5db9e9ef
[]
no_license
54993306/Classes
3458d9e86d1f0e2caa791cde87aff383b2a228bb
d4d1ec5ca100162bd64156deba3748ce1410151d
refs/heads/master
2020-04-12T06:23:49.273040
2016-11-17T04:00:19
2016-11-17T04:00:19
58,427,218
1
3
null
null
null
null
GB18030
C++
false
false
1,296
cpp
/************************************************************* * * * Data : 2016.6.12 * * Name : * * Author : Lin_Xiancheng * * Description : * * *************************************************************/ #include "Battle/AffectArea/AffectFrontArea.h" namespace BattleSpace { //前方单体 sAffectType AffectFrontSingle::getAreaType() { return sAffectType::eFrontSingle; } void AffectFrontSingle::initArea(AreaCountInfo& pInfo) { vector<BaseRole*>tRoles = pInfo.getAlive()->getCurrSkillTargets(); for (auto tRole : tRoles) { if (!tRole->getCaptain()) { pInfo.addGrid(tRole->getGridIndex()); return ; } } } /***************************************************************************/ //前方分散 sAffectType AffectFrontDisperse::getAreaType() { return sAffectType::eFrontDisperse; } void AffectFrontDisperse::initArea(AreaCountInfo& pInfo) { AffectFrontSingle::initArea(pInfo); pInfo.DisperseDispose(); } /***************************************************************************/ //前军n排 sAffectType AffectFrontRow::getAreaType() { return sAffectType::eFrontRow; } void AffectFrontRow::initArea(AreaCountInfo& pInfo) { AffectFrontSingle::initArea(pInfo); pInfo.RowType(eFrontDirection); } }
[ "54993306@qq.com" ]
54993306@qq.com
5d557514d512fd080bf0e3fe659d38c790aeb0ae
4a399bbb5129a2a413932c545050d7a7ad4ee05a
/Region.h
8439e8318954cdbb668c9035d1d756d95429823f
[]
no_license
voicelessreason/warlightBot
345e7341e226ad1c7c561c213b411f9ce71cfeda
5880d735e9f8ff1e6efa7335590745a36391a94d
refs/heads/master
2021-01-10T20:13:21.492331
2015-05-29T15:41:21
2015-05-29T15:41:21
28,961,043
0
0
null
null
null
null
UTF-8
C++
false
false
626
h
#ifndef REGION_H #define REGION_H #include <vector> #include <string> using namespace std; class Region { std::vector<int> neighbors; int id; int nbNeighbors; int superRegion; string owner; int armies; public: Region(); Region(int pId,int superRegion); virtual ~Region(); void addNeighbors(int Neighbors); void setArmies(int nbArmies); void setOwner(string owner); int getArmies(); string getOwner(); int getSuperRegion(); int getID(); vector<int>& getNeighbors(); protected: private: }; #endif // REGION_H
[ "arlenstrausman@gmail.com" ]
arlenstrausman@gmail.com
32f8c44644d5ecee3e7b6f7b229f6f559530949e
05654e33f9569bb4735af4936d553789684288e4
/Libraries/ZilchShaders/CycleDetection.cpp
43e865e662cc56ee475e4a94199c2483a9350b47
[ "MIT" ]
permissive
jodavis42/ZilchShaders
e8265c7768b2e4c2c8a314509364f7f9222541fe
a161323165c54d2824fe184f5d540e0a008b4d59
refs/heads/master
2021-06-20T16:49:35.760020
2021-04-30T01:06:33
2021-04-30T01:06:33
205,271,416
1
0
null
null
null
null
UTF-8
C++
false
false
12,226
cpp
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2018, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //-------------------------------------------------------------------CycleDetectionContext CycleDetectionContext::CycleDetectionContext() { mErrors = nullptr; mCurrentLibrary = nullptr; } //-------------------------------------------------------------------CycleDetectionObjectScope CycleDetectionObjectScope::CycleDetectionObjectScope(void* object, CycleDetectionContext* context) { mContext = context; mObject = object; PushScope(); } CycleDetectionObjectScope::~CycleDetectionObjectScope() { PopScope(); } void CycleDetectionObjectScope::PushScope() { mAlreadyVisited = false; mCycleDetected = false; // If we've visited this object twice in the DFS then we found a cycle. if(mContext->mProcessedObjectsStack.Contains(mObject)) { mAlreadyVisited = true; mCycleDetected = true; return; } // Otherwise if we've already processed this object but not in the current stack // this means this entire sub-tree has already been processed and has no cycles // (new function calling into a fully explored call graph) if(mContext->mAllProcessedObjects.Contains(mObject)) { mAlreadyVisited = true; return; } // Mark that we've visited this object mContext->mAllProcessedObjects.Insert(mObject); mContext->mProcessedObjectsStack.Insert(mObject); } void CycleDetectionObjectScope::PopScope() { // This object is no longer part of the call stack so it's not an error if we see it again mContext->mProcessedObjectsStack.Erase(mObject); } //-------------------------------------------------------------------CycleDetection CycleDetection::CycleDetection(ZilchShaderSpirVSettings* settings) { mErrors = nullptr; mSettings = settings; } bool CycleDetection::Run(Zilch::SyntaxTree& syntaxTree, ZilchShaderIRLibrary* library, ShaderCompilationErrors* errors) { mErrors = errors; CycleDetectionContext context; context.mErrors = mErrors; context.mCurrentLibrary = library; // Do a pre-walk in order to build a map of nodes to zilch objects. This is needed during // that actual pass as we'll have to recurse from a function call node into a function and // all of its statements. Only a function node has the actual function statements though // so we have to build a map here. Zilch::BranchWalker<CycleDetection, CycleDetectionContext> preWalker; preWalker.Register(&CycleDetection::PreWalkClassNode); preWalker.Register(&CycleDetection::PreWalkConstructor); preWalker.Register(&CycleDetection::PreWalkClassFunction); preWalker.Register(&CycleDetection::PreWalkClassMemberVariable); preWalker.Walk(this, syntaxTree.Root, &context); Zilch::BranchWalker<CycleDetection, CycleDetectionContext> walker; walker.Register(&CycleDetection::WalkClassNode); walker.Register(&CycleDetection::WalkClassConstructor); walker.Register(&CycleDetection::WalkClassFunction); walker.Register(&CycleDetection::WalkClassMemberVariable); walker.Register(&CycleDetection::WalkMemberAccessNode); walker.Register(&CycleDetection::WalkStaticTypeNode); walker.Walk(this, syntaxTree.Root, &context); return mErrors->mErrorTriggered; } void CycleDetection::PreWalkClassNode(Zilch::ClassNode*& node, CycleDetectionContext* context) { // Map the type to its node context->mTypeMap[node->Type] = node; // Walk all functions, constructors, and variables to do the same context->Walker->Walk(this, node->Functions, context); context->Walker->Walk(this, node->Constructors, context); context->Walker->Walk(this, node->Variables, context); } void CycleDetection::PreWalkConstructor(Zilch::ConstructorNode*& node, CycleDetectionContext* context) { context->mConstructorMap[node->DefinedFunction] = node; } void CycleDetection::PreWalkClassFunction(Zilch::FunctionNode*& node, CycleDetectionContext* context) { context->mFunctionMap[node->DefinedFunction] = node; } void CycleDetection::PreWalkClassMemberVariable(Zilch::MemberVariableNode*& node, CycleDetectionContext* context) { context->mVariableMap[node->CreatedProperty] = node; // Additionally handle get/set functions. if(node->Get != nullptr) context->mFunctionMap[node->Get->DefinedFunction] = node->Get; if(node->Set != nullptr) context->mFunctionMap[node->Set->DefinedFunction] = node->Set; } void CycleDetection::WalkClassNode(Zilch::ClassNode*& node, CycleDetectionContext* context) { WalkClassPreconstructor(node, context); context->Walker->Walk(this, node->Constructors, context); context->Walker->Walk(this, node->Functions, context); } void CycleDetection::WalkClassPreconstructor(Zilch::ClassNode*& node, CycleDetectionContext* context) { Zilch::Function* preConstructor = node->PreConstructor; if(preConstructor == nullptr) return; CycleDetectionObjectScope objectScope(preConstructor, context); // If the node has been visited already then early out if(objectScope.mAlreadyVisited) { // If we're visiting this twice because of a cycle then report an error if(objectScope.mCycleDetected) ReportError(context); return; } // Continue the DFS by walking all member variables (which walks their initializers) context->Walker->Walk(this, node->Variables, context); } void CycleDetection::WalkClassPreconstructor(Zilch::Function* preConstructor, CycleDetectionContext* context) { // Pre-constructors require walking the class node. Zilch::ClassNode* classNode = context->mTypeMap.FindValue(preConstructor->Owner, nullptr); if(classNode != nullptr) WalkClassPreconstructor(classNode, context); } void CycleDetection::WalkClassConstructor(Zilch::ConstructorNode*& node, CycleDetectionContext* context) { Zilch::Function* zilchConstructor = node->DefinedFunction; CycleDetectionObjectScope objectScope(zilchConstructor, context); // If the node has been visited already then early out if(objectScope.mAlreadyVisited) { // If we're visiting this twice because of a cycle then report an error if(objectScope.mCycleDetected) ReportError(context); return; } // Continue the DFS down the pre-construction function if it exists (instance variable initializers) Zilch::Function* preConstructor = zilchConstructor->Owner->PreConstructor; if(preConstructor != nullptr) { // Push the constructor node onto the call stack as calling the pre-constructor context->mCallStack.PushBack(node); WalkClassPreconstructor(preConstructor, context); context->mCallStack.PopBack(); } } void CycleDetection::WalkClassFunction(Zilch::FunctionNode*& node, CycleDetectionContext* context) { // Only walk a function once Zilch::Function* zilchFunction = node->DefinedFunction; CycleDetectionObjectScope objectScope(zilchFunction, context); // If the node has been visited already then early out if(objectScope.mAlreadyVisited) { // If we're visiting this twice because of a cycle then report an error if(objectScope.mCycleDetected) ReportError(context); return; } // Continue the DFS by walking all statements in the function context->Walker->Walk(this, node->Statements, context); } void CycleDetection::WalkClassMemberVariable(Zilch::MemberVariableNode*& node, CycleDetectionContext* context) { // Visit the member variable. If the user requests to not continue iteration then stop Zilch::Property* zilchProperty = node->CreatedProperty; CycleDetectionObjectScope objectScope(zilchProperty, context); // If the node has been visited already then early out if(objectScope.mAlreadyVisited) { // If we're visiting this twice because of a cycle then report an error if(objectScope.mCycleDetected) ReportError(context); return; } // Continue the DFS by walking variable initializers if(node->InitialValue != nullptr) context->Walker->Walk(this, node->InitialValue, context); } void CycleDetection::WalkMemberAccessNode(Zilch::MemberAccessNode*& node, CycleDetectionContext* context) { // Find the actual accessed function/property Zilch::Function* zilchFunction = nullptr; Zilch::Property* zilchProperty = nullptr; // If this is actually a getter/setter, then find the called get/set function if(node->AccessedGetterSetter != nullptr) { if(node->IoUsage & Zilch::IoMode::ReadRValue) zilchFunction = node->AccessedGetterSetter->Get; else if(node->IoUsage & Zilch::IoMode::WriteLValue) zilchFunction = node->AccessedGetterSetter->Set; } else if(node->AccessedFunction != nullptr) zilchFunction = node->AccessedFunction; else if(node->AccessedProperty != nullptr) zilchProperty = node->AccessedProperty; // Always push the given node onto the current call stack context->mCallStack.PushBack(node); // If we're calling a function (including getter/setters) if(zilchFunction != nullptr) { // Deal with [Implements]. If an implements is registered we'll find a shader function with // a different zilch function then the one we started with. This is the one that should // actually be walked to find dependencies. ZilchShaderIRFunction* shaderFunction = context->mCurrentLibrary->FindFunction(zilchFunction); if(shaderFunction != nullptr) zilchFunction = shaderFunction->mMeta->mZilchFunction; // Recursively walk the function we're calling if it's in the current library. // If it's not in the current library this will return null. Zilch::FunctionNode* fnNode = context->mFunctionMap.FindValue(zilchFunction, nullptr); if(fnNode != nullptr) context->Walker->Walk(this, fnNode, context); } // Otherwise, deal with member variables else if(zilchProperty != nullptr) { // Recursively walk the member we're referencing if it's in the current library Zilch::MemberVariableNode* varNode = context->mVariableMap.FindValue(zilchProperty, nullptr); if(varNode != nullptr) context->Walker->Walk(this, varNode, context); } context->mCallStack.PopBack(); } void CycleDetection::WalkStaticTypeNode(Zilch::StaticTypeNode*& node, CycleDetectionContext* context) { // Always push the given node onto the current call stack context->mCallStack.PushBack(node); // If there's a constructor function then walk its dependencies Zilch::Function* constructor = node->ConstructorFunction; if(constructor != nullptr) { // Find the node for this constructor so we can walk the statements within. // If this node is null then the constructor call is from a different library Zilch::ConstructorNode* constructorNode = context->mConstructorMap.FindValue(constructor, nullptr); if(constructorNode != nullptr) context->Walker->Walk(this, constructorNode, context); } // Otherwise this is a constructor call to a class with an implicit constructor. // In this case we have to traverse the pre-constructor. else { Zilch::Function* preConstructor = node->ReferencedType->PreConstructor; if(preConstructor != nullptr) { // Walk the pre-constructor to collect all its requirements WalkClassPreconstructor(preConstructor, context); } } context->mCallStack.PopBack(); } void CycleDetection::ReportError(CycleDetectionContext* context) { // Don't report duplicate errors if(context->mErrors->mErrorTriggered) return; ValidationErrorEvent toSend; toSend.mShortMessage = "Recursion is illegal in shaders"; toSend.mFullMessage = "Object calls itself via the stack:"; // Build the call stack from all of the call locations auto range = context->mCallStack.All(); for(; !range.Empty(); range.PopFront()) { Zilch::SyntaxNode* node = range.Front(); toSend.mCallStack.PushBack(node->Location); } // Set the primary location to be the start of the recursion toSend.mLocation = toSend.mCallStack.Front(); EventSend(context->mErrors, Events::ValidationError, &toSend); // Make sure to mark that we've triggered an error context->mErrors->mErrorTriggered = true; } }//namespace Zero
[ "22943955+jodavis42@users.noreply.github.com" ]
22943955+jodavis42@users.noreply.github.com
1f5b29fb763f6f1c85a26db5436ed9ba5ff264cc
072770cf3e7462a2a07d5ff55d78181b8e6b1b56
/week6/MaxProfitK.cpp
e90ac21005ea28454fcef4cd003b46628392af2e
[ "MIT" ]
permissive
AngelaJubeJudy/Algorithms
7e6e875e792d17ed770225bf977d4253011aec45
3a6eef59fd2fcb54d80013c067273d73bc6e79b9
refs/heads/main
2023-07-13T17:51:32.066394
2021-08-26T07:13:46
2021-08-26T07:13:46
378,541,394
0
0
MIT
2021-06-21T09:39:47
2021-06-20T02:21:38
null
UTF-8
C++
false
false
1,104
cpp
class MaxProfitK { public: int maxProfit(int k, vector<int>& prices) { return calc(prices, k, 0); } int calc(vector<int>& prices, int c, int fee){ // 初值 int n = prices.size(); vector<vector<vector<int>>> f(n+1, vector<vector<int>>(2, vector<int>(c+1, -10000000))); prices.insert(prices.begin(), 0); f[0][0][0] = 0; for(int i = 0; i < n; i++){ for(int j = 0; j <= 1; j++){ for(int k = 0; k <= c; k++){ // Buy if(j == 0 && k < c) f[i+1][1][k+1] = max(f[i+1][1][k+1], f[i][j][k]-prices[i+1]-fee); // Sell if(j == 1) f[i+1][0][k] = max(f[i+1][0][k], f[i][j][k]+prices[i+1]); // Rest f[i+1][j][k] = max(f[i+1][j][k], f[i][j][k]); } } } int ans = 0; for(int k = 0; k <= c; k++){ ans = max(ans, f[n][0][k]); } return ans; } };
[ "noreply@github.com" ]
AngelaJubeJudy.noreply@github.com
6def90c17822affb00ea6ac573a6e4cd9c7307f8
0fe2847bf222a3df0847a08de244000207514d05
/src/libseabreeze/include/vendors/OceanOptics/protocols/obp/exchanges/OBPGetGPIOExtensionAvailableModesExchange.h
21d536ff9a9d4044dec6605cf84bf12692c813f7
[ "MIT" ]
permissive
asenchristov/python-seabreeze
3656161eb2bf2be082839700f021a5957b81f00b
573bae1d9de4e819611b2f5b9c66f98d7d0fe066
refs/heads/master
2022-12-01T09:39:46.079901
2020-08-18T09:07:30
2020-08-18T09:07:30
288,403,712
0
0
MIT
2020-08-18T08:49:58
2020-08-18T08:49:57
null
UTF-8
C++
false
false
1,955
h
/***************************************************//** * @file OBPGetGPIOExtensionAvailableModesExchange.h * @date April 2017 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2017, Ocean Optics Inc * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #ifndef OBPGETGPIOEXTENSIONAVAILABLEMODESEXCHANGE_H #define OBPGETGPIOEXTENSIONAVAILABLEMODESEXCHANGE_H #include "vendors/OceanOptics/protocols/obp/exchanges/OBPQuery.h" namespace seabreeze { namespace oceanBinaryProtocol { class OBPGetGPIOExtensionAvailableModesExchange : public OBPQuery { public: OBPGetGPIOExtensionAvailableModesExchange(); virtual ~OBPGetGPIOExtensionAvailableModesExchange(); void setPinNumber(unsigned char eGPIO_Pin_Number); }; } } #endif /* OBPGETGPIOEXTENSIONAVAILABLEMODESEXCHANGE_H */
[ "andreas@poehlmann.io" ]
andreas@poehlmann.io
1d466e6c23876c6dab4d9e7a76fc2bed45d0e653
150fcfbade19dadc4cca7f8fc2d70093173c293a
/WarmmingUPLast/WarmmingUPLast/Question5.cpp
408b285a6b6ac7f2253a2990bef8810c214fc76b
[]
no_license
newmri/API
4e369cc02db05bde7e646c8f8cf0d95652919484
7c1ab621239628332a9a791a4e36b352fb63e871
refs/heads/master
2021-01-19T20:31:12.222307
2017-04-30T11:57:52
2017-04-30T11:57:52
83,756,338
0
0
null
null
null
null
UTF-8
C++
false
false
2,584
cpp
#include "Question5.h" Question5::Question5() { m_lvalue = 0; m_rvalue = 0; m_result = 0; m_errchk = false; } void Question5::CheckError() { for (int i = 0; i < MAX_SIZE; ++i) { if (1 & i == 1) { if ('*' != m_equation[i] && '/' != m_equation[i] && '+' != m_equation[i] && '-' != m_equation[i]) { m_errchk = true; return; } } else if(1 & i == 0){ if ('*' == m_equation[i] || '/' == m_equation[i] || '+' == m_equation[i] || '-' == m_equation[i]) { m_errchk = true; return; } } } } bool Question5::GetEquation() { cout << "Input numbers: "; cin >> m_equation; CheckError(); if (m_errchk) { cout << "Error has been ocuured bud! Ex) 1+2+3+4" << endl; return false; } DevideEquation(); return true; } void Question5::DevideEquation() { for (int i = 0; i < MAX_SIZE; ++i) { switch (m_equation[i]) { case '*': m_temparray[i - 1] = atoi(&m_equation[i - 1]); m_temparray[i] = 7; m_temparray[i + 1] = atoi(&m_equation[i + 1]); break; case '/': m_temparray[i - 1] = atoi(&m_equation[i - 1]); m_temparray[i] = 6; m_temparray[i + 1] = atoi(&m_equation[i + 1]); break; case '+': m_temparray[i - 1] = atoi(&m_equation[i - 1]); m_temparray[i] = 5; m_temparray[i + 1] = atoi(&m_equation[i + 1]); break; case '-': m_temparray[i - 1] = atoi(&m_equation[i - 1]); m_temparray[i] = 4; m_temparray[i + 1] = atoi(&m_equation[i + 1]); break; } } unsigned int tmp{}; unsigned int tem2{}; for (int i = 0; i < MAX_SIZE; i++) { for (int j = 0; j < MAX_SIZE - i - 1; j++) { if (j & 1 == 1) { if (m_temparray[j] < m_temparray[j + 2]) { tmp = m_temparray[j]; m_temparray[j] = m_temparray[j + 2]; m_temparray[j + 2] = tmp; tem2 = m_temparray[j - 1]; m_temparray[j - 1] = m_temparray[j + 1]; m_temparray[j + 1] = tem2; tem2 = m_temparray[j +1]; m_temparray[j + 1] = m_temparray[j + 3]; m_temparray[j + 3] = tem2; } } } } for (int i = 0; i < MAX_SIZE; ++i) { cout << m_temparray[i] << endl; } //m_temparray[MAX_SIZE] = '\0'; //cout << m_temparray << endl; } void Question5::CalculateByOperator() { for (int i = 0; i < MAX_SIZE; ++i) { if (!(2 & i == 1)) { } switch (m_temparray[1]) { case '*': m_result = m_lvalue*m_rvalue; break; case '/': m_result = m_lvalue / m_rvalue; break; case '+': m_result = m_lvalue + m_rvalue; break; case '-': m_result = m_lvalue - m_rvalue; break; } } //cout << m_result << endl; }
[ "newmri@naver.com" ]
newmri@naver.com
7cdd128081f1fa1780da614f5a73135fdc55ca8f
236753dbba656350d4a9f8ccd5efa27ef6886c32
/rayTracing/camera.cpp
494b43ebeceac71bc938a397edc1d16f399f2294
[]
no_license
xiajiaonly/rayTracing
31b6c8c156762bd5c2176e2c4a92a85c5f173225
53894946be8180748e90def66add18c58aa1e226
refs/heads/master
2021-05-28T03:56:54.016175
2015-01-17T16:36:52
2015-01-17T16:36:52
null
0
0
null
null
null
null
GB18030
C++
false
false
2,214
cpp
#include "stdafx.h" #include "camera.h" Camera::Camera(Point& pos, Point& headup, Point& lookat) :pos(pos),headup(headup),lookat(lookat) { unitise(); } Line Camera::getSightLight(double x, double y) { Point mov = xaxis * x + yaxis * y; return Line(pos + mov, lookat + mov); } void Camera::unitise() { dir = (lookat - pos).norm(); lookat = pos + dir; xaxis = dir.cross(headup); xaxis = xaxis / xaxis.len(); yaxis = xaxis.cross(dir); yaxis = yaxis / yaxis.len(); zaxis = xaxis.cross(yaxis); zaxis = zaxis / zaxis.len(); } Camera* CameraProspective::readCamera(FILE* fi) { Point a, b, c; a.readPoint(fi); b.readPoint(fi); c.readPoint(fi); double dist; fscanf(fi, "%lf", &dist); int DIFEnabled; double focusDist, focusOffset; fscanf(fi, "%d%lf%lf", &DIFEnabled, &focusDist, &focusOffset); return new CameraProspective(a, b, c, dist, DIFEnabled, focusDist, focusOffset); } void Camera::setPos(Point* _pos, Point* _headup, Point* _lookat) { if(_pos != 0) pos = *_pos; if(_headup != 0) headup = *_headup; if(_lookat != 0) lookat = *_lookat; unitise(); } CameraProspective::CameraProspective( Point& pos, Point& headup, Point& lookat, double dist, int DIFEnabled, double focusDist, double focusOffset) :Camera(pos, headup, lookat), dist(dist),DIFEnabled(DIFEnabled), focusDist(focusDist), focusOffset(focusOffset) { apetureCenter = pos + dir * dist; #define fabs(a) ((a)>0?(a):-(a)) focusCenter = apetureCenter + dir * focusDist; } Line CameraProspective::getSightLight(double x, double y) { Point p = pos + xaxis * x * xratio + yaxis * y * yratio; Point d = (apetureCenter - p).norm(); double cosa = fabs(d.dot(dir)); Point focusPoint = apetureCenter + d * (focusDist / cosa); Point mov = ( DIFEnabled == 1? Point(randf() * focusOffset, randf() * focusOffset, randf() * focusOffset): Point()); Point pp = apetureCenter + mov; // 在光圈上随机扰动 Point dd = focusPoint - pp; // 新的方向 dd.norm(); Line l(pp, pp + dd); return l; /* double movx = x / halfw * dist; double movy = y / halfh * dist; Point mov = xaxis * x + yaxis * y; Point mov2 = xaxis * (x + movx) + yaxis * (y + movy); return Line(pos + mov, lookat + mov2); */ }
[ "monocofe@gmail.com" ]
monocofe@gmail.com
14425a2c777abb43efb0802dc8f54d84b65d1463
f1072da7dbff060ca7b538a81d3936571fec56ea
/include/usfpp/bpg_rsp/RspOpContext.hpp
205da117fc551e35dfcb9f891c12a48e882a02f2
[]
no_license
Hkiller/workspace
e05374d30a6f309fa8cf1de83887ccb5d22736f9
660fc5900300786d7581a850a3fefc90f8d07a93
refs/heads/master
2021-03-30T22:44:17.469448
2017-04-12T06:08:02
2017-04-12T06:08:02
125,022,632
2
0
null
2018-03-13T09:07:03
2018-03-13T09:07:03
null
UTF-8
C++
false
false
698
hpp
#ifndef USFPP_BPG_RSP_OPCONTEXT_H #define USFPP_BPG_RSP_OPCONTEXT_H #include "usfpp/logic/LogicOpContext.hpp" #include "System.hpp" #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4624) #endif namespace Usf { namespace Bpg { class RspOpContext : public Logic::LogicOpContext { public: void addAdditionData(uint32_t meta_id); void removeAdditionData(uint32_t meta_id); void setClientId(uint64_t client_id); uint64_t clientId(void) const; void setCmd(uint32_t cmd); uint32_t cmd(void) const; void setSn(uint32_t sn); uint32_t sn(void) const; void setResponse(bool needResponse); }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #endif
[ "570385841@qq.com" ]
570385841@qq.com
883f5cf6f7c1d58bb5aeb81a474fee5acaee2856
9e450155723c9fcd15fa58daf080e0b681c2cd70
/Firebase_LED.ino
d302b1815aeb8e129fe2e7763d6e98af3d9d2a5e
[]
no_license
akshayshinde10x/Firebase
168a2d5185d7cc2ad662db9b862849005b8deb93
365a5b9ad37652cba0bb293538871a9caf1dc867
refs/heads/master
2020-06-11T06:15:08.926537
2019-12-27T13:39:21
2019-12-27T13:39:21
193,872,970
0
0
null
null
null
null
UTF-8
C++
false
false
2,348
ino
#include <WiFi.h> // esp32 library #include <IOXhop_FirebaseESP32.h> // firebase library #define FIREBASE_HOST "home-automation-a55b6.firebaseio.com" // the project name address from firebase id #define FIREBASE_AUTH "xPQMO5z9ju5Nu0kk5hzdcKlxBILL3siOX0zsjJIp" // the secret key generated from firebase #define WIFI_SSID "Amplifiers" // input your home or public wifi name #define WIFI_PASSWORD "123456789" //password of wifi ssid String fireStatus = ""; // led status received from firebase int led = 5; void setup() { Serial.begin(9600); delay(1000); pinMode(5, OUTPUT); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //try to connect with wifi Serial.print("Connecting to "); Serial.print(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID); Serial.print("IP Address is : "); Serial.println(WiFi.localIP()); //print local IP address Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to firebase Firebase.setString("LED_STATUS", "OFF"); //send initial string of led status } void loop() { fireStatus = Firebase.getString("ESP8266_Test/FAN"); // get led status input from firebase Serial.println(fireStatus); if(fireStatus == "\\\"ON\\\""){ Serial.println("Led Turned ON"); digitalWrite(2, HIGH); // make output led ON } else if (fireStatus == "\\\"OFF\\\"") { // compare the input of led status received from firebase Serial.println("Led Turned OFF"); digitalWrite(2, LOW); // make output led OFF } else { Serial.println("Wrong Credential! Please send ON/OFF"); } }
[ "noreply@github.com" ]
akshayshinde10x.noreply@github.com
86eb3736eac4a1e99c087d281d5d5a44bf3d31bc
fe91ffa11707887e4cdddde8f386a8c8e724aa58
/chrome/browser/ui/webui/settings/chromeos/search/search_handler_factory.cc
fba877837383e2e2adf04fd1143f2001c59b55c6
[ "BSD-3-Clause" ]
permissive
akshaymarch7/chromium
78baac2b45526031846ccbaeca96c639d1d60ace
d273c844a313b1e527dec0d59ce70c95fd2bd458
refs/heads/master
2023-02-26T23:48:03.686055
2020-04-15T01:20:07
2020-04-15T01:20:07
255,778,651
2
1
BSD-3-Clause
2020-04-15T02:04:56
2020-04-15T02:04:55
null
UTF-8
C++
false
false
2,323
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/chromeos/search/search_handler_factory.h" #include "chrome/browser/local_search_service/local_search_service_proxy.h" #include "chrome/browser/local_search_service/local_search_service_proxy_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/settings/chromeos/os_settings_localized_strings_provider_factory.h" #include "chrome/browser/ui/webui/settings/chromeos/search/search_handler.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" namespace chromeos { namespace settings { // static SearchHandler* SearchHandlerFactory::GetForProfile(Profile* profile) { return static_cast<SearchHandler*>( SearchHandlerFactory::GetInstance()->GetServiceForBrowserContext( profile, /*create=*/true)); } // static SearchHandlerFactory* SearchHandlerFactory::GetInstance() { return base::Singleton<SearchHandlerFactory>::get(); } SearchHandlerFactory::SearchHandlerFactory() : BrowserContextKeyedServiceFactory( "SearchHandler", BrowserContextDependencyManager::GetInstance()) { DependsOn( local_search_service::LocalSearchServiceProxyFactory::GetInstance()); DependsOn(OsSettingsLocalizedStringsProviderFactory::GetInstance()); } SearchHandlerFactory::~SearchHandlerFactory() = default; KeyedService* SearchHandlerFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); return new SearchHandler( OsSettingsLocalizedStringsProviderFactory::GetForProfile(profile), local_search_service::LocalSearchServiceProxyFactory::GetForProfile( Profile::FromBrowserContext(profile)) ->GetLocalSearchServiceImpl()); } bool SearchHandlerFactory::ServiceIsNULLWhileTesting() const { return true; } content::BrowserContext* SearchHandlerFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); } } // namespace settings } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8836ad5e32462fbe8a34796f62de5bdf8a4b774a
5c2a066016f9e9ee56a24251709bcd6fc777c153
/GLTestsApp/GLTestsApp/Classes/AppObjLoader/3d_resource_manager.h
589d35ebc41b0fb0438f430822778003c3f50f6d
[]
no_license
cleonro/ObjLoader
33f9969c4f7fd0a954f7fec10c447c191e215e51
d7483cd89376ed53684e5415d8a09be0df691228
refs/heads/master
2016-09-15T19:15:28.497983
2014-01-23T21:46:50
2014-01-23T21:46:50
25,855,975
0
0
null
null
null
null
UTF-8
C++
false
false
1,052
h
#ifndef _RESOURCE_MANAGER_H #define _RESOURCE_MANAGER_H #include "3d_model.h" #include <vector> #include <string> #include <map> using namespace std; class C_3D_RESOURCE_MANAGER { public: struct T_MODEL_INF { T_MODEL_INF(); unsigned int* indices; C_3D_MODEL::T_3D_MODEL_VERTEX* vertices; vector<unsigned int> object_start_indices; vector<string> object_names; unsigned int references; string name; }; C_3D_RESOURCE_MANAGER(); ~C_3D_RESOURCE_MANAGER(); C_3D_MODEL* build_model(vector<unsigned int>& indices, vector<C_3D_MODEL::T_3D_MODEL_VERTEX>& vertices, vector<unsigned int>& object_start_indices, vector<string>& object_names, string& model_name); void free_model(string name); void alloc_model(string name); protected: map<string, T_MODEL_INF> m_models; }; #endif // 3D_RESOURCE_MANAGER_H
[ "cleon_ro@yahoo.com" ]
cleon_ro@yahoo.com
454e0dfde2fae4ad7d987d37d910116cd99ff236
b96f35b56366e1024d963532064f14c2f6092dd3
/src/cpp_share/keys/ek_arith_seal1.cpp
f2d9221285701257bddf5c109483413cb0aa3a50
[]
no_license
oXis/e3
e89567df12d1fc20cb44f9efda69f17d4073b409
b2c29128f078fe6345b5c23d3f37c1ae37112181
refs/heads/master
2020-09-21T15:06:06.097444
2019-10-08T09:44:15
2019-10-08T09:44:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
#include <iostream> #include <fstream> #include "ek_arith_seal.h" #include "def_seal1.h" using std::cout; using namespace seal; bool e3::SealBaseEvalKey::load(string fname) { if (!NOCOUT) cout << "Loading evaluation key .. " << std::flush; auto fileParams = fname + ".params.key"; auto fileRelin = fname + ".relin.key"; std::ifstream inParams(fileParams, std::ios::binary); std::ifstream inRelin (fileRelin , std::ios::binary); if ( !inParams || !inRelin ) return false; static e3seal::SealEvalKey evalkey; try { static auto params = EncryptionParameters::Load(inParams); evalkey.context = SEALContext::Create(params); ///static auto evaluator = Evaluator(evalkey.context); static Evaluator evaluator(evalkey.context); evalkey.params = &params; evalkey.evaluator = &evaluator; evalkey.relinkeys.load(evalkey.context, inRelin); } catch (...) { throw "Bad " + filename() + " eval key"; } key = &evalkey; if (!NOCOUT) cout << "ok\n"; return true; }
[ "you@example.com" ]
you@example.com
8c25b627e263b7f2567d28fe9f7f7033a1a57081
73bdf06846b5c0e71d446581264b7b1e67a3bdd6
/741_Burrows_Wheeler_Decoder.cpp
706438393720624bbbb52e49b049a9bb614dfc72
[]
no_license
RasedulRussell/uva_problem_solve
0c11d7341316f4aca78e3c14a102aba8e65bd5e1
c3a2b8da544b9c05b2d459e81ee38c96f89eaffe
refs/heads/master
2021-06-13T09:10:42.936870
2021-03-24T15:49:15
2021-03-24T15:49:15
160,766,749
3
0
null
null
null
null
UTF-8
C++
false
false
771
cpp
#include<bits/stdc++.h> using namespace std; #define int long long #define MAX 10005 #define INF 100000000 #define EPS 1e-9 #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0) ///741_Burrows_Wheeler_Decoder.cpp int32_t main(){ __FastIO; string str; int pos; int cs = 0; while(cin >> str >> pos){ if(str == "END" && pos == 0)break; if(cs){ cout << "\n"; } cs = 1; int n = str.size(); vector<string>ans(n); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ ans[j].insert(ans[j].begin(), str[j]); } sort(ans.begin(), ans.end()); } cout << ans[pos - 1] << "\n"; } return 0; }
[ "rasedulrussell@gmail.com" ]
rasedulrussell@gmail.com
36d9561d4f352d1cdf8f1508af564be01b288914
0f8726a8394d2fbda60bdd24d6c9a82e9a4891ef
/src/RefProperty.cpp
e0efb7c31fe425703b2782963f819a73716080e9
[ "MIT" ]
permissive
gidapataki/undoable
4f9de6fa2fdf24424d6dfea2b4b00e3277bf62d2
aa59b40926d322cd04c84ee21611df8f56a0dfa2
refs/heads/master
2020-04-08T08:50:10.576046
2019-01-17T15:04:29
2019-01-17T15:04:29
159,195,668
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
#include "undoable/RefProperty.h" namespace undoable { // RefNode void RefNode::LinkRef(RefNode* u, RefNode* v) { u->next_ref_ = v; v->prev_ref_ = u; } void RefNode::UnlinkRef() { LinkRef(prev_ref_, next_ref_); LinkRef(this, this); referable_ = nullptr; } // Referable void Referable::LinkBack(RefPropertyBase* node) { RefNode::LinkRef(node->prev_ref_, node->next_ref_); RefNode::LinkRef(head_.prev_ref_, node); RefNode::LinkRef(node, &head_); node->referable_ = this; } void Referable::ResetAllReferences() { for (auto* p = head_.next_ref_; p != &head_; p = head_.next_ref_) { // Note: calling OnReset() could lead to a destroy loop static_cast<RefPropertyBase*>(p)->SetReferable(nullptr); } } // RefPropertyBase RefPropertyBase::RefPropertyBase(PropertyOwner* owner) : Property(owner) {} void RefPropertyBase::SetReferable(Referable* referable) { if (referable != referable_) { auto cmd = MakeUnique<Change>(this, referable); owner_->ApplyPropertyChange(std::move(cmd)); } } void RefPropertyBase::SetReferableInternal(Referable* referable) { if (referable) { referable->LinkBack(this); } else { UnlinkRef(); } } void RefPropertyBase::OnReset() { SetReferable(nullptr); } } // namespace undoable
[ "gida.pataki@prezi.com" ]
gida.pataki@prezi.com
3cdc27a73eb19e2a0d81e3ea79880f81ab6692cf
67281c684a1722151cfdbbba2f09c215b2bb7b19
/dp/maxSumofIncreasingseq.cpp
bb6cee8132634dad0cc104febb4d1b7df9800607
[]
no_license
ritikdhasmana/DS-Algo
e20d388de977e3f8a24fe0e1e7612275041c7e3d
c86e63cc5b868b391888d4b4995a39a00cf21aad
refs/heads/main
2023-06-29T03:31:36.117050
2021-08-06T05:27:26
2021-08-06T05:27:26
393,258,107
2
0
null
null
null
null
UTF-8
C++
false
false
857
cpp
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: int maxSumIS(int arr[], int n) { // Your code goes here int t[n+1]; int ans=0; for(int i=0;i<n;i++)t[i]=arr[i]; for(int i=1;i<n;i++) { for(int j=0;j<i;j++){ if(arr[i]>arr[j]&&t[i]<t[j]+arr[i])t[i]=t[j]+arr[i]; } } for(int i=0;i<n;i++)ans= max(ans,t[i]); return ans; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; for(int i = 0; i < n; i++) cin >> a[i]; Solution ob; cout << ob.maxSumIS(a, n) << "\n"; } return 0; } // } Driver Code Ends
[ "noreply@github.com" ]
ritikdhasmana.noreply@github.com
4cb43716d084c5fce066041e2e1507e9be8c2ec6
628aca1e8bf74174e7cde5bec365042240d3aaf7
/test/obj_develop/obj_develop/01_domain.cpp
48f9d4534f93308decdfedeadfd0e2668450b024
[ "Apache-2.0" ]
permissive
nvoronetskiy/obj
bbbdf59b745a33d1b7532a1bd078782b58aa6dbe
f44c4c71310b0be70e51c2759662dd04e32c747a
refs/heads/main
2023-03-19T22:00:41.674227
2021-03-07T20:51:43
2021-03-07T20:51:43
345,824,025
0
0
Apache-2.0
2021-03-08T23:28:24
2021-03-08T23:28:23
null
UTF-8
C++
false
false
5,517
cpp
// Copyright 2016 Aether 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 <iostream> #include <fstream> #include <map> #include <set> #include <filesystem> #include "../../../aether/obj/obj.h" // * - domain initially loaded // # - domain initially unloaded // 0 - zero pointer // B0 - class B, instance 0 // () - class factory // ZeroObjPointers: nullptr reference to the object // A0* // |-B = 0 // SingleObjReference // A0* // |-B0 // BaseClassReference: serialization/deserialization through reference to the base class // A0* // |-B0 (Obj::ptr) // MultipleObjReference: referencing different objects of a single class // A0* // |-B0 // |-B1 // Hierarchy // A0* // |-B0 // |-C0 // HierachichalDomains // A0* // |-B* // |-C0* // |-C1# // SharedReference: C0 is referenced twice // A0* // |-C0 // |-C0 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // SharedReference: C0 is referenced with child domain // A0* // |-C0 // |-B0* // |-C0 // CrossRerefenceDifferentLevel // A0* // |-B0 // |-A0 // CrossRerefenceSameLevel // A0* // |-B0 // |-B1 // |-B1 // |-B0 // LoadUnload: the state is saved/restored // Cross references within a single level // Cross references with different level // A0* // |-C0 // |-B0# // |-C0 // |-B0 // |-C1 // |-C1 // |-C0 /* #include <fstream> static std::unordered_map<aether::ObjStorage, std::string> storage_to_path_; static auto saver = [](const std::string& path, aether::ObjStorage storage, const AETHER_OMSTREAM& os){ std::filesystem::create_directories(std::filesystem::path{"state"} / storage_to_path_[storage]); auto p = std::filesystem::path{"state"} / storage_to_path_[storage] / path; std::ofstream f(p.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); // bool b = f.good(); f.write((const char*)os.stream_.data(), os.stream_.size()); std::cout << p.c_str() << " size: " << os.stream_.size() << "\n"; }; static auto loader = [](const std::string& path, aether::ObjStorage storage, AETHER_IMSTREAM& is){ auto p = std::filesystem::path{"state"} / storage_to_path_[storage] / path; std::ifstream f(p.c_str(), std::ios::in | std::ios::binary); f.seekg (0, f.end); std::streamoff length = f.tellg(); f.seekg (0, f.beg); is.stream_.resize(length); f.read((char*)is.stream_.data(), length); }; class B : public aether::Obj { public: AETHER_CLS(B); AETHER_SERIALIZE(B); AETHER_INTERFACES(B); B() = default; B(float f) : f_(f) {} virtual ~B() { std::cout << "~B[ " << id_.ToString() << " ]: " << f_ << "\n"; } float f_; std::vector<B::ptr> o_; template <typename T> void Serializator(T& s, int flags) { s & f_ & o_; } }; AETHER_IMPL(B); class Root : public aether::Obj { public: AETHER_CLS(Root); AETHER_SERIALIZE(Root); AETHER_INTERFACES(Root); Root() = default; Root(int i) : i_(i) {} virtual ~Root() { std::cout << "~Root " << i_ << "\n"; } int i_; std::vector<B::ptr> o_; template <typename T> void Serializator(T& s, int flags) { s & i_ & o_; } }; AETHER_IMPL(Root); void DomainTest() { std::filesystem::remove_all("state"); // { // Root::ptr root(new Root(123)); // root.SetFlags(aether::ObjFlags::kLoadable | aether::ObjFlags::kLoaded); // B::ptr b(new B(2.71f)); // B::ptr b2(new B(3.14f)); // b->o_.push_back(b2); // b2->o_.push_back(b); // root->o_.push_back(b); // root->o_.push_back(b2); // b = nullptr; // b2 = nullptr; // root.Serialize(saver, aether::Obj::Serialization::kConsts | aether::Obj::Serialization::kRefs | aether::Obj::Serialization::kData); // root.Unload(); // Root::ptr r1 = root.Clone(loader); // int sdf=0; // root = nullptr; // r1 = nullptr; // } Root::ptr root(new Root(123)); root.SetId(666); { B::ptr b1(new B(2.71f)); b1->o_.push_back({}); B::ptr b2(new B(3.14f)); b2.SetFlags(aether::ObjFlags::kLoadable | aether::ObjFlags::kLoaded); b2->o_.push_back(b1); b1->o_.push_back(b2); root->o_.push_back(b2); root->o_.push_back({}); // root->o_.push_back(b1); } { root->o_[0].Serialize(saver, aether::Obj::Serialization::kConsts | aether::Obj::Serialization::kRefs | aether::Obj::Serialization::kData); root->o_[0].Unload(); root.Serialize(saver, aether::Obj::Serialization::kConsts | aether::Obj::Serialization::kRefs | aether::Obj::Serialization::kData); root = nullptr; int sdf=0; } { std::cout << "Restoring...\n"; Root::ptr root; root.SetId(666); root.SetFlags(aether::ObjFlags::kLoaded); root.Load(loader); B::ptr r1 = root->o_[0].Clone(loader); B::ptr r2 = root->o_[0].Clone(loader); root->o_.push_back(r2); root->o_[0].Load(loader); r1 = nullptr; r2 = nullptr; root.Unload(); int sfd=0; } } */
[ "aethernetio@gmail.com" ]
aethernetio@gmail.com
62b78f6ef8e77244a00f86fb5acea1ca8fef267b
6728394d63024d85217726e08e292be78e986cf9
/kino/sqlgen/src/Dict.cpp
f2cbec17bffca054e55dee6a04e69756805fb823
[]
no_license
mustafirus/oldprojects
5632c886d98d0ed38469327c05690d0830a72070
51180b540b3a19964ae5a1776a743ca0bb9de204
refs/heads/master
2021-07-25T16:18:03.885015
2013-03-24T09:52:27
2013-03-24T09:52:27
109,653,046
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
/* * Dict.cpp * * Created on: 16 марта 2011 * Author: golubev */ #include "stdx.h" #include "Dict.h"
[ "7886143+mustafirus@users.noreply.github.com" ]
7886143+mustafirus@users.noreply.github.com
88971ed091455f01cd78b7d2200270da7f0dd428
11b679228b7f3fbb7521946adda9a4b3ba22aa3a
/ros/flytcore/include/dji_sdk/MissionStatusRequest.h
a55a580695c3417edb227695061273c6cb99b02f
[]
no_license
IgorLebed/spiiran_drone
7f49513a2fa3f2dffd54e43990b76145db9ae542
d73221243cabcf89090e7311de5a18fa0faef10c
refs/heads/master
2020-05-02T19:45:15.132838
2020-03-20T08:18:08
2020-03-20T08:18:08
178,167,867
0
0
null
null
null
null
UTF-8
C++
false
false
5,111
h
// Generated by gencpp from file dji_sdk/MissionStatusRequest.msg // DO NOT EDIT! #ifndef DJI_SDK_MESSAGE_MISSIONSTATUSREQUEST_H #define DJI_SDK_MESSAGE_MISSIONSTATUSREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace dji_sdk { template <class ContainerAllocator> struct MissionStatusRequest_ { typedef MissionStatusRequest_<ContainerAllocator> Type; MissionStatusRequest_() { } MissionStatusRequest_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> const> ConstPtr; }; // struct MissionStatusRequest_ typedef ::dji_sdk::MissionStatusRequest_<std::allocator<void> > MissionStatusRequest; typedef boost::shared_ptr< ::dji_sdk::MissionStatusRequest > MissionStatusRequestPtr; typedef boost::shared_ptr< ::dji_sdk::MissionStatusRequest const> MissionStatusRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::dji_sdk::MissionStatusRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace dji_sdk namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'nav_msgs': ['/opt/ros/kinetic/share/nav_msgs/cmake/../msg'], 'dji_sdk': ['/home/flytpod/flytos/src/flytOS/flyt_core/core_nodes/dji/dji_sdk/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::dji_sdk::MissionStatusRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > { static const char* value() { return "dji_sdk/MissionStatusRequest"; } static const char* value(const ::dji_sdk::MissionStatusRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > { static const char* value() { return "\n\ "; } static const char* value(const ::dji_sdk::MissionStatusRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct MissionStatusRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::dji_sdk::MissionStatusRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::dji_sdk::MissionStatusRequest_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // DJI_SDK_MESSAGE_MISSIONSTATUSREQUEST_H
[ "hazz808@gmail.com" ]
hazz808@gmail.com
cb176bef4268c7e83ee388a1aec1ada9ebaea5b7
05331297eca32128a5267ba82e4285d601277189
/src/headers/Object.h
e584ebc97e8c305a363a92262400365366d25c5f
[ "BSD-2-Clause" ]
permissive
joao29a/checkersGame
5a7eb21d637a24506c78f2ddbed8c4cdf6981a43
53982765a596fa2de7d9fb6d579bfb94f5bcf0aa
refs/heads/master
2021-01-10T19:04:45.378549
2013-07-28T03:56:41
2013-07-28T03:56:41
11,494,051
1
0
null
null
null
null
UTF-8
C++
false
false
331
h
#ifndef OBJECT_H #define OBJECT_H #include <map> #include <vector> #include "defines.h" class Object{ public: Object(int color); virtual ~Object(){} int color; int type; virtual map<int,int> positionValues(int id, vector<Object*> board); virtual void removeUnkilledPositions(map<int,int>* values); }; #endif
[ "john@john-programmer.(none)" ]
john@john-programmer.(none)
2dfad14998c8ae2b7ba34679723111c09e23fed3
4857d86e09d369f686cac2f8ae83b6ea28ce890f
/Engine/Input/InputSystem.cpp
b357544aaccc9b98de9e2eef402d395266ed4fbd
[]
no_license
Ghostninja2451/GAT150
423cdf4f689acd4c867a49aedd0b7758905689c5
bde4f0f859c68f804eb16ffe7eb064c50c7e664a
refs/heads/master
2023-07-20T19:58:48.593201
2021-08-17T21:41:49
2021-08-17T21:41:49
392,098,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,836
cpp
#include "InputSystem.h" namespace henry { void InputSystem::Startup() { const Uint8* keyboardStateSDL = SDL_GetKeyboardState(&numKeys); keyboardState.resize(numKeys); std::copy(keyboardStateSDL, keyboardStateSDL + numKeys, keyboardState.begin()); prevKeyboardState = keyboardState; } void InputSystem::Shutdown() { } void InputSystem::Update(float dt) { prevKeyboardState = keyboardState; const Uint8* keyboardStateSDL = SDL_GetKeyboardState(nullptr); std::copy(keyboardStateSDL, keyboardStateSDL + numKeys, keyboardState.begin()); prevMouseButtonState = mouseButtonState; int x, y; Uint32 buttons = SDL_GetMouseState(&x, &y); mousePosition = henry::Vector2{ x, y }; mouseButtonState[0] = buttons & SDL_BUTTON_LMASK; // buttons [0001] & [ORML] mouseButtonState[1] = buttons & SDL_BUTTON_MMASK; // buttons [0010] & [ORML] mouseButtonState[2] = buttons & SDL_BUTTON_RMASK; // buttons [0100] & [ORML] } InputSystem::eKeyState InputSystem::GetKeyState(int id) { eKeyState state = eKeyState::Idle; bool keyDown = IsKeyDown(id); bool prevKeyDown = IsPreviousKeyDown(id); if (keyDown) { state = (prevKeyDown) ? eKeyState::Held : eKeyState::Pressed ; } else { state = (prevKeyDown) ? eKeyState::Release: eKeyState::Idle; } return state; } bool InputSystem::IsKeyDown(int id) { return keyboardState[id]; } bool InputSystem::IsPreviousKeyDown(int id) { return prevKeyboardState[id]; } InputSystem::eKeyState InputSystem::GetButtonState(int id) { eKeyState state = eKeyState::Idle; bool keyDown = IsButtonDown(id); bool prevKeyDown = IsPrevButtonDown(id); if (keyDown) { state = (prevKeyDown) ? eKeyState::Held : eKeyState::Pressed; } else { state = (prevKeyDown) ? eKeyState::Release : eKeyState::Idle; } return state; } }
[ "80051664+Ghostninja2451@users.noreply.github.com" ]
80051664+Ghostninja2451@users.noreply.github.com
2d3e34fb92d7efa079940b12150b540f88985856
8e4f0c31c5ddc1eef16a61bf359a043b8cb3a6c3
/src/agent/jvm_readers_factory.cc
62759a9454adee39aec14771993e70fe21e517d4
[ "Apache-2.0" ]
permissive
botdevops/cloud-debug-java
22d90d8a95402cd4ffd96b9eeb41fdafd806b4a4
b18ab8cfec4b70dee6c5b1e28e4e35d00e33ae9c
refs/heads/master
2021-06-15T01:14:56.926516
2017-03-29T21:04:31
2017-03-29T21:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,728
cc
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jvm_readers_factory.h" #include <algorithm> #include "class_indexer.h" #include "class_metadata_reader.h" #include "class_path_lookup.h" #include "jvm_object_array_reader.h" #include "jvm_primitive_array_reader.h" #include "jvmti_buffer.h" #include "messages.h" #include "method_locals.h" #include "model.h" #include "safe_method_caller.h" #include "type_util.h" namespace devtools { namespace cdbg { JvmReadersFactory::JvmReadersFactory( JvmEvaluators* evaluators, jmethodID method, jlocation location) : evaluators_(evaluators), method_(method), location_(location) { } string JvmReadersFactory::GetEvaluationPointClassName() { jvmtiError err = JVMTI_ERROR_NONE; jclass cls = nullptr; err = jvmti()->GetMethodDeclaringClass(method_, &cls); if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetMethodDeclaringClass failed, error: " << err; return string(); } JniLocalRef auto_cls(cls); JvmtiBuffer<char> class_signature_buffer; err = jvmti()->GetClassSignature( cls, class_signature_buffer.ref(), nullptr); if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetClassSignature failed, error: " << err; return string(); } return TypeNameFromJObjectSignature(class_signature_buffer.get()); } JniLocalRef JvmReadersFactory::FindClassByName( const string& class_name, FormatMessageModel* error_message) { ClassIndexer* class_indexer = evaluators_->class_indexer; JniLocalRef cls; *error_message = {}; // Case 1: class name is fully qualified (i.e. includes the package name) // and has been already loaded by the JVM. cls = class_indexer->FindClassByName(class_name); if (cls != nullptr) { return cls; } // Case 2: class name is relative to "java.lang" package. We assume that // the class has been already loaded in this case. cls = class_indexer->FindClassByName("java.lang." + class_name); if (cls != nullptr) { return cls; } // Case 3: class name is relative to the current scope. string current_class_name = GetEvaluationPointClassName(); size_t name_pos = current_class_name.find_last_of('.'); if ((name_pos > 0) && (name_pos != string::npos)) { cls = class_indexer->FindClassByName( current_class_name.substr(0, name_pos + 1) + class_name); if (cls != nullptr) { return cls; } } // Case 4: the class is either unqualified (i.e. doesn't include the package // name) or hasn't been loaded yet. Note that this will not include JDK // classes (like java.lang.String). These classes are usually loaded very // eary and we don't want to waste resources indexing all of them. std::vector<string> candidates = evaluators_->class_path_lookup->FindClassesByName(class_name); std::sort(candidates.begin(), candidates.end()); switch (candidates.size()) { case 0: *error_message = { InvalidIdentifier, { class_name } }; return nullptr; case 1: cls = class_indexer->FindClassBySignature(candidates[0]); if (cls != nullptr) { return cls; } *error_message = { ClassNotLoaded, { TypeNameFromJObjectSignature(candidates[0]) } }; return nullptr; case 2: *error_message = { AmbiguousClassName2, { class_name, TypeNameFromJObjectSignature(candidates[0]), TypeNameFromJObjectSignature(candidates[1]) } }; return nullptr; case 3: *error_message = { AmbiguousClassName3, { class_name, TypeNameFromJObjectSignature(candidates[0]), TypeNameFromJObjectSignature(candidates[1]), TypeNameFromJObjectSignature(candidates[2]) } }; return nullptr; default: *error_message = { AmbiguousClassName4OrMore, { class_name, TypeNameFromJObjectSignature(candidates[0]), TypeNameFromJObjectSignature(candidates[1]), TypeNameFromJObjectSignature(candidates[2]), std::to_string(candidates.size() - 3) } }; return nullptr; } } bool JvmReadersFactory::IsAssignable( const string& from_signature, const string& to_signature) { ClassIndexer* class_indexer = evaluators_->class_indexer; // Currently array types not supported in this function. if (IsArrayObjectSignature(from_signature) || IsArrayObjectSignature(to_signature)) { return false; } // Get the class object corresponding to "from_signature". JniLocalRef from_cls = class_indexer->FindClassBySignature(from_signature); if (from_cls == nullptr) { return false; } // Get the class object corresponding to "to_signature". JniLocalRef to_cls = class_indexer->FindClassBySignature(to_signature); if (to_cls == nullptr) { return false; } return jni()->IsAssignableFrom( static_cast<jclass>(from_cls.get()), static_cast<jclass>(to_cls.get())); } std::unique_ptr<LocalVariableReader> JvmReadersFactory::CreateLocalVariableReader( const string& variable_name, FormatMessageModel* error_message) { std::shared_ptr<const MethodLocals::Entry> method = evaluators_->method_locals->GetLocalVariables(method_); for (const std::unique_ptr<LocalVariableReader>& local : method->locals) { if (local->IsDefinedAtLocation(location_) && (variable_name == local->GetName())) { return local->Clone(); } } return nullptr; } std::unique_ptr<LocalVariableReader> JvmReadersFactory::CreateLocalInstanceReader() { std::shared_ptr<const MethodLocals::Entry> method = evaluators_->method_locals->GetLocalVariables(method_); if (method->local_instance == nullptr) { return nullptr; } return method->local_instance->Clone(); } std::unique_ptr<InstanceFieldReader> JvmReadersFactory::CreateInstanceFieldReader( const string& class_signature, const string& field_name, FormatMessageModel* error_message) { JniLocalRef cls = evaluators_->class_indexer->FindClassBySignature(class_signature); if (cls == nullptr) { // JVM does not defer loading field types, so it should never happen. LOG(WARNING) << "Class not found: " << class_signature; *error_message = { ClassNotLoaded, { TypeNameFromJObjectSignature(class_signature) } }; return nullptr; } const ClassMetadataReader::Entry& metadata = evaluators_->class_metadata_reader->GetClassMetadata( static_cast<jclass>(cls.get())); for (const auto& field : metadata.instance_fields) { if (field->GetName() == field_name) { return field->Clone(); } } *error_message = { InstanceFieldNotFound, { field_name, TypeNameFromJObjectSignature(class_signature) } }; return nullptr; // No instance field named "field_name" found Java class. } std::unique_ptr<StaticFieldReader> JvmReadersFactory::CreateStaticFieldReader( const string& field_name, FormatMessageModel* error_message) { jvmtiError err = JVMTI_ERROR_NONE; jclass cls = nullptr; err = jvmti()->GetMethodDeclaringClass(method_, &cls); if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetMethodDeclaringClass failed, error: " << err; return nullptr; } JniLocalRef auto_cls(cls); std::unique_ptr<StaticFieldReader> reader = CreateStaticFieldReader(cls, field_name); if (reader == nullptr) { *error_message = { InvalidIdentifier, { field_name } }; } return reader; } std::unique_ptr<StaticFieldReader> JvmReadersFactory::CreateStaticFieldReader( const string& class_name, const string& field_name, FormatMessageModel* error_message) { JniLocalRef cls = FindClassByName(class_name, error_message); if (cls == nullptr) { return nullptr; } std::unique_ptr<StaticFieldReader> reader = CreateStaticFieldReader(static_cast<jclass>(cls.get()), field_name); if (reader == nullptr) { *error_message = { StaticFieldNotFound, { field_name, class_name } }; } return reader; } std::unique_ptr<StaticFieldReader> JvmReadersFactory::CreateStaticFieldReader( jclass cls, const string& field_name) { const ClassMetadataReader::Entry& metadata = evaluators_->class_metadata_reader->GetClassMetadata(cls); for (const auto& field : metadata.static_fields) { if (field->GetName() == field_name) { return field->Clone(); } } return nullptr; // No static field named "field_name" found Java class. } std::vector<ClassMetadataReader::Method> JvmReadersFactory::FindLocalInstanceMethods( const string& method_name) { std::shared_ptr<const MethodLocals::Entry> method = evaluators_->method_locals->GetLocalVariables(method_); if (method->local_instance == nullptr) { return {}; // This is a static method, no matches. } return FindInstanceMethods( method->local_instance->GetStaticType().object_signature, method_name); } std::vector<ClassMetadataReader::Method> JvmReadersFactory::FindInstanceMethods( const string& class_signature, const string& method_name) { JniLocalRef cls = evaluators_->class_indexer->FindClassBySignature(class_signature); if (cls == nullptr) { LOG(ERROR) << "Local instance class not found: " << class_signature; return {}; } return FindClassMethods(static_cast<jclass>(cls.get()), false, method_name); } std::vector<ClassMetadataReader::Method> JvmReadersFactory::FindStaticMethods( const string& method_name) { JniLocalRef cls = GetMethodDeclaringClass(method_); if (cls == nullptr) { return {}; } return FindClassMethods(static_cast<jclass>(cls.get()), true, method_name); } std::vector<ClassMetadataReader::Method> JvmReadersFactory::FindStaticMethods( const string& class_name, const string& method_name) { FormatMessageModel error_message; // TODO(vlif): propagate this error. JniLocalRef cls = FindClassByName(class_name, &error_message); if (cls == nullptr) { return {}; } return FindClassMethods(static_cast<jclass>(cls.get()), true, method_name); } std::vector<ClassMetadataReader::Method> JvmReadersFactory::FindClassMethods( jclass cls, bool is_static, const string& method_name) { const ClassMetadataReader::Entry& class_metadata = evaluators_->class_metadata_reader->GetClassMetadata(cls); std::vector<ClassMetadataReader::Method> matches; for (const auto& class_method : class_metadata.methods) { if ((class_method.is_static() == is_static) && (class_method.name == method_name)) { matches.push_back(class_method); } } return matches; } std::unique_ptr<ArrayReader> JvmReadersFactory::CreateArrayReader( const JSignature& array_signature) { if (!IsArrayObjectType(array_signature)) { return nullptr; } const JSignature array_element_signature = GetArrayElementJSignature(array_signature); switch (array_element_signature.type) { case JType::Void: return nullptr; // Bad "array_signature". case JType::Boolean: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jboolean>); case JType::Byte: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jbyte>); case JType::Char: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jchar>); case JType::Short: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jshort>); case JType::Int: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jint>); case JType::Long: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jlong>); case JType::Float: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jfloat>); case JType::Double: return std::unique_ptr<ArrayReader>( new JvmPrimitiveArrayReader<jdouble>); case JType::Object: return std::unique_ptr<ArrayReader>(new JvmObjectArrayReader); } return nullptr; } } // namespace cdbg } // namespace devtools
[ "vlif@google.com" ]
vlif@google.com
53c0480850cdb601b60f1b83158d8e139c641da5
ba6ef4e867d6b611b0058fc8d33a72ca6074e02a
/node_mgmt/chapter.cpp
adbcbc1bfe281d225790fa1eaa75e4923b2886df
[]
no_license
Proxmiff/XaraVG-lib
3d3f8c9d8176678a887672ab251b593e3913988c
8fd443b42c94c9fce26e4e4337dec4647756c530
refs/heads/master
2021-01-11T13:33:51.866796
2016-05-14T14:48:36
2016-05-14T14:48:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,955
cpp
// NodeRenderableChapter class #include "camtypes.h" #include "chapter.h" #include "cxftags.h" CC_IMPLEMENT_DYNAMIC(Chapter, NodeRenderablePaper) /********************************************************************************************* > Chapter::Chapter() Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 13/5/93 Inputs: - Outputs: Returns: - Purpose: This constructor creates a Chapter linked to no other nodes, with all status flags false, and NULL bounding and pasteboard rectangles. Errors: **********************************************************************************************/ Chapter::Chapter(): NodeRenderablePaper() { FoldLineXCoord = 0; ShowFoldLine = FALSE; } /*********************************************************************************************** > Chapter::Chapter ( Node* ContextNode, AttachNodeDirection Direction, MILLIPOINT FldLineXCoord, BOOL Locked = FALSE, BOOL Mangled = FALSE, BOOL Marked = FALSE, BOOL Selected = FALSE, ) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 26/4/93 Inputs: ContextNode: Pointer to a node which this node is to be attached to. Direction: Specifies the direction in which this node is to be attached to the ContextNode. The values this variable can take are as follows: PREV : Attach node as a previous sibling of the context node NEXT : Attach node as a next sibling of the context node FIRSTCHILD: Attach node as the first child of the context node LASTCHILD : Attach node as a last child of the context node FldLineXCoord: X Coordinate of the main fold line for the spreads in the chapter The remaining inputs specify the status of the node: Locked: Is node locked ? Mangled: Is node mangled ? Marked: Is node marked ? Selected: Is node selected ? Outputs: - Returns: - Purpose: This method initialises the node and links it to ContextNode in the direction specified by Direction. All neccesary tree links are updated. Errors: An assertion error will occur if ContextNode is NULL ***********************************************************************************************/ Chapter::Chapter(Node* ContextNode, AttachNodeDirection Direction, MILLIPOINT FldLineXCoord, BOOL Locked, BOOL Mangled, BOOL Marked, BOOL Selected ): NodeRenderablePaper(ContextNode, Direction, Locked, Mangled, Marked, Selected) { FoldLineXCoord = FldLineXCoord; ShowFoldLine = TRUE; } /******************************************************************************************** > virtual String Chapter::Describe(BOOL Plural, BOOL Verbose = TRUE) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 21/6/93 Inputs: Plural: Flag indicating if the string description should be plural or singular. Outputs: - Returns: Description of the object Purpose: To return a description of the Node object in either the singular or the plural. This method is called by the DescribeRange method. The description will always begin with a lower case letter. Errors: A resource exception will be thrown if a problem occurs when loading the string resource. SeeAlso: - ********************************************************************************************/ /* Technical Notes: The String resource identifiers should be of the form: ID_<Class>_DescriptionS for the singular description and ID_<Class>_DescriptionP for the plural. */ String Chapter::Describe(BOOL Plural, BOOL Verbose) { if (Plural) return(String(_R(IDS_CHAPTER_DESCRP))); else return(String(_R(IDS_CHAPTER_DESCRS))); }; /*********************************************************************************************** > Chapter* Chapter::FindPreviousChapter() Author: Justin_Flude (Xara Group Ltd) <camelotdev@xara.com> Created: 16/5/93 Inputs: - Outputs: - Returns: The previous sibling chapter or NULL if there are no more chapters Purpose: For finding the previous sibling chapter Errors: - SeeAlso: - ***********************************************************************************************/ Chapter* Chapter::FindPreviousChapter() { Node* CurrentNode = FindPrevious(); while (CurrentNode != 0) { if (CurrentNode->IsChapter()) return (Chapter*) CurrentNode; CurrentNode = CurrentNode->FindPrevious(); } return 0; // No chapter found } /*********************************************************************************************** > void Chapter::Render( RenderRegion* ) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 16/5/93 ***********************************************************************************************/ void Chapter::Render( RenderRegion* ) { } /*********************************************************************************************** > Spread* Chapter::FindFirstSpread() Author: Justin_Flude (Xara Group Ltd) <camelotdev@xara.com> Created: 11/8/94 Inputs: - Outputs: - Returns: Returns the first spread in the chapter (or NULL if there are no spreads) Purpose: Returns the first spread which is an immediate child of the chapter Errors: - SeeAlso: - ***********************************************************************************************/ Spread* Chapter::FindFirstSpread() { Node* pNode = FindFirstChild(); while(pNode != 0 && !pNode->IsSpread()) pNode = pNode->FindNext(); return (Spread*) pNode; } /*********************************************************************************************** > void Chapter::SetFoldLineXCoord(MILLIPOINT value, BOOL DisplayFoldLine = TRUE) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 11/5/93 Inputs: value: New value for the X coordinate of the chapters fold line DisplayFoldLine - TRUE if the fold line should be displayed FALSE to disable display of the fold line altogether Purpose: For setting the X coordinate of the chapters fold line, and enabling/disabling the display of the fold line (for single page spreads the fold line is disabled) Notes: The fold line is rendered in spread.cpp After setting this value, you'll need to redraw the document appropriately SeeAlso: Chapter::ShouldShowFoldLine; Chapter::GetFoldLineXCoord ***********************************************************************************************/ void Chapter::SetFoldLineXCoord(MILLIPOINT value, BOOL DisplayFoldLine) { FoldLineXCoord = value; ShowFoldLine = DisplayFoldLine; } /*********************************************************************************************** > BOOL Chapter::ShouldShowFoldLine(void) const Author: Jason_Williams (Xara Group Ltd) <camelotdev@xara.com> Created: 13/3/95 Returns: TRUE if the chapter fold line should be displayed FALSE if the chapter fold line should not be displayed Purpose: To determine if the chapter fold line is intended to be displayed SeeAlso: Chapter::SetFoldLineXCoord ***********************************************************************************************/ BOOL Chapter::ShouldShowFoldLine(void) const { return(ShowFoldLine); } /*********************************************************************************************** > MILLIPOINT Chapter::GetFoldLineXCoord() const Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 11/5/93 Inputs: - Outputs: - Returns: The value of the X coordinate of the chapters fold line Purpose: For finding the X coordinate of the chapters fold line Errors: - SeeAlso: - ***********************************************************************************************/ MILLIPOINT Chapter::GetFoldLineXCoord() const { return (FoldLineXCoord); } /*********************************************************************************************** > Node* Chapter::SimpleCopy() Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 28/4/93 Inputs: - Outputs: Returns: A copy of the node, or NULL if memory runs out Purpose: This method returns a shallow copy of the node with all Node pointers NULL. The function is virtual, and must be defined for all derived classes. Errors: If memory runs out when trying to copy, then ERROR is called with an out of memory error and the function returns NULL. Scope: protected **********************************************************************************************/ Node* Chapter::SimpleCopy() { Chapter* NodeCopy; NodeCopy = new Chapter(); ERRORIF(NodeCopy == NULL, _R(IDE_NOMORE_MEMORY), NULL); CopyNodeContents(NodeCopy); return (NodeCopy); } /*********************************************************************************************** > void Chapter::PolyCopyNodeContents(Chapter* pNodeCopy) Author: Phil_Martin (Xara Group Ltd) <camelotdev@xara.com> Created: 18/12/2003 Outputs: - Purpose: Polymorphically copies the contents of this node to another Errors: An assertion failure will occur if NodeCopy is NULL Scope: protected ***********************************************************************************************/ void Chapter::PolyCopyNodeContents(NodeRenderable* pNodeCopy) { ENSURE(pNodeCopy, "Trying to copy a node's contents into a NULL node"); ENSURE(IS_A(pNodeCopy, Chapter), "PolyCopyNodeContents given wrong dest node type"); if (IS_A(pNodeCopy, Chapter)) CopyNodeContents((Chapter*)pNodeCopy); } /*********************************************************************************************** > void Chapter::CopyNodeContents(Chapter* NodeCopy) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 28/4/93 Inputs: Outputs: A copy of this node Returns: - Purpose: This method copies the node's contents to the node pointed to by NodeCopy. Errors: An assertion failure will occur if NodeCopy is NULL Scope: protected ***********************************************************************************************/ void Chapter::CopyNodeContents(Chapter* NodeCopy) { ENSURE(NodeCopy != NULL,"Trying to copy node contents to\na node pointed to by a NULL pointer"); NodeRenderablePaper::CopyNodeContents(NodeCopy); NodeCopy->FoldLineXCoord = FoldLineXCoord; } /******************************************************************************************** > XLONG Chapter::GetChapterDepth() Author: Tim_Browse (Xara Group Ltd) <camelotdev@xara.com> Created: 15/12/93 Returns: Depth of the Chapter Purpose: Find the depth of a chapter in logical coords. i.e. how far from the top of the document the top of the chapter's pasteboard is. ********************************************************************************************/ XLONG Chapter::GetChapterDepth() { XLONG Depth = 0; // Loop through document tree calculating the logical coordinate offset for the // current chapter // Chapter *pChapter = Node::FindFirstChapter(FindOwnerDoc()); Node* pNode = FindParent(); ERROR2IF(!(pNode->IsNodeDocument()), 0, "Parent of Chapter is not NodeDocument"); Chapter *pChapter = (Chapter*)pNode->FindFirstChild(CC_RUNTIME_CLASS(Chapter)); ENSURE(pChapter != NULL, "Couldn't find first chapter in Chapter::GetChapterDepth"); while ((pChapter != NULL) && (pChapter != this)) { ENSURE(pChapter->IsKindOf(CC_RUNTIME_CLASS(Chapter)), "Chapter's sibling is not a Chapter"); const DocRect ChapRect = pChapter->GetPasteboardRect(); // Accumulate logical offset Depth += ChapRect.Height(); pChapter = (Chapter *) pChapter->FindNext(); } return Depth; } #ifdef _DEBUG void Chapter::ShowDebugTreeDetails() const { TRACE( _T("Chapter ") ); Node::ShowDebugTreeDetails(); } #endif /******************************************************************************************** > void* Chapter::GetDebugDetails(StringBase* Str) Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 21/9/93 Inputs: - Outputs: Str: String giving debug info about the node Returns: - Purpose: For obtaining debug information about the Node Errors: - SeeAlso: - ********************************************************************************************/ void Chapter::GetDebugDetails(StringBase* Str) { NodeRenderablePaper::GetDebugDetails(Str); String_256 TempStr; TempStr._MakeMsg(TEXT("\r\nFoldLine X Coord = #1%ld\r\n"), FoldLineXCoord); (*Str)+=TempStr; } /******************************************************************************************** > virtual UINT32 Chapter::GetNodeSize() const Author: Simon_Maneggio (Xara Group Ltd) <camelotdev@xara.com> Created: 6/10/93 Inputs: - Outputs: - Returns: The size of the node in bytes Purpose: For finding the size of the node SeeAlso: Node::GetSubtreeSize ********************************************************************************************/ UINT32 Chapter::GetNodeSize() const { return (sizeof(Chapter)); } /********************************************************************************************* > BOOL Chapter::IsChapter(void) const Author: Peter_Arnold (Xara Group Ltd) <camelotdev@xara.com> Created: 28/04/95 Returns: TRUE Purpose: For finding if a node is a chapter node. **********************************************************************************************/ BOOL Chapter::IsChapter() const { return TRUE; } /******************************************************************************************** > virtual BOOL Chapter::WritePreChildrenWeb(BaseCamelotFilter* pFilter) Author: Mark_Neves (Xara Group Ltd) <camelotdev@xara.com> Created: 31/7/96 Inputs: pFilter = ptr to filter to write to Returns: TRUE if the node has written out a record to the filter FALSE otherwise Purpose: Web files don't write out a chapter records. This code assumes the document will only contain one chapter SeeAlso: CanWriteChildrenWeb(), WritePostChildrenWeb() ********************************************************************************************/ BOOL Chapter::WritePreChildrenWeb(BaseCamelotFilter* pFilter) { return FALSE; } /******************************************************************************************** > virtual BOOL Chapter::WritePreChildrenWeb(BaseCamelotFilter* pFilter) Author: Mark_Neves (Xara Group Ltd) <camelotdev@xara.com> Created: 31/7/96 Inputs: pFilter = ptr to filter to write to Returns: TRUE if the node has written out a record to the filter FALSE otherwise Purpose: Writes out a chapter record. SeeAlso: CanWriteChildrenWeb(), WritePostChildrenWeb() ********************************************************************************************/ BOOL Chapter::WritePreChildrenNative(BaseCamelotFilter* pFilter) { #ifdef DO_EXPORT BOOL RecordWritten = FALSE; // Always write out the spread record in native files CXaraFileRecord Rec(TAG_CHAPTER,TAG_CHAPTER_SIZE); if (pFilter->Write(&Rec) != 0) RecordWritten = TRUE; else pFilter->GotError(_R(IDE_FILE_WRITE_ERROR)); return RecordWritten; #else return FALSE; #endif } /******************************************************************************************** > BOOL Chapter::WriteBeginChildRecordsWeb(BaseCamelotFilter* pFilter) Author: Mark_Neves (Xara Group Ltd) <camelotdev@xara.com> Created: 1/8/96 Inputs: pFilter = ptr to the filter to write to Outputs: - Returns: TRUE ok, FALSE otherwise Purpose: Begins the child record sequence for chapter in the web format Web export doesn't write out chapter records, so this overrides the default behaviour in Node by ensuring the Down record does not get written SeeAlso: WritePreChildrenNative() ********************************************************************************************/ BOOL Chapter::WriteBeginChildRecordsWeb(BaseCamelotFilter* pFilter) { return TRUE; } /******************************************************************************************** > BOOL Chapter::WriteEndChildRecordsWeb(BaseCamelotFilter* pFilter) Author: Mark_Neves (Xara Group Ltd) <camelotdev@xara.com> Created: 1/8/96 Inputs: pFilter = ptr to the filter to write to Outputs: - Returns: TRUE ok, FALSE otherwise Purpose: Ends the child record sequence for chapter in the web format Web export doesn't write out chapter records, so this overrides the default behaviour in Node by ensuring the Up record does not get written SeeAlso: WritePreChildrenNative() ********************************************************************************************/ BOOL Chapter::WriteEndChildRecordsWeb(BaseCamelotFilter* pFilter) { return TRUE; } //------------------------------------------------------------------------- // Stubs put here in case they need implementing BOOL Chapter::WriteBeginChildRecordsNative(BaseCamelotFilter* pFilter) { return Node::WriteBeginChildRecordsNative(pFilter); } BOOL Chapter::WriteEndChildRecordsNative(BaseCamelotFilter* pFilter) { return Node::WriteEndChildRecordsNative(pFilter); }
[ "neon.king.fr@gmail.com" ]
neon.king.fr@gmail.com
0695d3ea6c990647fc44bc46b02035e3735fdb19
fab298a55b6ef0cf9007f9d1e65bf225cc92da9c
/IntelliTrack.RFIDUDPReader/tools/gdal-1.8.0/port/cpl_multiproc.cpp
c3ff744e7804a94ceeed58818f384beab01e94a2
[ "MIT", "Zlib", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-info-zip-2005-02", "ISC", "LicenseRef-scancode-info-zip-2009-01" ]
permissive
diegowald/intellitrack
7fe5a22d7d3e5624f79dd7d9d0a1dc60887b7b0c
fa3397a373f296dba9518b1a8762c1b947f02eb5
refs/heads/master
2016-09-06T08:48:03.155393
2013-01-14T15:31:40
2013-01-14T15:31:40
7,606,666
1
0
null
null
null
null
UTF-8
C++
false
false
33,958
cpp
/********************************************************************** * $Id: cpl_multiproc.cpp 21055 2010-11-03 11:36:59Z dron $ * * Project: CPL - Common Portability Library * Purpose: CPL Multi-Threading, and process handling portability functions. * Author: Frank Warmerdam, warmerdam@pobox.com * ********************************************************************** * Copyright (c) 2002, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "cpl_multiproc.h" #include "cpl_conv.h" #if !defined(WIN32CE) # include <time.h> #else # include <wce_time.h> #endif CPL_CVSID("$Id: cpl_multiproc.cpp 21055 2010-11-03 11:36:59Z dron $"); #if defined(CPL_MULTIPROC_STUB) && !defined(DEBUG) # define MUTEX_NONE #endif /************************************************************************/ /* CPLMutexHolder() */ /************************************************************************/ CPLMutexHolder::CPLMutexHolder( void **phMutex, double dfWaitInSeconds, const char *pszFileIn, int nLineIn ) { #ifndef MUTEX_NONE pszFile = pszFileIn; nLine = nLineIn; #ifdef DEBUG_MUTEX /* * XXX: There is no way to use CPLDebug() here because it works with * mutexes itself so we will fall in infinite recursion. Good old * fprintf() will do the job right. */ fprintf( stderr, "CPLMutexHolder: Request %p for pid %ld at %d/%s.\n", *phMutex, (long) CPLGetPID(), nLine, pszFile ); #endif if( !CPLCreateOrAcquireMutex( phMutex, dfWaitInSeconds ) ) { fprintf( stderr, "CPLMutexHolder: Failed to acquire mutex!\n" ); hMutex = NULL; } else { #ifdef DEBUG_MUTEX fprintf( stderr, "CPLMutexHolder: Acquired %p for pid %ld at %d/%s.\n", *phMutex, (long) CPLGetPID(), nLine, pszFile ); #endif hMutex = *phMutex; } #endif /* ndef MUTEX_NONE */ } /************************************************************************/ /* ~CPLMutexHolder() */ /************************************************************************/ CPLMutexHolder::~CPLMutexHolder() { #ifndef MUTEX_NONE if( hMutex != NULL ) { #ifdef DEBUG_MUTEX fprintf( stderr, "~CPLMutexHolder: Release %p for pid %ld at %d/%s.\n", hMutex, (long) CPLGetPID(), nLine, pszFile ); #endif CPLReleaseMutex( hMutex ); } #endif /* ndef MUTEX_NONE */ } /************************************************************************/ /* CPLCreateOrAcquireMutex() */ /************************************************************************/ #ifndef CPL_MULTIPROC_PTHREAD int CPLCreateOrAcquireMutex( void **phMutex, double dfWaitInSeconds ) { int bSuccess = FALSE; #ifndef MUTEX_NONE static void *hCOAMutex = NULL; /* ** ironically, creation of this initial mutex is not threadsafe ** even though we use it to ensure that creation of other mutexes ** is threadsafe. */ if( hCOAMutex == NULL ) { hCOAMutex = CPLCreateMutex(); if (hCOAMutex == NULL) { *phMutex = NULL; return FALSE; } } else { CPLAcquireMutex( hCOAMutex, dfWaitInSeconds ); } if( *phMutex == NULL ) { *phMutex = CPLCreateMutex(); bSuccess = *phMutex != NULL; CPLReleaseMutex( hCOAMutex ); } else { CPLReleaseMutex( hCOAMutex ); bSuccess = CPLAcquireMutex( *phMutex, dfWaitInSeconds ); } #endif /* ndef MUTEX_NONE */ return bSuccess; } #endif /************************************************************************/ /* CPLCleanupTLSList() */ /* */ /* Free resources associated with a TLS vector (implementation */ /* independent). */ /************************************************************************/ static void CPLCleanupTLSList( void **papTLSList ) { int i; // printf( "CPLCleanupTLSList(%p)\n", papTLSList ); if( papTLSList == NULL ) return; for( i = 0; i < CTLS_MAX; i++ ) { if( papTLSList[i] != NULL && papTLSList[i+CTLS_MAX] != NULL ) { CPLTLSFreeFunc pfnFree = (CPLTLSFreeFunc) papTLSList[i + CTLS_MAX]; pfnFree( papTLSList[i] ); papTLSList[i] = NULL; } } CPLFree( papTLSList ); } #if defined(CPL_MULTIPROC_STUB) /************************************************************************/ /* ==================================================================== */ /* CPL_MULTIPROC_STUB */ /* */ /* Stub implementation. Mutexes don't provide exclusion, file */ /* locking is achieved with extra "lock files", and thread */ /* creation doesn't work. The PID is always just one. */ /* ==================================================================== */ /************************************************************************/ /************************************************************************/ /* CPLGetThreadingModel() */ /************************************************************************/ const char *CPLGetThreadingModel() { return "stub"; } /************************************************************************/ /* CPLCreateMutex() */ /************************************************************************/ void *CPLCreateMutex() { #ifndef MUTEX_NONE unsigned char *pabyMutex = (unsigned char *) CPLMalloc( 4 ); pabyMutex[0] = 1; pabyMutex[1] = 'r'; pabyMutex[2] = 'e'; pabyMutex[3] = 'd'; return (void *) pabyMutex; #else return (void *) 0xdeadbeef; #endif } /************************************************************************/ /* CPLAcquireMutex() */ /************************************************************************/ int CPLAcquireMutex( void *hMutex, double dfWaitInSeconds ) { #ifndef MUTEX_NONE unsigned char *pabyMutex = (unsigned char *) hMutex; CPLAssert( pabyMutex[1] == 'r' && pabyMutex[2] == 'e' && pabyMutex[3] == 'd' ); pabyMutex[0] += 1; return TRUE; #else return TRUE; #endif } /************************************************************************/ /* CPLReleaseMutex() */ /************************************************************************/ void CPLReleaseMutex( void *hMutex ) { #ifndef MUTEX_NONE unsigned char *pabyMutex = (unsigned char *) hMutex; CPLAssert( pabyMutex[1] == 'r' && pabyMutex[2] == 'e' && pabyMutex[3] == 'd' ); if( pabyMutex[0] < 1 ) CPLDebug( "CPLMultiProc", "CPLReleaseMutex() called on mutex with %d as ref count!", pabyMutex[0] ); pabyMutex[0] -= 1; #endif } /************************************************************************/ /* CPLDestroyMutex() */ /************************************************************************/ void CPLDestroyMutex( void *hMutex ) { #ifndef MUTEX_NONE unsigned char *pabyMutex = (unsigned char *) hMutex; CPLAssert( pabyMutex[1] == 'r' && pabyMutex[2] == 'e' && pabyMutex[3] == 'd' ); CPLFree( pabyMutex ); #endif } /************************************************************************/ /* CPLLockFile() */ /* */ /* Lock a file. This implementation has a terrible race */ /* condition. If we don't succeed in opening the lock file, we */ /* assume we can create one and own the target file, but other */ /* processes might easily try creating the target file at the */ /* same time, overlapping us. Death! Mayhem! The traditional */ /* solution is to use open() with _O_CREAT|_O_EXCL but this */ /* function and these arguments aren't trivially portable. */ /* Also, this still leaves a race condition on NFS drivers */ /* (apparently). */ /************************************************************************/ void *CPLLockFile( const char *pszPath, double dfWaitInSeconds ) { FILE *fpLock; char *pszLockFilename; /* -------------------------------------------------------------------- */ /* We use a lock file with a name derived from the file we want */ /* to lock to represent the file being locked. Note that for */ /* the stub implementation the target file does not even need */ /* to exist to be locked. */ /* -------------------------------------------------------------------- */ pszLockFilename = (char *) CPLMalloc(strlen(pszPath) + 30); sprintf( pszLockFilename, "%s.lock", pszPath ); fpLock = fopen( pszLockFilename, "r" ); while( fpLock != NULL && dfWaitInSeconds > 0.0 ) { fclose( fpLock ); CPLSleep( MIN(dfWaitInSeconds,0.5) ); dfWaitInSeconds -= 0.5; fpLock = fopen( pszLockFilename, "r" ); } if( fpLock != NULL ) { fclose( fpLock ); CPLFree( pszLockFilename ); return NULL; } fpLock = fopen( pszLockFilename, "w" ); if( fpLock == NULL ) { CPLFree( pszLockFilename ); return NULL; } fwrite( "held\n", 1, 5, fpLock ); fclose( fpLock ); return pszLockFilename; } /************************************************************************/ /* CPLUnlockFile() */ /************************************************************************/ void CPLUnlockFile( void *hLock ) { char *pszLockFilename = (char *) hLock; if( hLock == NULL ) return; VSIUnlink( pszLockFilename ); CPLFree( pszLockFilename ); } /************************************************************************/ /* CPLGetPID() */ /************************************************************************/ GIntBig CPLGetPID() { return 1; } /************************************************************************/ /* CPLCreateThread(); */ /************************************************************************/ int CPLCreateThread( CPLThreadFunc pfnMain, void *pArg ) { CPLDebug( "CPLCreateThread", "Fails to dummy implementation" ); return -1; } /************************************************************************/ /* CPLSleep() */ /************************************************************************/ void CPLSleep( double dfWaitInSeconds ) { time_t ltime; time_t ttime; time( &ltime ); ttime = ltime + (int) (dfWaitInSeconds+0.5); for( ; ltime < ttime; time(&ltime) ) { /* currently we just busy wait. Perhaps we could at least block on io? */ } } /************************************************************************/ /* CPLGetTLSList() */ /************************************************************************/ static void **papTLSList = NULL; static void **CPLGetTLSList() { if( papTLSList == NULL ) papTLSList = (void **) CPLCalloc(sizeof(void*),CTLS_MAX*2); return papTLSList; } /************************************************************************/ /* CPLCleanupTLS() */ /************************************************************************/ void CPLCleanupTLS() { CPLCleanupTLSList( papTLSList ); papTLSList = NULL; } /* endif CPL_MULTIPROC_STUB */ #elif defined(CPL_MULTIPROC_WIN32) /************************************************************************/ /* ==================================================================== */ /* CPL_MULTIPROC_WIN32 */ /* */ /* WIN32 Implementation of multiprocessing functions. */ /* ==================================================================== */ /************************************************************************/ #include <windows.h> /* windows.h header must be included above following lines. */ #if defined(WIN32CE) # include "cpl_win32ce_api.h" # define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF) #endif /************************************************************************/ /* CPLGetThreadingModel() */ /************************************************************************/ const char *CPLGetThreadingModel() { return "win32"; } /************************************************************************/ /* CPLCreateMutex() */ /************************************************************************/ void *CPLCreateMutex() { HANDLE hMutex; hMutex = CreateMutex( NULL, TRUE, NULL ); return (void *) hMutex; } /************************************************************************/ /* CPLAcquireMutex() */ /************************************************************************/ int CPLAcquireMutex( void *hMutexIn, double dfWaitInSeconds ) { HANDLE hMutex = (HANDLE) hMutexIn; DWORD hr; hr = WaitForSingleObject( hMutex, (int) (dfWaitInSeconds * 1000) ); return hr != WAIT_TIMEOUT; } /************************************************************************/ /* CPLReleaseMutex() */ /************************************************************************/ void CPLReleaseMutex( void *hMutexIn ) { HANDLE hMutex = (HANDLE) hMutexIn; ReleaseMutex( hMutex ); } /************************************************************************/ /* CPLDestroyMutex() */ /************************************************************************/ void CPLDestroyMutex( void *hMutexIn ) { HANDLE hMutex = (HANDLE) hMutexIn; CloseHandle( hMutex ); } /************************************************************************/ /* CPLLockFile() */ /************************************************************************/ void *CPLLockFile( const char *pszPath, double dfWaitInSeconds ) { char *pszLockFilename; HANDLE hLockFile; pszLockFilename = (char *) CPLMalloc(strlen(pszPath) + 30); sprintf( pszLockFilename, "%s.lock", pszPath ); hLockFile = CreateFile( pszLockFilename, GENERIC_WRITE, 0, NULL,CREATE_NEW, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_DELETE_ON_CLOSE, NULL ); while( GetLastError() == ERROR_ALREADY_EXISTS && dfWaitInSeconds > 0.0 ) { CloseHandle( hLockFile ); CPLSleep( MIN(dfWaitInSeconds,0.125) ); dfWaitInSeconds -= 0.125; hLockFile = CreateFile( pszLockFilename, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_DELETE_ON_CLOSE, NULL ); } CPLFree( pszLockFilename ); if( hLockFile == INVALID_HANDLE_VALUE ) return NULL; if( GetLastError() == ERROR_ALREADY_EXISTS ) { CloseHandle( hLockFile ); return NULL; } return (void *) hLockFile; } /************************************************************************/ /* CPLUnlockFile() */ /************************************************************************/ void CPLUnlockFile( void *hLock ) { HANDLE hLockFile = (HANDLE) hLock; CloseHandle( hLockFile ); } /************************************************************************/ /* CPLGetPID() */ /************************************************************************/ GIntBig CPLGetPID() { return (GIntBig) GetCurrentThreadId(); } /************************************************************************/ /* CPLStdCallThreadJacket() */ /************************************************************************/ typedef struct { void *pAppData; CPLThreadFunc pfnMain; } CPLStdCallThreadInfo; static DWORD WINAPI CPLStdCallThreadJacket( void *pData ) { CPLStdCallThreadInfo *psInfo = (CPLStdCallThreadInfo *) pData; psInfo->pfnMain( psInfo->pAppData ); CPLFree( psInfo ); CPLCleanupTLS(); return 0; } /************************************************************************/ /* CPLCreateThread() */ /* */ /* The WIN32 CreateThread() call requires an entry point that */ /* has __stdcall conventions, so we provide a jacket function */ /* to supply that. */ /************************************************************************/ int CPLCreateThread( CPLThreadFunc pfnMain, void *pThreadArg ) { HANDLE hThread; DWORD nThreadId; CPLStdCallThreadInfo *psInfo; psInfo = (CPLStdCallThreadInfo*) CPLCalloc(sizeof(CPLStdCallThreadInfo),1); psInfo->pAppData = pThreadArg; psInfo->pfnMain = pfnMain; hThread = CreateThread( NULL, 0, CPLStdCallThreadJacket, psInfo, 0, &nThreadId ); if( hThread == NULL ) return -1; CloseHandle( hThread ); return nThreadId; } /************************************************************************/ /* CPLSleep() */ /************************************************************************/ void CPLSleep( double dfWaitInSeconds ) { Sleep( (DWORD) (dfWaitInSeconds * 1000.0) ); } static int bTLSKeySetup = FALSE; static DWORD nTLSKey; /************************************************************************/ /* CPLGetTLSList() */ /************************************************************************/ static void **CPLGetTLSList() { void **papTLSList; if( !bTLSKeySetup ) { nTLSKey = TlsAlloc(); if( nTLSKey == TLS_OUT_OF_INDEXES ) { CPLError( CE_Fatal, CPLE_AppDefined, "TlsAlloc() failed!" ); } bTLSKeySetup = TRUE; } papTLSList = (void **) TlsGetValue( nTLSKey ); if( papTLSList == NULL ) { papTLSList = (void **) CPLCalloc(sizeof(void*),CTLS_MAX*2); if( TlsSetValue( nTLSKey, papTLSList ) == 0 ) { CPLError( CE_Fatal, CPLE_AppDefined, "TlsSetValue() failed!" ); } } return papTLSList; } /************************************************************************/ /* CPLCleanupTLS() */ /************************************************************************/ void CPLCleanupTLS() { void **papTLSList; if( !bTLSKeySetup ) return; papTLSList = (void **) TlsGetValue( nTLSKey ); if( papTLSList == NULL ) return; TlsSetValue( nTLSKey, NULL ); CPLCleanupTLSList( papTLSList ); } /* endif CPL_MULTIPROC_WIN32 */ #elif defined(CPL_MULTIPROC_PTHREAD) #include <pthread.h> #include <time.h> /************************************************************************/ /* ==================================================================== */ /* CPL_MULTIPROC_PTHREAD */ /* */ /* PTHREAD Implementation of multiprocessing functions. */ /* ==================================================================== */ /************************************************************************/ /************************************************************************/ /* CPLCreateOrAcquireMutex() */ /************************************************************************/ int CPLCreateOrAcquireMutex( void **phMutex, double dfWaitInSeconds ) { int bSuccess = FALSE; static pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&global_mutex); if( *phMutex == NULL ) { *phMutex = CPLCreateMutex(); bSuccess = *phMutex != NULL; pthread_mutex_unlock(&global_mutex); } else { pthread_mutex_unlock(&global_mutex); bSuccess = CPLAcquireMutex( *phMutex, dfWaitInSeconds ); } return bSuccess; } /************************************************************************/ /* CPLGetThreadingModel() */ /************************************************************************/ const char *CPLGetThreadingModel() { return "pthread"; } /************************************************************************/ /* CPLCreateMutex() */ /************************************************************************/ void *CPLCreateMutex() { pthread_mutex_t *hMutex; hMutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); if (hMutex == NULL) return NULL; #if defined(PTHREAD_MUTEX_RECURSIVE) || defined(HAVE_PTHREAD_MUTEX_RECURSIVE) { pthread_mutexattr_t attr; pthread_mutexattr_init( &attr ); pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( hMutex, &attr ); } /* BSDs have PTHREAD_MUTEX_RECURSIVE as an enum, not a define. */ /* But they have #define MUTEX_TYPE_COUNTING_FAST PTHREAD_MUTEX_RECURSIVE */ #elif defined(MUTEX_TYPE_COUNTING_FAST) { pthread_mutexattr_t attr; pthread_mutexattr_init( &attr ); pthread_mutexattr_settype( &attr, MUTEX_TYPE_COUNTING_FAST ); pthread_mutex_init( hMutex, &attr ); } #elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) pthread_mutex_t tmp_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; *hMutex = tmp_mutex; #else #error "Recursive mutexes apparently unsupported, configure --without-threads" #endif // mutexes are implicitly acquired when created. CPLAcquireMutex( hMutex, 0.0 ); return (void *) hMutex; } /************************************************************************/ /* CPLAcquireMutex() */ /************************************************************************/ int CPLAcquireMutex( void *hMutexIn, double dfWaitInSeconds ) { int err; /* we need to add timeout support */ err = pthread_mutex_lock( (pthread_mutex_t *) hMutexIn ); if( err != 0 ) { if( err == EDEADLK ) fprintf(stderr, "CPLAcquireMutex: Error = %d/EDEADLK", err ); else fprintf(stderr, "CPLAcquireMutex: Error = %d", err ); return FALSE; } return TRUE; } /************************************************************************/ /* CPLReleaseMutex() */ /************************************************************************/ void CPLReleaseMutex( void *hMutexIn ) { pthread_mutex_unlock( (pthread_mutex_t *) hMutexIn ); } /************************************************************************/ /* CPLDestroyMutex() */ /************************************************************************/ void CPLDestroyMutex( void *hMutexIn ) { pthread_mutex_destroy( (pthread_mutex_t *) hMutexIn ); free( hMutexIn ); } /************************************************************************/ /* CPLLockFile() */ /* */ /* This is really a stub implementation, see first */ /* CPLLockFile() for caveats. */ /************************************************************************/ void *CPLLockFile( const char *pszPath, double dfWaitInSeconds ) { FILE *fpLock; char *pszLockFilename; /* -------------------------------------------------------------------- */ /* We use a lock file with a name derived from the file we want */ /* to lock to represent the file being locked. Note that for */ /* the stub implementation the target file does not even need */ /* to exist to be locked. */ /* -------------------------------------------------------------------- */ pszLockFilename = (char *) CPLMalloc(strlen(pszPath) + 30); sprintf( pszLockFilename, "%s.lock", pszPath ); fpLock = fopen( pszLockFilename, "r" ); while( fpLock != NULL && dfWaitInSeconds > 0.0 ) { fclose( fpLock ); CPLSleep( MIN(dfWaitInSeconds,0.5) ); dfWaitInSeconds -= 0.5; fpLock = fopen( pszLockFilename, "r" ); } if( fpLock != NULL ) { fclose( fpLock ); CPLFree( pszLockFilename ); return NULL; } fpLock = fopen( pszLockFilename, "w" ); if( fpLock == NULL ) { CPLFree( pszLockFilename ); return NULL; } fwrite( "held\n", 1, 5, fpLock ); fclose( fpLock ); return pszLockFilename; } /************************************************************************/ /* CPLUnlockFile() */ /************************************************************************/ void CPLUnlockFile( void *hLock ) { char *pszLockFilename = (char *) hLock; if( hLock == NULL ) return; VSIUnlink( pszLockFilename ); CPLFree( pszLockFilename ); } /************************************************************************/ /* CPLGetPID() */ /************************************************************************/ GIntBig CPLGetPID() { return (GIntBig) pthread_self(); } /************************************************************************/ /* CPLStdCallThreadJacket() */ /************************************************************************/ typedef struct { void *pAppData; CPLThreadFunc pfnMain; pthread_t hThread; } CPLStdCallThreadInfo; static void *CPLStdCallThreadJacket( void *pData ) { CPLStdCallThreadInfo *psInfo = (CPLStdCallThreadInfo *) pData; psInfo->pfnMain( psInfo->pAppData ); CPLFree( psInfo ); return NULL; } /************************************************************************/ /* CPLCreateThread() */ /* */ /* The WIN32 CreateThread() call requires an entry point that */ /* has __stdcall conventions, so we provide a jacket function */ /* to supply that. */ /************************************************************************/ int CPLCreateThread( CPLThreadFunc pfnMain, void *pThreadArg ) { CPLStdCallThreadInfo *psInfo; pthread_attr_t hThreadAttr; psInfo = (CPLStdCallThreadInfo*) CPLCalloc(sizeof(CPLStdCallThreadInfo),1); psInfo->pAppData = pThreadArg; psInfo->pfnMain = pfnMain; pthread_attr_init( &hThreadAttr ); pthread_attr_setdetachstate( &hThreadAttr, PTHREAD_CREATE_DETACHED ); if( pthread_create( &(psInfo->hThread), &hThreadAttr, CPLStdCallThreadJacket, (void *) psInfo ) != 0 ) { CPLFree( psInfo ); return -1; } return 1; /* can we return the actual thread pid? */ } /************************************************************************/ /* CPLSleep() */ /************************************************************************/ void CPLSleep( double dfWaitInSeconds ) { struct timespec sRequest, sRemain; sRequest.tv_sec = (int) floor(dfWaitInSeconds); sRequest.tv_nsec = (int) ((dfWaitInSeconds - sRequest.tv_sec)*1000000000); nanosleep( &sRequest, &sRemain ); } static pthread_key_t oTLSKey; static pthread_once_t oTLSKeySetup = PTHREAD_ONCE_INIT; /************************************************************************/ /* CPLMake_key() */ /************************************************************************/ static void CPLMake_key() { if( pthread_key_create( &oTLSKey, (void (*)(void*)) CPLCleanupTLSList ) != 0 ) { CPLError( CE_Fatal, CPLE_AppDefined, "pthread_key_create() failed!" ); } } /************************************************************************/ /* CPLCleanupTLS() */ /************************************************************************/ void CPLCleanupTLS() { void **papTLSList; papTLSList = (void **) pthread_getspecific( oTLSKey ); if( papTLSList == NULL ) return; pthread_setspecific( oTLSKey, NULL ); CPLCleanupTLSList( papTLSList ); } /************************************************************************/ /* CPLGetTLSList() */ /************************************************************************/ static void **CPLGetTLSList() { void **papTLSList; if ( pthread_once(&oTLSKeySetup, CPLMake_key) != 0 ) { CPLError( CE_Fatal, CPLE_AppDefined, "pthread_once() failed!" ); } papTLSList = (void **) pthread_getspecific( oTLSKey ); if( papTLSList == NULL ) { papTLSList = (void **) CPLCalloc(sizeof(void*),CTLS_MAX*2); if( pthread_setspecific( oTLSKey, papTLSList ) != 0 ) { CPLError( CE_Fatal, CPLE_AppDefined, "pthread_setspecific() failed!" ); } } return papTLSList; } #endif /* def CPL_MULTIPROC_PTHREAD */ /************************************************************************/ /* CPLGetTLS() */ /************************************************************************/ void *CPLGetTLS( int nIndex ) { void** papTLSList = CPLGetTLSList(); CPLAssert( nIndex >= 0 && nIndex < CTLS_MAX ); return papTLSList[nIndex]; } /************************************************************************/ /* CPLSetTLS() */ /************************************************************************/ void CPLSetTLS( int nIndex, void *pData, int bFreeOnExit ) { CPLSetTLSWithFreeFunc(nIndex, pData, (bFreeOnExit) ? CPLFree : NULL); } /************************************************************************/ /* CPLSetTLSWithFreeFunc() */ /************************************************************************/ /* Warning : the CPLTLSFreeFunc must not in any case directly or indirectly */ /* use or fetch any TLS data, or a terminating thread will hang ! */ void CPLSetTLSWithFreeFunc( int nIndex, void *pData, CPLTLSFreeFunc pfnFree ) { void **papTLSList = CPLGetTLSList(); CPLAssert( nIndex >= 0 && nIndex < CTLS_MAX ); papTLSList[nIndex] = pData; papTLSList[CTLS_MAX + nIndex] = (void*) pfnFree; }
[ "diego.wald@gmail.com" ]
diego.wald@gmail.com
f2b4c49dd586c1c70d57438b20956cfcc94097b7
22c9de6760dc2b99b0189b1ce3b836ed749c0e2d
/crux-toolkit-master/src/model/MatchCollection.h
9494c68ef69c051bc75c535f3fd50942ddda9763
[ "Apache-2.0" ]
permissive
jkubath/protein_research
6a8df5d48582165063b5a6bfa9e24967424dada9
788b48545b402534d4782dd6b78a58a31d1120a7
refs/heads/master
2020-04-26T09:07:30.739950
2019-04-23T20:10:35
2019-04-23T20:10:35
173,444,748
0
0
null
null
null
null
UTF-8
C++
false
false
10,772
h
/** * \file MatchCollection.h * $Revision: 1.38 $ * \brief A set of peptide spectrum matches for one spectrum. * * Object for given a database and a spectrum, generate all match objects * Creating a match collection generates all matches (searches a * spectrum against a database. */ #ifndef MATCH_COLLECTION_H #define MATCH_COLLECTION_H #include <algorithm> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <ctype.h> #ifndef _MSC_VER #include <unistd.h> #endif #include <map> #include <time.h> #include "io/carp.h" #include "Spectrum.h" #include "io/SpectrumCollection.h" #include "Ion.h" #include "IonSeries.h" #include "util/crux-utils.h" #include "model/objects.h" #include "parameter.h" #include "Scorer.h" #include "Match.h" #include "PeptideSrc.h" #include "ProteinIndex.h" #include "util/modifications.h" #include "ModifiedPeptidesIterator.h" #include "io/MatchFileWriter.h" #include "MatchIterator.h" #include "io/PepXMLWriter.h" using namespace std; static const int _PSM_SAMPLE_SIZE = 500; ///< max number of peptides a single match collection can hold class MatchCollection { friend class MatchIterator; protected: std::vector<Crux::Match*> match_; ///< array of match object int experiment_size_; ///< total matches before any truncation int target_experiment_size_; ///< total target matches for same spectrum SpectrumZState zstate_; ///< zstate of the associated spectrum bool null_peptide_collection_; ///< are the peptides shuffled bool scored_type_[NUMBER_SCORER_TYPES]; ///< TRUE if matches have been scored by the type SCORER_TYPE_T last_sorted_; ///< the last type by which it's been sorted ( -1 if unsorted) bool iterator_lock_; ///< has an itterator been created? if TRUE can't manipulate matches bool has_distinct_matches_; ///< does the match collection have distinct matches? bool has_decoy_indexes_; // Values for fitting the Weibull distribution FLOAT_T eta_; ///< The eta parameter for the Weibull distribution. FLOAT_T beta_; ///< The beta parameter for the Weibull distribution. FLOAT_T shift_; ///< The location parameter for the Weibull distribution. FLOAT_T correlation_; ///< The correlation parameter for the Weibull distribution. vector<FLOAT_T> xcorrs_; ///< xcorrs to be used for weibull // The following features (post_*) are only valid when // post_process_collection boolean is true bool post_process_collection_; ///< Is this a post process match_collection? Crux::Match* top_scoring_sp_; ///< the match with Sp rank == 1 /** * initializes a MatchCollection object */ void init(); public: bool exact_pval_search_; /** * \brief Creates a new match collection with no matches in it. Sets * member variables from parameter.c. The charge and null_collection * variables are set with the method add_matches(). Search is * conducted in add_matches(). * * \returns A newly allocated match collection with member variables set. */ MatchCollection(bool is_decoy = false); /** * free the memory allocated match collection */ virtual ~MatchCollection(); /** * sort the match collection by score_type(SP, XCORR, ... ) *\returns true, if successfully sorts the match_collection */ void sort( SCORER_TYPE_T score_type ///< the score type (SP, XCORR) -in ); /** * Rank matches in a collection based on the given score type. * Requires that match_collection was already scored for that score type. * Rank 1, means highest score * \returns true, if populates the match rank in the match collection */ bool populateMatchRank( SCORER_TYPE_T score_type ///< the score type (SP, XCORR) -in ); /** * match_collection get, set method */ /** *\returns true, if the match collection has been scored by score_type */ bool getScoredType( SCORER_TYPE_T score_type ///< the score_type (MATCH_SP, MATCH_XCORR) -in ); /** * sets the score_type to value */ void setScoredType( SCORER_TYPE_T score_type, ///< the score_type (MATCH_SP, MATCH_XCORR) -in bool value ); void getCustomScoreNames( std::vector<std::string>& custom_score_names ); void preparePostProcess(); /** *\returns true, if there is a match_iterators instantiated by match collection */ bool getIteratorLock(); /** *\returns the total match objects avaliable in current match_collection */ int getMatchTotal(); /** * Sets the total peptides searched in the experiment in match_collection */ void setExperimentSize(int size); /** *\returns the total peptides searched in the experiment in match_collection */ int getExperimentSize(); /** * Sets the total number of target peptides searched for this * spectrum. Only to be used by decoy match collections. */ void setTargetExperimentSize(int numMatches); /** * \returns the number of target matches that this spectrum had. * Different than getExperimentSize() for decoy match collections. */ int getTargetExperimentSize(); /** * Set the filepath for all matches in the collection * \returns the associated file idx */ int setFilePath( const std::string& file_path, ///< File path to set bool overwrite = false ///< Overwrite existing files? ); /** * \returns true if the match_collection only contains decoy matches, * else (all target or mixed) returns false. */ bool isDecoy(); /** *\returns the charge of the spectrum that the match collection was created */ int getCharge(); bool calculateDeltaCn(); // Take a vector of scores and return a vector of <deltaCn, deltaLCn> static std::vector< std::pair<FLOAT_T, FLOAT_T> > calculateDeltaCns( std::vector<FLOAT_T>, SCORER_TYPE_T type); /** * \brief Transfer the Weibull distribution parameters, including the * correlation from one match_collection to another. No check to see * that the parameters have been estimated. */ static void transferWeibull( MatchCollection* from_collection, MatchCollection* to_collection ); /** * \brief Add a single match to a collection. * Only puts a copy of the pointer to the match in the * match_collection, does not allocate a new match. */ bool addMatch( Crux::Match* match ///< add this match ); /** * \brief Print the given match collection for one spectrum to all * appropriate files. */ void print( Crux::Spectrum* spectrum, bool is_decoy, FILE* psm_file, FILE* sqt_file, FILE* decoy_file, FILE* tab_file, FILE* decoy_tab_file ); /** * \brief Print the given match collection for several spectra to all * appropriate files. Takes the spectrum information from the matches * in the collection. */ void printMultiSpectra( MatchFileWriter* tab_file, MatchFileWriter* decoy_tab_file ); /** * \brief Print the given match collection for several spectra to * xml files only. Takes the spectrum information from the * matches in the collection. At least for now, prints all matches in * the collection rather than limiting by top-match parameter. */ void printMultiSpectraXml( PepXMLWriter* output ); /* * Print the XML file header */ static void printXmlHeader(FILE* outfile, const string& ms2file); /* * Print the SQT file header */ static void printSqtHeader( FILE* outfile, const char* type, string database, int num_proteins, bool exact_pval_search_ = false ); /* * Print the tab delimited file header */ static void printTabHeader( FILE* outfile ); /* * Print the XML file footer */ static void printXmlFooter( FILE* outfile ); /** * Print the psm features to output file up to 'top_match' number of * top peptides among the match_collection in xml file format * returns true, if sucessfully print xml format of the PSMs, else false */ bool printXml( PepXMLWriter* output, int top_match, Crux::Spectrum* spectrum, SCORER_TYPE_T main_score ); /** * Print the psm features to output file upto 'top_match' number of * top peptides among the match_collection in sqt file format *\returns true, if sucessfully print sqt format of the PSMs, else false */ bool printSqt( FILE* output, ///< the output file -out int top_match, ///< the top matches to output -in Crux::Spectrum* spectrum ///< the spectrum to print sqt -in ); /** * Print the psm features to output file upto 'top_match' number of * top peptides among the match_collection in tab delimited file format *\returns true, if sucessfully print sqt format of the PSMs, else false */ bool printTabDelimited( MatchFileWriter* output, ///< the output file -out int top_match, ///< the top matches to output -in Crux::Spectrum* spectrum, ///< the spectrum to print sqt -in SCORER_TYPE_T main_score ///< the main score to report -in ); /** * Retrieve the calibration parameter eta. */ FLOAT_T getCalibrationEta(); /** * Retrieve the calibration parameter beta. */ FLOAT_T getCalibrationBeta(); /** * Retrieve the calibration parameter shift. */ FLOAT_T getCalibrationShift(); /** * Retrieve the calibration parameter correlation. */ FLOAT_T getCalibrationCorr(); bool getHasDistinctMatches(); void setHasDistinctMatches(bool distinct_matches); bool hasDecoyIndexes() const; void setHasDecoyIndexes(bool value); /** * Try setting the match collection's zstate. Successful if the * current charge is 0 (i.e. hasn't yet been set) or if the current * charge is the same as the given value. Otherwise, returns false * * \returns true if the match_collection's zstate was changed. */ bool setZState( SpectrumZState& zstate ///< new zstate ); /** * Extract a given type of score into a vector. */ std::vector<FLOAT_T> extractScores( SCORER_TYPE_T score_type ///< Type of score to extract. ) const; /** * Given a hash table that maps from a score to its q-value, assign * q-values to all of the matches in a given collection. */ void assignQValues( const map<FLOAT_T, FLOAT_T>* score_to_qvalue_hash, SCORER_TYPE_T score_type, SCORER_TYPE_T derived_score_type ); /******************************************* * match_collection post_process extension ******************************************/ bool addMatchToPostMatchCollection(Crux::Match* match); }; #endif /* * Local Variables: * mode: c * c-basic-offset: 2 * End: */
[ "jkubath1@gmail.com" ]
jkubath1@gmail.com
027923fb25f6170457c5c52d75a4ca31e55f7f6a
b7388fa0fe9912e8b24a62fe9255f698af17079b
/pheet/ds/CircularArray/TwoLevelGrowing/TwoLevelGrowingCircularArray.h
1f36234bdbd1d09ae23a00219030ca6a2f16770d
[]
no_license
ginkgo/AMP-LockFreeSkipList
2764b4f528ac6969f21ee3fd0e2ba2444d36e04c
dc68750f5c9fd6d2491e656161ac7c8073f5389c
refs/heads/master
2021-01-20T07:50:51.818369
2014-07-01T01:21:04
2014-07-01T01:21:04
20,526,178
3
0
null
null
null
null
UTF-8
C++
false
false
4,259
h
/* * TwoLevelGrowingCircularArray.h * * Created on: 12.04.2011 * Author: Martin Wimmer * License: Boost Software License 1.0 (BSL1.0) */ #ifndef TWOLEVELGROWINGCIRCULARARRAY_H_ #define TWOLEVELGROWINGCIRCULARARRAY_H_ #include <pheet/settings.h> #include <pheet/misc/bitops.h> namespace pheet { template <class Pheet, typename TT, size_t MaxBuckets = 32> class TwoLevelGrowingCircularArrayImpl { public: typedef TT T; template<size_t NewVal> using WithMaxBuckets = TwoLevelGrowingCircularArrayImpl<Pheet, TT, NewVal>; TwoLevelGrowingCircularArrayImpl(); TwoLevelGrowingCircularArrayImpl(size_t initial_capacity); ~TwoLevelGrowingCircularArrayImpl(); size_t get_capacity(); bool is_growable(); // return value NEEDS to be const. When growing we cannot guarantee that the reference won't change T const& get(size_t i); void put(size_t i, T value); void grow(size_t bottom, size_t top); private: const size_t initial_buckets; size_t buckets; size_t capacity; T* data[MaxBuckets]; }; template <class Pheet, typename T, size_t MaxBuckets> TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::TwoLevelGrowingCircularArrayImpl() : initial_buckets(5), buckets(initial_buckets), capacity(1 << (buckets - 1)) { pheet_assert(buckets <= MaxBuckets); T* ptr = new T[capacity]; data[0] = ptr; ptr++; for(size_t i = 1; i < buckets; i++) { data[i] = ptr; ptr += 1 << (i - 1); } } template <class Pheet, typename T, size_t MaxBuckets> TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::TwoLevelGrowingCircularArrayImpl(size_t initial_capacity) : initial_buckets(find_last_bit_set(initial_capacity - 1) + 1), buckets(initial_buckets), capacity(1 << (buckets - 1)) { pheet_assert(initial_capacity > 0); pheet_assert(buckets <= MaxBuckets); T* ptr = new T[capacity]; data[0] = ptr; ptr++; for(size_t i = 1; i < buckets; i++) { data[i] = ptr; ptr += 1 << (i - 1); } } template <class Pheet, typename T, size_t MaxBuckets> TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::~TwoLevelGrowingCircularArrayImpl() { delete[] (data[0]); for(size_t i = initial_buckets; i < buckets; i++) delete [](data[i]); } template <class Pheet, typename T, size_t MaxBuckets> size_t TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::get_capacity() { return capacity; } template <class Pheet, typename T, size_t MaxBuckets> bool TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::is_growable() { return buckets < MaxBuckets; } // return value NEEDS to be const. When growing we cannot guarantee that the reference won't change template <class Pheet, typename T, size_t MaxBuckets> inline T const& TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::get(size_t i) { i = i % capacity; size_t hb = find_last_bit_set(i); return data[hb][i ^ ((1 << (hb)) >> 1)]; } template <class Pheet, typename T, size_t MaxBuckets> void TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::put(size_t i, T value) { i = i % capacity; size_t hb = find_last_bit_set(i); data[hb][i ^ ((1 << (hb)) >> 1)] = value; } template <class Pheet, typename T, size_t MaxBuckets> void TwoLevelGrowingCircularArrayImpl<Pheet, T, MaxBuckets>::grow(size_t bottom, size_t top) { pheet_assert(is_growable()); data[buckets] = new T[capacity]; buckets++; size_t newCapacity = capacity << 1; size_t start = top; size_t startMod = top % capacity; if(startMod == (top % newCapacity)) { // Make sure we don't iterate through useless indices start += capacity - startMod; } for(size_t i = start; i < bottom; i++) { size_t oldI = i % capacity; size_t newI = i % newCapacity; if(oldI != newI) { size_t oldBit = find_last_bit_set(oldI); size_t newBit = find_last_bit_set(newI); data[newBit][newI ^ ((1 << (newBit)) >> 1)] = data[oldBit][oldI ^ ((1 << (oldBit)) >> 1)]; } else { // Make sure we don't iterate through useless indices break; } } // Do we really need this? I guess we have to ensure that threads don't have // some senseless pointers in their data array MEMORY_FENCE (); capacity = newCapacity; } template<class Pheet, typename TT> using TwoLevelGrowingCircularArray = TwoLevelGrowingCircularArrayImpl<Pheet, TT>; } #endif /* TWOLEVELGROWINGCIRCULARARRAY_H_ */
[ "weber.t@cg.tuwien.at" ]
weber.t@cg.tuwien.at
e3f0645e97848f949f603beedd3aa97e6cc6c0f9
2b67f9827514224900469bc111f07f3f7aaec525
/10.cpp
c9b08bdd81286a59af4bcf52cf1072763217a454
[]
no_license
ZoeVonFeng/Project_Euler
b3c39aab02e7c54463a98371ac668b22f9214364
c294088a7dd13ba57b781521d6bde5c5b0b5a40c
refs/heads/master
2021-06-14T05:07:20.381498
2017-05-02T05:21:06
2017-05-02T05:21:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
/*The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. */ #include <iostream> #include <cmath> using namespace std; bool is_prime(unsigned long long); int main () { unsigned long long sum = 0; for (unsigned long long i = 2; i < 2000000; ++i) if (is_prime(i)) sum += i; cout << "Sum = " << sum << endl; } bool is_prime(unsigned long long n) { unsigned long long i,sq,count=0; if(n==1 || n==2) return true; if(n%2==0) return false; sq=sqrt(n); for(i=2;i<=sq;i++) { if(n%i==0) return false; } return true; }
[ "ziyi.feng@sjsu.edu" ]
ziyi.feng@sjsu.edu
f54c1aafa75ce585459f41415caa086c2acee5e8
ab6d163c4307d85acfe2419d4c6de8628797c6c9
/EP2_3/packages/Win2D.0.0.11/Include/Microsoft.Graphics.Canvas.DirectX.Direct3D11.interop.h
c8c557ce685c4fe578e771eab8f94142f88f6d32
[ "CC-BY-4.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Chubosaurus/Win2D-Getting-Started
55dab9037397c5c9e95e9e4d007e2f873e0ec08e
c37f0bb28a5aaa1ef255b530a863efde27641f06
refs/heads/master
2021-01-17T10:22:44.061878
2016-06-11T10:50:20
2016-06-11T10:50:20
58,127,427
17
0
null
null
null
null
UTF-8
C++
false
false
4,018
h
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may // not use these files 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. #if defined(_MSC_VER) #pragma once #endif #include <winapifamily.h> #pragma region Application Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #include <inspectable.h> #include <dxgi.h> STDAPI CreateDirect3D11DeviceFromDXGIDevice( _In_ IDXGIDevice* dxgiDevice, _COM_Outptr_ IInspectable** graphicsDevice); STDAPI CreateDirect3D11SurfaceFromDXGISurface( _In_ IDXGISurface* dgxiSurface, _COM_Outptr_ IInspectable** graphicsSurface); namespace Microsoft { namespace Graphics { namespace Canvas { namespace DirectX { namespace Direct3D11 { [uuid(6173F6BA-35C0-46F9-A944-BD7661DA6E6E)] class IDirect3DDxgiInterfaceAccess : public IUnknown { public: IFACEMETHOD(GetInterface)(REFIID iid, void** p) = 0; }; }}}}} #if defined(__cplusplus_winrt) #include <wrl.h> namespace Microsoft { namespace Graphics { namespace Canvas { namespace DirectX { namespace Direct3D11 { inline IDirect3DDevice^ CreateDirect3DDevice( _In_ IDXGIDevice* dxgiDevice) { using Microsoft::WRL::ComPtr; using Platform::Object; ComPtr<IInspectable> inspectableDevice; __abi_ThrowIfFailed(CreateDirect3D11DeviceFromDXGIDevice( dxgiDevice, &inspectableDevice)); Object^ objectDevice = reinterpret_cast<Object^>(inspectableDevice.Get()); return safe_cast<IDirect3DDevice^>(objectDevice); } inline IDirect3DSurface^ CreateDirect3DSurface( _In_ IDXGISurface* dxgiSurface) { using Microsoft::WRL::ComPtr; using Platform::Object; ComPtr<IInspectable> inspectableSurface; __abi_ThrowIfFailed(CreateDirect3D11SurfaceFromDXGISurface( dxgiSurface, &inspectableSurface)); Object^ objectSurface = reinterpret_cast<Object^>(inspectableSurface.Get()); return safe_cast<IDirect3DSurface^>(objectSurface); } inline HRESULT GetDXGIInterfaceFromObject( _In_ Platform::Object^ object, _In_ REFIID iid, _COM_Outptr_ void** p) { using Microsoft::WRL::ComPtr; using ::Microsoft::Graphics::Canvas::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess; IInspectable* deviceInspectable = reinterpret_cast<IInspectable*>(object); ComPtr<IDirect3DDxgiInterfaceAccess> dxgiInterfaceAccess; HRESULT hr = deviceInspectable->QueryInterface(IID_PPV_ARGS(&dxgiInterfaceAccess)); if (SUCCEEDED(hr)) { hr = dxgiInterfaceAccess->GetInterface(iid, p); } return hr; } template<typename DXGI_TYPE> HRESULT GetDXGIInterface( _In_ IDirect3DDevice^ device, _COM_Outptr_ DXGI_TYPE** dxgi) { return GetDXGIInterfaceFromObject(device, IID_PPV_ARGS(dxgi)); } template<typename DXGI_TYPE> HRESULT GetDXGIInterface( _In_ IDirect3DSurface^ surface, _Out_ DXGI_TYPE** dxgi) { return GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(dxgi)); } } /* Direct3D11 */ } /* DirectX */ } /* Canvas */ } /* Graphics */ } /* Windows */ #endif /* __cplusplus_winrt */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */ #pragma endregion
[ "dnguyen_wsu@hotmail.com" ]
dnguyen_wsu@hotmail.com
7e4f2ade420d88727d49e5b531f33bbab897a4eb
eb7047d5a8c00d4370a55c2806a2f051287b452d
/modulesrc/meshio/OutputTrigger.i
ec8c64b7338e2b8e109ac9d7b3e5d40c77cb1705
[ "MIT" ]
permissive
mousumiroy-unm/pylith
8361a1c0fbcde99657fd3c4e88678a8b5fc8398b
9a7b6b4ee8e1b89bc441bcedc5ed28a3318e2468
refs/heads/main
2023-05-27T18:40:57.145323
2021-06-09T19:32:19
2021-06-09T19:32:19
373,931,160
0
0
MIT
2021-06-04T18:40:09
2021-06-04T18:40:09
null
UTF-8
C++
false
false
1,674
i
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2016 University of California, Davis // // See COPYING for license information. // // ====================================================================== // /** * @file modulesrc/meshio/OutputTrigger.i * * @brief Python interface to C++ OutputTrigger object. */ namespace pylith { namespace meshio { class pylith::meshio::OutputTrigger : public pylith::utils::PyreComponent { // PUBLIC METHODS /////////////////////////////////////////////////////// public: /// Constructor OutputTrigger(void); /// Destructor virtual ~OutputTrigger(void); /** Set time scale for nondimensionalizing time. * * @param[in] value Time scale. */ void setTimeScale(const PylithReal value); /** Check whether we want to write output at time t. * * @param[in] t Time of proposed write. * @param[in] tindex Inxex of current time step. * @returns True if output should be written at time t, false otherwise. */ virtual bool shouldWrite(const PylithReal t, const PylithInt tindex) = 0; }; // OutputTrigger } // meshio } // pylith // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
c04e2978e7acc6ee67c37b555d0bcbf90c02ab4c
0129862ead895ddec58a11dbc82e51330fbc1058
/test.cpp
e0559d484bd2ce89ac8a75cc91736055002ed80b
[ "Apache-2.0" ]
permissive
FajarFirdaus2125/GCI-MakeFile
0ec51e0946c1472129169aae4bfdee499a7394f6
95c9bd81f2c0bdea6f1f1d8bea20c032b1aa6209
refs/heads/master
2020-11-25T19:12:53.398328
2019-12-18T14:07:35
2019-12-18T14:07:35
228,806,722
0
0
null
null
null
null
UTF-8
C++
false
false
100
cpp
#include <iostream> using namespace std; int main(){ cout << "Hello i'm <FajarTheGGman>\n"; }
[ "noreply@github.com" ]
FajarFirdaus2125.noreply@github.com
701f085a9d5c76aa5839cb65bf8b17d673b5ca4b
6814e6556e620bbcbcf16f0dce7a15134b7830f1
/Projects/Skylicht/Engine/Source/Animation/CAnimationTrack.h
fa6e975b5569be683201a5537c473597c85cf666
[ "MIT" ]
permissive
blizmax/skylicht-engine
1bfc506635a1e33b59ad0ce7b04183bcf87c7fc1
af99999f0a428ca8f3f144e662c1b23fd03b9ceb
refs/heads/master
2023-08-07T11:50:02.370130
2021-10-09T16:10:20
2021-10-09T16:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
h
/* !@ MIT License Copyright (c) 2019 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #pragma once namespace Skylicht { class CFrameData { public: struct SPositionKey { f32 frame; core::vector3df position; }; struct SScaleKey { f32 frame; core::vector3df scale; }; struct SRotationKey { f32 frame; core::quaternion rotation; }; struct SEventKey { f32 frame; core::stringc event; }; core::array<CFrameData::SPositionKey> PositionKeys; core::array<CFrameData::SScaleKey> ScaleKeys; core::array<CFrameData::SRotationKey> RotationKeys; core::array<CFrameData::SEventKey> EventKeys; core::quaternion DefaultRot; core::vector3df DefaultPos; core::vector3df DefaultScale; CFrameData() { } }; class CAnimationTrack { protected: s32 m_posHint; s32 m_scaleHint; s32 m_rotHint; CFrameData *m_data; public: std::string Name; bool HaveAnimation; public: CAnimationTrack(); virtual ~CAnimationTrack(); static void quaternionSlerp(core::quaternion& result, core::quaternion q1, core::quaternion q2, float t); void getFrameData(f32 frame, core::vector3df &position, core::vector3df &scale, core::quaternion &rotation); CFrameData* getAnimData(); void clearAllKeyFrame() { m_data = NULL; m_posHint = 0; m_scaleHint = 0; m_rotHint = 0; Name = ""; HaveAnimation = false; } void setFrameData(CFrameData *data) { m_data = data; } CFrameData* getFrameData() { return m_data; } }; }
[ "hongduc.pr@gmail.com" ]
hongduc.pr@gmail.com
d7724365595f6cd059e254dd8ec894db3124ece4
41d6b7e3b34b10cc02adb30c6dcf6078c82326a3
/src/plugins/poshuku/plugins/dcac/ssecommon.h
478baa151f1e718f54072dc9fe5778d93bbe5ad8
[ "BSL-1.0" ]
permissive
ForNeVeR/leechcraft
1c84da3690303e539e70c1323e39d9f24268cb0b
384d041d23b1cdb7cc3c758612ac8d68d3d3d88c
refs/heads/master
2020-04-04T19:08:48.065750
2016-11-27T02:08:30
2016-11-27T02:08:30
2,294,915
1
0
null
null
null
null
UTF-8
C++
false
false
5,296
h
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #pragma once #include <util/sll/intseq.h> namespace LeechCraft { namespace Poshuku { namespace DCAC { template<int Alignment, typename F> void HandleLoopBegin (const uchar * const scanline, int width, int& x, int& bytesCount, F&& f) { const auto beginUnaligned = (scanline - static_cast<const uchar*> (nullptr)) % Alignment; bytesCount = width * 4; if (beginUnaligned) { x += Alignment - beginUnaligned; bytesCount -= Alignment - beginUnaligned; for (int i = 0; i < Alignment - beginUnaligned; i += 4) f (i); } bytesCount -= bytesCount % Alignment; } template<typename F> void HandleLoopEnd (int width, int x, F&& f) { for (int i = x; i < width * 4; i += 4) f (i); } template<char From, char To, char ByteNum, char BytesPerElem> struct GenSeq; template<char From, char To, char ByteNum, char BytesPerElem> using EpiSeq = typename GenSeq<From, To, ByteNum, BytesPerElem>::type; template<char From, char To, char ByteNum, char BytesPerElem> struct GenSeq { using type = Util::IntSeq::Concat<EpiSeq<From, From, ByteNum, BytesPerElem>, EpiSeq<From - 1, To, ByteNum, BytesPerElem>>; }; template<char E, char ByteNum, char BytesPerElem> struct GenSeq<E, E, ByteNum, BytesPerElem> { using type = Util::IntSeq::Concat< Util::IntSeq::Repeat<uchar, 0x80, BytesPerElem - ByteNum - 1>, std::integer_sequence<uchar, E>, Util::IntSeq::Repeat<uchar, 0x80, ByteNum> >; }; template<size_t BytesCount, size_t Bucket, char ByteNum, char BytesPerElem> struct GenRevSeqS { static constexpr uchar EndValue = BytesCount * BytesPerElem - BytesPerElem; static constexpr auto TotalCount = BytesCount * BytesPerElem; static constexpr auto BeforeEmpty = BytesCount * Bucket; static constexpr auto AfterEmpty = TotalCount - BytesCount - BeforeEmpty; static_assert (AfterEmpty >= 0, "negative sequel size"); static_assert (BeforeEmpty >= 0, "negative prequel size"); template<uchar... Is> static auto BytesImpl (std::integer_sequence<uchar, Is...>) { return std::integer_sequence<uchar, (EndValue - Is * BytesPerElem + ByteNum)...> {}; } using type = Util::IntSeq::Concat< Util::IntSeq::Repeat<uchar, 0x80, AfterEmpty>, decltype (BytesImpl (std::make_integer_sequence<uchar, BytesCount> {})), Util::IntSeq::Repeat<uchar, 0x80, BeforeEmpty> >; }; template<size_t BytesCount, size_t Bucket, char ByteNum, char BytesPerElem> using GenRevSeq = typename GenRevSeqS<BytesCount, Bucket, ByteNum, BytesPerElem>::type; template<uint16_t> struct Tag {}; template<uchar... Is> auto MakeMaskImpl (Tag<128>, std::integer_sequence<uchar, Is...>) { return _mm_set_epi8 (Is...); } template<uchar... Is> __attribute__ ((target ("avx"))) auto MakeMaskImpl (Tag<256>, std::integer_sequence<uchar, Is...>) { return _mm256_set_epi8 (Is..., Is...); } template<uint32_t Bits, char From, char To, char ByteNum = 0> auto MakeMask () { constexpr char BytesPerElem = 16 / (From - To + 1); return MakeMaskImpl (Tag<Bits> {}, EpiSeq<From, To, ByteNum, BytesPerElem> {}); } template<uchar... Is> auto MakeRevMaskImpl (Tag<128>, std::integer_sequence<uchar, Is...>) { return _mm_set_epi8 (Is...); } template<uchar... Is> __attribute__ ((target ("avx"))) auto MakeRevMaskImpl (Tag<256>, std::integer_sequence<uchar, Is...>) { return _mm256_set_epi8 (Is..., Is...); } template<uint32_t Bits, size_t BytesCount, size_t Bucket, char ByteNum = 0> auto MakeRevMask () { constexpr char BytesPerElem = 16 / BytesCount; return MakeRevMaskImpl (Tag<Bits> {}, GenRevSeq<BytesCount, Bucket, ByteNum, BytesPerElem> {}); } } } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
18ac75857656d2c584a1eef0a0d1d6cce7f379a5
752562564130a952c145ed053b0171cfa0b2501f
/include/foonathan/lex/parser.hpp
d3da46d5d41a1f75487c40a596a671d23d4b9c71
[ "BSL-1.0" ]
permissive
foonathan/lex
81e9c3d5c2d70f5cbc980a5b9e6f29f7389fc7b0
2d0177d453f8c36afc78392065248de0b48c1e7d
refs/heads/master
2021-06-28T14:20:02.766922
2020-12-01T13:54:18
2020-12-01T13:54:18
148,897,732
145
10
NOASSERTION
2018-10-17T14:58:40
2018-09-15T11:55:07
C++
UTF-8
C++
false
false
2,315
hpp
// Copyright (C) 2018-2019 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef FOONATHAN_LEX_PARSER_HPP_INCLUDED #define FOONATHAN_LEX_PARSER_HPP_INCLUDED #include <foonathan/lex/grammar.hpp> #include <foonathan/lex/parse_error.hpp> #include <foonathan/lex/parse_result.hpp> #include <foonathan/lex/tokenizer.hpp> namespace foonathan { namespace lex { namespace detail { template <class Token, class TokenSpec> constexpr auto parse_token_impl(int, token<TokenSpec> token) -> static_token<Token, decltype(Token::parse(token))> { using type = static_token<Token, decltype(Token::parse(token))>; return type(token, Token::parse(token)); } template <class Token, class TokenSpec> constexpr auto parse_token_impl(short, token<TokenSpec> token) { return static_token<Token>(token); } template <class Token, class TokenSpec> constexpr auto parse_token(token<TokenSpec> token) { return parse_token_impl<Token>(0, token); } } // namespace detail template <class Grammar, class Func> constexpr auto parse(tokenizer<typename Grammar::token_spec>& tokenizer, Func&& f) { auto result = Grammar::start::parse(tokenizer, f); if (result.is_success() && !tokenizer.is_done()) { unexpected_token<Grammar, typename Grammar::start, eof_token> error(typename Grammar::start{}, eof_token{}); detail::report_error(f, error, tokenizer); } return result; } template <class Grammar, class Func> constexpr auto parse(const char* str, std::size_t size, Func&& f) { tokenizer<typename Grammar::token_spec> tok(str, size); return parse<Grammar>(tok, static_cast<Func&&>(f)); } template <class Grammar, class Func> constexpr auto parse(const char* begin, const char* end, Func&& f) { tokenizer<typename Grammar::token_spec> tok(begin, end); return parse<Grammar>(tok, static_cast<Func&&>(f)); } } // namespace lex } // namespace foonathan #endif // FOONATHAN_LEX_PARSER_HPP_INCLUDED
[ "git@foonathan.net" ]
git@foonathan.net
399b58b42eb97acf8c8559fd82f8ad49b8861f93
e8936f52c4d9e13407f4acaebaaa5d333c32675d
/include/boglfw/GUI/GuiHelper.h
30d5e4a47d97ea75d9176a40f56068648004045b
[ "MIT" ]
permissive
bog2k3/boglfw
1c5501a1f17f0d98a85ea008e8ce2f38f6b9459a
ecf297b368c54b2f85c31e94231041fef05da0f9
refs/heads/master
2021-06-07T16:26:56.222107
2020-03-05T08:34:03
2020-03-05T08:34:03
113,235,860
0
1
null
2020-03-05T08:34:05
2017-12-05T21:39:40
C++
UTF-8
C++
false
false
1,221
h
/* * GuiHelper.h * * Created on: Mar 25, 2015 * Author: bog */ #ifndef GUI_GUIHELPER_H_ #define GUI_GUIHELPER_H_ #include <glm/vec2.hpp> #include <memory> class GuiBasicElement; class GuiContainerElement; namespace GuiHelper { // searches recursively for the top-most element at the specified point. // the function assumes the elements in containers are sorted from lowest to highest z-index (top-most last). // if a container is found at the position, the function recurses within the container to find the deepest element at the point. // if a container's body is at the point, but none of its children and the container's background is not trasparent, the container is returned. // x and y are in local container's space (not client space) std::shared_ptr<GuiBasicElement> getTopElementAtPosition(GuiContainerElement const& container, float x, float y); // transforms coordinates from parent's client space into element's local space glm::vec2 parentToLocal(GuiBasicElement const& el, glm::vec2 pcoord); // transforms coordinates from viewport's space into element's local space glm::vec2 viewportToLocal(GuiBasicElement const& el, glm::vec2 vcoord); } // namespace #endif /* GUI_GUIHELPER_H_ */
[ "bog2k3@gmail.com" ]
bog2k3@gmail.com
6592b5ce8809c27e03ae2c35f7e36348fefd6d19
dabcf701173ddccf9bb12be43587b5d3432beed5
/Source/TRDsample/Private/ActionTRD.cpp
d2a86b5c21a9b1ceb736b1b32b0a27f0e54e805e
[]
no_license
emperor-katax/ThreadCPP
601984e969d369c4435e52e5f1215befeb4ccd88
a43dc5d7c3f2f114e2e95aa45bfd1a56261911e5
refs/heads/main
2023-07-09T04:38:11.810020
2021-08-10T08:25:13
2021-08-10T08:25:13
394,575,670
0
0
null
null
null
null
UTF-8
C++
false
false
2,038
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ActionTRD.h" FAsyncTask<TRDAbandonableTaskTest>* Tasker_01; // define thread variable // Sets default values for this component's properties UActionTRD::UActionTRD(){ PrimaryComponentTick.bCanEverTick = true; } // Called when the game starts void UActionTRD::BeginPlay(){ Super::BeginPlay(); } // Called every frame void UActionTRD::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction){ Super::TickComponent(DeltaTime, TickType, ThisTickFunction); } void UActionTRD::SetupItems(int max, float range, FVector shiftLoc, int seg ) { maxArrayItems = max; areaRange = range; areaSegment = seg; makeArray(); calibrateEmplace(shiftLoc); } void UActionTRD::makeArray(){ for (int i = 0; i < maxArrayItems; i++) { arrEmplace.Emplace(FMath::VRand()); items.Emplace(nullptr); } } void UActionTRD::calibrateEmplace(FVector shiftLoc){ int segmentCounter = 1; for (int i = 0; i < arrEmplace.Num(); i++) { arrEmplace[i] = (arrEmplace[i] * ((areaRange / areaSegment) * segmentCounter)) + shiftLoc; if (i > (segmentCounter * maxArrayItems / areaSegment)) segmentCounter++; } } void UActionTRD::checkTarget(FVector targetLocation, float range){ (new FAutoDeleteAsyncTask<TRDAbandonableTaskTest>(range, targetLocation, maxArrayItems, arrEmplace, items, od))->StartBackgroundTask(); } void UActionTRD::ActivateItems(int index, bool b) { const FString cmd = FString::Printf(TEXT("SetColor %s"), b ? TEXT("true") : TEXT("false")); if (items[index]) items[index]->CallFunctionByNameWithArguments(*cmd, od, NULL, true); } TArray<FVector> UActionTRD::getLocations() { return arrEmplace; } void UActionTRD::setItems(int index, AActor* obj) { items.EmplaceAt(index, obj); } /////////////////////////////////// // ----------- // destroy thread void UActionTRD::DestroyThread(){ if (Tasker_01){ Tasker_01->EnsureCompletion(); delete Tasker_01; Tasker_01 = NULL; } }
[ "katax.emperor@gmail.com" ]
katax.emperor@gmail.com
2e47aef57fa1257405b9a1dba824430b2c447a60
9acf665d0348a11d032a3a880bdbfb28a98ea3db
/DFAltisLife.Altis/The-Programmer/Iphone_X/dialogs/Gang.hpp
b417a5d5ea930acb0980221a7a27a743d0224970
[]
no_license
RoberioJr/DFAltisLife
4d605b51cefcf684b2d073fd25d68edb5ba226ca
4b90450e5b256cdb2162e4fc6b6f1c5914cb87f1
refs/heads/master
2022-09-30T10:42:39.506374
2019-05-04T04:03:04
2019-05-04T04:03:04
144,479,757
0
1
null
null
null
null
UTF-8
C++
false
false
4,853
hpp
/* Author: Jean_Park Teamspeak 3: ts.the-programmer.com Web site: www.the-programmer.com Discord : https://discord.gg/DhFUFsq Terms of use: - This file is forbidden unless you have permission from the author. If you have this file without permission to use it please do not use it and do not share it. - If you have permission to use this file, you can use it on your server however it is strictly forbidden to share it. - Out of respect for the author please do not delete this information. License number: Server's name: Owner's name: */ class The_Programmer_Iphone_Gang_Menu { idd = 2620; name = "The_Programmer_Iphone_Gang_Menu"; movingenable = 0; enablesimulation = 1; onload = ""; class controlsBackground { class Life_RscTitleBackground : Life_RscPicture { text = ""; idc = 2000; x = 0.6379405 * safezoneW + safezoneX; y = 0.288744481809243 * safezoneH + safezoneY; w = 0.21 * safezoneW; h = 0.7 * safezoneH; }; }; class controls { class GangMemberList : Life_RscListBox { idc = 2621; text = ""; colorbackground[] = {1,1,1,0}; sizeex = 0.035; x = 0.668854166666667 * safezoneW + safezoneX; y = 0.514670599803343 * safezoneH + safezoneY; w = 0.148 * safezoneW; h = 0.185 * safezoneH; }; class Fermer : Life_RscButtonInvisible { idc = -1; tooltip = "Home"; onbuttonclick = "closeDialog 0; [] spawn the_programmer_iphone_fnc_phone_init;"; x = 0.732093666666666 * safezoneW + safezoneX; y = 0.907587959685349 * safezoneH + safezoneY; w = 0.025877 * safezoneW; h = 0.0439812 * safezoneH; }; class Augementer : Life_RscButtonInvisible { idc = 2622; onbuttonclick = "[] spawn life_fnc_gangUpgrade;"; x = 0.659583333333333 * safezoneW + safezoneX; y = 0.802625368731563 * safezoneH + safezoneY; w = 0.17 * safezoneW; h = 0.03 * safezoneH; }; class GangKick : Life_RscButtonInvisible { idc = 2624; onbuttonclick = "[] call life_fnc_gangKick;"; x = 0.717395833333333 * safezoneW + safezoneX; y = 0.7670796460177 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.03 * safezoneH; }; class GangLeader : Life_RscButtonInvisible { idc = 2625; text = ""; onbuttonclick = "[] spawn life_fnc_gangNewLeader;"; x = 0.776770833333333 * safezoneW + safezoneX; y = 0.7670796460177 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.03 * safezoneH; }; class InviteMember : Life_RscButtonInvisible { idc = 2630; text = ""; onbuttonclick = "[] spawn life_fnc_gangInvitePlayer;"; y = 0.724208456243855 * safezoneH + safezoneY; x = 0.800625 * safezoneW + safezoneX; w = 0.03 * safezoneW; h = 0.03 * safezoneH; }; class DisbandGang : Life_RscButtonInvisible { idc = 2631; text = ""; onbuttonclick = ""; y = 0.837581120943953 * safezoneH + safezoneY; w = 0.17 * safezoneW; h = 0.03 * safezoneH; x = 0.659583333333333 * safezoneW + safezoneX; }; class ColorList : Life_RscCombo { idc = 2632; x = 0.664583333333333 * safezoneW + safezoneX; y = 0.728 * safezoneH + safezoneY; w = 0.13 * safezoneW; h = 0.022 * safezoneH; }; class GangBank : Life_RscStructuredText { idc = 601; style = 1; text = ""; w = 0.115 * safezoneW; h = 0.04 * safezoneH; x = 0.6965625 * safezoneW + safezoneX; y = 0.410422812192723 * safezoneH + safezoneY; }; class Nom : Life_RscStructuredText { idc = 2629; style = 1; text = ""; sizeex = 0.045; w = 0.1 * safezoneW; h = 0.025 * safezoneH; x = 0.705416666666667 * safezoneW + safezoneX; y = 0.471779744346115 * safezoneH + safezoneY; }; class Reboot : Life_RscButtonInvisible { idc = -1; tooltip = "Reboot"; onbuttonclick = "[] call the_programmer_iphone_fnc_reboot;"; x = 0.807894833333333 * safezoneW + safezoneX; y = 0.312326017502458 * safezoneH + safezoneY; w = 0.01 * safezoneW; h = 0.02 * safezoneH; }; }; };
[ "rrpontesjunior10@gmail.com" ]
rrpontesjunior10@gmail.com
83a4691b7f22c91980ba3db85865a1b384872cc8
edd5c16bfa896a91fc93a149b2fc72882a48a0e2
/Leetcode/Arrays/SpiralMatrix.cpp
e9c5476643a0ca7b2beddd2dab05a5a9d0c9b5c6
[]
no_license
prateeek1/DS-Algo
7b4d2fe849363ad8d7415530ebffc22b4126e5bc
db5c258ba44b4fbd6a369cbbaae673e44ae56c19
refs/heads/master
2023-08-10T01:31:24.548219
2021-09-16T15:14:56
2021-09-16T15:14:56
376,521,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,110
cpp
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int>ans; int n = matrix.size(); int m = matrix[0].size(); int rowBegin = 0; int rowEnd = n - 1; int colBegin = 0; int colEnd = m - 1; while (rowBegin <= rowEnd and colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; i++) { ans.push_back(matrix[rowBegin][i]); } rowBegin++; for (int i = rowBegin; i <= rowEnd; i++) { ans.push_back(matrix[i][colEnd]); } colEnd--; for (int i = colEnd; i >= colBegin; i--) { if (rowBegin <= rowEnd) ans.push_back(matrix[rowEnd][i]); } rowEnd--; for (int i = rowEnd; i >= rowBegin; i--) { if (colBegin <= colEnd) ans.push_back(matrix[i][colBegin]); } colBegin++; } return ans; } };
[ "bahukhandiprateek@gmail.com" ]
bahukhandiprateek@gmail.com
6baa3682872c150ef5a9c9dbb92dacfce3676be1
191f811440d1749b4b40a0ea319793ed8a24f38b
/Dynamic Memory/Dynamic Memory/ClientCode.cpp
9919428d97a9134efa21a28e5725df1533a08431
[]
no_license
GianlucaVend/Dynamic-Memory-
34461a02c1ba1cefc65188ec2aa58681e9735df2
61f0450954490ee270f32b272f9e8264165aeee5
refs/heads/master
2023-09-06T04:30:43.698959
2021-11-07T05:18:05
2021-11-07T05:18:05
423,583,453
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
#include "Beverage.h" //Client code for module 8 int main() { Beverage* beverageOne = new Beverage(12, "juice", "water"); // call to constructor assert(beverageOne); beverageOne->show(); system("pause"); }
[ "noreply@github.com" ]
GianlucaVend.noreply@github.com
4ea7d5140b2b8d0ad9a3990cc6fd9acc7eb979a5
bd2139703c556050403c10857bde66f688cd9ee6
/valhalla/62/webrev.00/src/hotspot/share/oops/valueKlass.cpp
a5f5377d3328f55189de99c62115611045b5b3ae
[]
no_license
isabella232/cr-archive
d03427e6fbc708403dd5882d36371e1b660ec1ac
8a3c9ddcfacb32d1a65d7ca084921478362ec2d1
refs/heads/master
2023-02-01T17:33:44.383410
2020-12-17T13:47:48
2020-12-17T13:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,932
cpp
/* * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "gc/shared/barrierSet.hpp" #include "gc/shared/collectedHeap.inline.hpp" #include "gc/shared/gcLocker.inline.hpp" #include "interpreter/interpreter.hpp" #include "logging/log.hpp" #include "memory/metaspaceClosure.hpp" #include "memory/metadataFactory.hpp" #include "oops/access.hpp" #include "oops/compressedOops.inline.hpp" #include "oops/fieldStreams.inline.hpp" #include "oops/instanceKlass.inline.hpp" #include "oops/method.hpp" #include "oops/oop.inline.hpp" #include "oops/objArrayKlass.hpp" #include "oops/valueKlass.inline.hpp" #include "oops/valueArrayKlass.hpp" #include "runtime/fieldDescriptor.inline.hpp" #include "runtime/handles.inline.hpp" #include "runtime/safepointVerifiers.hpp" #include "runtime/sharedRuntime.hpp" #include "runtime/signature.hpp" #include "runtime/thread.inline.hpp" #include "utilities/copy.hpp" // Constructor ValueKlass::ValueKlass(const ClassFileParser& parser) : InstanceKlass(parser, InstanceKlass::_misc_kind_inline_type, InstanceKlass::ID) { _adr_valueklass_fixed_block = valueklass_static_block(); // Addresses used for value type calling convention *((Array<SigEntry>**)adr_extended_sig()) = NULL; *((Array<VMRegPair>**)adr_return_regs()) = NULL; *((address*)adr_pack_handler()) = NULL; *((address*)adr_pack_handler_jobject()) = NULL; *((address*)adr_unpack_handler()) = NULL; assert(pack_handler() == NULL, "pack handler not null"); *((int*)adr_default_value_offset()) = 0; *((Klass**)adr_value_array_klass()) = NULL; set_prototype_header(markWord::always_locked_prototype()); } oop ValueKlass::default_value() { oop val = java_mirror()->obj_field_acquire(default_value_offset()); assert(oopDesc::is_oop(val), "Sanity check"); assert(val->is_value(), "Sanity check"); assert(val->klass() == this, "sanity check"); return val; } int ValueKlass::first_field_offset_old() { #ifdef ASSERT int first_offset = INT_MAX; for (AllFieldStream fs(this); !fs.done(); fs.next()) { if (fs.offset() < first_offset) first_offset= fs.offset(); } #endif int base_offset = instanceOopDesc::base_offset_in_bytes(); // The first field of value types is aligned on a long boundary base_offset = align_up(base_offset, BytesPerLong); assert(base_offset == first_offset, "inconsistent offsets"); return base_offset; } int ValueKlass::raw_value_byte_size() { int heapOopAlignedSize = nonstatic_field_size() << LogBytesPerHeapOop; // If bigger than 64 bits or needs oop alignment, then use jlong aligned // which for values should be jlong aligned, asserts in raw_field_copy otherwise if (heapOopAlignedSize >= longSize || contains_oops()) { return heapOopAlignedSize; } // Small primitives... // If a few small basic type fields, return the actual size, i.e. // 1 byte = 1 // 2 byte = 2 // 3 byte = 4, because pow2 needed for element stores int first_offset = first_field_offset(); int last_offset = 0; // find the last offset, add basic type size int last_tsz = 0; for (AllFieldStream fs(this); !fs.done(); fs.next()) { if (fs.access_flags().is_static()) { continue; } else if (fs.offset() > last_offset) { BasicType type = Signature::basic_type(fs.signature()); if (is_java_primitive(type)) { last_tsz = type2aelembytes(type); } else if (type == T_VALUETYPE) { // Not just primitives. Layout aligns embedded value, so use jlong aligned it is return heapOopAlignedSize; } else { guarantee(0, "Unknown type %d", type); } assert(last_tsz != 0, "Invariant"); last_offset = fs.offset(); } } // Assumes VT with no fields are meaningless and illegal last_offset += last_tsz; assert(last_offset > first_offset && last_tsz, "Invariant"); return 1 << upper_log2(last_offset - first_offset); } instanceOop ValueKlass::allocate_instance(TRAPS) { int size = size_helper(); // Query before forming handle. instanceOop oop = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL); assert(oop->mark().is_always_locked(), "Unlocked value type"); return oop; } instanceOop ValueKlass::allocate_instance_buffer(TRAPS) { int size = size_helper(); // Query before forming handle. instanceOop oop = (instanceOop)Universe::heap()->obj_buffer_allocate(this, size, CHECK_NULL); assert(oop->mark().is_always_locked(), "Unlocked value type"); return oop; } int ValueKlass::nonstatic_oop_count() { int oops = 0; int map_count = nonstatic_oop_map_count(); OopMapBlock* block = start_of_nonstatic_oop_maps(); OopMapBlock* end = block + map_count; while (block != end) { oops += block->count(); block++; } return oops; } oop ValueKlass::read_flattened_field(oop obj, int offset, TRAPS) { oop res = NULL; this->initialize(CHECK_NULL); // will throw an exception if in error state if (is_empty_inline_type()) { res = (instanceOop)default_value(); } else { Handle obj_h(THREAD, obj); res = allocate_instance_buffer(CHECK_NULL); value_copy_payload_to_new_oop(((char*)(oopDesc*)obj_h()) + offset, res); } assert(res != NULL, "Must be set in one of two paths above"); return res; } void ValueKlass::write_flattened_field(oop obj, int offset, oop value, TRAPS) { if (value == NULL) { THROW(vmSymbols::java_lang_NullPointerException()); } if (!is_empty_inline_type()) { value_copy_oop_to_payload(value, ((char*)(oopDesc*)obj) + offset); } } // Arrays of... bool ValueKlass::flatten_array() { if (!ValueArrayFlatten) { return false; } // Too big int elem_bytes = raw_value_byte_size(); if ((ValueArrayElemMaxFlatSize >= 0) && (elem_bytes > ValueArrayElemMaxFlatSize)) { return false; } // Too many embedded oops if ((ValueArrayElemMaxFlatOops >= 0) && (nonstatic_oop_count() > ValueArrayElemMaxFlatOops)) { return false; } // Declared atomic but not naturally atomic. if (is_declared_atomic() && !is_naturally_atomic()) { return false; } // VM enforcing ValueArrayAtomicAccess only... if (ValueArrayAtomicAccess && (!is_naturally_atomic())) { return false; } return true; } void ValueKlass::remove_unshareable_info() { InstanceKlass::remove_unshareable_info(); *((Array<SigEntry>**)adr_extended_sig()) = NULL; *((Array<VMRegPair>**)adr_return_regs()) = NULL; *((address*)adr_pack_handler()) = NULL; *((address*)adr_pack_handler_jobject()) = NULL; *((address*)adr_unpack_handler()) = NULL; assert(pack_handler() == NULL, "pack handler not null"); *((Klass**)adr_value_array_klass()) = NULL; } void ValueKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, PackageEntry* pkg_entry, TRAPS) { InstanceKlass::restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK); oop val = allocate_instance(CHECK); set_default_value(val); } Klass* ValueKlass::array_klass_impl(bool or_null, int n, TRAPS) { if (flatten_array()) { return value_array_klass(or_null, n, THREAD); } else { return InstanceKlass::array_klass_impl(or_null, n, THREAD); } } Klass* ValueKlass::array_klass_impl(bool or_null, TRAPS) { return array_klass_impl(or_null, 1, THREAD); } Klass* ValueKlass::value_array_klass(bool or_null, int rank, TRAPS) { Klass* vak = acquire_value_array_klass(); if (vak == NULL) { if (or_null) return NULL; ResourceMark rm; { // Atomic creation of array_klasses MutexLocker ma(THREAD, MultiArray_lock); if (get_value_array_klass() == NULL) { vak = allocate_value_array_klass(CHECK_NULL); Atomic::release_store((Klass**)adr_value_array_klass(), vak); } } } if (or_null) { return vak->array_klass_or_null(rank); } return vak->array_klass(rank, THREAD); } Klass* ValueKlass::allocate_value_array_klass(TRAPS) { if (flatten_array()) { return ValueArrayKlass::allocate_klass(this, THREAD); } return ObjArrayKlass::allocate_objArray_klass(1, this, THREAD); } void ValueKlass::array_klasses_do(void f(Klass* k)) { InstanceKlass::array_klasses_do(f); if (get_value_array_klass() != NULL) ArrayKlass::cast(get_value_array_klass())->array_klasses_do(f); } // Value type arguments are not passed by reference, instead each // field of the value type is passed as an argument. This helper // function collects the fields of the value types (including embedded // value type's fields) in a list. Included with the field's type is // the offset of each field in the value type: i2c and c2i adapters // need that to load or store fields. Finally, the list of fields is // sorted in order of increasing offsets: the adapters and the // compiled code need to agree upon the order of fields. // // The list of basic types that is returned starts with a T_VALUETYPE // and ends with an extra T_VOID. T_VALUETYPE/T_VOID pairs are used as // delimiters. Every entry between the two is a field of the value // type. If there's an embedded value type in the list, it also starts // with a T_VALUETYPE and ends with a T_VOID. This is so we can // generate a unique fingerprint for the method's adapters and we can // generate the list of basic types from the interpreter point of view // (value types passed as reference: iterate on the list until a // T_VALUETYPE, drop everything until and including the closing // T_VOID) or the compiler point of view (each field of the value // types is an argument: drop all T_VALUETYPE/T_VOID from the list). int ValueKlass::collect_fields(GrowableArray<SigEntry>* sig, int base_off) { int count = 0; SigEntry::add_entry(sig, T_VALUETYPE, base_off); for (AllFieldStream fs(this); !fs.done(); fs.next()) { if (fs.access_flags().is_static()) continue; int offset = base_off + fs.offset() - (base_off > 0 ? first_field_offset() : 0); if (fs.is_flattened()) { // Resolve klass of flattened value type field and recursively collect fields Klass* vk = get_value_field_klass(fs.index()); count += ValueKlass::cast(vk)->collect_fields(sig, offset); } else { BasicType bt = Signature::basic_type(fs.signature()); if (bt == T_VALUETYPE) { bt = T_OBJECT; } SigEntry::add_entry(sig, bt, offset); count += type2size[bt]; } } int offset = base_off + size_helper()*HeapWordSize - (base_off > 0 ? first_field_offset() : 0); SigEntry::add_entry(sig, T_VOID, offset); if (base_off == 0) { sig->sort(SigEntry::compare); } assert(sig->at(0)._bt == T_VALUETYPE && sig->at(sig->length()-1)._bt == T_VOID, "broken structure"); return count; } void ValueKlass::initialize_calling_convention(TRAPS) { // Because the pack and unpack handler addresses need to be loadable from generated code, // they are stored at a fixed offset in the klass metadata. Since value type klasses do // not have a vtable, the vtable offset is used to store these addresses. if (is_scalarizable() && (ValueTypeReturnedAsFields || ValueTypePassFieldsAsArgs)) { ResourceMark rm; GrowableArray<SigEntry> sig_vk; int nb_fields = collect_fields(&sig_vk); Array<SigEntry>* extended_sig = MetadataFactory::new_array<SigEntry>(class_loader_data(), sig_vk.length(), CHECK); *((Array<SigEntry>**)adr_extended_sig()) = extended_sig; for (int i = 0; i < sig_vk.length(); i++) { extended_sig->at_put(i, sig_vk.at(i)); } if (ValueTypeReturnedAsFields) { nb_fields++; BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nb_fields); sig_bt[0] = T_METADATA; SigEntry::fill_sig_bt(&sig_vk, sig_bt+1); VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, nb_fields); int total = SharedRuntime::java_return_convention(sig_bt, regs, nb_fields); if (total > 0) { Array<VMRegPair>* return_regs = MetadataFactory::new_array<VMRegPair>(class_loader_data(), nb_fields, CHECK); *((Array<VMRegPair>**)adr_return_regs()) = return_regs; for (int i = 0; i < nb_fields; i++) { return_regs->at_put(i, regs[i]); } BufferedValueTypeBlob* buffered_blob = SharedRuntime::generate_buffered_value_type_adapter(this); *((address*)adr_pack_handler()) = buffered_blob->pack_fields(); *((address*)adr_pack_handler_jobject()) = buffered_blob->pack_fields_jobject(); *((address*)adr_unpack_handler()) = buffered_blob->unpack_fields(); assert(CodeCache::find_blob(pack_handler()) == buffered_blob, "lost track of blob"); } } } } void ValueKlass::deallocate_contents(ClassLoaderData* loader_data) { if (extended_sig() != NULL) { MetadataFactory::free_array<SigEntry>(loader_data, extended_sig()); } if (return_regs() != NULL) { MetadataFactory::free_array<VMRegPair>(loader_data, return_regs()); } cleanup_blobs(); InstanceKlass::deallocate_contents(loader_data); } void ValueKlass::cleanup(ValueKlass* ik) { ik->cleanup_blobs(); } void ValueKlass::cleanup_blobs() { if (pack_handler() != NULL) { CodeBlob* buffered_blob = CodeCache::find_blob(pack_handler()); assert(buffered_blob->is_buffered_value_type_blob(), "bad blob type"); BufferBlob::free((BufferBlob*)buffered_blob); *((address*)adr_pack_handler()) = NULL; *((address*)adr_pack_handler_jobject()) = NULL; *((address*)adr_unpack_handler()) = NULL; } } // Can this value type be scalarized? bool ValueKlass::is_scalarizable() const { return ScalarizeValueTypes; } // Can this value type be returned as multiple values? bool ValueKlass::can_be_returned_as_fields() const { return return_regs() != NULL; } // Create handles for all oop fields returned in registers that are going to be live across a safepoint void ValueKlass::save_oop_fields(const RegisterMap& reg_map, GrowableArray<Handle>& handles) const { Thread* thread = Thread::current(); const Array<SigEntry>* sig_vk = extended_sig(); const Array<VMRegPair>* regs = return_regs(); int j = 1; for (int i = 0; i < sig_vk->length(); i++) { BasicType bt = sig_vk->at(i)._bt; if (bt == T_OBJECT || bt == T_ARRAY) { VMRegPair pair = regs->at(j); address loc = reg_map.location(pair.first()); oop v = *(oop*)loc; assert(v == NULL || oopDesc::is_oop(v), "not an oop?"); assert(Universe::heap()->is_in_or_null(v), "must be heap pointer"); handles.push(Handle(thread, v)); } if (bt == T_VALUETYPE) { continue; } if (bt == T_VOID && sig_vk->at(i-1)._bt != T_LONG && sig_vk->at(i-1)._bt != T_DOUBLE) { continue; } j++; } assert(j == regs->length(), "missed a field?"); } // Update oop fields in registers from handles after a safepoint void ValueKlass::restore_oop_results(RegisterMap& reg_map, GrowableArray<Handle>& handles) const { assert(ValueTypeReturnedAsFields, "inconsistent"); const Array<SigEntry>* sig_vk = extended_sig(); const Array<VMRegPair>* regs = return_regs(); assert(regs != NULL, "inconsistent"); int j = 1; for (int i = 0, k = 0; i < sig_vk->length(); i++) { BasicType bt = sig_vk->at(i)._bt; if (bt == T_OBJECT || bt == T_ARRAY) { VMRegPair pair = regs->at(j); address loc = reg_map.location(pair.first()); *(oop*)loc = handles.at(k++)(); } if (bt == T_VALUETYPE) { continue; } if (bt == T_VOID && sig_vk->at(i-1)._bt != T_LONG && sig_vk->at(i-1)._bt != T_DOUBLE) { continue; } j++; } assert(j == regs->length(), "missed a field?"); } // Fields are in registers. Create an instance of the value type and // initialize it with the values of the fields. oop ValueKlass::realloc_result(const RegisterMap& reg_map, const GrowableArray<Handle>& handles, TRAPS) { oop new_vt = allocate_instance(CHECK_NULL); const Array<SigEntry>* sig_vk = extended_sig(); const Array<VMRegPair>* regs = return_regs(); int j = 1; int k = 0; for (int i = 0; i < sig_vk->length(); i++) { BasicType bt = sig_vk->at(i)._bt; if (bt == T_VALUETYPE) { continue; } if (bt == T_VOID) { if (sig_vk->at(i-1)._bt == T_LONG || sig_vk->at(i-1)._bt == T_DOUBLE) { j++; } continue; } int off = sig_vk->at(i)._offset; assert(off > 0, "offset in object should be positive"); VMRegPair pair = regs->at(j); address loc = reg_map.location(pair.first()); switch(bt) { case T_BOOLEAN: { new_vt->bool_field_put(off, *(jboolean*)loc); break; } case T_CHAR: { new_vt->char_field_put(off, *(jchar*)loc); break; } case T_BYTE: { new_vt->byte_field_put(off, *(jbyte*)loc); break; } case T_SHORT: { new_vt->short_field_put(off, *(jshort*)loc); break; } case T_INT: { new_vt->int_field_put(off, *(jint*)loc); break; } case T_LONG: { #ifdef _LP64 new_vt->double_field_put(off, *(jdouble*)loc); #else Unimplemented(); #endif break; } case T_OBJECT: case T_ARRAY: { Handle handle = handles.at(k++); new_vt->obj_field_put(off, handle()); break; } case T_FLOAT: { new_vt->float_field_put(off, *(jfloat*)loc); break; } case T_DOUBLE: { new_vt->double_field_put(off, *(jdouble*)loc); break; } default: ShouldNotReachHere(); } *(intptr_t*)loc = 0xDEAD; j++; } assert(j == regs->length(), "missed a field?"); assert(k == handles.length(), "missed an oop?"); return new_vt; } // Check the return register for a ValueKlass oop ValueKlass* ValueKlass::returned_value_klass(const RegisterMap& map) { BasicType bt = T_METADATA; VMRegPair pair; int nb = SharedRuntime::java_return_convention(&bt, &pair, 1); assert(nb == 1, "broken"); address loc = map.location(pair.first()); intptr_t ptr = *(intptr_t*)loc; if (is_set_nth_bit(ptr, 0)) { // Oop is tagged, must be a ValueKlass oop clear_nth_bit(ptr, 0); assert(Metaspace::contains((void*)ptr), "should be klass"); ValueKlass* vk = (ValueKlass*)ptr; assert(vk->can_be_returned_as_fields(), "must be able to return as fields"); return vk; } #ifdef ASSERT // Oop is not tagged, must be a valid oop if (VerifyOops) { oopDesc::verify(oop((HeapWord*)ptr)); } #endif return NULL; } void ValueKlass::verify_on(outputStream* st) { InstanceKlass::verify_on(st); guarantee(prototype_header().is_always_locked(), "Prototype header is not always locked"); } void ValueKlass::oop_verify_on(oop obj, outputStream* st) { InstanceKlass::oop_verify_on(obj, st); guarantee(obj->mark().is_always_locked(), "Header is not always locked"); } void ValueKlass::metaspace_pointers_do(MetaspaceClosure* it) { InstanceKlass::metaspace_pointers_do(it); ValueKlass* this_ptr = this; it->push_internal_pointer(&this_ptr, (intptr_t*)&_adr_valueklass_fixed_block); }
[ "robin.westberg@oracle.com" ]
robin.westberg@oracle.com