hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6103e30e9979fe5f02c6e7636e57309d0f7f09ff
| 9,351
|
cpp
|
C++
|
texture-view/src/main/cpp/android_main.cpp
|
yge58/real-time-caffe-ndkcamera
|
ad7117787cfdd70d4a276a2ec12286b9d88e04df
|
[
"MIT"
] | 20
|
2017-10-24T00:25:07.000Z
|
2021-05-15T08:25:09.000Z
|
texture-view/src/main/cpp/android_main.cpp
|
yge58/real-time-caffe-ndkcamera
|
ad7117787cfdd70d4a276a2ec12286b9d88e04df
|
[
"MIT"
] | 1
|
2017-11-13T08:32:18.000Z
|
2017-11-14T01:53:03.000Z
|
texture-view/src/main/cpp/android_main.cpp
|
yge58/real-time-caffe-ndkcamera
|
ad7117787cfdd70d4a276a2ec12286b9d88e04df
|
[
"MIT"
] | 6
|
2018-04-06T13:38:35.000Z
|
2020-06-05T03:22:15.000Z
|
/**
* Copyright (C) 2017 The Android 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 <jni.h>
#include <string>
#include "native_debug.h"
#include "camera/camera_manager.h"
#include "camera/camera_engine.h"
#include <android/asset_manager_jni.h>
#define PROTOBUF_USE_DLLS 1
#define CAFFE2_USE_LITE_PROTO 1
CameraAppEngine *pEngineObj = nullptr;
jboolean _caffe_is_running = 0;
static caffe2::NetDef _initNet, _predictNet;
static caffe2::Predictor *_predictor;
// A function to load the NetDefs from protobufs.
void loadToNetDef(AAssetManager* mgr, caffe2::NetDef* net, const char *filename) {
AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_BUFFER);
assert(asset != nullptr);
const void *data = AAsset_getBuffer(asset);
assert(data != nullptr);
off_t len = AAsset_getLength(asset);
assert(len != 0);
if (!net->ParseFromArray(data, len)) {
LOGI("Couldn't parse net from data.\n");
}
AAsset_close(asset);
}
extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_initCaffe2( JNIEnv* env,
jobject thiz ,
jobject assetManager) {
AAssetManager *mgr = AAssetManager_fromJava(env, assetManager);
LOGI("Attempting to load protobuf netdefs...");
loadToNetDef(mgr, &_initNet, "squeeze_init_net.pb");
loadToNetDef(mgr, &_predictNet,"squeeze_predict_net.pb");
_predictor = new caffe2::Predictor(_initNet, _predictNet);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_sample_textureview_ViewActivity_IsCaffeRunning( JNIEnv* env,
jobject thiz,
jlong ndkCameraObj)
{
ASSERT(ndkCameraObj, "NativeObject should not be null Pointer");
//CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
return _caffe_is_running;
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_sample_textureview_ViewActivity_RunCaffe( JNIEnv* env,
jobject thiz,
jlong ndkCameraObj )
{
ASSERT(ndkCameraObj, "NativeObject should not be null Pointer");
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
_caffe_is_running = 1;
pApp->GetJPGImageReader()->_caffe_result_is_ready = false;
pApp->GetJPGImageReader()->SetCaffePredictor(_predictor);
std::thread takePhotoHandler(&CameraAppEngine::TakePhoto, pEngineObj);
takePhotoHandler.detach();
while(pApp->GetJPGImageReader()->_caffe_result_is_ready == false);
_caffe_is_running = 0;
return env->NewStringUTF((pApp->GetJPGImageReader()->_CaffeResult).c_str());
}
/**
* createCamera() Create application instance and NDK camera object
* @param width is the texture view window width
* @param height is the texture view window height
* In this sample, it takes the simplest approach in that:
* the android system display size is used to view full screen
* preview camera images. Onboard Camera most likely to
* support the onboard panel size on that device. Camera is most likely
* to be oriented as landscape mode, the input width/height is in
* landscape mode. TextureView on Java side handles rotation for
* portrait mode.
* @return application object instance ( not used in this sample )
*/
extern "C" JNIEXPORT jlong JNICALL
Java_com_sample_textureview_ViewActivity_createCamera(JNIEnv *env,
jobject instance,
jint width, jint height)
{
pEngineObj = new CameraAppEngine(env, instance, width, height);
return reinterpret_cast<jlong>(pEngineObj);
}
/**
* deleteCamera():
* releases native application object, which
* triggers native camera object be released
*/
extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_deleteCamera(JNIEnv *env,
jobject instance,
jlong ndkCameraObj) {
if (!pEngineObj || !ndkCameraObj) {
return;
}
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
ASSERT(pApp == pEngineObj, "NdkCamera Obj mismatch");
delete pApp;
// also reset the private global object
pEngineObj = nullptr;
}
/**
* getCameraCompatibleSize()
* @returns minimium camera preview window size for the given
* requested camera size in CreateCamera() function, with the same
* ascpect ratio. essentially,
* 1) Display device size decides NDKCamera object preview size
* 2) Chosen NDKCamera preview size passed to TextView to
* reset textureView size
* 3) textureView size is stretched when previewing image
* on display device
*/
extern "C" JNIEXPORT jobject JNICALL
Java_com_sample_textureview_ViewActivity_getMinimumCompatiblePreviewSize( JNIEnv *env,
jobject instance,
jlong ndkCameraObj)
{
if (!ndkCameraObj) {
return nullptr;
}
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
jclass cls = env->FindClass("android/util/Size");
jobject previewSize =
env->NewObject(cls, env->GetMethodID(cls, "<init>", "(II)V"),
pApp->GetCompatibleCameraRes().width,
pApp->GetCompatibleCameraRes().height);
return previewSize;
}
/**
* getCameraSensorOrientation()
* @ return camera sensor orientation angle relative to Android device's
* display orientation. This sample only deal to back facing camera.
*/
extern "C" JNIEXPORT jint JNICALL
Java_com_sample_textureview_ViewActivity_getCameraSensorOrientation( JNIEnv *env,
jobject instance,
jlong ndkCameraObj )
{
ASSERT(ndkCameraObj, "NativeObject should not be null Pointer");
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
return pApp->GetCameraSensorOrientation(ACAMERA_LENS_FACING_BACK);
}
/**
* OnPreviewSurfaceCreated()
* Notification to native camera that java TextureView is ready
* to preview video. Simply create cameraSession and
* start camera preview
*/
extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_onPreviewSurfaceCreated( JNIEnv *env,
jobject thiz,
jlong ndkCameraObj,
jobject surface,
jstring dir)
{
ASSERT(ndkCameraObj && (jlong) pEngineObj == ndkCameraObj,
"NativeObject should not be null Pointer");
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
pApp->CreateJPGImageReader();
pApp->CreateCameraSession(surface);
pApp->StartPreview(true);
}
/**
* OnPreviewSurfaceDestroyed()
* Notification to native camera that java TextureView is destroyed
* Native camera would:
* * stop preview
*/
extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_onPreviewSurfaceDestroyed( JNIEnv *env,
jobject instance,
jlong ndkCameraObj,
jobject surface )
{
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj);
ASSERT(ndkCameraObj && pEngineObj == pApp,
"NativeObject should not be null Pointer");
jclass cls = env->FindClass("android/view/Surface");
jmethodID toString =
env->GetMethodID(cls, "toString", "()Ljava/lang/String;");
jstring destroyObjStr =
reinterpret_cast<jstring>(env->CallObjectMethod(surface, toString));
const char *destroyObjName = env->GetStringUTFChars(destroyObjStr, nullptr);
jstring appObjStr = reinterpret_cast<jstring>(
env->CallObjectMethod(pApp->GetSurfaceObject(), toString));
const char *appObjName = env->GetStringUTFChars(appObjStr, nullptr);
ASSERT(!strcmp(destroyObjName, appObjName), "object Name MisMatch");
env->ReleaseStringUTFChars(destroyObjStr, destroyObjName);
env->ReleaseStringUTFChars(appObjStr, appObjName);
pApp->StartPreview(false);
}
| 39.622881
| 93
| 0.637686
|
yge58
|
6106308efdb5b30b5d34e6fd914095d0aa3c519f
| 30,110
|
hpp
|
C++
|
msys64/mingw64/include/c++/8.2.1/ext/pb_ds/assoc_container.hpp
|
Bhuvanesh1208/ruby2.6.1
|
17642e3f37233f6d0e0523af68d7600a91ece1c7
|
[
"Ruby"
] | 432
|
2015-01-03T20:05:29.000Z
|
2022-03-24T16:39:09.000Z
|
msys64/mingw64/include/c++/8.2.1/ext/pb_ds/assoc_container.hpp
|
Bhuvanesh1208/ruby2.6.1
|
17642e3f37233f6d0e0523af68d7600a91ece1c7
|
[
"Ruby"
] | 75
|
2020-10-28T00:44:55.000Z
|
2022-03-05T20:21:53.000Z
|
msys64/mingw64/include/c++/8.2.1/ext/pb_ds/assoc_container.hpp
|
Bhuvanesh1208/ruby2.6.1
|
17642e3f37233f6d0e0523af68d7600a91ece1c7
|
[
"Ruby"
] | 114
|
2015-01-07T16:23:00.000Z
|
2022-03-23T18:26:01.000Z
|
// -*- C++ -*-
// Copyright (C) 2005-2018 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/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file assoc_container.hpp
* Contains associative containers.
*/
#ifndef PB_DS_ASSOC_CNTNR_HPP
#define PB_DS_ASSOC_CNTNR_HPP
#include <bits/c++config.h>
#include <ext/typelist.h>
#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include <ext/pb_ds/detail/container_base_dispatch.hpp>
#include <ext/pb_ds/detail/branch_policy/traits.hpp>
namespace __gnu_pbds
{
/**
* @defgroup containers-pbds Containers
* @ingroup pbds
* @{
*/
/**
* @defgroup hash-based Hash-Based
* @ingroup containers-pbds
* @{
*/
#define PB_DS_HASH_BASE \
detail::container_base_dispatch<Key, Mapped, _Alloc, Tag, \
typename __gnu_cxx::typelist::append< \
typename __gnu_cxx::typelist::create4<Hash_Fn, Eq_Fn, Resize_Policy, \
detail::integral_constant<int, Store_Hash> >::type, Policy_Tl>::type>::type
/**
* @defgroup hash-detail Base and Policy Classes
* @ingroup hash-based
*/
/**
* A hashed container abstraction.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Hash_Fn Hashing functor.
* @tparam Eq_Fn Equal functor.
* @tparam Resize_Policy Resizes hash.
* @tparam Store_Hash Indicates whether the hash value
* will be stored along with each key.
* @tparam Tag Instantiating data structure type,
* see container_tag.
* @tparam Policy_TL Policy typelist.
* @tparam _Alloc Allocator type.
*
* Base is dispatched at compile time via Tag, from the following
* choices: cc_hash_tag, gp_hash_tag, and descendants of basic_hash_tag.
*
* Base choices are: detail::cc_ht_map, detail::gp_ht_map
*/
template<typename Key,
typename Mapped,
typename Hash_Fn,
typename Eq_Fn,
typename Resize_Policy,
bool Store_Hash,
typename Tag,
typename Policy_Tl,
typename _Alloc>
class basic_hash_table : public PB_DS_HASH_BASE
{
private:
typedef typename PB_DS_HASH_BASE base_type;
public:
virtual
~basic_hash_table() { }
protected:
basic_hash_table() { }
basic_hash_table(const basic_hash_table& other)
: base_type((const base_type&)other) { }
template<typename T0>
basic_hash_table(T0 t0) : base_type(t0) { }
template<typename T0, typename T1>
basic_hash_table(T0 t0, T1 t1) : base_type(t0, t1) { }
template<typename T0, typename T1, typename T2>
basic_hash_table(T0 t0, T1 t1, T2 t2) : base_type(t0, t1, t2) { }
template<typename T0, typename T1, typename T2, typename T3>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3)
: base_type(t0, t1, t2, t3) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4)
: base_type(t0, t1, t2, t3, t4) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
: base_type(t0, t1, t2, t3, t4, t5) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
: base_type(t0, t1, t2, t3, t4, t5, t6) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7)
: base_type(t0, t1, t2, t3, t4, t5, t6, t7) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8>
basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6,
T7 t7, T8 t8)
: base_type(t0, t1, t2, t3, t4, t5, t6, t7, t8)
{ }
private:
basic_hash_table&
operator=(const base_type&);
};
#undef PB_DS_HASH_BASE
#define PB_DS_CC_HASH_BASE \
basic_hash_table<Key, Mapped, Hash_Fn, Eq_Fn, Resize_Policy, Store_Hash, \
cc_hash_tag, \
typename __gnu_cxx::typelist::create1<Comb_Hash_Fn>::type, _Alloc>
/**
* A collision-chaining hash-based associative container.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Hash_Fn Hashing functor.
* @tparam Eq_Fn Equal functor.
* @tparam Comb_Hash_Fn Combining hash functor.
* If Hash_Fn is not null_type, then this
* is the ranged-hash functor; otherwise,
* this is the range-hashing functor.
* XXX(See Design::Hash-Based Containers::Hash Policies.)
* @tparam Resize_Policy Resizes hash.
* @tparam Store_Hash Indicates whether the hash value
* will be stored along with each key.
* If Hash_Fn is null_type, then the
* container will not compile if this
* value is true
* @tparam _Alloc Allocator type.
*
* Base tag choices are: cc_hash_tag.
*
* Base is basic_hash_table.
*/
template<typename Key,
typename Mapped,
typename Hash_Fn = typename detail::default_hash_fn<Key>::type,
typename Eq_Fn = typename detail::default_eq_fn<Key>::type,
typename Comb_Hash_Fn = detail::default_comb_hash_fn::type,
typename Resize_Policy = typename detail::default_resize_policy<Comb_Hash_Fn>::type,
bool Store_Hash = detail::default_store_hash,
typename _Alloc = std::allocator<char> >
class cc_hash_table : public PB_DS_CC_HASH_BASE
{
private:
typedef PB_DS_CC_HASH_BASE base_type;
public:
typedef cc_hash_tag container_category;
typedef Hash_Fn hash_fn;
typedef Eq_Fn eq_fn;
typedef Resize_Policy resize_policy;
typedef Comb_Hash_Fn comb_hash_fn;
/// Default constructor.
cc_hash_table() { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the Hash_Fn object of the container object.
cc_hash_table(const hash_fn& h)
: base_type(h) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, and
/// r_eq_fn will be copied by the eq_fn object of the container
/// object.
cc_hash_table(const hash_fn& h, const eq_fn& e)
: base_type(h, e) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, r_eq_fn
/// will be copied by the eq_fn object of the container object,
/// and r_comb_hash_fn will be copied by the comb_hash_fn object
/// of the container object.
cc_hash_table(const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch)
: base_type(h, e, ch) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, r_eq_fn
/// will be copied by the eq_fn object of the container object,
/// r_comb_hash_fn will be copied by the comb_hash_fn object of
/// the container object, and r_resize_policy will be copied by
/// the resize_policy object of the container object.
cc_hash_table(const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch,
const resize_policy& rp)
: base_type(h, e, ch, rp) { }
/// Constructor taking __iterators to a range of value_types. The
/// value_types between first_it and last_it will be inserted into
/// the container object.
template<typename It>
cc_hash_table(It first, It last)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object.
template<typename It>
cc_hash_table(It first, It last, const hash_fn& h)
: base_type(h)
{ this->copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// and r_eq_fn will be copied by the eq_fn object of the
/// container object.
template<typename It>
cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e)
: base_type(h, e)
{ this->copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// r_eq_fn will be copied by the eq_fn object of the container
/// object, and r_comb_hash_fn will be copied by the comb_hash_fn
/// object of the container object.
template<typename It>
cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e,
const comb_hash_fn& ch)
: base_type(h, e, ch)
{ this->copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// r_eq_fn will be copied by the eq_fn object of the container
/// object, r_comb_hash_fn will be copied by the comb_hash_fn
/// object of the container object, and r_resize_policy will be
/// copied by the resize_policy object of the container object.
template<typename It>
cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e,
const comb_hash_fn& ch, const resize_policy& rp)
: base_type(h, e, ch, rp)
{ this->copy_from_range(first, last); }
cc_hash_table(const cc_hash_table& other)
: base_type((const base_type&)other)
{ }
virtual
~cc_hash_table() { }
cc_hash_table&
operator=(const cc_hash_table& other)
{
if (this != &other)
{
cc_hash_table tmp(other);
swap(tmp);
}
return *this;
}
void
swap(cc_hash_table& other)
{ base_type::swap(other); }
};
#undef PB_DS_CC_HASH_BASE
#define PB_DS_GP_HASH_BASE \
basic_hash_table<Key, Mapped, Hash_Fn, Eq_Fn, Resize_Policy, Store_Hash, \
gp_hash_tag, \
typename __gnu_cxx::typelist::create2<Comb_Probe_Fn, Probe_Fn>::type, _Alloc>
/**
* A general-probing hash-based associative container.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Hash_Fn Hashing functor.
* @tparam Eq_Fn Equal functor.
* @tparam Comb_Probe_Fn Combining probe functor.
* If Hash_Fn is not null_type, then this
* is the ranged-probe functor; otherwise,
* this is the range-hashing functor.
* XXX See Design::Hash-Based Containers::Hash Policies.
* @tparam Probe_Fn Probe functor.
* @tparam Resize_Policy Resizes hash.
* @tparam Store_Hash Indicates whether the hash value
* will be stored along with each key.
* If Hash_Fn is null_type, then the
* container will not compile if this
* value is true
* @tparam _Alloc Allocator type.
*
* Base tag choices are: gp_hash_tag.
*
* Base is basic_hash_table.
*/
template<typename Key,
typename Mapped,
typename Hash_Fn = typename detail::default_hash_fn<Key>::type,
typename Eq_Fn = typename detail::default_eq_fn<Key>::type,
typename Comb_Probe_Fn = detail::default_comb_hash_fn::type,
typename Probe_Fn = typename detail::default_probe_fn<Comb_Probe_Fn>::type,
typename Resize_Policy = typename detail::default_resize_policy<Comb_Probe_Fn>::type,
bool Store_Hash = detail::default_store_hash,
typename _Alloc = std::allocator<char> >
class gp_hash_table : public PB_DS_GP_HASH_BASE
{
private:
typedef PB_DS_GP_HASH_BASE base_type;
public:
typedef gp_hash_tag container_category;
typedef Hash_Fn hash_fn;
typedef Eq_Fn eq_fn;
typedef Comb_Probe_Fn comb_probe_fn;
typedef Probe_Fn probe_fn;
typedef Resize_Policy resize_policy;
/// Default constructor.
gp_hash_table() { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object.
gp_hash_table(const hash_fn& h)
: base_type(h) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, and
/// r_eq_fn will be copied by the eq_fn object of the container
/// object.
gp_hash_table(const hash_fn& h, const eq_fn& e)
: base_type(h, e) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, r_eq_fn
/// will be copied by the eq_fn object of the container object,
/// and r_comb_probe_fn will be copied by the comb_probe_fn object
/// of the container object.
gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp)
: base_type(h, e, cp) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, r_eq_fn
/// will be copied by the eq_fn object of the container object,
/// r_comb_probe_fn will be copied by the comb_probe_fn object of
/// the container object, and r_probe_fn will be copied by the
/// probe_fn object of the container object.
gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp,
const probe_fn& p)
: base_type(h, e, cp, p) { }
/// Constructor taking some policy objects. r_hash_fn will be
/// copied by the hash_fn object of the container object, r_eq_fn
/// will be copied by the eq_fn object of the container object,
/// r_comb_probe_fn will be copied by the comb_probe_fn object of
/// the container object, r_probe_fn will be copied by the
/// probe_fn object of the container object, and r_resize_policy
/// will be copied by the Resize_Policy object of the container
/// object.
gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp,
const probe_fn& p, const resize_policy& rp)
: base_type(h, e, cp, p, rp) { }
/// Constructor taking __iterators to a range of value_types. The
/// value_types between first_it and last_it will be inserted into
/// the container object.
template<typename It>
gp_hash_table(It first, It last)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object.
template<typename It>
gp_hash_table(It first, It last, const hash_fn& h)
: base_type(h)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// and r_eq_fn will be copied by the eq_fn object of the
/// container object.
template<typename It>
gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e)
: base_type(h, e)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// r_eq_fn will be copied by the eq_fn object of the container
/// object, and r_comb_probe_fn will be copied by the
/// comb_probe_fn object of the container object.
template<typename It>
gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e,
const comb_probe_fn& cp)
: base_type(h, e, cp)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// r_eq_fn will be copied by the eq_fn object of the container
/// object, r_comb_probe_fn will be copied by the comb_probe_fn
/// object of the container object, and r_probe_fn will be copied
/// by the probe_fn object of the container object.
template<typename It>
gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e,
const comb_probe_fn& cp, const probe_fn& p)
: base_type(h, e, cp, p)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object. r_hash_fn
/// will be copied by the hash_fn object of the container object,
/// r_eq_fn will be copied by the eq_fn object of the container
/// object, r_comb_probe_fn will be copied by the comb_probe_fn
/// object of the container object, r_probe_fn will be copied by
/// the probe_fn object of the container object, and
/// r_resize_policy will be copied by the resize_policy object of
/// the container object.
template<typename It>
gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e,
const comb_probe_fn& cp, const probe_fn& p,
const resize_policy& rp)
: base_type(h, e, cp, p, rp)
{ base_type::copy_from_range(first, last); }
gp_hash_table(const gp_hash_table& other)
: base_type((const base_type&)other)
{ }
virtual
~gp_hash_table() { }
gp_hash_table&
operator=(const gp_hash_table& other)
{
if (this != &other)
{
gp_hash_table tmp(other);
swap(tmp);
}
return *this;
}
void
swap(gp_hash_table& other)
{ base_type::swap(other); }
};
//@} hash-based
#undef PB_DS_GP_HASH_BASE
/**
* @defgroup branch-based Branch-Based
* @ingroup containers-pbds
* @{
*/
#define PB_DS_BRANCH_BASE \
detail::container_base_dispatch<Key, Mapped, _Alloc, Tag, Policy_Tl>::type
/**
* @defgroup branch-detail Base and Policy Classes
* @ingroup branch-based
*/
/**
* A branched, tree-like (tree, trie) container abstraction.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Tag Instantiating data structure type,
* see container_tag.
* @tparam Node_Update Updates nodes, restores invariants.
* @tparam Policy_TL Policy typelist.
* @tparam _Alloc Allocator type.
*
* Base is dispatched at compile time via Tag, from the following
* choices: tree_tag, trie_tag, and their descendants.
*
* Base choices are: detail::ov_tree_map, detail::rb_tree_map,
* detail::splay_tree_map, and detail::pat_trie_map.
*/
template<typename Key, typename Mapped, typename Tag,
typename Node_Update, typename Policy_Tl, typename _Alloc>
class basic_branch : public PB_DS_BRANCH_BASE
{
private:
typedef typename PB_DS_BRANCH_BASE base_type;
public:
typedef Node_Update node_update;
virtual
~basic_branch() { }
protected:
basic_branch() { }
basic_branch(const basic_branch& other)
: base_type((const base_type&)other) { }
template<typename T0>
basic_branch(T0 t0) : base_type(t0) { }
template<typename T0, typename T1>
basic_branch(T0 t0, T1 t1) : base_type(t0, t1) { }
template<typename T0, typename T1, typename T2>
basic_branch(T0 t0, T1 t1, T2 t2) : base_type(t0, t1, t2) { }
template<typename T0, typename T1, typename T2, typename T3>
basic_branch(T0 t0, T1 t1, T2 t2, T3 t3)
: base_type(t0, t1, t2, t3) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4>
basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4)
: base_type(t0, t1, t2, t3, t4) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5>
basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
: base_type(t0, t1, t2, t3, t4, t5) { }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
: base_type(t0, t1, t2, t3, t4, t5, t6) { }
};
#undef PB_DS_BRANCH_BASE
#define PB_DS_TREE_NODE_AND_IT_TRAITS \
detail::tree_traits<Key, Mapped,Cmp_Fn,Node_Update,Tag,_Alloc>
#define PB_DS_TREE_BASE \
basic_branch<Key,Mapped, Tag, \
typename PB_DS_TREE_NODE_AND_IT_TRAITS::node_update, \
typename __gnu_cxx::typelist::create2<Cmp_Fn, \
PB_DS_TREE_NODE_AND_IT_TRAITS>::type, _Alloc>
/**
* A tree-based container.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Cmp_Fn Comparison functor.
* @tparam Tag Instantiating data structure type,
* see container_tag.
* @tparam Node_Update Updates tree internal-nodes,
* restores invariants when invalidated.
* XXX See design::tree-based-containers::node invariants.
* @tparam _Alloc Allocator type.
*
* Base tag choices are: ov_tree_tag, rb_tree_tag, splay_tree_tag.
*
* Base is basic_branch.
*/
template<typename Key, typename Mapped, typename Cmp_Fn = std::less<Key>,
typename Tag = rb_tree_tag,
template<typename Node_CItr, typename Node_Itr,
typename Cmp_Fn_, typename _Alloc_>
class Node_Update = null_node_update,
typename _Alloc = std::allocator<char> >
class tree : public PB_DS_TREE_BASE
{
private:
typedef PB_DS_TREE_BASE base_type;
public:
/// Comparison functor type.
typedef Cmp_Fn cmp_fn;
tree() { }
/// Constructor taking some policy objects. r_cmp_fn will be
/// copied by the Cmp_Fn object of the container object.
tree(const cmp_fn& c)
: base_type(c) { }
/// Constructor taking __iterators to a range of value_types. The
/// value_types between first_it and last_it will be inserted into
/// the container object.
template<typename It>
tree(It first, It last)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects The value_types between first_it and
/// last_it will be inserted into the container object. r_cmp_fn
/// will be copied by the cmp_fn object of the container object.
template<typename It>
tree(It first, It last, const cmp_fn& c)
: base_type(c)
{ base_type::copy_from_range(first, last); }
tree(const tree& other)
: base_type((const base_type&)other) { }
virtual
~tree() { }
tree&
operator=(const tree& other)
{
if (this != &other)
{
tree tmp(other);
swap(tmp);
}
return *this;
}
void
swap(tree& other)
{ base_type::swap(other); }
};
#undef PB_DS_TREE_BASE
#undef PB_DS_TREE_NODE_AND_IT_TRAITS
#define PB_DS_TRIE_NODE_AND_IT_TRAITS \
detail::trie_traits<Key,Mapped,_ATraits,Node_Update,Tag,_Alloc>
#define PB_DS_TRIE_BASE \
basic_branch<Key,Mapped,Tag, \
typename PB_DS_TRIE_NODE_AND_IT_TRAITS::node_update, \
typename __gnu_cxx::typelist::create2<_ATraits, \
PB_DS_TRIE_NODE_AND_IT_TRAITS >::type, _Alloc>
/**
* A trie-based container.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam _ATraits Element access traits.
* @tparam Tag Instantiating data structure type,
* see container_tag.
* @tparam Node_Update Updates trie internal-nodes,
* restores invariants when invalidated.
* XXX See design::tree-based-containers::node invariants.
* @tparam _Alloc Allocator type.
*
* Base tag choice is pat_trie_tag.
*
* Base is basic_branch.
*/
template<typename Key,
typename Mapped,
typename _ATraits = \
typename detail::default_trie_access_traits<Key>::type,
typename Tag = pat_trie_tag,
template<typename Node_CItr,
typename Node_Itr,
typename _ATraits_,
typename _Alloc_>
class Node_Update = null_node_update,
typename _Alloc = std::allocator<char> >
class trie : public PB_DS_TRIE_BASE
{
private:
typedef PB_DS_TRIE_BASE base_type;
public:
/// Element access traits type.
typedef _ATraits access_traits;
trie() { }
/// Constructor taking some policy objects. r_access_traits will
/// be copied by the _ATraits object of the container object.
trie(const access_traits& t)
: base_type(t) { }
/// Constructor taking __iterators to a range of value_types. The
/// value_types between first_it and last_it will be inserted into
/// the container object.
template<typename It>
trie(It first, It last)
{ base_type::copy_from_range(first, last); }
/// Constructor taking __iterators to a range of value_types and
/// some policy objects. The value_types between first_it and
/// last_it will be inserted into the container object.
template<typename It>
trie(It first, It last, const access_traits& t)
: base_type(t)
{ base_type::copy_from_range(first, last); }
trie(const trie& other)
: base_type((const base_type&)other) { }
virtual
~trie() { }
trie&
operator=(const trie& other)
{
if (this != &other)
{
trie tmp(other);
swap(tmp);
}
return *this;
}
void
swap(trie& other)
{ base_type::swap(other); }
};
//@} branch-based
#undef PB_DS_TRIE_BASE
#undef PB_DS_TRIE_NODE_AND_IT_TRAITS
/**
* @defgroup list-based List-Based
* @ingroup containers-pbds
* @{
*/
#define PB_DS_LU_BASE \
detail::container_base_dispatch<Key, Mapped, _Alloc, list_update_tag, \
typename __gnu_cxx::typelist::create2<Eq_Fn, Update_Policy>::type>::type
/**
* A list-update based associative container.
*
* @tparam Key Key type.
* @tparam Mapped Map type.
* @tparam Eq_Fn Equal functor.
* @tparam Update_Policy Update policy, determines when an element
* will be moved to the front of the list.
* @tparam _Alloc Allocator type.
*
* Base is detail::lu_map.
*/
template<typename Key,
typename Mapped,
class Eq_Fn = typename detail::default_eq_fn<Key>::type,
class Update_Policy = detail::default_update_policy::type,
class _Alloc = std::allocator<char> >
class list_update : public PB_DS_LU_BASE
{
private:
typedef typename PB_DS_LU_BASE base_type;
public:
typedef list_update_tag container_category;
typedef Eq_Fn eq_fn;
typedef Update_Policy update_policy;
list_update() { }
/// Constructor taking __iterators to a range of value_types. The
/// value_types between first_it and last_it will be inserted into
/// the container object.
template<typename It>
list_update(It first, It last)
{ base_type::copy_from_range(first, last); }
list_update(const list_update& other)
: base_type((const base_type&)other) { }
virtual
~list_update() { }
list_update&
operator=(const list_update& other)
{
if (this !=& other)
{
list_update tmp(other);
swap(tmp);
}
return *this;
}
void
swap(list_update& other)
{ base_type::swap(other); }
};
//@} list-based
#undef PB_DS_LU_BASE
// @} group containers-pbds
} // namespace __gnu_pbds
#endif
| 34.930394
| 89
| 0.667486
|
Bhuvanesh1208
|
61069d1b0599f2ea9c0bab435f67b9c5edec5860
| 1,215
|
cpp
|
C++
|
test/scene_tree/test_stree.cpp
|
samkellett/g2
|
99e0598fd5c85fd329a5d820f99563e7d39b65d3
|
[
"MIT"
] | 1
|
2015-12-15T15:03:14.000Z
|
2015-12-15T15:03:14.000Z
|
test/scene_tree/test_stree.cpp
|
samkellett/g2
|
99e0598fd5c85fd329a5d820f99563e7d39b65d3
|
[
"MIT"
] | 1
|
2015-10-23T20:20:23.000Z
|
2015-10-23T20:20:23.000Z
|
test/scene_tree/test_stree.cpp
|
samkellett/g2
|
99e0598fd5c85fd329a5d820f99563e7d39b65d3
|
[
"MIT"
] | null | null | null |
#include "scene_tree/stree.hpp"
#include <gtest/gtest.h>
using namespace g2;
using testing::Test;
struct Fixture : public Test
{
scene_tree::stree uut;
const scene_tree::stree &const_uut;
Fixture()
: uut("badger", 640, 480),
const_uut(uut)
{
}
};
TEST_F(Fixture, TitleIsCorrect)
{
ASSERT_EQ("badger", uut.title());
}
TEST_F(Fixture, ConstTitleIsCorrect)
{
ASSERT_EQ("badger", const_uut.title());
}
TEST_F(Fixture, TitleModified)
{
uut.title() = "fox";
ASSERT_EQ("fox", uut.title());
}
TEST_F(Fixture, WidthIsCorrect)
{
ASSERT_EQ(640, uut.width());
}
TEST_F(Fixture, ConstWidthIsCorrect)
{
ASSERT_EQ(640, const_uut.width());
}
TEST_F(Fixture, HeightIsCorrect)
{
ASSERT_EQ(480, uut.height());
}
TEST_F(Fixture, ConstHeightIsCorrect)
{
ASSERT_EQ(480, const_uut.height());
}
TEST_F(Fixture, Equality_Matches)
{
ASSERT_EQ(scene_tree::stree("badger", 640, 480), uut);
}
TEST_F(Fixture, DifferentTitle_DoesntMatch)
{
ASSERT_NE(scene_tree::stree("fox", 640, 480), uut);
}
TEST_F(Fixture, DifferentWidth_DoesntMatch)
{
ASSERT_NE(scene_tree::stree("badger", 42, 480), uut);
}
TEST_F(Fixture, DifferentHeight_DoesntMatch)
{
ASSERT_NE(scene_tree::stree("badger", 640, 42), uut);
}
| 15.779221
| 55
| 0.706996
|
samkellett
|
610ba6c60f739ed079fe62c40a790d793697a46c
| 854
|
cpp
|
C++
|
Experiment 8.cpp
|
Pr33datorrr/DS-Practical-File
|
a5f3e60f59bb768b28b916e036ef936f20f4618c
|
[
"Apache-2.0"
] | null | null | null |
Experiment 8.cpp
|
Pr33datorrr/DS-Practical-File
|
a5f3e60f59bb768b28b916e036ef936f20f4618c
|
[
"Apache-2.0"
] | null | null | null |
Experiment 8.cpp
|
Pr33datorrr/DS-Practical-File
|
a5f3e60f59bb768b28b916e036ef936f20f4618c
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
void insertionsort(int ar[],int n)
{
int i,j,k,temp,m;
for(i=0;i<n;i++)
{
m=ar[i];
j=i;
while(ar[j-1]>m && j>0)
{
ar[j]=ar[j-1];
j--;
}
ar[j]=m;
}
}
int main()
{
int i,ar[20],n,item;;
cout<<"Enter no of elements";
cin>>n;
for(i=0;i<n;i++)
{
cin>>ar[i];
}
insertionsort(ar,n);
for(i=0;i<n;i++)
{
cout<<ar[i]<<" ";
}
cout<<"\nEnter new value to be inserted : ";
cin>>item;
i = n-1;
while(item<ar[i] && i>=0)
{
ar[i+1]=ar[i];
i--;
}
ar[i+1]=item;
n++;
cout<<"\nAfter insertion array is :\n";
for(i=0;i<n;i++)
{
cout<<ar[i]<<" ";
}
}
| 16.745098
| 49
| 0.362998
|
Pr33datorrr
|
610cbf57f73e65f49b9467358031751fdcc7b6d1
| 2,573
|
cc
|
C++
|
src/orbit/RFCavities/Dual_Harmonic_Cav.cc
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 17
|
2018-02-09T23:39:06.000Z
|
2022-03-04T16:27:04.000Z
|
src/orbit/RFCavities/Dual_Harmonic_Cav.cc
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 22
|
2017-05-31T19:40:14.000Z
|
2021-09-24T22:07:47.000Z
|
src/orbit/RFCavities/Dual_Harmonic_Cav.cc
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 37
|
2016-12-08T19:39:35.000Z
|
2022-02-11T19:59:34.000Z
|
#include "Dual_Harmonic_Cav.hh"
#include "ParticleMacroSize.hh"
#include <iostream>
#include <cmath>
#include "Bunch.hh"
#include "OrbitConst.hh"
using namespace OrbitUtils;
// Constructor
Dual_Harmonic_Cav::Dual_Harmonic_Cav(double ZtoPhi ,
double RFHNum ,
double RatioRFHNum,
double RFVoltage,
double RatioVoltage,
double RFPhase,
double RFPhase2): CppPyWrapper(NULL)
{
_ZtoPhi = ZtoPhi;
_RFHNum = RFHNum;
_RatioRFHNum = RatioRFHNum;
_RFVoltage = RFVoltage;
_RatioVoltage = RatioVoltage;
_RFPhase = RFPhase;
_RFPhase2 = RFPhase2;
}
// Destructor
Dual_Harmonic_Cav::~Dual_Harmonic_Cav()
{
}
void Dual_Harmonic_Cav::setZtoPhi(double ZtoPhi)
{
_ZtoPhi = ZtoPhi;
}
double Dual_Harmonic_Cav::getZtoPhi()
{
return _ZtoPhi;
}
void Dual_Harmonic_Cav::setRatioRFHNum(double RatioRFHNum)
{
_RatioRFHNum = RatioRFHNum;
}
double Dual_Harmonic_Cav::getRatioRFHNum()
{
return _RatioRFHNum;
}
void Dual_Harmonic_Cav::setRFHNum(double RFHNum)
{
_RFHNum = RFHNum;
}
double Dual_Harmonic_Cav::getRFHNum()
{
return _RFHNum;
}
void Dual_Harmonic_Cav::setRFVoltage(double RFVoltage)
{
_RFVoltage = RFVoltage;
}
double Dual_Harmonic_Cav::getRFVoltage()
{
return _RFVoltage;
}
void Dual_Harmonic_Cav::setRatioVoltage(double RatioVoltage)
{
_RatioVoltage = RatioVoltage;
}
double Dual_Harmonic_Cav::getRatioVoltage()
{
return _RatioVoltage;
}
void Dual_Harmonic_Cav::setRFPhase(double RFPhase)
{
_RFPhase = RFPhase;
}
double Dual_Harmonic_Cav::getRFPhase()
{
return _RFPhase;
}
void Dual_Harmonic_Cav::setRFPhase2(double RFPhase2)
{
_RFPhase2 = RFPhase2;
}
double Dual_Harmonic_Cav::getRFPhase2()
{
return _RFPhase2;
}
void Dual_Harmonic_Cav::trackBunch(Bunch* bunch)
{
double ZtoPhi = _ZtoPhi;
double RFHNum = _RFHNum;
double RatioRFHNum = _RatioRFHNum;
double RFVoltage = _RFVoltage;
double RatioVoltage = _RatioVoltage;
double RFPhase = OrbitConst::PI * _RFPhase / 180.0;
double RFPhase2 = OrbitConst::PI * _RFPhase2 / 180.0;
double dERF, phase;
bunch->compress();
SyncPart* syncPart = bunch->getSyncPart();
double** arr = bunch->coordArr();
for(int i = 0; i < bunch->getSize(); i++)
{
phase = -ZtoPhi * arr[i][4] * RFHNum ;
dERF = bunch->getCharge()* RFVoltage * (sin(phase) - sin(RFPhase) - RatioVoltage * ( sin(RFPhase + RatioRFHNum * (phase - RFPhase)) - sin(RFPhase2) ));
arr[i][5] += dERF;
}
}
| 19.492424
| 155
| 0.678197
|
LeoRya
|
610cc30296ba60167615440ae075f7d3014a5d0b
| 2,612
|
cpp
|
C++
|
game/roydWalkingState.cpp
|
theepsi/simpsons-arcade
|
26f716a2aed6a914a799adb00c6cf02e60aab1da
|
[
"MIT"
] | 1
|
2017-01-04T16:00:15.000Z
|
2017-01-04T16:00:15.000Z
|
game/roydWalkingState.cpp
|
theepsi/simpsons-arcade
|
26f716a2aed6a914a799adb00c6cf02e60aab1da
|
[
"MIT"
] | 15
|
2016-12-28T18:27:27.000Z
|
2017-02-17T09:47:52.000Z
|
game/roydWalkingState.cpp
|
theepsi/simpsons-arcade
|
26f716a2aed6a914a799adb00c6cf02e60aab1da
|
[
"MIT"
] | 1
|
2019-09-13T09:55:07.000Z
|
2019-09-13T09:55:07.000Z
|
#include "core.h"
#include "royd.h"
#include "player.h"
#include "enemy.h"
#include "roydIdleState.h"
#include "roydWalkingState.h"
using namespace std;
RoydWalkingState::RoydWalkingState()
{
}
RoydWalkingState::~RoydWalkingState()
{
}
void RoydWalkingState::Update(Character& player)
{
Enemy* enemy = static_cast<Enemy*>(&player);
Player* enemy_objective = enemy->objective;
enemy->attacking = false;
if (!enemy->after_attack) {
if (enemy->position.x < enemy_objective->position.x + MIN_DISTANCE &&
enemy->position.x > enemy_objective->position.x - MIN_DISTANCE) {
if (enemy->flipped)
enemy->position.x -= (int)enemy->speed;
else
enemy->position.x += (int)enemy->speed;
}
else {
if (enemy->position.x >= enemy_objective->position.x) {
if (enemy->position.x == enemy_objective->position.x + MIN_DISTANCE) {
if (enemy->position.z == enemy_objective->position.z)
enemy->ChangeState(new RoydIdleState, "idle");
}
else {
enemy->flipped = true;
enemy->position.x -= (int)enemy->speed;
}
}
else if (enemy->position.x <= enemy_objective->position.x) {
if (enemy->position.x == enemy_objective->position.x - MIN_DISTANCE) {
if (enemy->position.z == enemy_objective->position.z)
enemy->ChangeState(new RoydIdleState, "idle");
}
else {
enemy->flipped = false;
enemy->position.x += (int)enemy->speed;
}
}
}
if (enemy->position.z > enemy_objective->position.z) {
if (enemy->CheckCurrentAnimation("walking") || enemy->CheckCurrentAnimation("walking_down"))
enemy->SetCurrentAnimation("walking_up");
enemy->position.z -= (int)enemy->speed;
}
if (enemy->position.z < enemy_objective->position.z) {
if (enemy->CheckCurrentAnimation("walking_up") || enemy->CheckCurrentAnimation("walking"))
enemy->SetCurrentAnimation("walking_down");
enemy->position.z += (int)enemy->speed;
}
if (enemy->position.z == enemy_objective->position.z) {
if (enemy->CheckCurrentAnimation("walking_up") || enemy->CheckCurrentAnimation("walking_down"))
enemy->SetCurrentAnimation("walking");
}
}
else {
if (enemy->random_moves_counter <= enemy->random_moves) {
//Do random movements
if (enemy->position.x > enemy_objective->position.x) {
enemy->flipped = false;
enemy->position.x += (int)enemy->speed;
}
else if (enemy->position.x < enemy_objective->position.x) {
enemy->flipped = true;
enemy->position.x -= (int)enemy->speed;
}
++enemy->random_moves_counter;
}
else {
enemy->random_moves_counter = 0;
enemy->after_attack = false;
}
}
}
| 28.703297
| 98
| 0.667688
|
theepsi
|
610d0bdd53fd948743ef66c4b155d6e2ed4c3da6
| 678
|
hpp
|
C++
|
library/ATF/_QUEST_CASH.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/_QUEST_CASH.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/_QUEST_CASH.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
#pragma pack(push, 4)
struct _QUEST_CASH
{
unsigned int dwAvatorSerial;
char byQuestType;
int nPvpPoint;
unsigned __int16 wKillPoint;
unsigned __int16 wDiePoint;
char byCristalBattleDBInfo;
char byHSKTime;
public:
_QUEST_CASH();
void ctor__QUEST_CASH();
void init();
bool isload();
};
#pragma pack(pop)
static_assert(ATF::checkSize<_QUEST_CASH, 20>(), "_QUEST_CASH");
END_ATF_NAMESPACE
| 25.111111
| 108
| 0.647493
|
lemkova
|
610d2ea418d14532463cf87a2a95dd6c1e6ea3df
| 168
|
cpp
|
C++
|
docs/mfc/codesnippet/CPP/exceptions-changes-to-exception-macros-in-version-3-0_4.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/mfc/codesnippet/CPP/exceptions-changes-to-exception-macros-in-version-3-0_4.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/mfc/codesnippet/CPP/exceptions-changes-to-exception-macros-in-version-3-0_4.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
TRY
{
// Do something to throw an exception.
AfxThrowUserException();
}
CATCH(CException, e)
{
THROW(e); // Wrong. Use THROW_LAST() instead
}
END_CATCH
}
| 15.272727
| 50
| 0.64881
|
bobbrow
|
610e8dc7e559b2708faf04f58935bee62dad72f7
| 2,251
|
cpp
|
C++
|
vm/native_libraries.cpp
|
larrytheliquid/rubinius
|
5af42280ab95626f33517ca5f6330e17be04ec64
|
[
"BSD-3-Clause"
] | 1
|
2016-05-09T10:45:38.000Z
|
2016-05-09T10:45:38.000Z
|
vm/native_libraries.cpp
|
samleb/rubinius
|
38eec1983b9b6739d7a552081e208aa433b99483
|
[
"BSD-3-Clause"
] | 1
|
2022-03-12T14:09:00.000Z
|
2022-03-12T14:09:00.000Z
|
vm/native_libraries.cpp
|
isabella232/rubinius
|
5af42280ab95626f33517ca5f6330e17be04ec64
|
[
"BSD-3-Clause"
] | 1
|
2022-03-12T12:08:44.000Z
|
2022-03-12T12:08:44.000Z
|
#include <string>
#include "builtin/exception.hpp"
#include "builtin/module.hpp"
#include "builtin/string.hpp"
#include "vm.hpp"
#include "native_libraries.hpp"
#include "vm/object_utils.hpp"
namespace rubinius {
void VM::init_native_libraries() {
globals.rubinius.get()->set_const(this, "LIBSUFFIX", String::create(this, RBX_LIBSUFFIX));
rbx_dlinit();
}
// @todo Fix this. There should be a single interface to getting a symbol.
// FFI expects to be able to search several libraries and fail to bind a
// symbol, handling the ultimate failure itself. NativeMethod (subtend)
// expects to fail if unable to bind and searches only the current process.
// When is there ever a need to open a library without binding a symbol?
// Also, rbx_dldefault returns different values on different systems.
void* NativeLibrary::find_symbol(STATE, String* name, Object* library_name, bool raise) {
rbx_dlhandle library = NativeLibrary::open(state, library_name, raise);
void* symbol = rbx_dlsym(library, name->c_str());
if(rbx_dlnosuch(symbol)) {
if(raise) {
std::string message("NativeLibrary::load_symbol(): ");
Exception::system_call_error(state, message + rbx_dlerror());
} else {
return NULL;
}
}
return symbol;
}
rbx_dlhandle NativeLibrary::open(STATE, Object* name, bool raise) {
if (name->nil_p()) {
return NativeLibrary::use_this_process();
}
/* We should always get path without file extension. */
std::string path(as<String>(name)->c_str());
std::ostringstream error_message("NativeLibrary::open(): ");
rbx_dlhandle library = rbx_dlopen((path + RBX_LIBSUFFIX).c_str());
#ifdef RBX_LIBSUFFIX2
if(rbx_dlnosuch(library)) {
error_message << rbx_dlerror() << "; ";
library = rbx_dlopen((path + RBX_LIBSUFFIX2).c_str());
}
#endif
if(rbx_dlnosuch(library)) {
if(raise) {
error_message << rbx_dlerror();
Exception::system_call_error(state, error_message.str());
} else {
return NULL;
}
}
return library;
}
rbx_dlhandle NativeLibrary::use_this_process() {
static rbx_dlhandle self = rbx_dldefault();
return self;
}
}
| 27.790123
| 94
| 0.667703
|
larrytheliquid
|
6111a8f73dd93079b7812474296829519950b2a2
| 1,162
|
hpp
|
C++
|
src/region.hpp
|
eldariont/vg
|
aa394a8477eb3f27ccfe421457e2e013e7907493
|
[
"BSL-1.0"
] | null | null | null |
src/region.hpp
|
eldariont/vg
|
aa394a8477eb3f27ccfe421457e2e013e7907493
|
[
"BSL-1.0"
] | null | null | null |
src/region.hpp
|
eldariont/vg
|
aa394a8477eb3f27ccfe421457e2e013e7907493
|
[
"BSL-1.0"
] | null | null | null |
#ifndef VG_REGION_HPP_INCLUDED
#define VG_REGION_HPP_INCLUDED
#include <string>
#include <vector>
#include <sstream>
#include "xg.hpp"
namespace vg {
using namespace std;
// Represent a parsed genomic region.
// A -1 for start or end indicates that that coordinate is not used.
// Generally regions parsed form user input will be 1-based.
struct Region {
string seq;
int64_t start;
int64_t end;
};
// Parse a genomic contig[:start-end] region. Outputs -1 for missing start or end.
void parse_region(const string& target, string& name, int64_t& start, int64_t& end);
// Parse a genomic contig[:start-end] region. Outputs -1 for missing start or end.
inline void parse_region(string& region,
Region& out_region) {
parse_region(region,
out_region.seq,
out_region.start,
out_region.end);
}
// parse a bed file and return a list of regions (like above)
// IMPORTANT: expects usual 0-based BED format.
// So bedline "chr1 5 10" will return start=5 stop=9
void parse_bed_regions(
const string& bed_path,
vector<Region>& out_regions);
}
#endif
| 25.822222
| 84
| 0.678141
|
eldariont
|
611998fe0894ddc8da3fc6e6512a7208a7fa3b8b
| 7,171
|
cpp
|
C++
|
Dynamic Programming/943. Find the Shortest Superstring.cpp
|
beckswu/Leetcode
|
480e8dc276b1f65961166d66efa5497d7ff0bdfd
|
[
"MIT"
] | 138
|
2020-02-08T05:25:26.000Z
|
2021-11-04T11:59:28.000Z
|
Dynamic Programming/943. Find the Shortest Superstring.cpp
|
beckswu/Leetcode
|
480e8dc276b1f65961166d66efa5497d7ff0bdfd
|
[
"MIT"
] | null | null | null |
Dynamic Programming/943. Find the Shortest Superstring.cpp
|
beckswu/Leetcode
|
480e8dc276b1f65961166d66efa5497d7ff0bdfd
|
[
"MIT"
] | 24
|
2021-01-02T07:18:43.000Z
|
2022-03-20T08:17:54.000Z
|
/*
Travelling Salesman Problem
dp[val][i]: 走过的路径为val, 最后的到达的i所需要的最小cost
path[val][i]: 走过的路径为val, 最后的到达的i所需要的最小cost 的上一点
*/
class Solution {
public:
string shortestSuperstring(vector<string>& A) {
int n = A.size();
vector<vector<int>>graph(n, vector<int>(n));
for(int i = 0; i<n; ++i){
for(int j = 0; j<n; ++j){
graph[i][j] = calc(A[i], A[j]);
graph[j][i] = calc(A[j], A[i]);
}
}
vector<vector<int>>dp(1<<n, vector<int>(n,numeric_limits<int>::max()));
vector<vector<int>>path(1<<n, vector<int>(n));
int minv = numeric_limits<int>::max();
int last = -1;
for(int i = 1; i<(1<<n);++i){
for(int j = 0; j<n; ++j){
if(i & (1<<j)){
int prev = i - (1<<j);
if(prev == 0)
{
dp[i][j] = A[j].size();
}
else{
for(int k = 0; k<n; ++k){
if(dp[prev][k]!= numeric_limits<int>::max() && dp[prev][k] + graph[k][j] < dp[i][j]){
dp[i][j] = dp[prev][k] + graph[k][j];
path[i][j] = k;
/*
比如 i = 3, j = 0
dp[3][0] = min(dp[2][0] + graph[0][0], dp[2][1] + graph[1][0]); //dp[2][0] = INTMAX
所以如果更新 dp[3][0] 只能是 dp[2][1] + graph[1][0], 0和1点都经过
*/
}
}
}
}
if(i == (1 << n)- 1 && dp[i][j] < minv){
minv = dp[i][j];
last = j;
}
}
}
string res = A[last];
int lastTwo = path[(1<<n)-1][last];
int val = (1<<n)-1 - (1<<last);
while(val){
int nlastTwo = A[lastTwo].size(), nlast = A[last].size();
res = A[lastTwo].substr(0, nlastTwo-(nlast-graph[lastTwo][last])) + res;
last = lastTwo;
int tmp = path[val][lastTwo];
val -= (1 << lastTwo);
lastTwo = tmp;
}
return res;
}
int calc(const string& A, const string&B){
int na = A.size(), nb = B.size();
for(int i = 1; i<A.size(); ++i){//从1开始,因为no string in A is substring of another string in A.
if(B.substr(0, na-i) == A.substr(i) ){
return nb - (na - i);
}
}
return nb;
}
};
class Solution {
public:
string shortestSuperstring(vector<string>& A) {
int n = A.size();
// dp[mask][i] : min superstring made by strings in mask,
// and the last one is A[i]
vector<vector<string>> dp(1<<n,vector<string>(n));
vector<vector<int>> overlap(n,vector<int>(n,0));
// 1. calculate overlap for A[i]+A[j].substr(?)
for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) if(i!=j){
for(int k = min(A[i].size(), A[j].size()); k>0; --k)
if(A[i].substr(A[i].size()-k)==A[j].substr(0,k)){
overlap[i][j] = k;
break;
}
}
// 2. set inital val for dp
for(int i=0; i<n; ++i) dp[1<<i][i] += A[i];
// 3. fill the dp
for(int mask=1; mask<(1<<n); ++mask){
for(int j=0; j<n; ++j) if((mask&(1<<j))>0){
for(int i=0; i<n; ++i) if(i!=j && (mask&(1<<i))>0){
string tmp = dp[mask^(1<<j)][i]+A[j].substr(overlap[i][j]);
if(dp[mask][j].empty() || tmp.size()<dp[mask][j].size())
dp[mask][j] = tmp;
}
}
}
// 4. get the result
int last = (1<<n)-1;
string res = dp[last][0];
for(int i=1; i<n; ++i) if(dp[last][i].size()<res.size()){
res = dp[last][i];
}
return res;
}
};
/*
Travelling Salesman Problem
dp[val][i]: 走过的路径为val, 最后的到达的i所需要的最小cost
path[val][i]: 走过的路径为val, 最后的到达的i所需要的最小cost 的上一点
*/
class Solution {
public:
string shortestSuperstring(vector<string>& A) {
int n = A.size();
vector<vector<int>> overlaps(n, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int m = min(A[i].size(), A[j].size());
for (int k = m; k >= 0; --k) {
if (A[i].substr(A[i].size() - k) == A[j].substr(0, k)) {
overlaps[i][j] = k;
break;
}
}
}
}
// dp[mask][i] = most overlap with mask, ending with ith element (ith 也包含在了mask里面)
vector<vector<int>> dp(1<<n, vector<int>(n, 0));
vector<vector<int>> parent(1<<n, vector<int>(n, -1));
for (int mask = 0; mask < (1<<n); ++mask) {
//以下循环是为了计算dp[mask][bit]
for (int bit = 0; bit < n; ++bit) {
if (((mask>>bit)&1) > 0) {//说明bit位在mask里面,此时dp[mask][bit]才有意义
int pmask = mask^(1<<bit);//这一步是为了把bit位从mask里面去掉
if (pmask == 0) continue;//如果mask里面只有一个词,那么跳过
for (int i = 0; i < n; ++i) {
if (((pmask>>i)&1) > 0) {//如果pmask里面包含了第i位,那么计算以i结尾的pmask,再接上bit位
int val = dp[pmask][i] + overlaps[i][bit];
/*
因为val 是取最大值,比如 ["alexb","loves","kosds"], overlap都是1,
从而parent, dp 都没有更新
*/
if (val > dp[mask][bit]) {//如果新算出来的overlap比较大,那么替换原有overlap
dp[mask][bit] = val;
parent[mask][bit] = i;//保存这种情况下以bit结尾的前一个词。
}
}
}
}
}
}
vector<int> perm;
vector<bool> seen(n);
int mask = (1<<n) - 1;
int p = 0;//先计算出答案的最后一个单词
for (int i = 0; i < n; ++i) {
if (dp[(1<<n) - 1][i] > dp[(1<<n) - 1][p]) {
p = i;
}
}
//通过parent数组依次回溯出最后一个单词是p这种情况下,前面所有的排列
while (p != -1) {
perm.push_back(p);
seen[p] = true;
int p2 = parent[mask][p];
mask ^= (1<<p);//从mask里面移走p
p = p2;
}
//由于回溯出来的是反的,倒一下
reverse(perm.begin(), perm.end());
//加上没有出现的单词
for (int i = 0; i < n; ++i) {
if (!seen[i]) {
perm.push_back(i);
}
}
string ans = A[perm[0]];
for (int i = 1; i < n; ++i) {
int overlap = overlaps[perm[i - 1]][perm[i]];
ans += A[perm[i]].substr(overlap);
}
return ans;
}
};
| 32.894495
| 115
| 0.375819
|
beckswu
|
6119f227acd33b0b3b34cec6eeeb6f9f93f0a5c1
| 4,467
|
hpp
|
C++
|
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/aligned_store.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 34
|
2017-05-19T18:10:17.000Z
|
2022-01-04T02:18:13.000Z
|
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/aligned_store.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/boost/simd/sdk/include/boost/simd/memory/functions/scalar/aligned_store.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 7
|
2017-12-02T12:59:17.000Z
|
2021-07-31T12:46:14.000Z
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
// Copyright 2011 - 2014 MetaScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_MEMORY_FUNCTIONS_SCALAR_ALIGNED_STORE_HPP_INCLUDED
#define BOOST_SIMD_MEMORY_FUNCTIONS_SCALAR_ALIGNED_STORE_HPP_INCLUDED
#include <boost/simd/memory/functions/aligned_store.hpp>
#include <boost/simd/memory/functions/scalar/store.hpp>
#include <boost/dispatch/functor/preprocessor/call.hpp>
#include <boost/simd/memory/iterator_category.hpp>
#include <boost/simd/sdk/functor/hierarchy.hpp>
#include <boost/dispatch/attributes.hpp>
#include <boost/dispatch/meta/mpl.hpp>
namespace boost { namespace simd { namespace ext
{
/// INTERNAL ONLY - masked Regular scalar store with offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)(A2)(A3)
, (unspecified_<A0>)
(iterator_< unspecified_<A1> >)
(scalar_< integer_<A2> >)
(scalar_< fundamental_<A3> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 a1, A2 a2, A3 const& a3) const
{
if (a3)
*(a1+a2) = a0;
}
};
/// INTERNAL ONLY - Regular scalar store with offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)(A2)
, (unspecified_<A0>)
(iterator_< unspecified_<A1> >)
(scalar_< integer_<A2> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 a1, A2 a2) const
{
*(a1+a2) = a0;
}
};
/// INTERNAL ONLY - mask Regular scalar store without offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)(A2)
, (unspecified_<A0>)
(iterator_< unspecified_<A1> >)
(scalar_< fundamental_<A2> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 a1, A2 const& a2) const
{
if (a2)
*a1 = a0;
}
};
/// INTERNAL ONLY - Regular scalar store without offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)
, (unspecified_<A0>)
(iterator_< unspecified_<A1> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 a1) const
{
*a1 = a0;
}
};
/// INTERNAL ONLY - Fusion sequence store with offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)(A2)
, (fusion_sequence_<A0>)
(fusion_sequence_<A1>)
(generic_< integer_<A2> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 const& a1, A2 a2) const
{
boost::simd::store(a0,a1,a2);
}
};
/// INTERNAL ONLY - Fusion sequence store without offset
BOOST_DISPATCH_IMPLEMENT ( aligned_store_, tag::cpu_
, (A0)(A1)
, (fusion_sequence_<A0>)
(fusion_sequence_<A1>)
)
{
typedef void result_type;
BOOST_FORCEINLINE result_type
operator()(A0 const& a0, A1 const& a1) const
{
boost::simd::store(a0,a1);
}
};
} } }
#endif
| 34.898438
| 80
| 0.478173
|
psiha
|
611f5caca5c1c3caba123f9ad30210b802f190f2
| 571
|
cpp
|
C++
|
tests/test1.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | 1
|
2020-10-26T02:45:22.000Z
|
2020-10-26T02:45:22.000Z
|
tests/test1.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | null | null | null |
tests/test1.cpp
|
chrisroman/llvm-pass-skeleton
|
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
|
[
"MIT"
] | null | null | null |
#include <stdlib.h> /* exit, EXIT_FAILURE */
#include "track_nullptr.h"
void foo(void *p) {
return;
}
// TODO:
// create a nullp
// call escale(rnullp)
// replace all instances of nullptr with nullp
void deref_null(int argc) {
//void *nullp = nullptr;
//escape(&nullp);
int *p = (int*) nullptr;
if (argc == 1) {
p = new int(5);
}
int *q = p;
if (argc == 2) {
q = new int(10);
}
foo(p);
foo(q);
//int *q = p;
//int x = *p;
}
int main(int argc, char **argv) {
deref_null(argc);
return 0;
}
| 17.30303
| 48
| 0.52014
|
chrisroman
|
6122ab3b23e22c49c9646a3c445f567e7ccd13a8
| 4,257
|
cpp
|
C++
|
gdal/frmts/nitf/nitfbilevel.cpp
|
dtusk/gdal1
|
30dcdc1eccbca2331674f6421f1c5013807da609
|
[
"MIT"
] | 3
|
2017-01-12T10:18:56.000Z
|
2020-03-21T16:42:55.000Z
|
gdal/frmts/nitf/nitfbilevel.cpp
|
ShinNoNoir/gdal-1.11.5-vs2015
|
5d544e176a4c11f9bcd12a0fe66f97fd157824e6
|
[
"MIT"
] | null | null | null |
gdal/frmts/nitf/nitfbilevel.cpp
|
ShinNoNoir/gdal-1.11.5-vs2015
|
5d544e176a4c11f9bcd12a0fe66f97fd157824e6
|
[
"MIT"
] | null | null | null |
/******************************************************************************
* $Id$
*
* Project: NITF Read/Write Library
* Purpose: Module implement BILEVEL (C1) compressed image reading.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
**********************************************************************
* Copyright (c) 2007, Frank Warmerdam
* Copyright (c) 2009, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "gdal.h"
#include "nitflib.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"
CPL_C_START
#include "tiffio.h"
CPL_C_END
TIFF* VSI_TIFFOpen(const char* name, const char* mode);
CPL_CVSID("$Id$");
/************************************************************************/
/* NITFUncompressBILEVEL() */
/************************************************************************/
int NITFUncompressBILEVEL( NITFImage *psImage,
GByte *pabyInputData, int nInputBytes,
GByte *pabyOutputImage )
{
int nOutputBytes= (psImage->nBlockWidth * psImage->nBlockHeight + 7)/8;
/* -------------------------------------------------------------------- */
/* Write memory TIFF with the bilevel data. */
/* -------------------------------------------------------------------- */
CPLString osFilename;
osFilename.Printf( "/vsimem/nitf-wrk-%ld.tif", (long) CPLGetPID() );
TIFF *hTIFF = VSI_TIFFOpen( osFilename, "w+" );
if (hTIFF == NULL)
{
return FALSE;
}
TIFFSetField( hTIFF, TIFFTAG_IMAGEWIDTH, psImage->nBlockWidth );
TIFFSetField( hTIFF, TIFFTAG_IMAGELENGTH, psImage->nBlockHeight );
TIFFSetField( hTIFF, TIFFTAG_BITSPERSAMPLE, 1 );
TIFFSetField( hTIFF, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT );
TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG );
TIFFSetField( hTIFF, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB );
TIFFSetField( hTIFF, TIFFTAG_ROWSPERSTRIP, psImage->nBlockHeight );
TIFFSetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL, 1 );
TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK );
TIFFSetField( hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX3 );
if( psImage->szCOMRAT[0] == '2' )
TIFFSetField( hTIFF, TIFFTAG_GROUP3OPTIONS, GROUP3OPT_2DENCODING );
TIFFWriteRawStrip( hTIFF, 0, pabyInputData, nInputBytes );
TIFFWriteDirectory( hTIFF );
TIFFClose( hTIFF );
/* -------------------------------------------------------------------- */
/* Now open and read it back. */
/* -------------------------------------------------------------------- */
int bResult = TRUE;
hTIFF = VSI_TIFFOpen( osFilename, "r" );
if (hTIFF == NULL)
{
return FALSE;
}
if( TIFFReadEncodedStrip( hTIFF, 0, pabyOutputImage, nOutputBytes ) == -1 )
{
memset( pabyOutputImage, 0, nOutputBytes );
bResult = FALSE;
}
TIFFClose( hTIFF );
VSIUnlink( osFilename );
return bResult;
}
| 37.672566
| 79
| 0.571294
|
dtusk
|
6123a23ea132e1dca89108f53c573f719945941b
| 340
|
cpp
|
C++
|
test/incrementalTest/taskexecutor.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 16
|
2019-05-23T08:10:39.000Z
|
2021-12-21T11:20:37.000Z
|
test/incrementalTest/taskexecutor.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | null | null | null |
test/incrementalTest/taskexecutor.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 2
|
2019-05-23T18:37:43.000Z
|
2021-08-24T21:29:40.000Z
|
#include "taskexecutor.h"
#include <QCoreApplication>
#include <QDebug>
#include "factory.h"
#include "task.h"
TaskExecutor::TaskExecutor()
{
}
void TaskExecutor::Exec()
{
qDebug() << Factory::Instance().GetTasks().keys();
for (Task *task : Factory::Instance().GetTasks())
{
task->Exec();
}
qApp->exit();
}
| 14.782609
| 54
| 0.617647
|
JamesMBallard
|
6124788fc0796d3af47371f6248c4b272111f6d3
| 2,492
|
cpp
|
C++
|
src/generated/rpg_skill.cpp
|
TestGabu/liblcf
|
c4b58844ef10179910b92a7cfbf23ab593cc2ade
|
[
"MIT"
] | 1
|
2020-06-13T08:21:53.000Z
|
2020-06-13T08:21:53.000Z
|
src/generated/rpg_skill.cpp
|
TestGabu/liblcf
|
c4b58844ef10179910b92a7cfbf23ab593cc2ade
|
[
"MIT"
] | 8
|
2020-06-13T08:22:17.000Z
|
2022-03-02T00:56:44.000Z
|
src/generated/rpg_skill.cpp
|
TestGabu/liblcf
|
c4b58844ef10179910b92a7cfbf23ab593cc2ade
|
[
"MIT"
] | null | null | null |
/* !!!! GENERATED FILE - DO NOT EDIT !!!!
* --------------------------------------
*
* This file is part of liblcf. Copyright (c) 2020 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
// Headers
#include "lcf/rpg/skill.h"
namespace lcf {
namespace rpg {
std::ostream& operator<<(std::ostream& os, const Skill& obj) {
os << "Skill{";
os << "name="<< obj.name;
os << ", description="<< obj.description;
os << ", using_message1="<< obj.using_message1;
os << ", using_message2="<< obj.using_message2;
os << ", failure_message="<< obj.failure_message;
os << ", type="<< obj.type;
os << ", sp_type="<< obj.sp_type;
os << ", sp_percent="<< obj.sp_percent;
os << ", sp_cost="<< obj.sp_cost;
os << ", scope="<< obj.scope;
os << ", switch_id="<< obj.switch_id;
os << ", animation_id="<< obj.animation_id;
os << ", sound_effect="<< obj.sound_effect;
os << ", occasion_field="<< obj.occasion_field;
os << ", occasion_battle="<< obj.occasion_battle;
os << ", reverse_state_effect="<< obj.reverse_state_effect;
os << ", physical_rate="<< obj.physical_rate;
os << ", magical_rate="<< obj.magical_rate;
os << ", variance="<< obj.variance;
os << ", power="<< obj.power;
os << ", hit="<< obj.hit;
os << ", affect_hp="<< obj.affect_hp;
os << ", affect_sp="<< obj.affect_sp;
os << ", affect_attack="<< obj.affect_attack;
os << ", affect_defense="<< obj.affect_defense;
os << ", affect_spirit="<< obj.affect_spirit;
os << ", affect_agility="<< obj.affect_agility;
os << ", absorb_damage="<< obj.absorb_damage;
os << ", ignore_defense="<< obj.ignore_defense;
os << ", state_effects=";
for (size_t i = 0; i < obj.state_effects.size(); ++i) {
os << (i == 0 ? "[" : ", ") << obj.state_effects[i];
}
os << "]";
os << ", attribute_effects=";
for (size_t i = 0; i < obj.attribute_effects.size(); ++i) {
os << (i == 0 ? "[" : ", ") << obj.attribute_effects[i];
}
os << "]";
os << ", affect_attr_defence="<< obj.affect_attr_defence;
os << ", battler_animation="<< obj.battler_animation;
os << ", battler_animation_data=";
for (size_t i = 0; i < obj.battler_animation_data.size(); ++i) {
os << (i == 0 ? "[" : ", ") << obj.battler_animation_data[i];
}
os << "]";
os << "}";
return os;
}
} // namespace rpg
} // namespace lcf
| 34.136986
| 77
| 0.607143
|
TestGabu
|
61291c6337289c39a0f16036e033bfec3e31c400
| 25,726
|
cpp
|
C++
|
Firmware/graphics/fonts/LcdNova16px.cpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 39
|
2019-10-23T12:06:16.000Z
|
2022-01-26T04:28:29.000Z
|
Firmware/graphics/fonts/LcdNova16px.cpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 20
|
2020-03-21T20:21:46.000Z
|
2021-11-19T14:34:03.000Z
|
Firmware/graphics/fonts/LcdNova16px.cpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 7
|
2019-10-18T09:44:10.000Z
|
2021-06-11T13:05:16.000Z
|
/*******************************************************************************
* Size: 16 px
* Bpp: 2
* Opts:
******************************************************************************/
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#ifndef LCDNOVA16PX
#define LCDNOVA16PX 1
#endif
#if LCDNOVA16PX
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t glyph_bitmap[] = {
/* U+0020 " " */
/* U+0021 "!" */
0x21, 0xc7, 0x1c, 0x70, 0x82, 0x1c, 0x70, 0x83,
0x8,
/* U+0022 "\"" */
0x21, 0x9c, 0xb7, 0x2c, 0x86,
/* U+0023 "#" */
0x0, 0x4, 0x0, 0xa, 0x34, 0x0, 0x28, 0xd0,
0x0, 0xa3, 0x40, 0xbf, 0xfb, 0xf4, 0x5a, 0x75,
0x40, 0x28, 0xd0, 0x0, 0xa3, 0x40, 0xbf, 0xfb,
0xf4, 0x5a, 0x75, 0x40, 0x28, 0xd0, 0x0, 0xa3,
0x40, 0x1, 0x44, 0x0,
/* U+0024 "$" */
0x0, 0x80, 0x2, 0xc0, 0xf, 0xb8, 0x35, 0x1e,
0x70, 0xa, 0x70, 0x0, 0x70, 0x0, 0x1f, 0xf8,
0x5, 0x5a, 0x0, 0xe, 0x10, 0xe, 0x70, 0xe,
0x35, 0x1a, 0xf, 0xb8, 0x2, 0xc0, 0x0, 0x80,
/* U+0025 "%" */
0xf, 0xd0, 0x0, 0x3, 0x57, 0x40, 0x40, 0x70,
0x34, 0x2c, 0x7, 0x3, 0x4b, 0x40, 0x70, 0x36,
0xe0, 0x1, 0xfe, 0xbf, 0xf0, 0x5, 0x6f, 0xd5,
0xc0, 0xb, 0x6c, 0x1c, 0x2, 0xd2, 0xc1, 0xc0,
0x74, 0x2c, 0x1c, 0x1, 0x1, 0xd6, 0xc0, 0x0,
0xb, 0xf0,
/* U+0026 "&" */
0xf, 0xe0, 0x3, 0x54, 0x0, 0x70, 0x0, 0x7,
0x0, 0xa0, 0x70, 0xe, 0x1, 0xff, 0xfc, 0x35,
0x5a, 0x47, 0x0, 0xe0, 0x70, 0xe, 0x7, 0x0,
0xe0, 0x35, 0x5a, 0x0, 0xff, 0x80,
/* U+0027 "'" */
0x21, 0xc7, 0x8,
/* U+0028 "(" */
0xf, 0xd, 0x47, 0x1, 0xc0, 0x70, 0x8, 0x2,
0x1, 0xc0, 0x70, 0x1c, 0x3, 0x50, 0x3c,
/* U+0029 ")" */
0x3c, 0x6, 0xc0, 0x70, 0x1c, 0x7, 0x0, 0x80,
0x20, 0x1c, 0x7, 0x1, 0xc1, 0xb0, 0xf0,
/* U+002A "*" */
0x0, 0x0, 0x22, 0x24, 0x3c, 0xb0, 0x4f, 0xd4,
0x8a, 0xc8, 0x2d, 0xf0, 0x75, 0x34, 0x1, 0x0,
/* U+002B "+" */
0x0, 0x0, 0x0, 0xb0, 0x0, 0x2c, 0x0, 0xb,
0x0, 0xbf, 0xbf, 0x5, 0xb5, 0x0, 0x2c, 0x0,
0xb, 0x0, 0x0, 0x40, 0x0,
/* U+002C "," */
0x0, 0xc7, 0x0,
/* U+002D "-" */
0x0, 0xb, 0xfc, 0x15, 0x40,
/* U+002E "." */
0x21, 0xc1, 0x0,
/* U+002F "/" */
0x0, 0xa0, 0xd, 0x1, 0xc0, 0x38, 0x3, 0x0,
0xb0, 0xd, 0x1, 0xc0, 0x28, 0x3, 0x40, 0xb0,
0x9, 0x0,
/* U+0030 "0" */
0xf, 0xf8, 0x35, 0x7e, 0x70, 0x7e, 0x70, 0xbe,
0x70, 0xde, 0x21, 0xc9, 0x22, 0x89, 0x73, 0x4e,
0x7b, 0xe, 0x7e, 0xe, 0x3a, 0x5e, 0xf, 0xf8,
/* U+0031 "1" */
0xf, 0x80, 0x1, 0xb0, 0x0, 0x1c, 0x0, 0x7,
0x0, 0x1, 0xc0, 0x0, 0x60, 0x0, 0x18, 0x0,
0x7, 0x0, 0x1, 0xc0, 0x0, 0x70, 0x1, 0x6d,
0x51, 0xfd, 0xfc,
/* U+0032 "2" */
0xf, 0xf8, 0x5, 0x5e, 0x0, 0xe, 0x0, 0xe,
0x0, 0xe, 0x1f, 0xf8, 0x35, 0x50, 0x70, 0x0,
0x70, 0x0, 0x70, 0x0, 0x75, 0x54, 0x3f, 0xfd,
/* U+0033 "3" */
0x3f, 0xfd, 0x15, 0xb8, 0x0, 0xe0, 0x7, 0x80,
0xa, 0x0, 0xf, 0xf8, 0x5, 0x5a, 0x0, 0xe,
0x0, 0xe, 0x0, 0xe, 0x15, 0x5a, 0x3f, 0xf8,
/* U+0034 "4" */
0x0, 0xba, 0x2, 0xcb, 0xf, 0xb, 0x3c, 0xb,
0x30, 0xa, 0xbf, 0xfc, 0x15, 0x5a, 0x0, 0xb,
0x0, 0xb, 0x0, 0xb, 0x0, 0xb, 0x0, 0x0,
/* U+0035 "5" */
0x3f, 0xfc, 0x75, 0x50, 0x70, 0x0, 0x70, 0x0,
0x70, 0x0, 0x1f, 0xf8, 0x5, 0x5a, 0x0, 0xe,
0x0, 0xe, 0x0, 0xe, 0x15, 0x5a, 0x3f, 0xf8,
/* U+0036 "6" */
0xf, 0xf8, 0x35, 0x50, 0x70, 0x0, 0x70, 0x0,
0x70, 0x0, 0x1f, 0xf8, 0x35, 0x5a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0037 "7" */
0x3f, 0xfd, 0x15, 0x5e, 0x0, 0xe, 0x0, 0xe,
0x0, 0xe, 0x0, 0xb8, 0x2, 0xd0, 0x2, 0xc0,
0x2, 0xc0, 0x2, 0xc0, 0x2, 0xc0, 0x0, 0x0,
/* U+0038 "8" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0039 "9" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x5, 0x5a, 0x0, 0xe,
0x0, 0xe, 0x0, 0xe, 0x5, 0x5a, 0xf, 0xf8,
/* U+003A ":" */
0x0, 0xc3, 0x0, 0x0, 0x3, 0x8,
/* U+003B ";" */
0x0, 0xc3, 0x0, 0x0, 0x3, 0x1c, 0x0,
/* U+003C "<" */
0x0, 0x0, 0xe0, 0xf0, 0xb0, 0x2d, 0x2, 0xd0,
0x2c,
/* U+003D "=" */
0x0, 0x3, 0xfe, 0x5, 0x40, 0x0, 0x3f, 0xe0,
0x54,
/* U+003E ">" */
0x0, 0x1d, 0x2, 0xd0, 0x2d, 0xf, 0x4f, 0x47,
0x40,
/* U+003F "?" */
0xbf, 0xe0, 0x55, 0xa0, 0x2, 0xc0, 0xb, 0x0,
0x2c, 0x7, 0xc0, 0x74, 0x1, 0xc0, 0x3, 0x0,
0x8, 0x0, 0x70, 0x0, 0x40,
/* U+0040 "@" */
0xf, 0xfb, 0xff, 0xd, 0x54, 0x55, 0xb7, 0x0,
0x0, 0x2d, 0xc0, 0xbd, 0xb, 0x70, 0xa5, 0xc2,
0xc8, 0x28, 0x34, 0xb3, 0xa, 0xd, 0x2d, 0xc0,
0xbe, 0xfc, 0x70, 0x5, 0x4, 0x1c, 0x0, 0x0,
0x3, 0x55, 0x0, 0x0, 0x3f, 0xe0, 0x0,
/* U+0041 "A" */
0xf, 0xfe, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5e, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x10, 0x0,
/* U+0042 "B" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x75, 0x5a, 0x3f, 0xf8,
/* U+0043 "C" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0x4,
0x70, 0x0, 0x20, 0x0, 0x20, 0x0, 0x70, 0x0,
0x70, 0x4, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0044 "D" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x75, 0x5e, 0x3f, 0xf8,
/* U+0045 "E" */
0x3f, 0xf9, 0xd5, 0x47, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x7f, 0xe3, 0x55, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x55, 0xf, 0xfe,
/* U+0046 "F" */
0x3f, 0xf9, 0xd5, 0x47, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x7f, 0xe3, 0x55, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x0, 0x4, 0x0,
/* U+0047 "G" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xa, 0x70, 0x0,
0x70, 0x0, 0x20, 0xfe, 0x30, 0x1a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0048 "H" */
0x0, 0x0, 0x30, 0xa, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5e,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x10, 0x0,
/* U+0049 "I" */
0x3f, 0x7d, 0x16, 0xd4, 0x2, 0xc0, 0x2, 0xc0,
0x2, 0xc0, 0x1, 0x80, 0x1, 0x80, 0x2, 0xc0,
0x2, 0xc0, 0x2, 0xc0, 0x16, 0xd4, 0x3f, 0x7d,
/* U+004A "J" */
0x0, 0x9, 0x0, 0xe, 0x0, 0xe, 0x0, 0xe,
0x0, 0xe, 0x0, 0x5, 0x20, 0x5, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+004B "K" */
0x30, 0x1c, 0x70, 0x74, 0x71, 0xd0, 0x77, 0x40,
0x7a, 0x0, 0x1f, 0xf8, 0x35, 0x5e, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x10, 0x0,
/* U+004C "L" */
0x20, 0x1, 0xc0, 0x7, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x80, 0x2, 0x0, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x55, 0xf, 0xfe,
/* U+004D "M" */
0x10, 0x0, 0x11, 0xf8, 0x7, 0xd7, 0x74, 0x37,
0x5c, 0xb3, 0x8d, 0x70, 0xfc, 0x34, 0xc0, 0x90,
0xd2, 0x0, 0x1, 0x1c, 0x0, 0xd, 0x70, 0x0,
0x35, 0xc0, 0x0, 0xd7, 0x0, 0x3, 0x4c, 0x0,
0xd, 0x0, 0x0, 0x0,
/* U+004E "N" */
0x0, 0x0, 0x35, 0xa, 0x7b, 0xe, 0x73, 0xce,
0x70, 0xee, 0x70, 0x7e, 0x20, 0x5, 0x30, 0xa,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x10, 0x4,
/* U+004F "O" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0050 "P" */
0x3f, 0xf8, 0x75, 0x5a, 0x70, 0xb, 0x70, 0xb,
0x70, 0xb, 0x1f, 0xfc, 0x35, 0x50, 0x70, 0x0,
0x70, 0x0, 0x70, 0x0, 0x70, 0x0, 0x10, 0x0,
/* U+0051 "Q" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x71, 0xce, 0x36, 0xde, 0xf, 0xb8,
0x2, 0xc0, 0x1, 0xc0, 0x0, 0xb8, 0x0, 0x10,
/* U+0052 "R" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xf8, 0x3a, 0x50, 0x7b, 0x40,
0x72, 0xc0, 0x70, 0xf0, 0x70, 0x3c, 0x20, 0xd,
/* U+0053 "S" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xa, 0x70, 0x0,
0x70, 0x0, 0x1f, 0xf8, 0x5, 0x5a, 0x0, 0xe,
0x10, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0054 "T" */
0xbf, 0x7f, 0x85, 0xb5, 0x40, 0x1c, 0x0, 0x7,
0x0, 0x1, 0xc0, 0x0, 0x20, 0x0, 0x8, 0x0,
0x7, 0x0, 0x1, 0xc0, 0x0, 0x70, 0x0, 0x1c,
0x0, 0x2, 0x0,
/* U+0055 "U" */
0x20, 0x9, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0056 "V" */
0x20, 0x8, 0x70, 0xd, 0x70, 0xd, 0x70, 0xd,
0x70, 0xd, 0x20, 0xc, 0x20, 0x34, 0x70, 0xf0,
0x77, 0xc0, 0x7f, 0x0, 0x78, 0x0, 0x20, 0x0,
/* U+0057 "W" */
0x0, 0x0, 0x0, 0xc0, 0x0, 0xd7, 0x0, 0x3,
0x5c, 0x0, 0xd, 0x70, 0x0, 0x35, 0xc0, 0x0,
0xd2, 0x0, 0x1, 0xc, 0x9, 0xd, 0x70, 0xfc,
0x35, 0xcb, 0x38, 0xd7, 0x74, 0x37, 0x5f, 0x80,
0x7d, 0x10, 0x0, 0x10,
/* U+0058 "X" */
0x70, 0x3, 0xe, 0x2, 0xc1, 0xc0, 0xd0, 0x38,
0xb0, 0x7, 0x74, 0x0, 0xf8, 0x0, 0x3e, 0x0,
0x1d, 0xd0, 0xe, 0x2c, 0x7, 0x3, 0x43, 0x80,
0xb1, 0xc0, 0xc,
/* U+0059 "Y" */
0x0, 0x0, 0x30, 0xa, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x1f, 0xfc, 0x5, 0x5a,
0x0, 0xe, 0x0, 0xe, 0x0, 0xe, 0x15, 0x5a,
0x3f, 0xf8,
/* U+005A "Z" */
0xbf, 0xfd, 0x15, 0x5c, 0x0, 0x2c, 0x0, 0x34,
0x0, 0xf0, 0x0, 0xc0, 0x3, 0x0, 0xf, 0x0,
0x2c, 0x0, 0x38, 0x0, 0x35, 0x54, 0xbf, 0xfd,
/* U+005B "[" */
0x3f, 0x1d, 0x47, 0x1, 0xc0, 0x70, 0x8, 0x2,
0x1, 0xc0, 0x70, 0x1c, 0x7, 0x50, 0xfc,
/* U+005C "\\" */
0x90, 0xb, 0x0, 0x34, 0x2, 0x80, 0x1c, 0x0,
0xd0, 0xb, 0x0, 0x30, 0x3, 0x80, 0x1c, 0x0,
0xd0, 0xa,
/* U+005D "]" */
0xbd, 0x1e, 0xe, 0xe, 0xe, 0x9, 0x9, 0xe,
0xe, 0xe, 0x1e, 0xbd,
/* U+005E "^" */
0x0, 0x0, 0x18, 0x1, 0xfc, 0x1e, 0x3c, 0xe0,
0x34,
/* U+005F "_" */
0x0, 0x0, 0x0, 0x2f, 0xff, 0xff, 0xc1, 0x55,
0x55, 0x40,
/* U+0060 "`" */
0xe0, 0x78, 0x1c,
/* U+0061 "a" */
0xf, 0xfe, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5e, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x10, 0x0,
/* U+0062 "b" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x75, 0x5a, 0x3f, 0xf8,
/* U+0063 "c" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0x4,
0x70, 0x0, 0x20, 0x0, 0x20, 0x0, 0x70, 0x0,
0x70, 0x4, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0064 "d" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x75, 0x5e, 0x3f, 0xf8,
/* U+0065 "e" */
0x3f, 0xf9, 0xd5, 0x47, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x7f, 0xe3, 0x55, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x55, 0xf, 0xfe,
/* U+0066 "f" */
0x3f, 0xf9, 0xd5, 0x47, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x7f, 0xe3, 0x55, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x0, 0x4, 0x0,
/* U+0067 "g" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xa, 0x70, 0x0,
0x70, 0x0, 0x20, 0xfe, 0x30, 0x1a, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0068 "h" */
0x0, 0x0, 0x30, 0xa, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x1f, 0xfc, 0x35, 0x5e,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x10, 0x0,
/* U+0069 "i" */
0x3f, 0x7d, 0x16, 0xd4, 0x2, 0xc0, 0x2, 0xc0,
0x2, 0xc0, 0x1, 0x80, 0x1, 0x80, 0x2, 0xc0,
0x2, 0xc0, 0x2, 0xc0, 0x16, 0xd4, 0x3f, 0x7d,
/* U+006A "j" */
0x0, 0x9, 0x0, 0xe, 0x0, 0xe, 0x0, 0xe,
0x0, 0xe, 0x0, 0x5, 0x20, 0x5, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+006B "k" */
0x30, 0x1c, 0x70, 0x74, 0x71, 0xd0, 0x77, 0x40,
0x7a, 0x0, 0x1f, 0xf8, 0x35, 0x5e, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x10, 0x0,
/* U+006C "l" */
0x20, 0x1, 0xc0, 0x7, 0x0, 0x1c, 0x0, 0x70,
0x0, 0x80, 0x2, 0x0, 0x1c, 0x0, 0x70, 0x1,
0xc0, 0x7, 0x55, 0xf, 0xfe,
/* U+006D "m" */
0x10, 0x0, 0x11, 0xf8, 0x7, 0xd7, 0x74, 0x37,
0x5c, 0xb3, 0x8d, 0x70, 0xfc, 0x34, 0xc0, 0x90,
0xd2, 0x0, 0x1, 0x1c, 0x0, 0xd, 0x70, 0x0,
0x35, 0xc0, 0x0, 0xd7, 0x0, 0x3, 0x4c, 0x0,
0xd, 0x0, 0x0, 0x0,
/* U+006E "n" */
0x0, 0x0, 0x35, 0xa, 0x7b, 0xe, 0x73, 0xce,
0x70, 0xee, 0x70, 0x7e, 0x20, 0x5, 0x30, 0xa,
0x70, 0xe, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x10, 0x4,
/* U+006F "o" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0070 "p" */
0x3f, 0xf8, 0x75, 0x5a, 0x70, 0xb, 0x70, 0xb,
0x70, 0xb, 0x1f, 0xfc, 0x35, 0x50, 0x70, 0x0,
0x70, 0x0, 0x70, 0x0, 0x70, 0x0, 0x10, 0x0,
/* U+0071 "q" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x71, 0xce, 0x36, 0xde, 0xf, 0xb8,
0x2, 0xc0, 0x1, 0xc0, 0x0, 0xb8, 0x0, 0x10,
/* U+0072 "r" */
0x3f, 0xf8, 0x75, 0x5e, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x1f, 0xf8, 0x3a, 0x50, 0x7b, 0x40,
0x72, 0xc0, 0x70, 0xf0, 0x70, 0x3c, 0x20, 0xd,
/* U+0073 "s" */
0xf, 0xf8, 0x35, 0x5e, 0x70, 0xa, 0x70, 0x0,
0x70, 0x0, 0x1f, 0xf8, 0x5, 0x5a, 0x0, 0xe,
0x10, 0xe, 0x70, 0xe, 0x35, 0x5a, 0xf, 0xf8,
/* U+0074 "t" */
0xbf, 0x7f, 0x85, 0xb5, 0x40, 0x1c, 0x0, 0x7,
0x0, 0x1, 0xc0, 0x0, 0x20, 0x0, 0x8, 0x0,
0x7, 0x0, 0x1, 0xc0, 0x0, 0x70, 0x0, 0x1c,
0x0, 0x2, 0x0,
/* U+0075 "u" */
0x20, 0x9, 0x70, 0xe, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x20, 0x9, 0x20, 0x9, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x35, 0x5e, 0xf, 0xf8,
/* U+0076 "v" */
0x20, 0x8, 0x70, 0xd, 0x70, 0xd, 0x70, 0xd,
0x70, 0xd, 0x20, 0xc, 0x20, 0x34, 0x70, 0xf0,
0x77, 0xc0, 0x7f, 0x0, 0x78, 0x0, 0x20, 0x0,
/* U+0077 "w" */
0x0, 0x0, 0x0, 0xc0, 0x0, 0xd7, 0x0, 0x3,
0x5c, 0x0, 0xd, 0x70, 0x0, 0x35, 0xc0, 0x0,
0xd2, 0x0, 0x1, 0xc, 0x9, 0xd, 0x70, 0xfc,
0x35, 0xcb, 0x38, 0xd7, 0x74, 0x37, 0x5f, 0x80,
0x7d, 0x10, 0x0, 0x10,
/* U+0078 "x" */
0x70, 0x3, 0xe, 0x2, 0xc1, 0xc0, 0xd0, 0x38,
0xb0, 0x7, 0x74, 0x0, 0xf8, 0x0, 0x3e, 0x0,
0x1d, 0xd0, 0xe, 0x2c, 0x7, 0x3, 0x43, 0x80,
0xb1, 0xc0, 0xc,
/* U+0079 "y" */
0x0, 0x0, 0x30, 0xa, 0x70, 0xe, 0x70, 0xe,
0x70, 0xe, 0x70, 0xe, 0x1f, 0xfc, 0x5, 0x5a,
0x0, 0xe, 0x0, 0xe, 0x0, 0xe, 0x15, 0x5a,
0x3f, 0xf8,
/* U+007A "z" */
0xbf, 0xfd, 0x15, 0x5c, 0x0, 0x2c, 0x0, 0x34,
0x0, 0xf0, 0x0, 0xc0, 0x3, 0x0, 0xf, 0x0,
0x2c, 0x0, 0x38, 0x0, 0x35, 0x54, 0xbf, 0xfd,
/* U+007B "{" */
0x3, 0xc0, 0xe4, 0xd, 0x0, 0xd0, 0xd, 0xb,
0x80, 0x1d, 0x0, 0xd0, 0xd, 0x0, 0xd0, 0xe,
0x40, 0x3c,
/* U+007C "|" */
0x21, 0xc7, 0x1c, 0x70, 0x82, 0x1c, 0x71, 0xc7,
0x8,
/* U+007D "}" */
0xb4, 0x1, 0xd0, 0xe, 0x0, 0xe0, 0xe, 0x0,
0x7c, 0xe, 0x0, 0xe0, 0xe, 0x0, 0xe0, 0x1d,
0xb, 0x40,
/* U+007E "~" */
0x1f, 0xc0, 0xe7, 0x8f, 0x3c, 0xe0, 0x3f, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 66, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 46, .box_w = 3, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 9, .adv_w = 88, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 8},
{.bitmap_index = 14, .adv_w = 170, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 50, .adv_w = 134, .box_w = 8, .box_h = 16, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 82, .adv_w = 222, .box_w = 14, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 124, .adv_w = 152, .box_w = 10, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 154, .adv_w = 46, .box_w = 3, .box_h = 4, .ofs_x = 0, .ofs_y = 8},
{.bitmap_index = 157, .adv_w = 77, .box_w = 5, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 172, .adv_w = 77, .box_w = 5, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 187, .adv_w = 115, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 203, .adv_w = 131, .box_w = 9, .box_h = 9, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 224, .adv_w = 46, .box_w = 3, .box_h = 4, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 227, .adv_w = 90, .box_w = 6, .box_h = 3, .ofs_x = 0, .ofs_y = 5},
{.bitmap_index = 232, .adv_w = 46, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 235, .adv_w = 94, .box_w = 6, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 253, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 277, .adv_w = 134, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 304, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 328, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 352, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 376, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 400, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 424, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 448, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 472, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 496, .adv_w = 46, .box_w = 3, .box_h = 8, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 502, .adv_w = 46, .box_w = 3, .box_h = 9, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 509, .adv_w = 88, .box_w = 5, .box_h = 7, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 518, .adv_w = 107, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 527, .adv_w = 88, .box_w = 5, .box_h = 7, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 536, .adv_w = 122, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 557, .adv_w = 219, .box_w = 13, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 596, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 620, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 644, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 668, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 692, .adv_w = 114, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 713, .adv_w = 114, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 734, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 758, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 784, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 808, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 832, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 856, .adv_w = 111, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 877, .adv_w = 179, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 913, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 939, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 963, .adv_w = 136, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 987, .adv_w = 134, .box_w = 8, .box_h = 16, .ofs_x = 0, .ofs_y = -4},
{.bitmap_index = 1019, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1043, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1067, .adv_w = 142, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1094, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1118, .adv_w = 128, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1142, .adv_w = 179, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1178, .adv_w = 143, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1205, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1231, .adv_w = 127, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1255, .adv_w = 68, .box_w = 5, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1270, .adv_w = 94, .box_w = 6, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1288, .adv_w = 68, .box_w = 4, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1300, .adv_w = 106, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 8},
{.bitmap_index = 1309, .adv_w = 193, .box_w = 13, .box_h = 3, .ofs_x = 0, .ofs_y = -4},
{.bitmap_index = 1319, .adv_w = 54, .box_w = 4, .box_h = 3, .ofs_x = 0, .ofs_y = 9},
{.bitmap_index = 1322, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1346, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1370, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1394, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1418, .adv_w = 114, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1439, .adv_w = 114, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1460, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1484, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1510, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1534, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1558, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1582, .adv_w = 111, .box_w = 7, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1603, .adv_w = 179, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1639, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1665, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1689, .adv_w = 136, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1713, .adv_w = 134, .box_w = 8, .box_h = 16, .ofs_x = 0, .ofs_y = -4},
{.bitmap_index = 1745, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1769, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1793, .adv_w = 142, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1820, .adv_w = 134, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1844, .adv_w = 128, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1868, .adv_w = 179, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1904, .adv_w = 143, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1931, .adv_w = 134, .box_w = 8, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1957, .adv_w = 127, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1981, .adv_w = 89, .box_w = 6, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1999, .adv_w = 46, .box_w = 3, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2008, .adv_w = 89, .box_w = 6, .box_h = 12, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2026, .adv_w = 157, .box_w = 10, .box_h = 3, .ofs_x = 0, .ofs_y = 5}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 95, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
}
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
#if LV_VERSION_CHECK(8, 0, 0)
/*Store all the custom data of the font*/
static lv_font_fmt_txt_glyph_cache_t cache;
static const lv_font_fmt_txt_dsc_t font_dsc = {
#else
static lv_font_fmt_txt_dsc_t font_dsc = {
#endif
.glyph_bitmap = glyph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = NULL,
.kern_scale = 0,
.cmap_num = 1,
.bpp = 2,
.kern_classes = 0,
.bitmap_format = 0,
#if LV_VERSION_CHECK(8, 0, 0)
.cache = &cache
#endif
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
#if LV_VERSION_CHECK(8, 0, 0)
const lv_font_t LcdNova16px = {
#else
lv_font_t LcdNova16px = {
#endif
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 18, /*The maximum line height required by the font*/
.base_line = 4, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
#if LV_VERSION_CHECK(7, 4, 0)
.underline_position = -2,
.underline_thickness = 1,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if LCDNOVA16PX*/
| 38.225854
| 116
| 0.539571
|
ValentiWorkLearning
|
612ab4a1d6d24658a06cf445b492f4b86ff929b7
| 4,132
|
cpp
|
C++
|
Cala/src/Graphics/Camera.cpp
|
dominikcondric/Cala
|
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
|
[
"Apache-2.0"
] | null | null | null |
Cala/src/Graphics/Camera.cpp
|
dominikcondric/Cala
|
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
|
[
"Apache-2.0"
] | null | null | null |
Cala/src/Graphics/Camera.cpp
|
dominikcondric/Cala
|
1393d5266b2d7e709a3a7aa0abcc7c0d86a4a810
|
[
"Apache-2.0"
] | null | null | null |
#include "Camera.h"
#include <iostream>
#include <glm/gtx/string_cast.hpp>
#define SPACE_MOVE (movCalagth * deltaTime)
#define FULL_CIRCLE (2 * glm::pi<float>())
Camera::Camera()
{
recalculateEulerAngles();
}
void Camera::recalculateEulerAngles()
{
wDirection = glm::normalize(center - position);
center = position + wDirection;
uDirection = glm::cross(wDirection, lookUp);
vDirection = glm::cross(uDirection, wDirection);
pitch = glm::asin(glm::dot(glm::vec3(0.f, 1.f, 0.f), wDirection));
yaw = glm::atan(glm::dot(glm::vec3(0.f, 0.f, -1.f), wDirection) / glm::dot(glm::vec3(1.f, 0.f, 0.f), wDirection));
if (wDirection.z < 0.f)
{
yaw = FULL_CIRCLE - yaw;
}
view = glm::lookAt(position, center, lookUp);
viewChanged = true;
}
void Camera::setPosition(const glm::vec3& newPosition)
{
position = newPosition;
center = position + wDirection;
view = glm::lookAt(position, center, lookUp);
viewChanged = true;
}
void Camera::setCenter(const glm::vec3& newCenter)
{
center = newCenter;
recalculateEulerAngles();
}
void Camera::setUp(const glm::vec3& up)
{
lookUp = up;
recalculateEulerAngles();
}
void Camera::setProjectionNearPlane(float near)
{
nearPlane = near;
project();
}
void Camera::setProjectionFarPlane(float far)
{
farPlane = far;
project();
}
void Camera::rotateCamera(const glm::vec2& offset)
{
float mouseOffsetX = offset.x;
float mouseOffsetY = offset.y;
yaw += mouseOffsetX * mouseSensitivity;
if (yaw < 0.f)
yaw += FULL_CIRCLE;
else if (yaw > FULL_CIRCLE)
yaw -= FULL_CIRCLE;
if (pitch + (mouseOffsetY * mouseSensitivity) < glm::pi<float>() / 2 && pitch + (mouseOffsetY * mouseSensitivity) > -glm::pi<float>() / 2)
pitch += mouseOffsetY * mouseSensitivity;
wDirection.x = glm::cos(yaw) * glm::cos(pitch);
wDirection.y = glm::sin(pitch);
wDirection.z = glm::sin(yaw) * glm::cos(pitch);
wDirection = glm::normalize(wDirection);
center = position + wDirection;
uDirection = glm::cross(wDirection, lookUp);
vDirection = glm::cross(uDirection, wDirection);
view = glm::lookAt(position, center, lookUp);
viewChanged = true;
}
void Camera::setMouseSensitivity(float sensitivity)
{
mouseSensitivity = sensitivity;
recalculateEulerAngles();
}
void Camera::setMoveSensitivity(float sensitivity)
{
movCalagth = sensitivity;
recalculateEulerAngles();
}
void Camera::moveCamera(Directions direction, float deltaTime)
{
switch (direction)
{
case Directions::FORWARD:
position += wDirection * SPACE_MOVE;
center += wDirection * SPACE_MOVE;
break;
case Directions::BACKWARD:
position -= wDirection * SPACE_MOVE;
center -= wDirection * SPACE_MOVE;
break;
case Directions::LEFT:
position -= uDirection * SPACE_MOVE;
center -= uDirection * SPACE_MOVE;
break;
case Directions::RIGHT:
position += uDirection * SPACE_MOVE;
center += uDirection * SPACE_MOVE;
break;
case Directions::UP:
position += lookUp * SPACE_MOVE;
center += lookUp * SPACE_MOVE;
break;
case Directions::DOWN:
position -= lookUp * SPACE_MOVE;
center -= lookUp * SPACE_MOVE;
break;
}
view = glm::lookAt(position, center, lookUp);
viewChanged = true;
}
PerspectiveCamera::PerspectiveCamera()
{
project();
}
void PerspectiveCamera::setProjectionViewingAngle(float angle)
{
viewingAngle = angle;
project();
}
void PerspectiveCamera::setProjectionAspectRatio(float ratio)
{
aspectRatio = ratio;
project();
}
void PerspectiveCamera::project()
{
projection = glm::perspective(glm::radians(viewingAngle), aspectRatio, nearPlane, farPlane);
projectionChanged = true;
}
OrthograficCamera::OrthograficCamera()
{
project();
}
void OrthograficCamera::setProjectionLeftPlane(float left)
{
leftPlane = left;
project();
}
void OrthograficCamera::setProjectionRightPlane(float right)
{
rightPlane = right;
project();
}
void OrthograficCamera::setProjectionTopPlane(float top)
{
topPlane = top;
project();
}
void OrthograficCamera::setProjectionBottomPlane(float bottom)
{
bottomPlane = bottom;
project();
}
void OrthograficCamera::project()
{
projection = glm::ortho(leftPlane, rightPlane, nearPlane, farPlane);
projectionChanged = true;
}
| 20.974619
| 139
| 0.717086
|
dominikcondric
|
9ed412a174a0385263fdc0d2a8dcbdb0169e1ec7
| 1,102
|
cpp
|
C++
|
test/cpp/asyncworker.cpp
|
yorkie/nan
|
f500c71a31da98de4278d8e1d009068b72a34344
|
[
"MITNFA"
] | 380
|
2015-01-06T15:52:07.000Z
|
2021-11-08T11:17:02.000Z
|
test/cpp/asyncworker.cpp
|
yorkie/nan
|
f500c71a31da98de4278d8e1d009068b72a34344
|
[
"MITNFA"
] | 124
|
2015-01-01T02:51:40.000Z
|
2021-03-03T18:06:55.000Z
|
test/cpp/asyncworker.cpp
|
yorkie/nan
|
f500c71a31da98de4278d8e1d009068b72a34344
|
[
"MITNFA"
] | 36
|
2015-01-09T19:01:16.000Z
|
2019-09-05T05:34:12.000Z
|
/**********************************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2014 NAN contributors
*
* MIT +no-false-attribs License <https://github.com/rvagg/nan/blob/master/LICENSE>
**********************************************************************************/
#ifndef _WIN32
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
#include <nan.h>
class SleepWorker : public NanAsyncWorker {
public:
SleepWorker(NanCallback *callback, int milliseconds)
: NanAsyncWorker(callback), milliseconds(milliseconds) {}
~SleepWorker() {}
void Execute () {
Sleep(milliseconds);
}
private:
int milliseconds;
};
NAN_METHOD(DoSleep) {
NanScope();
NanCallback *callback = new NanCallback(args[1].As<v8::Function>());
NanAsyncQueueWorker(new SleepWorker(callback, args[0]->Uint32Value()));
NanReturnUndefined();
}
void Init(v8::Handle<v8::Object> exports) {
exports->Set(
NanNew<v8::String>("a")
, NanNew<v8::FunctionTemplate>(DoSleep)->GetFunction());
}
NODE_MODULE(asyncworker, Init)
| 25.627907
| 84
| 0.594374
|
yorkie
|
9ed5c858eaa34150ae4a77912341a4047fd70f46
| 22,679
|
cpp
|
C++
|
app.cpp
|
wang-bin/keygen
|
4d00bf41b88b1a7e0fec228e89fb94a3a871ffe7
|
[
"MIT"
] | 6
|
2021-04-09T03:04:11.000Z
|
2022-02-18T01:38:38.000Z
|
app.cpp
|
wang-bin/keygen
|
4d00bf41b88b1a7e0fec228e89fb94a3a871ffe7
|
[
"MIT"
] | null | null | null |
app.cpp
|
wang-bin/keygen
|
4d00bf41b88b1a7e0fec228e89fb94a3a871ffe7
|
[
"MIT"
] | 1
|
2021-04-09T08:42:25.000Z
|
2021-04-09T08:42:25.000Z
|
/*
* Copyright (c) 2019-2021 WangBin <wbsecg1 at gmail.com>
* This file is part of MDK
* MDK SDK: https://github.com/wang-bin/mdk-sdk
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* This code is public domain.
*/
#ifndef EDDSA_STATIC
# define EDDSA_STATIC
#endif
#include "app.h"
#include "key_pub.h"
#include "base/log.h"
#include "cppcompat/cstdlib.hpp"
extern "C" const char *getprogname(); //stdlib.h. apple, bsd, android21
#if !(_WIN32+0)
_Pragma("weak getprogname"); // android 21+
#endif
//__progname: qnx, glibc, bionic libc. set in __init_misc
#if defined(__linux__) // || defined(__QNX__) || defined(__QNXNTO__)
extern "C" const char *__progname; // bionic libc. no __progname_full and alias
#endif
// android: getprogname() and __progname is package name via android.app.Application.GetPackageName(), because no main executable
#ifdef _GNU_SOURCE
#include <errno.h> // program_invocation_short_name, gnu extension
//weak_alias (__progname_full, program_invocation_name)
//weak_alias (__progname, program_invocation_short_name)
#endif
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#if (__APPLE__+0)
#include <CoreFoundation/CFBundle.h>
#endif
#include <algorithm>
#include <cassert>
#include <cstring>
#include <chrono>
#include <ctime>
#include <iostream>
#include <sstream>
#include <vector>
#include <locale>
#include <iomanip>
#if (__linux__+0) && (__GLIBCXX__+0)
#define USE_STRPTIME 1
#include <time.h>
#endif
#include "cryptograph/eddsa.h"
using namespace std;
////#include <sys/prctl.h>
//prctl(PR_SET_NAME, name); //linux gnu
// _POSIX_VERSION (unistd.h)
/*! Stringify \a x. */
#define _TOSTR(x) #x
/*! Stringify \a x, perform macro expansion. */
#define TOSTR(x) _TOSTR(x)
static const char kIdJoin[] = "/";
MDK_NS_BEGIN
namespace App {
using namespace chrono;
static auto buildTime()
{
std::tm t0 = {};
std::istringstream ss(string(__DATE__).append(" ").append(__TIME__));
#ifdef USE_STRPTIME
if (!strptime(ss.str().data(), "%b %e %Y %H:%M:%S", &t0)) {
#else
ss.imbue(std::locale::classic()); // other locales abort in wine
ss >> std::get_time(&t0, "%b %e %Y %H:%M:%S");
if (ss.fail()) {
#endif
std::clog << LogLevel::Warning << "Parse date failed: " << ss.str() << std::endl;
return system_clock::now();
}
return system_clock::from_time_t(std::mktime(&t0));
}
int64_t timeAfterBuild()
{
static const auto build = buildTime();
return duration_cast<seconds>(system_clock::now() - build).count();
}
static uint32_t gCP = 65001; // CP_UTF8
void setCodePage(uint32_t cp)
{
gCP = cp;
}
#if (_WIN32+0)
static string convert_codepage(const wchar_t* wstr, size_t wlen)
{
const auto len = WideCharToMultiByte(gCP, 0, (LPCWSTR)wstr, wlen, nullptr, 0, nullptr, nullptr);
string str(len, 0);
WideCharToMultiByte(gCP, 0, (LPCWSTR)wstr, wlen, (LPSTR)str.c_str(), len, nullptr, nullptr);
return str;
}
#endif
string Name()
{
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__BIONIC__)
if (getprogname)
return getprogname();
#endif
#if defined(_GNU_SOURCE) && !defined(__BIONIC__)
return program_invocation_short_name;
#endif
#if defined(__linux__) // android<21
return __progname;
#endif
#ifdef _WIN32
wstring wexe(MAX_PATH, 0); // TODO: get size
const auto len = GetModuleFileNameW(nullptr, &wexe[0], (DWORD)wexe.size());
auto exe = convert_codepage(wexe.data(), len);
auto d = exe.rfind("\\");
if (d != wstring::npos)
return exe.substr(d+1, exe.rfind(".exe") - d - 1);
#endif
return "";
}
string id()
{
#if defined(__APPLE__)
auto b = CFBundleGetMainBundle();
auto cfid = CFBundleGetIdentifier(b); // or use app folder name(player.app), which MUST be unique1
auto id = CFStringGetCStringPtr(cfid, kCFStringEncodingUTF8);
if (id)
return id;
#endif
#ifdef _WIN32
# if !(MDK_WINRT+0)
TCHAR exe[MAX_PATH]{};
GetModuleFileName(nullptr, &exe[0], sizeof(exe));
DWORD h = 0;
auto sz = GetFileVersionInfoSize(&exe[0], &h);
if (!sz)
return Name();
auto data = malloc(sz);
if (!GetFileVersionInfo(&exe[0], h, sz, data)) {
free(data);
return Name();
}
wchar_t* buf = nullptr;
UINT bufLen = 0;
string product, company;
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *lpTranslate;
UINT cbTranslate = 0;
VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate);
// Read the file description for each language and code page.
for (int i = 0; i < cbTranslate/sizeof(LANGANDCODEPAGE); i++) {
wstring sub(64, 0);
swprintf_s(&sub[0], sub.size(), L"\\StringFileInfo\\%04x%04x\\ProductName", lpTranslate[i].wLanguage, lpTranslate[i].wCodePage);
if (VerQueryValueW(data, sub.data(), (LPVOID*)&buf, &bufLen))
product = convert_codepage(buf, bufLen - 1); // bufLen: including terminal 0
swprintf_s(&sub[0], sub.size(), L"\\StringFileInfo\\%04x%04x\\CompanyName", lpTranslate[i].wLanguage, lpTranslate[i].wCodePage);
if (VerQueryValueW(data, sub.data(), (LPVOID*)&buf, &bufLen))
company = convert_codepage(buf, bufLen - 1);
if (!product.empty() || !company.empty())
break;
}
free(data);
return product + kIdJoin + company;
# endif
// TODO: GetFileVersionInfo() query company name
#endif
return Name();
}
static bool skipLicense()
{
#if defined(RTLD_DEFAULT)
_Pragma("weak dladdr") // dladdr is not always supported
static Dl_info dli;
if (dladdr && dladdr(&dli, &dli)) { // dladdr(global_sth_address_in_image, ...)
// i'm glad to be a linux system lib
if (strstr(dli.dli_fname, "/usr/lib/") == dli.dli_fname)
return true;
}
#endif
return false;
}
static bool expired()
{
const auto dt = timeAfterBuild();
return dt > 3600*24*44 || dt < 0; // < 0: system time can not be earlier than build time
}
enum class OS : uint16_t {
Unknown = 0,
macOS = 1,
iOS = 1 << 1, // including maccatalyst
tvOS = 1 << 2,
Apple = macOS | iOS | tvOS,
Win32 = 1 << 3,
UWP = 1 << 4,
Windows = Win32 | UWP,
Android = 1 << 5,
Linux = 1 << 6,
RaspberryPi = 1 << 7,
Sunxi = 1 << 8,
Sailfish = 1 << 9,
// BSD
All = 0xffff,
};
enum class ARCH : uint16_t {
Unknown = 0,
ARM = 1,
AArch64 = 1 << 1,
I386 = 1 << 2,
X86_64 = 1 << 3,
X86 = I386 | X86_64,
RISCV = 1 << 4,
WebAssembly = 1 << 5,
Mips = 1 << 6,
PowerPC = 1 << 7,
Sparc = 1 << 8,
SystemZ = 1 << 9,
Alpha = 1 << 15,
All = 0xffff,
};
enum class Restriction : uint16_t {
None = 0,
GPL = 1,
OpenSource = 1 << 1,
Nonprofit = 1 << 2,
Education = 1 << 3,
Sponsor = 1 << 4,
Test = 1 << 6,
};
} // namespace App
template<> struct is_flag<App::OS> : std::true_type {};
template<> struct is_flag<App::ARCH> : std::true_type {};
template<> struct is_flag<App::Restriction> : std::true_type {};
namespace App {
static OS os_from_names(const string& S)
{
string s(S);
std::transform(s.begin(), s.end(), s.begin(), [](char c){
return std::tolower(c);
});
OS os = OS::Unknown;
if (s.find("mac") != string::npos)
os |= OS::macOS;
if (s.find("ios") != string::npos)
os |= OS::iOS;
if (s.find("tvos") != string::npos)
os |= OS::tvOS;
if (s.find("apple") != string::npos)
os |= OS::Apple;
if (s.find("win32") != string::npos)
os |= OS::Win32;
if (s.find("uwp") != string::npos)
os |= OS::UWP;
if (s.find("windows") != string::npos)
os |= OS::Windows;
if (s.find("android") != string::npos)
os |= OS::Android;
if (s.find("linux") != string::npos)
os |= OS::Linux;
if (s.find("rpi") != string::npos)
os |= OS::RaspberryPi;
if (s.find("sunxi") != string::npos)
os |= OS::Sunxi;
if (s.find("sailfish") != string::npos)
os |= OS::Sailfish;
if (s.find("all") != string::npos)
os |= OS::All;
return os;
}
static ARCH arch_from_names(const string& S)
{
string s(S);
std::transform(s.begin(), s.end(), s.begin(), [](char c){
return std::tolower(c);
});
ARCH arch = ARCH::Unknown;
if (s.find("arm") != string::npos)
arch |= ARCH::ARM;
if (s.find("aarch64") != string::npos)
arch |= ARCH::AArch64;
if (s.find("i386") != string::npos)
arch |= ARCH::I386;
if (s.find("x86_64") != string::npos)
arch |= ARCH::X86_64;
if (s.find("x64") != string::npos)
arch |= ARCH::X86_64;
if (s.find("x86") != string::npos)
arch |= ARCH::X86;
if (s.find("riscv") != string::npos)
arch |= ARCH::RISCV;
if (s.find("web") != string::npos)
arch |= ARCH::WebAssembly;
if (s.find("mips") != string::npos)
arch |= ARCH::Mips;
if (s.find("pc") != string::npos)
arch |= ARCH::PowerPC;
if (s.find("sparc") != string::npos)
arch |= ARCH::Sparc;
if (s.find("systemz") != string::npos)
arch |= ARCH::SystemZ;
if (s.find("alpha") != string::npos)
arch |= ARCH::Alpha;
if (s.find("all") != string::npos)
arch |= ARCH::All;
return arch;
}
Restriction restriction_from_names(const string& S)
{
string s(S);
std::transform(s.begin(), s.end(), s.begin(), [](char c){
return std::tolower(c);
});
Restriction r = Restriction::None;
if (s.find("gpl") != string::npos)
r |= Restriction::GPL;
if (s.find("open") != string::npos)
r |= Restriction::OpenSource;
if (s.find("nonprofit") != string::npos)
r |= Restriction::Nonprofit;
if (s.find("edu") != string::npos)
r |= Restriction::Education;
if (s.find("sponsor") != string::npos)
r |= Restriction::Sponsor;
if (s.find("test") != string::npos)
r |= Restriction::Test;
return r;
}
void data_from_hex_str(const char* s, size_t len, vector<uint8_t>& v)
{
v.resize(len/2);
for (int i = 0; i < len/2; ++i) {
char x[3] = {s[2*i], s[2*i+1], 0};
v[i] = std::stoi(x, nullptr, 16);
}
}
static vector<uint8_t> sig_from_key_hex(const char* key)
{
vector<uint8_t> sig;
sig.reserve(ED25519_SIG_LEN);
data_from_hex_str(key, ED25519_SIG_LEN*2, sig);
return sig;
}
// sig[64] and data[64] pair
// key_hex = sig + (sig^data)
static bool sig_data_from_key_hex(const string& key, vector<uint8_t>& sig, vector<uint8_t>& data)
{
if (key.size() < ED25519_SIG_LEN*4) {
std::clog << LogLevel::Error << "wrong key size. must >= " << ED25519_SIG_LEN*4 << std::endl;
return false;
}
sig = sig_from_key_hex(&key[0]);
data = sig_from_key_hex(&key[ED25519_SIG_LEN*2]);
//stringstream sigs;
//stringstream datas;
for (int i = 0; i < sig.size(); ++i) {
data[i] ^= sig[i];
//sigs << int(sig[i]);
//datas << int(data[i]);
}
//cout << "verify sig int:\n" << sigs.str() << std::endl;
//cout << "verify data origin int:\n" << datas.str() << std::endl;
return true;
}
static bool data_from_key_verify(const string& key, const uint8_t pub[ED25519_KEY_LEN], vector<uint8_t>& data)
{
vector<uint8_t> sig;
if (!sig_data_from_key_hex(key, sig, data))
return false;
if (ed25519_verify(sig.data(), pub, data.data(), data.size())) {
std::clog << LogLevel::Info << TOSTR(MDK_NS) " verify key signature ok" << std::endl;
return true;
}
std::clog << LogLevel::Error << TOSTR(MDK_NS) " failed to verify key signature" << std::endl;
return false;
}
struct KeyData { // MUST be unique layout on all platforms!
OS os = OS::All;
ARCH arch = ARCH::Alpha;
int16_t major = INT16_MAX;
int16_t minor = INT16_MAX;
int64_t time = INT64_MAX; // seconds
Restriction restriction = Restriction::None;
uint8_t appid[46];
};
static_assert(sizeof(KeyData) == ED25519_SIG_LEN, "bad KeyData size");
static bool verify_data_os(const KeyData& data, OS test = OS::Unknown)
{
const auto os = data.os;
if (test != OS::Unknown) {
std::clog << TOSTR(MDK_NS) " verify test os: " << int(test) << "/" << int(data.os) << std::endl;
if ((os & test) == test)
return true;
}
else if (test_flag(os &
#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
OS::macOS
#elif defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
OS::iOS
#elif defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__)
OS::tvOS
#elif defined(__ANDROID__)
OS::Android
#elif defined(_WIN32)
# if defined(MDK_WINRT)
OS::UWP
# else
OS::Win32
# endif
#elif defined(OS_RPI)
OS::RaspberryPi
#elif defined(OS_SUNXI)
OS::Sunxi
#elif defined(__linux__)
OS::Linux
#else
OS::Unknown
#endif
))
return true;
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key does not support current OS" << std::endl;
return false;
}
static bool verify_data_arch(const KeyData& data, ARCH test = ARCH::Unknown)
{
const auto arch = data.arch;
if (test != ARCH::Unknown) {
std::clog << TOSTR(MDK_NS) " verify test arch: " << int(test) << "/" << int(data.arch) << std::endl;
if ((arch & test) == test)
return true;
}
else if (test_flag(arch &
#if (__aarch64__+0) || /*vc*/defined(_M_ARM64)
ARCH::AArch64
#elif (__ARM_ARCH+0) || (_M_ARM+0)
ARCH::ARM
#elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || /*vc*/defined(_M_X64) || defined(_M_AMD64)
ARCH::X86_64
#elif defined(__i386) || defined(__i386__) || /*vc*/defined(_M_IX86)
ARCH::I386
#else
ARCH::Unknown
#endif
))
return true;
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key does not support current cpu" << std::endl;
return false;
}
static bool verify_data_restriction(const KeyData& data, Restriction test = Restriction::None)
{
const auto r = data.restriction;
if (test != Restriction::None) {
std::clog << TOSTR(MDK_NS) " verify test restriction: " << int(test) << "/" << int(r) << std::endl;
if ((r & test) == test)
return true;
} else {
string rs;
if (test_flag(r & Restriction::GPL))
rs += "GPL, ";
if (test_flag(r & Restriction::OpenSource))
rs += "OpenSource, ";
if (test_flag(r & Restriction::Nonprofit))
rs += "Nonprofit, ";
if (test_flag(r & Restriction::Sponsor))
rs += "Sponsor, ";
if (test_flag(r & Restriction::Education))
rs += "Education, ";
if (test_flag(r & Restriction::Test))
rs += "Test, ";
if (!rs.empty())
std::clog << LogLevel::Info << TOSTR(MDK_NS) " license key restrictions: " << rs << std::endl;
return true;
}
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key is restricted" << std::endl;
return false;
}
static bool verify_data_time(const KeyData& data, int64_t test = -1)
{
if (data.time < 0)
return true;
if (test >= 0) {
std::clog << "verify test time: " << test << "/" << data.time << std::endl;
if (test < data.time)
return true;
} else {
auto now = chrono::system_clock::now().time_since_epoch();
#if DEBUG
std::clog << LogLevel::Info << TOSTR(MDK_NS) " license key will expire in " << data.time - chrono::duration_cast<chrono::seconds>(now).count() << " seconds" << std::endl;
#endif
static const bool earlier_than_build = timeAfterBuild() < 0;
if (earlier_than_build) {
std::clog << LogLevel::Error << "System time is earlier than " TOSTR(MDK_NS) " was built" << std::endl;
return false;
}
if (chrono::duration_cast<chrono::seconds>(now).count() < data.time)
return true;
}
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key is expired" << std::endl;
return false;
}
static bool verify_data_version(const KeyData& data, int16_t test_major = -1, int16_t test_minor = -1)
{
if (data.major < 0 || data.minor < 0)
return true;
if (test_major >= 0 && test_minor >= 0) {
std::clog << "verify test time: " << test_major << "." << test_minor << "/" << data.major << "." << data.minor << std::endl;
if (((test_major << 16) | test_minor) <= ((data.major << 16) | data.minor))
return true;
} else {
std::clog << LogLevel::Info << TOSTR(MDK_NS) " license key for sdk version <= " << data.major << "." << data.minor << std::endl;
if (((MDK_MAJOR << 16) | MDK_MINOR) <= ((data.major << 16) | data.minor))
return true;
}
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key does not support current sdk version: > " << data.major << "." << data.minor << std::endl;
return false;
}
static bool verify_data_appid(const KeyData& data, const string& test = string())
{
int len = data.appid[0];
if (len == 0)
return true;
string AppId;
AppId.resize(len);
memcpy(&AppId[0], &data.appid[1], len);
auto appid = AppId;
std::transform(appid.begin(), appid.end(), appid.begin(), [](char c){
return std::tolower(c);
});
auto name = Name();
if (AppId.find(kIdJoin) != string::npos || AppId.find('.') != string::npos)
name = id();
std::transform(name.begin(), name.end(), name.begin(), [](char c){
return std::tolower(c);
});
if (!test.empty()) {
std::clog << "verify test appid: " << test << "/" << appid << std::endl;
if (test == appid)
return true;
} else {
std::clog << LogLevel::Info << TOSTR(MDK_NS) " license key for app: " << AppId << std::endl;
if (len < sizeof(data.appid) - 1) {
if (name == appid)
return true;
} else {
if (name.find(appid) == 0)
return true;
}
}
std::clog << LogLevel::Error << TOSTR(MDK_NS) " license key does not support current app: " << name << std::endl;
return false;
}
bool verify_key(const string& key, const uint8_t pub[ED25519_KEY_LEN])
{
vector<uint8_t> data;
if (!data_from_key_verify(key, pub, data))
return false;
KeyData kd;
assert(sizeof(kd) == data.size());
memcpy(&kd, data.data(), sizeof(kd));
return verify_data_os(kd)
&& verify_data_arch(kd)
&& verify_data_restriction(kd)
&& verify_data_time(kd)
&& verify_data_version(kd)
&& verify_data_appid(kd)
;
}
bool verify_key(const std::string& key, const uint8_t pub[32], const std::string& osnames, const std::string& archnames, const std::string& restrictions, int64_t seconds, int16_t major, int16_t minor, const std::string& appid)
{
vector<uint8_t> data;
if (!data_from_key_verify(key, pub, data))
return false;
KeyData kd;
assert(sizeof(kd) == data.size());
memcpy(&kd, data.data(), sizeof(kd));
return verify_data_os(kd, os_from_names(osnames))
&& verify_data_arch(kd, arch_from_names(archnames))
&& verify_data_restriction(kd, restriction_from_names(restrictions))
&& verify_data_time(kd, seconds)
&& verify_data_version(kd, major, minor)
&& verify_data_appid(kd, appid)
;
}
static KeyData gen_data(const string& osnames, const string& archnames, const std::string& restrictions, int64_t seconds, int16_t major, int16_t minor, const string& appid)
{
KeyData kd;
kd.os = os_from_names(osnames);
kd.arch = arch_from_names(archnames);
kd.restriction = restriction_from_names(restrictions);
kd.major = major;
kd.minor = minor;
kd.time = seconds;
string id = appid;
if (sizeof(kd.appid) - 1 < id.size()) {
std::clog << LogLevel::Error << "appid is too long, must <= " << sizeof(kd.appid) - 1 << std::endl;
id.resize(sizeof(kd.appid) - 1);
}
auto appid_len = uint8_t(id.size());
kd.appid[0] = appid_len;
clog << "appid[0]: " << (int)kd.appid[0] << endl;
memcpy(&kd.appid[1], &id[0], id.size());
auto offset = 1 + id.size();
// append random data to ensure data is unique. free to modify
std::srand(std::time(nullptr)%UINT_MAX);
for (size_t i = offset; i <= sizeof(kd.appid) -sizeof(int); i+=sizeof(int)) {
auto idata = reinterpret_cast<int*>(&kd.appid[i]);
*idata = std::rand();
}
return std::move(kd);
}
void gen_pub(const uint8_t priv[ED25519_KEY_LEN], uint8_t pub[ED25519_KEY_LEN])
{
ed25519_genpub(pub, priv);
}
string gen_key(const uint8_t priv[ED25519_KEY_LEN], const uint8_t pub[ED25519_KEY_LEN], const string& osnames, const string& archnames, const std::string& restrictions, int64_t seconds, int16_t major, int16_t minor, const string& appid)
{
vector<uint8_t> key(2*ED25519_SIG_LEN);
auto kd = gen_data(osnames, archnames, restrictions, seconds, major, minor, appid);
ed25519_sign(&key[0], priv, pub, (const uint8_t*)&kd, sizeof(kd));
auto data = &key[ED25519_SIG_LEN];
memcpy(data, &kd, sizeof(kd));
//std::cout << "data origin int:\n";
for (int i = 0; i < ED25519_SIG_LEN; ++i) {
//std::cout << int(data[i]);
data[i] ^= key[i];
}
//std::cout << "key int:\n";
std::stringstream ss;
for (const auto& k : key) {
ss << std::uppercase << std::setw(2) << std::setfill('0')<< std::hex << (int)k;
//std::cout << int(k);
}
//std::cout << std::endl;
return ss.str();
}
bool checkLicense(const char* key)
{
static int licensed = -1;
if (licensed > 0 && !key)
return true;
if (skipLicense())
return true;
if (!key)
key = std::getenv("MDK_KEY");
if (!key) {
if (!expired())
return licensed != 0; // license == 0 means expired or a wrong key was set
} else {
// DO NOT print key in log! Print details instead
if (verify_key(key, kKeyPub)) {
licensed = 1;
return true;
}
}
std::clog << LogLevel::Error << "Bad " TOSTR(MDK_NS) " license!" << std::endl;
std::clog << LogLevel::Error << TOSTR(MDK_NS) " SDK is outdated. Get a new free sdk from https://sourceforge.net/projects/mdk-sdk/files, or purchase a license.\n"
"paypal: https://www.paypal.me/ibingow/500 or https://www.qtav.org/donate.html\n" << std::endl << std::flush;
licensed = 0;
return false;
}
} // namespace App
MDK_NS_END
| 31.897328
| 236
| 0.59888
|
wang-bin
|
9ed9b5fd17228803f9947dc8b3580215bc18ad57
| 15,066
|
cpp
|
C++
|
ros/src/airsim_ros_pkgs/src/pd_position_controller_simple.cpp
|
whatseven/AirSim
|
fe7e4e7c782cf1077594c1ee6cc1bbfec3f66bd1
|
[
"MIT"
] | 4
|
2018-06-27T02:18:53.000Z
|
2019-08-27T18:52:32.000Z
|
ros/src/airsim_ros_pkgs/src/pd_position_controller_simple.cpp
|
Abdulkadir-Muhendis/AirSim
|
c6f0729006ecd6d792a750edc7e27021469c5649
|
[
"MIT"
] | 4
|
2020-03-05T15:42:17.000Z
|
2020-03-19T05:37:58.000Z
|
ros/src/airsim_ros_pkgs/src/pd_position_controller_simple.cpp
|
Abdulkadir-Muhendis/AirSim
|
c6f0729006ecd6d792a750edc7e27021469c5649
|
[
"MIT"
] | 4
|
2020-04-08T21:53:00.000Z
|
2022-01-14T17:04:29.000Z
|
#include "pd_position_controller_simple.h"
bool PIDParams::load_from_rosparams(const ros::NodeHandle &nh)
{
bool found = true;
found = found && nh.getParam("kp_x", kp_x);
found = found && nh.getParam("kp_y", kp_y);
found = found && nh.getParam("kp_z", kp_z);
found = found && nh.getParam("kp_yaw", kp_yaw);
found = found && nh.getParam("kd_x", kd_x);
found = found && nh.getParam("kd_y", kd_y);
found = found && nh.getParam("kd_z", kd_z);
found = found && nh.getParam("kd_yaw", kd_yaw);
found = found && nh.getParam("reached_thresh_xyz", reached_thresh_xyz);
found = found && nh.getParam("reached_yaw_degrees", reached_yaw_degrees);
return found;
}
bool DynamicConstraints::load_from_rosparams(const ros::NodeHandle &nh)
{
bool found = true;
found = found && nh.getParam("max_vel_horz_abs", max_vel_horz_abs);
found = found && nh.getParam("max_vel_vert_abs", max_vel_vert_abs);
found = found && nh.getParam("max_yaw_rate_degree", max_yaw_rate_degree);
return found;
}
PIDPositionController::PIDPositionController(const ros::NodeHandle &nh, const ros::NodeHandle &nh_private)
: nh_(nh), nh_private_(nh_private),
has_odom_(false), has_goal_(false), reached_goal_(false), got_goal_once_(false), has_home_geo_(false), use_eth_lib_for_geodetic_conv_(true)
{
params_.load_from_rosparams(nh_private_);
constraints_.load_from_rosparams(nh_);
initialize_ros();
reset_errors();
}
void PIDPositionController::reset_errors()
{
prev_error_.x = 0.0;
prev_error_.y = 0.0;
prev_error_.z = 0.0;
prev_error_.yaw = 0.0;
}
void PIDPositionController::initialize_ros()
{
vel_cmd_ = airsim_ros_pkgs::VelCmd();
// ROS params
double update_control_every_n_sec;
nh_private_.getParam("update_control_every_n_sec", update_control_every_n_sec);
// ROS publishers
airsim_vel_cmd_world_frame_pub_ = nh_private_.advertise<airsim_ros_pkgs::VelCmd>("/vel_cmd_world_frame", 1);
// ROS subscribers
airsim_odom_sub_ = nh_.subscribe("/airsim_node/odom_local_ned", 50, &PIDPositionController::airsim_odom_cb, this);
home_geopoint_sub_ = nh_.subscribe("/airsim_node/home_geo_point", 50, &PIDPositionController::home_geopoint_cb, this);
// todo publish this under global nodehandle / "airsim node" and hide it from user
local_position_goal_srvr_ = nh_.advertiseService("/airsim_node/local_position_goal", &PIDPositionController::local_position_goal_srv_cb, this);
local_position_goal_override_srvr_ = nh_.advertiseService("/airsim_node/local_position_goal/override", &PIDPositionController::local_position_goal_srv_override_cb, this);
gps_goal_srvr_ = nh_.advertiseService("/airsim_node/gps_goal", &PIDPositionController::gps_goal_srv_cb, this);
gps_goal_override_srvr_ = nh_.advertiseService("/airsim_node/gps_goal/override", &PIDPositionController::gps_goal_srv_override_cb, this);
// ROS timers
update_control_cmd_timer_ = nh_private_.createTimer(ros::Duration(update_control_every_n_sec), &PIDPositionController::update_control_cmd_timer_cb, this);
}
void PIDPositionController::airsim_odom_cb(const nav_msgs::Odometry& odom_msg)
{
has_odom_ = true;
curr_odom_ = odom_msg;
curr_position_.x = odom_msg.pose.pose.position.x;
curr_position_.y = odom_msg.pose.pose.position.y;
curr_position_.z = odom_msg.pose.pose.position.z;
curr_position_.yaw = utils::get_yaw_from_quat_msg(odom_msg.pose.pose.orientation);
}
// todo maintain internal representation as eigen vec?
// todo check if low velocity if within thresh?
// todo maintain separate errors for XY and Z
void PIDPositionController::check_reached_goal()
{
double diff_xyz = sqrt((target_position_.x - curr_position_.x) * (target_position_.x - curr_position_.x)
+ (target_position_.y - curr_position_.y) * (target_position_.y - curr_position_.y)
+ (target_position_.z - curr_position_.z) * (target_position_.z - curr_position_.z));
double diff_yaw = math_common::angular_dist(target_position_.yaw, curr_position_.yaw);
// todo save this in degrees somewhere to avoid repeated conversion
if (diff_xyz < params_.reached_thresh_xyz && diff_yaw < math_common::deg2rad(params_.reached_yaw_degrees))
reached_goal_ = true;
}
bool PIDPositionController::local_position_goal_srv_cb(airsim_ros_pkgs::SetLocalPosition::Request& request, airsim_ros_pkgs::SetLocalPosition::Response& response)
{
// this tells the update timer callback to not do active hovering
if(!got_goal_once_)
got_goal_once_ = true;
if (has_goal_ && !reached_goal_)
{
// todo maintain array of position goals
ROS_ERROR_STREAM("[PIDPositionController] denying position goal request. I am still following the previous goal");
return false;
}
if (!has_goal_)
{
target_position_.x = request.x;
target_position_.y = request.y;
target_position_.z = request.z;
target_position_.yaw = request.yaw;
ROS_INFO_STREAM("[PIDPositionController] got goal: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw );
// todo error checks
// todo fill response
has_goal_ = true;
reached_goal_ = false;
reset_errors(); // todo
return true;
}
}
bool PIDPositionController::local_position_goal_srv_override_cb(airsim_ros_pkgs::SetLocalPosition::Request& request, airsim_ros_pkgs::SetLocalPosition::Response& response)
{
// this tells the update timer callback to not do active hovering
if(!got_goal_once_)
got_goal_once_ = true;
target_position_.x = request.x;
target_position_.y = request.y;
target_position_.z = request.z;
target_position_.yaw = request.yaw;
ROS_INFO_STREAM("[PIDPositionController] got goal: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw );
// todo error checks
// todo fill response
has_goal_ = true;
reached_goal_ = false;
reset_errors(); // todo
return true;
}
void PIDPositionController::home_geopoint_cb(const airsim_ros_pkgs::GPSYaw& gps_msg)
{
if(has_home_geo_)
return;
gps_home_msg_ = gps_msg;
has_home_geo_ = true;
ROS_INFO_STREAM("[PIDPositionController] GPS reference initializing " << gps_msg.latitude << ", "<< gps_msg.longitude << ", " << gps_msg.altitude);
geodetic_converter_.initialiseReference(gps_msg.latitude, gps_msg.longitude, gps_msg.altitude);
}
// todo do relative altitude, or add an option for the same?
bool PIDPositionController::gps_goal_srv_cb(airsim_ros_pkgs::SetGPSPosition::Request& request, airsim_ros_pkgs::SetGPSPosition::Response& response)
{
if(!has_home_geo_)
{
ROS_ERROR_STREAM("[PIDPositionController] I don't have home GPS coord. Can't go to GPS goal!");
response.success = false;
}
// convert GPS goal to NED goal
if (!has_goal_)
{
msr::airlib::GeoPoint goal_gps_point(request.latitude, request.longitude, request.altitude);
msr::airlib::GeoPoint gps_home(gps_home_msg_.latitude, gps_home_msg_.longitude, gps_home_msg_.altitude);
bool use_eth_lib = true;
if (use_eth_lib_for_geodetic_conv_)
{
double initial_latitude, initial_longitude, initial_altitude;
geodetic_converter_.getReference(&initial_latitude, &initial_longitude, &initial_altitude);
double n, e, d;
geodetic_converter_.geodetic2Ned(request.latitude, request.longitude, request.altitude, &n, &e, &d);
// ROS_INFO_STREAM("[PIDPositionController] geodetic_converter_ GPS reference initialized correctly (lat long in radians) " << initial_latitude << ", "<< initial_longitude << ", " << initial_altitude);
target_position_.x = n;
target_position_.y = e;
target_position_.z = d;
}
else // use airlib::GeodeticToNedFast
{
ROS_INFO_STREAM("[PIDPositionController] home geopoint: lat=" << gps_home.latitude << " long=" << gps_home.longitude << " alt=" << gps_home.altitude << " yaw=" << "todo" );
msr::airlib::Vector3r ned_goal = msr::airlib::EarthUtils::GeodeticToNedFast(goal_gps_point, gps_home);
target_position_.x = ned_goal[0];
target_position_.y = ned_goal[1];
target_position_.z = ned_goal[2];
}
target_position_.yaw = request.yaw; // todo
ROS_INFO_STREAM("[PIDPositionController] got GPS goal: lat=" << goal_gps_point.latitude << " long=" << goal_gps_point.longitude << " alt=" << goal_gps_point.altitude << " yaw=" << target_position_.yaw );
ROS_INFO_STREAM("[PIDPositionController] converted NED goal is: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw );
// todo error checks
// todo fill response
has_goal_ = true;
reached_goal_ = false;
reset_errors(); // todo
return true;
}
}
// todo do relative altitude, or add an option for the same?
bool PIDPositionController::gps_goal_srv_override_cb(airsim_ros_pkgs::SetGPSPosition::Request& request, airsim_ros_pkgs::SetGPSPosition::Response& response)
{
if(!has_home_geo_)
{
ROS_ERROR_STREAM("[PIDPositionController] I don't have home GPS coord. Can't go to GPS goal!");
response.success = false;
}
// convert GPS goal to NED goal
msr::airlib::GeoPoint goal_gps_point(request.latitude, request.longitude, request.altitude);
msr::airlib::GeoPoint gps_home(gps_home_msg_.latitude, gps_home_msg_.longitude, gps_home_msg_.altitude);
bool use_eth_lib = true;
if (use_eth_lib_for_geodetic_conv_)
{
double initial_latitude, initial_longitude, initial_altitude;
geodetic_converter_.getReference(&initial_latitude, &initial_longitude, &initial_altitude);
double n, e, d;
geodetic_converter_.geodetic2Ned(request.latitude, request.longitude, request.altitude, &n, &e, &d);
// ROS_INFO_STREAM("[PIDPositionController] geodetic_converter_ GPS reference initialized correctly (lat long in radians) " << initial_latitude << ", "<< initial_longitude << ", " << initial_altitude);
target_position_.x = n;
target_position_.y = e;
target_position_.z = d;
}
else // use airlib::GeodeticToNedFast
{
ROS_INFO_STREAM("[PIDPositionController] home geopoint: lat=" << gps_home.latitude << " long=" << gps_home.longitude << " alt=" << gps_home.altitude << " yaw=" << "todo" );
msr::airlib::Vector3r ned_goal = msr::airlib::EarthUtils::GeodeticToNedFast(goal_gps_point, gps_home);
target_position_.x = ned_goal[0];
target_position_.y = ned_goal[1];
target_position_.z = ned_goal[2];
}
target_position_.yaw = request.yaw; // todo
ROS_INFO_STREAM("[PIDPositionController] got GPS goal: lat=" << goal_gps_point.latitude << " long=" << goal_gps_point.longitude << " alt=" << goal_gps_point.altitude << " yaw=" << target_position_.yaw );
ROS_INFO_STREAM("[PIDPositionController] converted NED goal is: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw );
// todo error checks
// todo fill response
has_goal_ = true;
reached_goal_ = false;
reset_errors(); // todo
return true;
}
void PIDPositionController::update_control_cmd_timer_cb(const ros::TimerEvent& event)
{
// todo check if odometry is too old!!
// if no odom, don't do anything.
if (!has_odom_)
{
ROS_ERROR_STREAM("[PIDPositionController] Waiting for odometry!");
return;
}
if (has_goal_)
{
check_reached_goal();
if(reached_goal_)
{
ROS_INFO_STREAM("[PIDPositionController] Reached goal! Hovering at position.");
has_goal_ = false;
// dear future self, this function doesn't return coz we need to keep on actively hovering at last goal pose. don't act smart
}
else
{
ROS_INFO_STREAM("[PIDPositionController] Moving to goal.");
}
}
// only compute and send control commands for hovering / moving to pose, if we received a goal at least once in the past
if (got_goal_once_)
{
compute_control_cmd();
enforce_dynamic_constraints();
publish_control_cmd();
}
}
void PIDPositionController::compute_control_cmd()
{
curr_error_.x = target_position_.x - curr_position_.x;
curr_error_.y = target_position_.y - curr_position_.y;
curr_error_.z = target_position_.z - curr_position_.z;
curr_error_.yaw = math_common::angular_dist(curr_position_.yaw, target_position_.yaw);
double p_term_x = params_.kp_x * curr_error_.x;
double p_term_y = params_.kp_y * curr_error_.y;
double p_term_z = params_.kp_z * curr_error_.z;
double p_term_yaw = params_.kp_yaw * curr_error_.yaw;
double d_term_x = params_.kd_x * prev_error_.x;
double d_term_y = params_.kd_y * prev_error_.y;
double d_term_z = params_.kd_z * prev_error_.z;
double d_term_yaw = params_.kp_yaw * prev_error_.yaw;
prev_error_ = curr_error_;
vel_cmd_.twist.linear.x = p_term_x + d_term_x;
vel_cmd_.twist.linear.y = p_term_y + d_term_y;
vel_cmd_.twist.linear.z = p_term_z + d_term_z;
vel_cmd_.twist.angular.z = p_term_yaw + d_term_yaw; // todo
}
void PIDPositionController::enforce_dynamic_constraints()
{
double vel_norm_horz = sqrt((vel_cmd_.twist.linear.x * vel_cmd_.twist.linear.x)
+ (vel_cmd_.twist.linear.y * vel_cmd_.twist.linear.y));
if (vel_norm_horz > constraints_.max_vel_horz_abs)
{
vel_cmd_.twist.linear.x = (vel_cmd_.twist.linear.x / vel_norm_horz) * constraints_.max_vel_horz_abs;
vel_cmd_.twist.linear.y = (vel_cmd_.twist.linear.y / vel_norm_horz) * constraints_.max_vel_horz_abs;
}
if (std::fabs(vel_cmd_.twist.linear.z) > constraints_.max_vel_vert_abs)
{
// todo just add a sgn funciton in common utils? return double to be safe.
// template <typename T> double sgn(T val) { return (T(0) < val) - (val < T(0)); }
vel_cmd_.twist.linear.z = (vel_cmd_.twist.linear.z / std::fabs(vel_cmd_.twist.linear.z)) * constraints_.max_vel_vert_abs;
}
// todo yaw limits
if (std::fabs(vel_cmd_.twist.linear.z) > constraints_.max_yaw_rate_degree)
{
// todo just add a sgn funciton in common utils? return double to be safe.
// template <typename T> double sgn(T val) { return (T(0) < val) - (val < T(0)); }
vel_cmd_.twist.linear.z = (vel_cmd_.twist.linear.z / std::fabs(vel_cmd_.twist.linear.z)) * constraints_.max_yaw_rate_degree;
}
}
void PIDPositionController::publish_control_cmd()
{
airsim_vel_cmd_world_frame_pub_.publish(vel_cmd_);
}
| 43.543353
| 213
| 0.694544
|
whatseven
|
9ede66f8f8c0478160490390440cd9c6f62476c4
| 7,571
|
cpp
|
C++
|
level_zero/core/test/unit_tests/sources/debugger/linux/test_l0_debugger_linux.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 1
|
2019-03-01T13:54:45.000Z
|
2019-03-01T13:54:45.000Z
|
level_zero/core/test/unit_tests/sources/debugger/linux/test_l0_debugger_linux.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 5
|
2019-03-26T17:26:07.000Z
|
2021-03-30T12:17:10.000Z
|
level_zero/core/test/unit_tests/sources/debugger/linux/test_l0_debugger_linux.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 4
|
2018-05-09T10:04:27.000Z
|
2018-07-12T13:33:31.000Z
|
/*
* Copyright (C) 2020-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/execution_environment/root_device_environment.h"
#include "shared/source/kernel/debug_data.h"
#include "shared/source/os_interface/linux/os_interface.h"
#include "opencl/test/unit_test/mocks/linux/mock_drm_allocation.h"
#include "opencl/test/unit_test/os_interface/linux/drm_mock.h"
#include "test.h"
#include "level_zero/core/test/unit_tests/sources/debugger/l0_debugger_fixture.h"
using namespace NEO;
namespace L0 {
namespace ult {
struct L0DebuggerLinuxFixture {
void SetUp() {
auto executionEnvironment = new NEO::ExecutionEnvironment();
auto mockBuiltIns = new MockBuiltins();
executionEnvironment->prepareRootDeviceEnvironments(1);
executionEnvironment->setDebuggingEnabled();
executionEnvironment->rootDeviceEnvironments[0]->builtins.reset(mockBuiltIns);
executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(defaultHwInfo.get());
executionEnvironment->initializeMemoryManager();
auto osInterface = new OSInterface();
drmMock = new DrmMockResources(*executionEnvironment->rootDeviceEnvironments[0]);
executionEnvironment->rootDeviceEnvironments[0]->osInterface.reset(osInterface);
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(static_cast<Drm *>(drmMock));
neoDevice = NEO::MockDevice::create<NEO::MockDevice>(executionEnvironment, 0u);
NEO::DeviceVector devices;
devices.push_back(std::unique_ptr<NEO::Device>(neoDevice));
driverHandle = std::make_unique<Mock<L0::DriverHandleImp>>();
driverHandle->enableProgramDebugging = true;
driverHandle->initialize(std::move(devices));
device = driverHandle->devices[0];
}
void TearDown() {
}
std::unique_ptr<Mock<L0::DriverHandleImp>> driverHandle;
NEO::MockDevice *neoDevice = nullptr;
L0::Device *device = nullptr;
DrmMockResources *drmMock = nullptr;
};
using L0DebuggerLinuxTest = Test<L0DebuggerLinuxFixture>;
TEST_F(L0DebuggerLinuxTest, givenProgramDebuggingEnabledWhenDriverHandleIsCreatedThenItAllocatesL0Debugger) {
EXPECT_NE(nullptr, neoDevice->getDebugger());
EXPECT_FALSE(neoDevice->getDebugger()->isLegacy());
EXPECT_EQ(nullptr, neoDevice->getSourceLevelDebugger());
}
TEST_F(L0DebuggerLinuxTest, whenDebuggerIsCreatedThenItCallsDrmToRegisterResourceClasses) {
EXPECT_NE(nullptr, neoDevice->getDebugger());
EXPECT_TRUE(drmMock->registerClassesCalled);
}
TEST(L0DebuggerLinux, givenVmBindAndPerContextVmEnabledInDrmWhenInitializingDebuggingInOsThenRegisterResourceClassesIsCalled) {
auto executionEnvironment = std::make_unique<NEO::ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
executionEnvironment->setDebuggingEnabled();
executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(defaultHwInfo.get());
executionEnvironment->initializeMemoryManager();
auto osInterface = new OSInterface();
auto drmMock = new DrmMockResources(*executionEnvironment->rootDeviceEnvironments[0]);
drmMock->bindAvailable = true;
drmMock->setPerContextVMRequired(true);
executionEnvironment->rootDeviceEnvironments[0]->osInterface.reset(osInterface);
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(static_cast<Drm *>(drmMock));
auto result = WhiteBox<::L0::DebuggerL0>::initDebuggingInOs(osInterface);
EXPECT_TRUE(result);
EXPECT_TRUE(drmMock->registerClassesCalled);
}
TEST(L0DebuggerLinux, givenVmBindNotAvailableInDrmWhenInitializingDebuggingInOsThenRegisterResourceClassesIsNotCalled) {
auto executionEnvironment = std::make_unique<NEO::ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
executionEnvironment->setDebuggingEnabled();
executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(defaultHwInfo.get());
executionEnvironment->initializeMemoryManager();
auto osInterface = new OSInterface();
auto drmMock = new DrmMockResources(*executionEnvironment->rootDeviceEnvironments[0]);
drmMock->bindAvailable = false;
drmMock->setPerContextVMRequired(true);
executionEnvironment->rootDeviceEnvironments[0]->osInterface.reset(osInterface);
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(static_cast<Drm *>(drmMock));
auto result = WhiteBox<::L0::DebuggerL0>::initDebuggingInOs(osInterface);
EXPECT_FALSE(result);
EXPECT_FALSE(drmMock->registerClassesCalled);
}
TEST(L0DebuggerLinux, givenPerContextVmNotEnabledWhenInitializingDebuggingInOsThenRegisterResourceClassesIsNotCalled) {
auto executionEnvironment = std::make_unique<NEO::ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
executionEnvironment->setDebuggingEnabled();
executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(defaultHwInfo.get());
executionEnvironment->initializeMemoryManager();
auto osInterface = new OSInterface();
auto drmMock = new DrmMockResources(*executionEnvironment->rootDeviceEnvironments[0]);
drmMock->bindAvailable = true;
drmMock->setPerContextVMRequired(false);
executionEnvironment->rootDeviceEnvironments[0]->osInterface.reset(osInterface);
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(static_cast<Drm *>(drmMock));
auto result = WhiteBox<::L0::DebuggerL0>::initDebuggingInOs(osInterface);
EXPECT_FALSE(result);
EXPECT_FALSE(drmMock->registerClassesCalled);
}
TEST_F(L0DebuggerLinuxTest, whenRegisterElfisCalledThenItRegistersBindExtHandles) {
NEO::DebugData debugData;
debugData.vIsa = "01234567890";
debugData.vIsaSize = 10;
MockDrmAllocation isaAllocation(GraphicsAllocation::AllocationType::KERNEL_ISA, MemoryPool::System4KBPages);
MockBufferObject bo(drmMock, 0, 0, 1);
isaAllocation.bufferObjects[0] = &bo;
device->getL0Debugger()->registerElf(&debugData, &isaAllocation);
EXPECT_EQ(static_cast<size_t>(10), drmMock->registeredDataSize);
auto &bos = isaAllocation.getBOs();
for (auto bo : bos) {
if (bo) {
auto extBindHandles = bo->getBindExtHandles();
EXPECT_NE(static_cast<size_t>(0), extBindHandles.size());
}
}
}
TEST_F(L0DebuggerLinuxTest, whenRegisterElfisCalledInAllocationWithNoBOThenItRegistersBindExtHandles) {
NEO::DebugData debugData;
debugData.vIsa = "01234567890";
debugData.vIsaSize = 10;
MockDrmAllocation isaAllocation(GraphicsAllocation::AllocationType::KERNEL_ISA, MemoryPool::System4KBPages);
device->getL0Debugger()->registerElf(&debugData, &isaAllocation);
EXPECT_EQ(static_cast<size_t>(10u), drmMock->registeredDataSize);
}
TEST_F(L0DebuggerLinuxTest, givenNoOSInterfaceThenRegisterElfDoesNothing) {
NEO::OSInterface *OSInterface_tmp = neoDevice->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.release();
NEO::DebugData debugData;
debugData.vIsa = "01234567890";
debugData.vIsaSize = 10;
drmMock->registeredDataSize = 0;
MockDrmAllocation isaAllocation(GraphicsAllocation::AllocationType::KERNEL_ISA, MemoryPool::System4KBPages);
device->getL0Debugger()->registerElf(&debugData, &isaAllocation);
EXPECT_EQ(static_cast<size_t>(0u), drmMock->registeredDataSize);
neoDevice->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.reset(OSInterface_tmp);
}
} // namespace ult
} // namespace L0
| 41.828729
| 127
| 0.766874
|
lukaszgotszaldintel
|
9edee36420ae6d029fe5e7c08bfa2fe67a3ebb86
| 1,782
|
cpp
|
C++
|
111. Minimum Depth of Binary Tree.cpp
|
NeoYY/Leetcode-Solution
|
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
|
[
"MIT"
] | null | null | null |
111. Minimum Depth of Binary Tree.cpp
|
NeoYY/Leetcode-Solution
|
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
|
[
"MIT"
] | null | null | null |
111. Minimum Depth of Binary Tree.cpp
|
NeoYY/Leetcode-Solution
|
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
|
[
"MIT"
] | null | null | null |
/*
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
Solution one is recursive, two is iterative.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if ( !root ) return 0;
if ( !root->left ) return minDepth( root->right ) + 1;
if ( !root->right ) return minDepth( root->left ) + 1;
return min( minDepth( root->left ), minDepth( root->right ) ) + 1;
}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if ( !root ) return 0;
int depth = 0;
int width = 0;
queue<TreeNode*> q;
TreeNode *temp = root;
q.push( temp );
while ( !q.empty() )
{
depth++;
width = q.size();
//width is used to clear all nodes in one layer
for ( int i = 0; i < width; i++ )
{
temp = q.front();
q.pop();
if ( !temp->left && !temp->right ) return depth;
if ( temp->left ) q.push( temp->left );
if ( temp->right ) q.push( temp->right );
}
}
return depth;
}
};
| 25.826087
| 114
| 0.517957
|
NeoYY
|
9ee550ee6ddf842985c6a79ad3843bd996d9ad36
| 11,290
|
c++
|
C++
|
c++/src/kj/mutex.c++
|
michaeledgar/capnproto
|
a211aa603c74ff5ce9ac1b1b8c7b1871148c39ab
|
[
"MIT"
] | null | null | null |
c++/src/kj/mutex.c++
|
michaeledgar/capnproto
|
a211aa603c74ff5ce9ac1b1b8c7b1871148c39ab
|
[
"MIT"
] | null | null | null |
c++/src/kj/mutex.c++
|
michaeledgar/capnproto
|
a211aa603c74ff5ce9ac1b1b8c7b1871148c39ab
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "mutex.h"
#include "debug.h"
#if KJ_USE_FUTEX
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <limits.h>
#endif
namespace kj {
namespace _ { // private
#if KJ_USE_FUTEX
// =======================================================================================
// Futex-based implementation (Linux-only)
Mutex::Mutex(): futex(0) {}
Mutex::~Mutex() {
// This will crash anyway, might as well crash with a nice error message.
KJ_ASSERT(futex == 0, "Mutex destroyed while locked.") { break; }
}
void Mutex::lock(Exclusivity exclusivity) {
switch (exclusivity) {
case EXCLUSIVE:
for (;;) {
uint state = 0;
if (KJ_LIKELY(__atomic_compare_exchange_n(&futex, &state, EXCLUSIVE_HELD, false,
__ATOMIC_ACQUIRE, __ATOMIC_RELAXED))) {
// Acquired.
break;
}
// The mutex is contended. Set the exclusive-requested bit and wait.
if ((state & EXCLUSIVE_REQUESTED) == 0) {
if (!__atomic_compare_exchange_n(&futex, &state, state | EXCLUSIVE_REQUESTED, false,
__ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
// Oops, the state changed before we could set the request bit. Start over.
continue;
}
state |= EXCLUSIVE_REQUESTED;
}
syscall(SYS_futex, &futex, FUTEX_WAIT_PRIVATE, state, NULL, NULL, 0);
}
break;
case SHARED: {
uint state = __atomic_add_fetch(&futex, 1, __ATOMIC_ACQUIRE);
for (;;) {
if (KJ_LIKELY((state & EXCLUSIVE_HELD) == 0)) {
// Acquired.
break;
}
// The mutex is exclusively locked by another thread. Since we incremented the counter
// already, we just have to wait for it to be unlocked.
syscall(SYS_futex, &futex, FUTEX_WAIT_PRIVATE, state, NULL, NULL, 0);
state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
}
break;
}
}
}
void Mutex::unlock(Exclusivity exclusivity) {
switch (exclusivity) {
case EXCLUSIVE: {
KJ_DASSERT(futex & EXCLUSIVE_HELD, "Unlocked a mutex that wasn't locked.");
uint oldState = __atomic_fetch_and(
&futex, ~(EXCLUSIVE_HELD | EXCLUSIVE_REQUESTED), __ATOMIC_RELEASE);
if (KJ_UNLIKELY(oldState & ~EXCLUSIVE_HELD)) {
// Other threads are waiting. If there are any shared waiters, they now collectively hold
// the lock, and we must wake them up. If there are any exclusive waiters, we must wake
// them up even if readers are waiting so that at the very least they may re-establish the
// EXCLUSIVE_REQUESTED bit that we just removed.
syscall(SYS_futex, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
}
break;
}
case SHARED: {
KJ_DASSERT(futex & SHARED_COUNT_MASK, "Unshared a mutex that wasn't shared.");
uint state = __atomic_sub_fetch(&futex, 1, __ATOMIC_RELEASE);
// The only case where anyone is waiting is if EXCLUSIVE_REQUESTED is set, and the only time
// it makes sense to wake up that waiter is if the shared count has reached zero.
if (KJ_UNLIKELY(state == EXCLUSIVE_REQUESTED)) {
if (__atomic_compare_exchange_n(
&futex, &state, 0, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
// Wake all exclusive waiters. We have to wake all of them because one of them will
// grab the lock while the others will re-establish the exclusive-requested bit.
syscall(SYS_futex, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
}
}
break;
}
}
}
void Mutex::assertLockedByCaller(Exclusivity exclusivity) {
switch (exclusivity) {
case EXCLUSIVE:
KJ_ASSERT(futex & EXCLUSIVE_HELD,
"Tried to call getAlreadyLocked*() but lock is not held.");
break;
case SHARED:
KJ_ASSERT(futex & SHARED_COUNT_MASK,
"Tried to call getAlreadyLocked*() but lock is not held.");
break;
}
}
void Once::runOnce(Initializer& init) {
startOver:
uint state = UNINITIALIZED;
if (__atomic_compare_exchange_n(&futex, &state, INITIALIZING, false,
__ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
// It's our job to initialize!
{
KJ_ON_SCOPE_FAILURE({
// An exception was thrown by the initializer. We have to revert.
if (__atomic_exchange_n(&futex, UNINITIALIZED, __ATOMIC_RELEASE) ==
INITIALIZING_WITH_WAITERS) {
// Someone was waiting for us to finish.
syscall(SYS_futex, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
}
});
init.run();
}
if (__atomic_exchange_n(&futex, INITIALIZED, __ATOMIC_RELEASE) ==
INITIALIZING_WITH_WAITERS) {
// Someone was waiting for us to finish.
syscall(SYS_futex, &futex, FUTEX_WAKE_PRIVATE, INT_MAX, NULL, NULL, 0);
}
} else {
for (;;) {
if (state == INITIALIZED || state == DISABLED) {
break;
} else if (state == INITIALIZING) {
// Initialization is taking place in another thread. Indicate that we're waiting.
if (!__atomic_compare_exchange_n(&futex, &state, INITIALIZING_WITH_WAITERS, true,
__ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) {
// State changed, retry.
continue;
}
} else {
KJ_DASSERT(state == INITIALIZING_WITH_WAITERS);
}
// Wait for initialization.
syscall(SYS_futex, &futex, FUTEX_WAIT_PRIVATE, INITIALIZING_WITH_WAITERS, NULL, NULL, 0);
state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
if (state == UNINITIALIZED) {
// Oh hey, apparently whoever was trying to initialize gave up. Let's take it from the
// top.
goto startOver;
}
}
}
}
void Once::reset() {
uint state = INITIALIZED;
if (!__atomic_compare_exchange_n(&futex, &state, UNINITIALIZED,
false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
KJ_REQUIRE(state == DISABLED, "reset() called while not initialized.");
}
}
void Once::disable() noexcept {
uint state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
for (;;) {
switch (state) {
case DISABLED:
default:
return;
case UNINITIALIZED:
case INITIALIZED:
// Try to transition the state to DISABLED.
if (!__atomic_compare_exchange_n(&futex, &state, DISABLED, true,
__ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
// State changed, retry.
continue;
}
// Success.
return;
case INITIALIZING:
// Initialization is taking place in another thread. Indicate that we're waiting.
if (!__atomic_compare_exchange_n(&futex, &state, INITIALIZING_WITH_WAITERS, true,
__ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) {
// State changed, retry.
continue;
}
// no break
case INITIALIZING_WITH_WAITERS:
// Wait for initialization.
syscall(SYS_futex, &futex, FUTEX_WAIT_PRIVATE, INITIALIZING_WITH_WAITERS, NULL, NULL, 0);
state = __atomic_load_n(&futex, __ATOMIC_ACQUIRE);
continue;
}
}
}
#else
// =======================================================================================
// Generic pthreads-based implementation
#define KJ_PTHREAD_CALL(code) \
{ \
int pthreadError = code; \
if (pthreadError != 0) { \
KJ_FAIL_SYSCALL(#code, pthreadError); \
} \
}
#define KJ_PTHREAD_CLEANUP(code) \
{ \
int pthreadError = code; \
if (pthreadError != 0) { \
KJ_LOG(ERROR, #code, strerror(pthreadError)); \
} \
}
Mutex::Mutex() {
KJ_PTHREAD_CALL(pthread_rwlock_init(&mutex, nullptr));
}
Mutex::~Mutex() {
KJ_PTHREAD_CLEANUP(pthread_rwlock_destroy(&mutex));
}
void Mutex::lock(Exclusivity exclusivity) {
switch (exclusivity) {
case EXCLUSIVE:
KJ_PTHREAD_CALL(pthread_rwlock_wrlock(&mutex));
break;
case SHARED:
KJ_PTHREAD_CALL(pthread_rwlock_rdlock(&mutex));
break;
}
}
void Mutex::unlock(Exclusivity exclusivity) {
KJ_PTHREAD_CALL(pthread_rwlock_unlock(&mutex));
}
void Mutex::assertLockedByCaller(Exclusivity exclusivity) {
switch (exclusivity) {
case EXCLUSIVE:
// A read lock should fail if the mutex is already held for writing.
if (pthread_rwlock_tryrdlock(&mutex) == 0) {
pthread_rwlock_unlock(&mutex);
KJ_FAIL_ASSERT("Tried to call getAlreadyLocked*() but lock is not held.");
}
break;
case SHARED:
// A write lock should fail if the mutex is already held for reading or writing. We don't
// have any way to prove that the lock is held only for reading.
if (pthread_rwlock_trywrlock(&mutex) == 0) {
pthread_rwlock_unlock(&mutex);
KJ_FAIL_ASSERT("Tried to call getAlreadyLocked*() but lock is not held.");
}
break;
}
}
Once::Once(bool startInitialized): state(startInitialized ? INITIALIZED : UNINITIALIZED) {
KJ_PTHREAD_CALL(pthread_mutex_init(&mutex, nullptr));
}
Once::~Once() {
KJ_PTHREAD_CLEANUP(pthread_mutex_destroy(&mutex));
}
void Once::runOnce(Initializer& init) {
KJ_PTHREAD_CALL(pthread_mutex_lock(&mutex));
KJ_DEFER(KJ_PTHREAD_CALL(pthread_mutex_unlock(&mutex)));
if (state != UNINITIALIZED) {
return;
}
init.run();
__atomic_store_n(&state, INITIALIZED, __ATOMIC_RELEASE);
}
void Once::reset() {
State oldState = INITIALIZED;
if (!__atomic_compare_exchange_n(&state, &oldState, UNINITIALIZED,
false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
KJ_REQUIRE(oldState == DISABLED, "reset() called while not initialized.");
}
}
void Once::disable() noexcept {
KJ_PTHREAD_CALL(pthread_mutex_lock(&mutex));
KJ_DEFER(KJ_PTHREAD_CALL(pthread_mutex_unlock(&mutex)));
__atomic_store_n(&state, DISABLED, __ATOMIC_RELAXED);
}
#endif
} // namespace _ (private)
} // namespace kj
| 33.802395
| 98
| 0.636935
|
michaeledgar
|
9ee9bb95e61fce5de7a41a560133841e914e03f2
| 15,343
|
cpp
|
C++
|
data/409.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/409.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/409.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
int/**/
dK /*OSX*/,ta , /*LIV*/ cbh
,
Vf8aBIx
, lKz,
JW ,
RPh , h ,/*HD*/ rOZ
, ODplY,Qn , kn5H5B , S9c, OZv
//2F
, Pc5
,Wk ,ageqw4H,
UP
, x74 , WB
,t8f//7WX4R
,//af
Zo ,
EpY, tYq1//l
, FMLIpo, yy4BNG,
RZyG
, cSq,Gc ,QvLJ,SXJ,
u2TZ ,//BKv
DZn
,dEwTH,
tBKTulS8
,wTiQr ,DP, di9
,uUe ,vohZ ,HgJ
,
rCX
, su4 ,
FQM/**/ ,y425
,YueB
,
OBt,Ur9KSFU//TB5
,Xi , Ynju ,op //
, k9zf
,
WyT , dei,jsxI ,Yf4,v ,
//jZS
f1;void f_f0(){
int BL;volatile int oV,
a , Zl
,/*L*/zHx, r
,Qgs,OB ,Yn7R /*80d*/,
VsSG,JwqJRbW ,vSEV ; BL
=//6
vSEV +
oV+a //E
+ Zl+
zHx
+
r
;
f1=Qgs+
OB+ Yn7R+ VsSG
+ JwqJRbW;
{//
int pq7//Tt
, VK ;
volatile int
fy6m
, VNWc ,wIPfN,Mu , pW0WbY ,/**/xkK5, t, bgNOE ,//g
e,
u0Xh ,gz , OJo4F, XSwZ
,MmO, mtx
;dK
=//dKM
mtx + fy6m+ VNWc +wIPfN +Mu
;return ;if (
true ) VK = pW0WbY
+ xkK5 +t+/*bO7Pa*/bgNOE + e+ u0Xh; else
pq7 =gz /*x2Lu*/+ OJo4F+
XSwZ
+
MmO;
}
{ int mUH ;/*4*/volatile int xwikl
,
cw,mN , RzK3V9 , J5V ; if
(
true)
for (int i=1
/**/
;i<
1;++i /**/ )
if(true ){
{{ return//
; } //rX
for(int
i=1
;i<
2
;++i
){
} for (int i=1
;i<
3 ;++i ) {;
{
}
}}
{return ; }}else if
(
true
)/*m*/{return
;
{ { } }//7
{{
int w ;
volatile int QFHMQ
,N3G ; w = N3G + QFHMQ
;}if
(
true) if(true)if ( true
)
{{ }
} /*zEh6*/else if (true//
)
{}
//rh9
else
{ /*io*/ }else
{ ;/*Ce*/
return ; } else
{//a
} ;}for
(int i=1
;i</*pt*/4 ;++i)return ;//siP
}
else
{{ /*lpA1O*/{
} }{
for//
(int i=1;i<
5 ;++i)
if( true )if(true) {return ; {
;{
} } }else
{ {
}
}else for
(int
i=1 ;i<6 ;++i)for
(int //
i=1;i< 7;++i )
{{
}//Lz
}} if (true
)
{
{
{ { } } {}//J
for
(int i=1;
i< 8
;++i
) if
(
true//
)
;
else {
} //0tn1
} }else
{
for(int i=1 ;
i<
9;++i
)
{
}}{ /*OQS*/int
ggG ;volatile int
bzU , RbWL//
;{}ggG= RbWL /*Iy*/+bzU ;}
} else
return ;{volatile int KpYU,Ska //
, TbrM
, eZR,//U4
NKS2,
Gg ,V
,
Qtx; ta
= Qtx +
KpYU+Ska+
TbrM;for (int i=1
;i</*IjE*/10 ;++i ) for (int i=1 ; i<11;++i
) for
(int i=1 ;i<12
;++i//
)cbh =eZR+NKS2+ Gg +//
V ; }mUH = J5V +
xwikl+//fzP
cw+ mN
+
RzK3V9 ; {
volatile int
xDiV ,
AQ
, NE //U
,XQ;/*GVe*/Vf8aBIx
=
XQ
+
xDiV+AQ
+NE ;{for(int i=1 ;
i< 13 ;++i) { {} }
}}{ int Pvb ;
volatile int AzA,
NWrG
, gXjmJ,B1A,
gru,
OI /*B7*/, u6 ,dr , h3 ;/**/
lKz
= h3 + AzA
/**/ + NWrG +
gXjmJ +
B1A ;
return ;
Pvb
=gru
+/*MYTC*/OI+ u6
+ dr
;
}for
(int
/*4*/i=1
;i<14 ;++i )
{for (int
i=1 ;
i<15;++i )/**/{
volatile int WHWs
,
QcIAx
//rfWC
,of;return
;JW =of+
WHWs+ QcIAx;}if
( true
) { {
} for (int i=1 ; //
i<//
16 ;++i){ { } }}
else{
{for (int
i=1
;i<
17 ;++i){ }
}} } } { { {int WtD ;
volatile int
DQ7v , vA,bk5
,
Pv
/*5*//*H*/,r4/*9w*/ , wUe , k
; if( true)
{}
else
RPh=
k +/*NX0t*/DQ7v+vA +
bk5 ;WtD=Pv + //U
r4 +
wUe ; } {//
;
}
{ return ;
{ return ;return ; }} }for(int i=1 ;
//d
i< 18 ;++i)/*2*/{
int
RC ;volatile int ZAm ,Wq8D,lh ,/**/laz
,S
,ZCBAL ;
; { ;
{{}
{}//lf
} {
for (int i=1; i<19;++i )if(true
){}else if( true
)return ;
else{
} } } RC=//Y
ZCBAL /*tWNBK*/ +//R
ZAm+
Wq8D+lh+ /*W*/laz
+/*2LkJ*/
S ;
} if (true
){//OPa
{if( true
){//eT
int
//o
rgOQwS; volatile int hi,aQq ,ibGy
;if
( true) ;
else
if(//XI
true )rgOQwS//Gt
= ibGy +
hi
;
else
;for (int
i=1//N
;i<20 ;++i )
h =/*Bhw*/aQq ;}else{ };//XU
//MMY
}
{{{/*2*/}
{ }}
{ }
} {
for
(int i=1;i< 21
;++i
)for(int
i=1;
i<22 ;++i//ALg
)
{}} }else{{int A1q
;volatile int fSPJP ,QqAl
,Gj ;
return ; A1q =Gj+ fSPJP +QqAl
;
}{ for(int i=1
;
i<
23
;++i
) if (true ) { {{{ }
} }/*qK*/ }else ;
{/*qw*/
}}if(true )
return ;else ;
{{volatile int
ffY0
,
XZDY3
;rOZ = XZDY3 +ffY0/*f5*/;} }}for
(int i=1 ;i<
24 ;++i
)
/*G*/{volatile int VWe, VtL
,
GmEY ,
Rm
;
{//3OK
volatile int GH,/*2*/Tf ;;
ODplY
=Tf+ /*k*/GH
/*ZX*/; return ;//q
}
Qn
=//dt
/*B*/Rm +VWe /*on*/+
VtL
+
GmEY ;
}
; }
return ;
}void f_f1//Cr4W
(){
{
;
; { { {
} {
{ }for
(int i=1
;//G7X9
i< 25;++i ) { }
}; {}}{
{ if
(true )/*aR4F*/ //NIT
for (int i=1 ; i< 26 ;++i )
{ }else if (true
); else
;for//SLQ6H
(int i=1 ;i<27;++i
)
{ }}
if/*fH*/(true) {volatile int z6o
, zeQ ;//V
kn5H5B=zeQ+ z6o
;
return
;}else ;}}
}
if//7
(
true
)for/*D0*/(int i=1 ;i<28;++i ){ volatile int SEqQ ,XcC1,
qln9 ,//a
zrvn8
,Zqrx
,
QF//Vphm
//tn
,cFo2;
for
/*j6*/(int i=1;i<29;++i //cL
)for(int i=1 ;/*2Dvj*/i<30 ;++i )S9c =cFo2+ SEqQ +XcC1+
qln9
+/*hyv*/zrvn8
+Zqrx+QF
/*lIB*/;{ int
FwI //go
;volatile int MXcH,ju, JRn6V7/*Fg*/, Ct ; if (
true
)//c
{if(true )return ;else
;{
int EL;volatile int R1,czRR9
;EL = czRR9
+
R1 ;}/*i*/ }
else if ( true ) ;
else ; {;if(
true) ;
else {
volatile int o,bu , iMWG , rjlyj;{{
} } OZv= rjlyj
+o ;
Pc5
=
bu+ iMWG
/*C*/;if (true
)
{/*q1w*/}
else if(//7
true
){ return ;
}//q6p
else
/*qVq*/{
}
} ;}FwI = //Kh
Ct+MXcH
+
ju +JRn6V7 ;
/*Fw8*/}{
{ int yhR ; volatile int
qt ,D;;yhR =D +
qt ; } {volatile int
z ,
iYEKv,nuUI;//5T
Wk
=
nuUI
+z + iYEKv ;//FzoF
}; } } else/*pCu*/{ volatile int TS34,
Nf1,//X
aI , MNy ,hB
;for (int /**/
i=1 ;
i<31;++i )if( true)
for(int i=1 ; i< 32
;++i)
ageqw4H =
hB+TS34 + Nf1 + aI
+ MNy//M
; else for(int i=1; i<
33;++i)
if(
true) { int yx; volatile int
Xb ,Xv/*m*/
,
jL ;if( true/**/)
{/*K*/return
;{}return ;}else /*O*/ { { {} for (int
i=1 ;i<
34 ;++i
)for (int i=1;
i<
35
;++i) { { }
}{
}
}for(int i=1;i< 36 ;++i//aF
)
{ {if( true)
{} else { } }{volatile int Ey ; for (int i=1
; i<//zy4H
37;++i ) UP =Ey;
} }
{ } }//Cc
//byV
//p
for(int
i=1 ;
i< 38
;++i
) //4
if (true ) //3
//Ik
{
{{ }
} {
if(true
)
{} else
for(int i=1
;i<39;++i
) if/*il*/(true){ } else return ;}}else{{int AhR/*YPHX5x*/;volatile int A5NW ,vbmnH
,
UrDK
,/**/ qukt; { } { }if (true)
AhR=qukt
+
A5NW ;
else x74 =
vbmnH//S
+
UrDK; }
for (int i=1 ; i<
40 ;++i){for (int i=1; i<41;++i) for(int
i=1
/**/;i<42
;++i ) { } return ;{
}//rJP
} } for//XW
(int i=1;i<//r
43
;++i) for (int i=1 ; i<44 ;++i); yx = jL/*py*/+Xb+Xv; ;}
else{volatile int gaU8/**/ ,
eNS , bU;{
{
return ;
}} for
(int
i=1
;
i<45//c74Of
;++i )WB
/*gxY*/=bU+ gaU8
+eNS;
}{
{
volatile int KZm,
a0
,
Kb
;if( true)if(
true){ ; }else t8f=
Kb
+
KZm //bN
+a0;else{}} /*C*/;//a0
{volatile int okg,
sp9l
, Fx;Zo
/*Ho5g*///
=Fx+ /*EU*/okg+sp9l;
if
( true
) {/*1m*/;
} else{
}{} }};for(int i=1
;i< 46
;++i)
for (int i=1
;
i< //o
47 ;++i )if (true
) if ( true ) ;else if
( true )
{ int Qa ; volatile int UAL,Oh, Or //Hw
,o0 ,i1; {
{{} }if (true );
//P
else {} {volatile int/*w*/ bs1N
,F,oE/*U*/;
for (int i=1;i<48 ;++i)
EpY= oE +
bs1N+
F/*peQdgk*//*i5f*/ ;}} if(
true)Qa
=i1 +UAL +Oh+Or+ o0; else return ;
{{{
} {
/*F*/
}}/*HB*/{
}} } else
{ {volatile int WPw
,
iQ/*t*/
; tYq1 =iQ + WPw; }
{
if /*D*/(true) ;
else
; } {int oY;volatile int
b ,MfoE4 , d;
if
(//Lvn
true)
for (int i=1 ;/*j*/i< /*n*/49//Tl
;++i)oY= d+b +MfoE4//5Yg
; else return
; }/*F*/ } else {
{ {{
//nsIZ
}{} }} {{ //
volatile int/*Ic*/ DUj,IX ,
Tp; for (int i=1 ;i< 50;++i
)for (int i=1
; i<51;++i) {} FMLIpo = Tp + //
DUj +
IX;} ;
{{}}
}}
}
if(
true/*9uy*/) {
volatile int Qf , /*j*/VZBS5 ,
DA,
A1lw,M7NZ2//
,c
;
{volatile int FA, tD,rht ;
{
{for
(int i=1 ;i<52;++i
){}/*k*/ }} yy4BNG =
rht+ FA +
tD;
} RZyG =c +Qf
+VZBS5//q
+/*Kl*/
DA
+
A1lw +/*JT*/ M7NZ2;
;{
for(int i=1 ;i< 53//0Nrg
;++i)if
( true) {
for
(int i=1;
i<54;++i)return ;if (true ) {
{volatile int
BTJP,
FEvfM //kmBVHg
;{ }cSq=FEvfM +BTJP
;
}}
else /*G*/{ {
}
}}else{{int
GW;volatile int FgO
,wuII ,Vd
;GW=
Vd +FgO+
wuII ; }
{volatile int sdOhE
;Gc /*6*/
= sdOhE
; }} ;{ {
for(int i=1
;i< 55
;++i ) ;{ {}
{ }}
}//H
for/*1*//*PO*/(int
i=1
;i<//MeR
56;++i)
for(int /*Vt*/
i=1;i< 57;++i )
{
} for(int
i=1 ; i<
58 ;++i )for
(int
i=1
;i<
59 ;++i){ ; } { return ;} } }} else
return ;//
{volatile int Lck,
EgZ//dsE3
,rg6RE
,
SN ; {return
;if
(true/*Fs2*/) {{ //4
} /*hCf*/ /*uo*/for
(int i=1;
/*yxnA*/i<
60;++i)
{} }else//fX
{
{
} }//aE
/*v*/
if (true ){ int
sA; volatile int
Q7 , ckB
; if
/*xec7*/ (true){ } else//EEPjF
sA=ckB + Q7; }
else
{ ;;;}
}//d9
for
/*5*/(int i=1;
i< 61;++i) ;
QvLJ
=SN+ Lck
+
EgZ
+rg6RE ; return ;
{ {for//Q
(int i=1;
i<//OHRk
62//n1M
;++i
)
return
;
{for(int i=1; //y
i<63/**/;++i)
/*2Aj*/{} } {}//1cqDW
}{volatile int
AoJ
,
lNR,
Y;if
( true)
{for (int i=1 ; i<
/**/
64;++i/*jUP*/ //hjL
)
;} else{
} { volatile int//fwl
KP
, mo , jQF; if(true )SXJ =jQF+KP+
mo//3A64
;
else return ; } u2TZ =
Y//pXE
+
AoJ
+lNR
; }{{ }
}for//1
(int i=1 ; i<65;++i ) {if /*Wv*/
( //M
true)
/**/{ }/**/else
return ;//Hlz
;}
}
}return ;
} void
f_f2(){ volatile int O97XF
,R , XwL4
,
jl ,d59y;{/*Svh*/return ; { volatile int U
, JUTr
,TEmB,NIqU ;{;/*OP*/{ { } }} for(int
i=1
;//1QV
i<
66
;++i
)DZn
= /*G1Wv*/NIqU
+U+ JUTr+TEmB ;{ { {
/*Hlw*/}}
{} }{{int//AlX
CV ;
volatile int WR ;CV = WR ;} } }{ ; //bH
for(int i=1
;
i<67 ;++i) {
{ } {//
;
{;}
return ; }
/*G*/}}
}dEwTH=d59y +
O97XF+
R +XwL4 +jl;if (true ) {
int GWn ; volatile int gsrHu,Fw, Rq3,GJO , Dq; {return ; { {}}{
{ return/*iBH*/ ;} }}
{//
{
volatile int
sYQ3
,g
,Onbd ;tBKTulS8 =
Onbd +sYQ3+g; for(int i=1;i<
68;++i) { { }{//chxz
{
}} {}
{} }};{for (int i=1
; i<69;++i
/*cO*/ )return ; for
(int i=1
; i<70
/*XK*/;++i)
return ; } { int IuB;
volatile int
A
,
s;for//sw
(int
i=1
; i<
71;++i)IuB=s+
A;}/*up*/return//k
; } GWn=Dq+gsrHu
+ Fw +Rq3 +/*L*/GJO; if( true
/**/){//
int CQ
;volatile int oPn
,
XS3,
Aqcd, hH , q6ESS
,O, ro, Pd
, ZB ,/*SQ0N*/
a2
; {
{;{ } } } if (
true )if (true)//lG8
wTiQr
= a2
+
oPn +XS3 + Aqcd ;else if(true)
DP =hH
+
q6ESS +
O;else{
int djTp ;volatile int JHQxon//7SMq
,
AS//cH5
,
r2k;
{ } for(int
i=1
; i<72;++i
/**/)
for(int
i=1 ;/*T*/ i</*hrG*/73 ;++i ) for (int i=1
;
i<74 ;++i ){
//jSS4
}for (int i=1 ;i<75
;++i
) djTp
=
/*gY*/ r2k
+ JHQxon
+AS/*Hq*/ ;} //ba65
else{{/*rlf*/{}}
{
if
(true ) return ;else { if
(
true)return
/**/ ;
else{
;}
} }{ return
; return ;for(int //3sGwNe
i=1 ;
i<
76;++i )//RTZNc3
/**/{
}/*Ih*/} //
}
if(true ) CQ
= ro
+Pd + ZB;else{
{/*usS*/}
if
(//AGhQU
true )//cUu9
//9f
return
;else{} //xr
} } else {int EE//6
;
volatile int
fl0 , Cqq, mb//UYn
; {return
; //A2
return//MNX
;{{}{volatile int
AV3;//IYF
for (int //mi
i=1
;i<77
;++i )di9
=AV3 ;//f5h
//KwC1
{ }
{ }}{ {
/**/} } }
{ {
} }} EE
//ZK
=mb+ fl0
+/*gt*/ Cqq ;
{
{ {
}if(//x
/*FTn*/true ) {} else
; }//DFXJ
}}{ {
{ for(int i=1 ; i<
78
;++i )//XQ
{{} {for(int i=1 ; i<79;++i)
{
}//2Xr5J
//ef
} }}
}
{ volatile int
XUG,
x3cN ;
{int OJ ;volatile int
jE
,
CSNaG ;
OJ= CSNaG/*Q*/+ jE;} uUe= x3cN+XUG ; ; }
for/*4xz*/
(int
i=1 ;
i<80/*VwXb*/
;++i ){
{{
{/*amo*/
} } if//ek
( true){ }else {}
}}
/*4*/{ volatile int
kg,HbL
,ZhHJbC//N
,//dPn
yszT
;
{/*e*/
}vohZ
= yszT+
kg+
HbL +
ZhHJbC; }{
//i
{ } {} } } { {{
int //dlayH
c79/*UXE*/;//w
volatile int
WH,OBn ,fv
;{ ; }/*9u*/c79=fv
//l
+ WH
+OBn
; }
if
(true )
if ( true ) { for
(int i=1; i< 81//
;++i )
{}
}else return
;
else {
} { for //k
(int
i=1
;i<82 ;++i
)
return ; }}for (int //RSc
i=1;
i<
83;++i ){
;
;
}{ { /*wr*/{}{int/*Vlb*/
Bas;
volatile int NT9l, wwROd/*6CG*/
;for(int i=1/*Q6K*/
;i< 84 ;++i) if ( /*vf*/true );
else return
; Bas= wwROd +NT9l
;} }
} } }
else {
volatile int i/**/, pNkD ,
uZNi,TsVb//3Qwn
;
{
int IEMT5
;volatile int //Axjc
hg
,nv,pa,DjO,kHm ,qy9
,
OM,
oow//
,
u3C3/**/,
Nm1Bn;HgJ =
Nm1Bn + hg+
nv + pa ;if( true){
volatile int//G
O6XKs ,
cuK , tA, yy6j
, HSND;if ( true) { ;}else return ;{for
/*D*/(int i=1
; i<
85 ;++i )
; }rCX=HSND+O6XKs+cuK
+tA+ yy6j;}else
//LC1
; if
(true
) IEMT5 =DjO
+kHm
+ qy9; else su4=OM +oow
+u3C3; }{ return
;
{
{/*0*/{
/*zVB*/} } /*z*/ }}
FQM=TsVb +
i
+pNkD
+/*G*/uZNi
; return//nPNm
;}
{ int rtb ; volatile int A3,a9, ypR6S
, xq,Wr ,
XwRHc
,
xN ,jBW
, //qtQ
P6,
BQ; if(true)//jn
rtb =BQ +A3 +
a9
+ ypR6S+xq; else {;return ;
{{/*dLQJj*/ } for(int
i=1 ;i< 86;++i)
{
}
} {
{}}if (
true
) ; else return ;}
{ {{ {
}}
return ;}
;
}
y425
=Wr +XwRHc +xN+ jBW
+P6
;;
}
/*4*/
{volatile int
pFe//
,
Q0lP , M14lA02 , qI
, ki
,fmU8O,CWn,
I,
sGl ; YueB= sGl
+pFe +Q0lP +M14lA02 ; for (int i=1 ; i<87 ;++i
)
{{for(int i=1
;/*AWxqd*/i<
88;++i
){ for(int i=1;
i<89 /**/;++i
){//
if ( true );else/*Zd*/
for/*uWgK*/(int i=1;i<
/*JP*/90;++i) ;
}}
{volatile int J8qL;OBt
=J8qL;;;
} }{
for
(int i=1;
i< 91/*dom*/
;++i/*u*/) //C
;}} if
( true )
{ int TPFiM ;volatile int/*5*/ Aip , f
,/*FC*/
Fzo,uMHX8R, zG
,s6gD , uW5W//b3
;TPFiM =uW5W+
Aip+ f +Fzo
;for (int i=1
; i<
92 ;++i )return ; Ur9KSFU
= uMHX8R
+zG+ s6gD ; //o
}
else Xi = qI+ ki
+
fmU8O +
CWn+I
;{/*5O*/int AE /*l*/
;//35
volatile int
ViS
,
oLf
,BNzp ;AE =BNzp+ViS +oLf ;
return ;;/*6p*/}
}
{ volatile int //B1
sjD
,L/**/,
Q0
,fQ8
,m ,K7 ,
cO ,lr
, QV5H;//jA
Ynju =QV5H+sjD
+ L
+Q0
+fQ8 ;return ;
{ return ;
if(true ){/*u49aC*/{
//yj
}/*6w*/} else { {{ }
{
}
}}if/*i*/(true//sQ
)return ; else if ( true) //VD
for
(int
i=1;i<
93;++i) ;
else{ {}
}}
{
volatile int/*M9L*/
dDE ,xCJ
,
Gq7 , EDFYw ; //k
{ {}{ } }for //FcS
(int i=1 ;
i< 94
;++i
) {
volatile int KY ,
FFfO,
rS//V
; op=rS + KY+
FFfO ;/*D*/for (int i=1 ;i<95
//5J
;++i
) {return ; {}{}} } {{{
{
}
/*2W8X*/
}}
}
k9zf
=/*928x*/EDFYw
+dDE+xCJ+ Gq7 ; }for(int i=1;i<//YFQL
96
;++i) WyT =
m+/*y*/K7
+
cO +lr ;}/*K*/
return
;/**/} int main(){
int ads
; volatile int
ib, NZhS,
g6Ex, l, NSFck,
XGdKR2l,
U1H
, J6l, ll ,Rt ,QS;
dei=QS
+ ib
+
NZhS +
g6Ex//ex
+
l +
NSFck;
ads = XGdKR2l + U1H
+J6l +ll
/*vm*/+ Rt;
{{int wNX//h29FL
;volatile int sBtI ,Ex,
Cnp,
zCC, lhPR , nkUvWJ, O8yU, LE0WQ
,//ja
nM5,bvXQ0Y, ugW, aaG3B
; {{}
{
;//01
;
for (int i=1 ; i<97 ;++i ) if(
true)
for (int i=1;i< //t
98/*P*/;++i )
//E
{} else {}
}
} for(int i=1; i<99
//MqK
;++i )//C
if (true
) jsxI =
aaG3B+ sBtI+
//P8YBC
Ex+
Cnp;else wNX /*0U*/=zCC +lhPR + nkUvWJ +
O8yU +LE0WQ /*PBw*/ ;
Yf4=nM5 +/*a*/bvXQ0Y
+
ugW;
{ {}for (int
i=1
//cSb
;i<
100 ;++i) {//TO
volatile int P4aZ ; { }v =P4aZ ;
{ }}{{ int Lov;volatile int bA;if(/*O*/true
)
for
(int i=1; i<101 ;++i
) Lov= bA ;else return
1283542792
; if/**/( true
){ }
else { }} {
for(int
i=1;i<102
;++i
)for(int i=1;
i< 103;++i )if (
true ){ } else {}}}}};{ return
1548425715
;//AFe
if (//rK8jE
true){for
(int i=1;i< 104
;++i
) {{;}{ ;}
}for(int i=1; i<
//ijP
105 ;++i) {
{
}{
} }
} else
for(int
//63
i=1 ;i< 106
;++i){
{ }
}
for
(int
i=1;
i<107;++i)
{
{
return 137378445;}{
}
} }
} if
(
true) return 327693335
;else return 839992021 ; }
| 10.221852
| 87
| 0.453106
|
TianyiChen
|
9eeac98af5009ed592d4fdb55c08b26df865e519
| 2,850
|
cpp
|
C++
|
BAC_2nd/ch9/uva10618.cpp
|
Anyrainel/aoapc-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | 3
|
2017-08-15T06:00:01.000Z
|
2018-12-10T09:05:53.000Z
|
BAC_2nd/ch9/uva10618.cpp
|
Anyrainel/aoapc-related-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | null | null | null |
BAC_2nd/ch9/uva10618.cpp
|
Anyrainel/aoapc-related-code
|
e787a01380698fb9236d933462052f97b20e6132
|
[
"Apache-2.0"
] | 2
|
2017-09-16T18:46:27.000Z
|
2018-05-22T05:42:03.000Z
|
// UVa10618 Tango Tango Insurrection
// Rujia Liu
// Tricky case: .RDLU
// Answer: RLRLR (yes, you TURNED around!)
#include<cstdio>
#include<cstring>
#include<cassert>
const int UP = 0;
const int LEFT = 1;
const int RIGHT = 2;
const int DOWN = 3;
const int maxn = 70 + 5;
// d[i][a][b][s] means the minimal future energy when you already tapped i notes
// your left foot at a, right foot at b, last foot is s
int d[maxn][4][4][3];
// if the optimal strategy is to move foot f(0~2) to position t, action=f*4+t
int action[maxn][4][4][3];
char seq[maxn], pos[256], footch[] = ".LR";
// energy needed to move a foot FOR THE SECOND TIME, from a to ta
int energy(int a, int ta) {
if(a == ta) return 3;
if(a + ta == 3) return 7; // across
return 5; // adjacent
}
int energy(int i, int a, int b, int s, int f, int t, int& ta, int& tb) {
ta = a; tb = b;
if(f == 1) ta = t;
else if(f == 2) tb = t;
// check target arrows
if(ta == tb) return -1;
if(ta == RIGHT && tb == LEFT) return -1;
if(a == RIGHT && tb != b) return -1; // you can't move you right foot before your left foot comes back
if(b == LEFT && ta != a) return -1;
// compute energy
int e;
if(f == 0) e = 0; // no move
else if(f != s) e = 1; // alternative foot, low energy
else {
if(f == 1) e = energy(a, ta);
else e = energy(b, tb);
}
return e;
}
// update state (i,a,b,s). foot f is moved to t
void update(int i, int a, int b, int s, int f, int t) {
int ta, tb;
int e = energy(i, a, b, s, f, t, ta, tb);
if(e < 0) return; // invalid
int cost = d[i+1][ta][tb][f] + e;
int& ans = d[i][a][b][s];
if(cost < ans) {
ans = cost;
action[i][a][b][s] = f * 4 + t;
}
}
int main() {
pos['U'] = 0; pos['L'] = 1; pos['R'] = 2; pos['D'] = 3;
while(scanf("%s", seq) == 1) {
if(seq[0] == '#') break;
int n = strlen(seq);
memset(d, 0, sizeof(d));
for(int i = n-1; i >= 0; i--)
for(int a = 0; a < 4; a++)
for(int b = 0; b < 4; b++) if(a != b)
for(int s = 0; s < 3; s++) {
d[i][a][b][s] = 10*n;
if(seq[i] == '.') {
update(i, a, b, s, 0, 0); // no move
for(int t = 0; t < 4; t++) {
update(i, a, b, s, 1, t); // move left foot
update(i, a, b, s, 2, t); // move right foot
}
} else {
update(i, a, b, s, 1, pos[seq[i]]); // move left foot
update(i, a, b, s, 2, pos[seq[i]]); // move right foot
}
}
// print solution
int a = LEFT, b = RIGHT, s = 0; // d[0][1][2][0] is out answer
for(int i = 0; i < n; i++) {
int f = action[i][a][b][s] / 4;
int t = action[i][a][b][s] % 4;
printf("%c", footch[f]);
s = f;
if(f == 1) a = t;
else if(f == 2) b = t;
}
printf("\n");
}
return 0;
}
| 26.886792
| 104
| 0.488421
|
Anyrainel
|
9eed1baa918fa824b153af7b47a3524aa46d02d7
| 12,572
|
hpp
|
C++
|
src/container/ordered_map.hpp
|
clienthax/neptools
|
90f3e1cc8cf388e7050b15c44fa51e330973fd53
|
[
"WTFPL"
] | 1
|
2021-04-23T20:23:26.000Z
|
2021-04-23T20:23:26.000Z
|
src/container/ordered_map.hpp
|
clienthax/neptools
|
90f3e1cc8cf388e7050b15c44fa51e330973fd53
|
[
"WTFPL"
] | null | null | null |
src/container/ordered_map.hpp
|
clienthax/neptools
|
90f3e1cc8cf388e7050b15c44fa51e330973fd53
|
[
"WTFPL"
] | null | null | null |
#ifndef UUID_6D8552D7_1BF6_468A_A6E3_D0829B5390C1
#define UUID_6D8552D7_1BF6_468A_A6E3_D0829B5390C1
#pragma once
#include "intrusive.hpp"
#include "../shared_ptr.hpp"
#include <boost/intrusive/set.hpp>
#include <vector>
namespace Neptools
{
NEPTOOLS_GEN_EXCEPTION_TYPE(ItemAlreadyAdded, std::logic_error);
template <typename T, typename KeyOfValue,
typename Compare = std::less<typename KeyOfValue::type>>
class OrderedMap;
using OrderedMapItemHook = boost::intrusive::set_base_hook<
boost::intrusive::tag<struct OrderedMapItemTag>,
boost::intrusive::optimize_size<true>,
LinkMode>;
struct OrderedMapItem : public RefCounted, public OrderedMapItemHook
{
private:
size_t vector_index = -1;
template <typename T, typename KeyOfValue, typename Compare>
friend class OrderedMap;
};
template <typename Smart, typename T>
class OrderedMapIterator
: public std::iterator<std::random_access_iterator_tag, T>
{
using VectorType = std::vector<Smart>;
using Ptr = typename VectorType::pointer;
public:
OrderedMapIterator() = default;
friend class OrderedMapIterator<Smart, const T>;
OrderedMapIterator(const OrderedMapIterator<Smart, std::remove_const_t<T>>& it)
: ptr{it.ptr} {}
T& operator*() const noexcept { return **ptr; }
T* operator->() const noexcept { return &**ptr; }
T& operator[](std::ptrdiff_t n) { return *(*this + n); }
#define NEPTOOLS_GEN(op) \
bool operator op(const OrderedMapIterator& o) const noexcept \
{ return ptr op o.ptr; }
NEPTOOLS_GEN(==) NEPTOOLS_GEN(!=) NEPTOOLS_GEN(<) NEPTOOLS_GEN(<=)
NEPTOOLS_GEN(>) NEPTOOLS_GEN(>=)
#undef NEPTOOLS_GEN
#define NEPTOOLS_GEN(op) \
OrderedMapIterator& operator op##op() noexcept \
{ op##op ptr; return *this; } \
OrderedMapIterator operator op##op(int) noexcept \
{ auto ret = *this; op##op ptr; return ret; } \
\
OrderedMapIterator& operator op##=(std::ptrdiff_t n) noexcept \
{ ptr op##= n; return *this; } \
OrderedMapIterator operator op(std::ptrdiff_t n) const noexcept \
{ auto ret = *this; ret op##= n; return ret; } \
friend OrderedMapIterator operator op( \
std::ptrdiff_t n, OrderedMapIterator it) noexcept \
{ it op##= n; return it; }
NEPTOOLS_GEN(+) NEPTOOLS_GEN(-)
#undef NEPTOOLS_GEN
std::ptrdiff_t operator-(OrderedMapIterator o) const noexcept
{ return ptr - o.ptr; }
private:
template <typename U>
explicit OrderedMapIterator(U ptr) : ptr{const_cast<Ptr>(ptr)} {}
Ptr ptr = nullptr;
std::remove_const_t<T>* Get() const noexcept { return ptr->get(); }
template <typename U, typename KeyOfValue, typename Compare>
friend class OrderedMap;
};
template <typename T, typename Traits, typename Compare>
class OrderedMap
{
using VectorType = std::vector<NotNull<SmartPtr<T>>>;
using SetType = boost::intrusive::set<
T, boost::intrusive::base_hook<OrderedMapItemHook>,
boost::intrusive::constant_time_size<false>,
boost::intrusive::compare<Compare>,
boost::intrusive::key_of_value<Traits>>;
public:
using value_type = T;
using reference = T&;
using const_reference = const T&;
using iterator = OrderedMapIterator<NotNull<SmartPtr<T>>, T>;
using const_iterator = OrderedMapIterator<NotNull<SmartPtr<T>>, const T>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using difference_type = std::size_t;
using size_type = std::size_t;
using key_type = typename SetType::key_type;
OrderedMap() = default;
~OrderedMap() { for (auto& x : vect) RemoveItem(*x); }
// set should have a move ctor but no copy ctor
T& at(size_t i)
{
NEPTOOLS_ASSERT(VectorIndex(*vect.at(i)) == i);
return *vect.at(i);
}
const T& at(size_t i) const
{
NEPTOOLS_ASSERT(VectorIndex(*vect.at(i)) == i);
return *vect.at(i);
}
T& operator[](size_t i)
{
NEPTOOLS_ASSERT(VectorIndex(*vect.at(i)) == i);
return *vect[i];
}
const T& operator[](size_t i) const
{
NEPTOOLS_ASSERT(VectorIndex(*vect.get(i)) == i);
return *vect[i];
}
T& front()
{
NEPTOOLS_ASSERT(VectorIndex(*vect.front()) == 0);
return *vect.front();
}
const T& front() const
{
NEPTOOLS_ASSERT(VectorIndex(*vect.front()) == 0);
return *vect.front();
}
T& back()
{
NEPTOOLS_ASSERT(VectorIndex(*vect.back()) == vect.size()-1);
return *vect.back();
}
const T& back() const
{
NEPTOOLS_ASSERT(VectorIndex(*vect.back()) == vect.size()-1);
return *vect.back();
}
#define NEPTOOLS_GEN(dir, typ) \
typ##iterator dir() noexcept \
{ return ToIt(vect.dir()); } \
const_##typ##iterator c##dir() const noexcept \
{ return ToIt(vect.c##dir()); } \
const_##typ##iterator dir() const noexcept \
{ return ToIt(vect.c##dir()); }
NEPTOOLS_GEN(begin,) NEPTOOLS_GEN(end,)
NEPTOOLS_GEN(rbegin, reverse_) NEPTOOLS_GEN(rend, reverse_)
#undef NEPTOOLS_GEN
bool empty() const noexcept
{
NEPTOOLS_ASSERT(vect.empty() == set.empty());
return vect.empty();
}
size_t size() const noexcept { return vect.size(); }
// boost::intrusive doesn't have max size
size_t max_size() const noexcept { return vect.max_size(); }
// only modifies the vector part
void reserve(size_t cap) { vect.reserve(cap); }
size_t capacity() const noexcept { return vect.capacity(); }
void shrink_to_fit() { vect.shrink_to_fit(); }
// modify both
void clear() noexcept
{
for (auto& x : vect) RemoveItem(*x);
set.clear(); vect.clear();
}
std::pair<iterator, bool> insert(
const_iterator p, const NotNull<SmartPtr<T>>& t)
{ return InsertGen(p, t); }
std::pair<iterator, bool> insert(const_iterator p, NotNull<SmartPtr<T>>&& t)
{ return InsertGen(p, std::move(t)); }
template <typename... Args>
std::pair<iterator, bool> emplace(const_iterator p, Args&&... args)
{ return InsertGen(p, MakeSmart<T>(std::forward<Args>(args)...)); }
iterator erase(const_iterator it) noexcept
{
set.erase(ToSetIt(it));
return VectErase(it);
}
iterator erase(const_iterator b, const_iterator e) noexcept
{
// RemoveItem would break assert in ToVecIt if it'd executed at vect.erase
auto bi = ToVectIt(b), ei = ToVectIt(e);
for (auto it = b; it != e; ++it)
{
RemoveItem(const_cast<T&>(*it));
set.erase(ToSetIt(it));
}
auto ret = vect.erase(bi, ei);
FixupIndex(ret);
return ToIt(ret);
}
std::pair<iterator, bool> push_back(const NotNull<SmartPtr<T>>& t)
{ return InsertGen(end(), t); }
std::pair<iterator, bool> push_back(NotNull<SmartPtr<T>>&& t)
{ return InsertGen(end(), std::move(t)); }
template <typename... Args>
std::pair<iterator, bool> emplace_back(Args&&... args)
{ return InsertGen(end(), MakeSmart<T>(std::forward<Args>(args)...)); }
void pop_back() noexcept
{
auto& back = *vect.back();
RemoveItem(back);
set.erase(Traits{}(back));
vect.pop_back();
}
void swap(OrderedMap& o)
{
vect.swap(o.vect);
set.swap(o.set);
}
// boost extensions
iterator nth(size_t i) noexcept { return ToIt(vect.begin() + i); }
const_iterator nth(size_t i) const noexcept { return ToIt(vect.begin() + i); }
size_t index_of(const_iterator it) const noexcept
{
return VectorIndex(*it);
}
// map portions
size_t count(const key_type& key) const { return set.count(key); }
template <typename Key, typename Comp>
size_t count(const Key& key, Comp comp) const { return set.count(key, comp); }
iterator find(const key_type& key)
{ return ToMaybeEndIt(set.find(key)); }
template <typename Key, typename Comp>
iterator find(const Key& key, Comp comp)
{ return ToMaybeEndIt(set.find(key, comp)); }
const_iterator find(const key_type& key) const
{ return ToMaybeEndIt(set.find(key)); }
template <typename Key, typename Comp>
const_iterator find(const Key& key, Comp comp) const
{ return ToMaybeEndIt(set.find(key, comp)); }
// misc intrusive
iterator iterator_to(T& t) noexcept { return ToIt(t); }
const_iterator iterator_to(const T& t) const noexcept { return ToIt(t); }
// return end() on invalid ptr
iterator checked_iterator_to(T& t) noexcept
{
if (vect[VectorIndex(t)].get() == &t) return ToIt(t);
else return end();
}
const_iterator checked_iterator_to(const T& t) const noexcept
{
if (vect[VectorIndex(t)].get() == &t) return ToIt(t);
else return cend();
}
// we'd need pointer to smartptr inside vector
// static iterator s_iterator_to(T& t) noexcept { return iterator{t}; }
// static const_iterator s_iterator_to(const T& t) noexcept
// { return const_iterator{t}; }
std::pair<iterator, bool> key_change(iterator it) noexcept
{
set.erase(ToSetIt(it));
auto ins = set.insert(*it);
auto rit = it;
if (!ins.second)
{
VectErase(it);
rit = ToIt(*ins.first);
}
return {rit, ins.second};
}
private:
static size_t& VectorIndex(OrderedMapItem& i) noexcept
{ return i.vector_index; }
static size_t VectorIndex(const OrderedMapItem& i) noexcept
{ return i.vector_index; }
void FixupIndex(typename VectorType::iterator b) noexcept
{ for (; b != vect.end(); ++b) VectorIndex(**b) = b - vect.begin(); }
void RemoveItem(T& t) noexcept { VectorIndex(t) = -1; }
template <typename U>
std::pair<iterator, bool> InsertGen(const_iterator p, U&& t)
{
if (VectorIndex(*t) != size_t(-1))
NEPTOOLS_THROW(ItemAlreadyAdded{"Item already added to an OrderedMap"});
typename SetType::insert_commit_data data{};
auto itp = set.insert_check(Traits{}(*t), data);
if (itp.second)
{
auto& ref = *t;
auto it = vect.insert(ToVectIt(p), std::forward<U>(t));
// noexcept from here
FixupIndex(it);
set.insert_commit(ref, data);
return {ToIt(it), true};
}
return {ToIt(*itp.first), false};
}
iterator VectErase(const_iterator it) noexcept
{
auto vit = ToVectIt(it); // prevent assert after RemoveItem
RemoveItem(*it.Get());
auto ret = vect.erase(vit);
FixupIndex(ret);
return ToIt(ret);
}
iterator ToIt(const OrderedMapItem& it) const noexcept
{
NEPTOOLS_ASSERT(vect[VectorIndex(it)].get() == &it);
return iterator{&vect[VectorIndex(it)]};
}
iterator ToIt(typename VectorType::iterator it) noexcept
{
NEPTOOLS_ASSERT(it == vect.end() ||
VectorIndex(**it) == size_t(it-vect.begin()));
return iterator{&*it};
}
const_iterator ToIt(typename VectorType::const_iterator it) const noexcept
{
NEPTOOLS_ASSERT(it == vect.end() ||
VectorIndex(**it) == size_t(it-vect.begin()));
return const_iterator{&*it};
}
typename VectorType::iterator ToVectIt(iterator it)
{ return vect.begin() + (it-begin()); }
typename VectorType::const_iterator ToVectIt(const_iterator it) const
{ return vect.begin() + (it-begin()); }
typename SetType::const_iterator ToSetIt(const_iterator it) const
{
NEPTOOLS_ASSERT(it != cend());
return set.iterator_to(*it);
}
iterator ToMaybeEndIt(typename SetType::const_iterator it) const
{
if (it == set.end())
return iterator{&*vect.end()};
else return ToIt(*it);
}
VectorType vect;
SetType set;
};
template <typename T, typename Traits, typename Compare>
void swap(OrderedMap<T, Traits, Compare>& a,
OrderedMap<T, Traits, Compare>& b)
{ a.swap(b); }
}
#endif
| 32.569948
| 84
| 0.606984
|
clienthax
|
9eee905d9168959b415257b0e45eb82e1bdacda0
| 620
|
cpp
|
C++
|
extra/news/src/apk/hgdm/phr-graph/phr-graph-core/token/phr-graph-statement-info.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
extra/news/src/apk/hgdm/phr-graph/phr-graph-core/token/phr-graph-statement-info.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
extra/news/src/apk/hgdm/phr-graph/phr-graph-core/token/phr-graph-statement-info.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Nathaniel Christen 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "phr-graph-statement-info.h"
#include <QRegularExpression>
#include <QDebug>
#include "rzns.h"
USING_RZNS(PhrGraphCore)
PHR_Graph_Statement_Info::PHR_Graph_Statement_Info(QString anchor_name,
QString channel_name, QString anchor_kind)
: anchor_name_(anchor_name), channel_name_(channel_name), anchor_kind_(anchor_kind)
{
}
PHR_Graph_Statement_Info::PHR_Graph_Statement_Info()
{
}
| 23.846154
| 85
| 0.759677
|
scignscape
|
9eef4e7d197ab709c6b0043b1db9641b07d6b67a
| 2,395
|
cpp
|
C++
|
src/os/linux/VulkanSurfaceXcb.cpp
|
mlfarrell/VGL-Vulkan-Core
|
9528f18920c67abd0f722db0e1472972a77c51be
|
[
"Apache-2.0"
] | 60
|
2018-12-17T07:35:32.000Z
|
2022-01-27T11:21:03.000Z
|
src/os/linux/VulkanSurfaceXcb.cpp
|
mlfarrell/VGL-Vulkan-Core
|
9528f18920c67abd0f722db0e1472972a77c51be
|
[
"Apache-2.0"
] | 12
|
2018-12-16T23:30:15.000Z
|
2020-10-02T06:29:45.000Z
|
src/os/linux/VulkanSurfaceXcb.cpp
|
mlfarrell/VulkanConcepts
|
9528f18920c67abd0f722db0e1472972a77c51be
|
[
"Apache-2.0"
] | 8
|
2018-12-18T14:16:23.000Z
|
2021-08-05T01:08:59.000Z
|
/*********************************************************************
Copyright 2018 VERTO STUDIO LLC.
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 "pch.h"
#include "VulkanSwapChain.h"
#include "VulkanExtensionLoader.h"
#include "VulkanInstance.h"
#include "VulkanSurface.h"
using namespace std;
namespace vgl
{
namespace core
{
VulkanSurfaceLinux::LinuxWindow VulkanSurfaceLinux::lwnd = {};
void VulkanSurfaceLinux::setLinuxWindow(LinuxWindow lwnd)
{
VulkanSurfaceLinux::lwnd = lwnd;
}
VulkanSurfaceLinux::VulkanSurfaceLinux(VulkanInstance *instance) : instance(instance)
{
if(!lwnd.connection || !lwnd.window)
throw vgl_runtime_error("You must call VulkanSwapChain::setLinuxWindow() before initializing vulkan swap chain");
updateDimensions();
createSurface();
}
void VulkanSurfaceLinux::createSurface()
{
VkXcbSurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
createInfo.connection = lwnd.connection;
createInfo.window = lwnd.window;
if(vkCreateXcbSurfaceKHR(instance->get(), &createInfo, NULL, &surface) != VK_SUCCESS)
throw vgl_runtime_error("Failed to create Vulkan window surface!");
}
void VulkanSurfaceLinux::updateDimensions()
{
xcb_get_geometry_cookie_t cookie;
xcb_get_geometry_reply_t *reply;
//this cookie tastes terrible..
cookie = xcb_get_geometry(lwnd.connection, lwnd.window);
if((reply = xcb_get_geometry_reply(lwnd.connection, cookie, NULL)))
{
w = reply->width;
h = reply->height;
}
free(reply);
}
VulkanSurfaceLinux::~VulkanSurfaceLinux()
{
vkDestroySurfaceKHR(instance->get(), surface, nullptr);
}
}
}
| 30.705128
| 121
| 0.662213
|
mlfarrell
|
9ef052b7ec67264d226353784f7f301ff23734de
| 30,311
|
hpp
|
C++
|
master/core/third/boost/ratio/detail/ratio_io.hpp
|
importlib/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 198
|
2015-01-13T05:47:18.000Z
|
2022-03-09T04:46:46.000Z
|
master/core/third/boost/ratio/detail/ratio_io.hpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 197
|
2017-07-06T16:53:59.000Z
|
2019-05-31T17:57:51.000Z
|
master/core/third/boost/ratio/detail/ratio_io.hpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 139
|
2015-01-15T20:09:31.000Z
|
2022-01-31T15:21:16.000Z
|
// ratio_io
//
// (C) Copyright Howard Hinnant
// (C) Copyright 2010 Vicente J. Botet Escriba
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// This code was adapted by Vicente from Howard Hinnant's experimental work
// on chrono i/o under lvm/libc++ to Boost
#ifndef BOOST_RATIO_DETAIL_RATIO_IO_HPP
#define BOOST_RATIO_DETAIL_RATIO_IO_HPP
/*
ratio_io synopsis
#include <ratio>
#include <string>
namespace boost
{
template <class Ratio, class CharT>
struct ratio_string
{
static basic_string<CharT> short_name();
static basic_string<CharT> long_name();
};
} // boost
*/
#include <boost/config.hpp>
#include <boost/ratio/ratio.hpp>
#include <boost/type_traits/integral_constant.hpp>
#include <string>
#include <sstream>
#ifdef BOOST_RATIO_HAS_STATIC_STRING
#include <boost/ratio/ratio_static_string.hpp>
#include <boost/static_string/static_string.hpp>
#endif
#if defined(BOOST_NO_CXX11_UNICODE_LITERALS) || defined(BOOST_NO_CXX11_CHAR16_T) || defined(BOOST_NO_CXX11_CHAR32_T) || defined(BOOST_NO_CXX11_U16STRING) || defined(BOOST_NO_CXX11_U32STRING)
#if defined BOOST_RATIO_HAS_UNICODE_SUPPORT
#undef BOOST_RATIO_HAS_UNICODE_SUPPORT
#endif
#else
#define BOOST_RATIO_HAS_UNICODE_SUPPORT 1
#endif
namespace boost {
//template <class Ratio>
//struct ratio_string_is_localizable : false_type {};
//template <class Ratio>
//struct ratio_string_id : integral_constant<int,0> {};
template <class Ratio, class CharT>
struct ratio_string
{
static std::basic_string<CharT> short_name() {return long_name();}
static std::basic_string<CharT> long_name();
static std::basic_string<CharT> symbol() {return short_name();}
static std::basic_string<CharT> prefix() {return long_name();}
};
template <class Ratio, class CharT>
std::basic_string<CharT>
ratio_string<Ratio, CharT>::long_name()
{
std::basic_ostringstream<CharT> os;
os << CharT('[') << Ratio::num << CharT('/')
<< Ratio::den << CharT(']');
return os.str();
}
#ifdef BOOST_RATIO_HAS_STATIC_STRING
namespace ratio_detail {
template <class Ratio, class CharT>
struct ratio_string_static
{
static std::string short_name() {
return std::basic_string<CharT>(
static_string::c_str<
typename ratio_static_string<Ratio, CharT>::short_name
>::value);
}
static std::string long_name() {
return std::basic_string<CharT>(
static_string::c_str<
typename ratio_static_string<Ratio, CharT>::long_name
>::value);
}
static std::basic_string<CharT> symbol() {return short_name();}
static std::basic_string<CharT> prefix() {return long_name();}
};
}
#endif
// atto
//template <>
//struct ratio_string_is_localizable<atto> : true_type {};
//
//template <>
//struct ratio_string_id<atto> : integral_constant<int,-18> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<atto, CharT> :
ratio_detail::ratio_string_static<atto,CharT>
{};
#else
template <>
struct ratio_string<atto, char>
{
static std::string short_name() {return std::string(1, 'a');}
static std::string long_name() {return std::string("atto");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<atto, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'a');}
static std::u16string long_name() {return std::u16string(u"atto");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<atto, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'a');}
static std::u32string long_name() {return std::u32string(U"atto");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<atto, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'a');}
static std::wstring long_name() {return std::wstring(L"atto");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// femto
//template <>
//struct ratio_string_is_localizable<femto> : true_type {};
//
//template <>
//struct ratio_string_id<femto> : integral_constant<int,-15> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<femto, CharT> :
ratio_detail::ratio_string_static<femto,CharT>
{};
#else
template <>
struct ratio_string<femto, char>
{
static std::string short_name() {return std::string(1, 'f');}
static std::string long_name() {return std::string("femto");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<femto, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'f');}
static std::u16string long_name() {return std::u16string(u"femto");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<femto, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'f');}
static std::u32string long_name() {return std::u32string(U"femto");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<femto, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'f');}
static std::wstring long_name() {return std::wstring(L"femto");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// pico
//template <>
//struct ratio_string_is_localizable<pico> : true_type {};
//
//template <>
//struct ratio_string_id<pico> : integral_constant<int,-12> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<pico, CharT> :
ratio_detail::ratio_string_static<pico,CharT>
{};
#else
template <>
struct ratio_string<pico, char>
{
static std::string short_name() {return std::string(1, 'p');}
static std::string long_name() {return std::string("pico");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<pico, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'p');}
static std::u16string long_name() {return std::u16string(u"pico");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<pico, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'p');}
static std::u32string long_name() {return std::u32string(U"pico");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<pico, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'p');}
static std::wstring long_name() {return std::wstring(L"pico");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// nano
//template <>
//struct ratio_string_is_localizable<nano> : true_type {};
//
//template <>
//struct ratio_string_id<nano> : integral_constant<int,-9> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<nano, CharT> :
ratio_detail::ratio_string_static<nano,CharT>
{};
#else
template <>
struct ratio_string<nano, char>
{
static std::string short_name() {return std::string(1, 'n');}
static std::string long_name() {return std::string("nano");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<nano, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'n');}
static std::u16string long_name() {return std::u16string(u"nano");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<nano, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'n');}
static std::u32string long_name() {return std::u32string(U"nano");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<nano, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'n');}
static std::wstring long_name() {return std::wstring(L"nano");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// micro
//template <>
//struct ratio_string_is_localizable<micro> : true_type {};
//
//template <>
//struct ratio_string_id<micro> : integral_constant<int,-6> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<micro, CharT> :
ratio_detail::ratio_string_static<micro,CharT>
{};
#else
template <>
struct ratio_string<micro, char>
{
static std::string short_name() {return std::string("\xC2\xB5");}
static std::string long_name() {return std::string("micro");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<micro, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'\xB5');}
static std::u16string long_name() {return std::u16string(u"micro");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<micro, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'\xB5');}
static std::u32string long_name() {return std::u32string(U"micro");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<micro, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'\xB5');}
static std::wstring long_name() {return std::wstring(L"micro");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// milli
//template <>
//struct ratio_string_is_localizable<milli> : true_type {};
//
//template <>
//struct ratio_string_id<milli> : integral_constant<int,-3> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<milli, CharT> :
ratio_detail::ratio_string_static<milli,CharT>
{};
#else
template <>
struct ratio_string<milli, char>
{
static std::string short_name() {return std::string(1, 'm');}
static std::string long_name() {return std::string("milli");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<milli, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'm');}
static std::u16string long_name() {return std::u16string(u"milli");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<milli, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'm');}
static std::u32string long_name() {return std::u32string(U"milli");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<milli, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'm');}
static std::wstring long_name() {return std::wstring(L"milli");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// centi
//template <>
//struct ratio_string_is_localizable<centi> : true_type {};
//
//template <>
//struct ratio_string_id<centi> : integral_constant<int,-2> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<centi, CharT> :
ratio_detail::ratio_string_static<centi,CharT>
{};
#else
template <>
struct ratio_string<centi, char>
{
static std::string short_name() {return std::string(1, 'c');}
static std::string long_name() {return std::string("centi");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<centi, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'c');}
static std::u16string long_name() {return std::u16string(u"centi");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<centi, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'c');}
static std::u32string long_name() {return std::u32string(U"centi");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<centi, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'c');}
static std::wstring long_name() {return std::wstring(L"centi");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// deci
//template <>
//struct ratio_string_is_localizable<deci> : true_type {};
//
//template <>
//struct ratio_string_id<deci> : integral_constant<int,-1> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<deci, CharT> :
ratio_detail::ratio_string_static<deci,CharT>
{};
#else
template <>
struct ratio_string<deci, char>
{
static std::string short_name() {return std::string(1, 'd');}
static std::string long_name() {return std::string("deci");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<deci, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'd');}
static std::u16string long_name() {return std::u16string(u"deci");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<deci, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'd');}
static std::u32string long_name() {return std::u32string(U"deci");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<deci, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'd');}
static std::wstring long_name() {return std::wstring(L"deci");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// unit
//template <>
//struct ratio_string_is_localizable<ratio<1> > : true_type {};
//
//template <>
//struct ratio_string_id<ratio<1> > : integral_constant<int,0> {};
// deca
//template <>
//struct ratio_string_is_localizable<deca> : true_type {};
//
//template <>
//struct ratio_string_id<deca> : integral_constant<int,1> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<deca, CharT> :
ratio_detail::ratio_string_static<deca,CharT>
{};
#else
template <>
struct ratio_string<deca, char>
{
static std::string short_name() {return std::string("da");}
static std::string long_name() {return std::string("deca");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<deca, char16_t>
{
static std::u16string short_name() {return std::u16string(u"da");}
static std::u16string long_name() {return std::u16string(u"deca");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<deca, char32_t>
{
static std::u32string short_name() {return std::u32string(U"da");}
static std::u32string long_name() {return std::u32string(U"deca");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<deca, wchar_t>
{
static std::wstring short_name() {return std::wstring(L"da");}
static std::wstring long_name() {return std::wstring(L"deca");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// hecto
//template <>
//struct ratio_string_is_localizable<hecto> : true_type {};
//
//template <>
//struct ratio_string_id<hecto> : integral_constant<int,2> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<hecto, CharT> :
ratio_detail::ratio_string_static<hecto,CharT>
{};
#else
template <>
struct ratio_string<hecto, char>
{
static std::string short_name() {return std::string(1, 'h');}
static std::string long_name() {return std::string("hecto");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<hecto, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'h');}
static std::u16string long_name() {return std::u16string(u"hecto");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<hecto, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'h');}
static std::u32string long_name() {return std::u32string(U"hecto");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<hecto, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'h');}
static std::wstring long_name() {return std::wstring(L"hecto");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// kilo
//template <>
//struct ratio_string_is_localizable<kilo> : true_type {};
//
//template <>
//struct ratio_string_id<kilo> : integral_constant<int,3> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<kilo, CharT> :
ratio_detail::ratio_string_static<kilo,CharT>
{};
#else
template <>
struct ratio_string<kilo, char>
{
static std::string short_name() {return std::string(1, 'k');}
static std::string long_name() {return std::string("kilo");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<kilo, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'k');}
static std::u16string long_name() {return std::u16string(u"kilo");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<kilo, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'k');}
static std::u32string long_name() {return std::u32string(U"kilo");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<kilo, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'k');}
static std::wstring long_name() {return std::wstring(L"kilo");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// mega
//template <>
//struct ratio_string_is_localizable<mega> : true_type {};
//
//template <>
//struct ratio_string_id<mega> : integral_constant<int,6> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<mega, CharT> :
ratio_detail::ratio_string_static<mega,CharT>
{};
#else
template <>
struct ratio_string<mega, char>
{
static std::string short_name() {return std::string(1, 'M');}
static std::string long_name() {return std::string("mega");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<mega, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'M');}
static std::u16string long_name() {return std::u16string(u"mega");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<mega, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'M');}
static std::u32string long_name() {return std::u32string(U"mega");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<mega, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'M');}
static std::wstring long_name() {return std::wstring(L"mega");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// giga
//template <>
//struct ratio_string_is_localizable<giga> : true_type {};
//
//template <>
//struct ratio_string_id<giga> : integral_constant<int,9> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<giga, CharT> :
ratio_detail::ratio_string_static<giga,CharT>
{};
#else
template <>
struct ratio_string<giga, char>
{
static std::string short_name() {return std::string(1, 'G');}
static std::string long_name() {return std::string("giga");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<giga, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'G');}
static std::u16string long_name() {return std::u16string(u"giga");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<giga, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'G');}
static std::u32string long_name() {return std::u32string(U"giga");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<giga, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'G');}
static std::wstring long_name() {return std::wstring(L"giga");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// tera
//template <>
//struct ratio_string_is_localizable<tera> : true_type {};
//
//template <>
//struct ratio_string_id<tera> : integral_constant<int,12> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<tera, CharT> :
ratio_detail::ratio_string_static<tera,CharT>
{};
#else
template <>
struct ratio_string<tera, char>
{
static std::string short_name() {return std::string(1, 'T');}
static std::string long_name() {return std::string("tera");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<tera, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'T');}
static std::u16string long_name() {return std::u16string(u"tera");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<tera, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'T');}
static std::u32string long_name() {return std::u32string(U"tera");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<tera, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'T');}
static std::wstring long_name() {return std::wstring(L"tera");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// peta
//template <>
//struct ratio_string_is_localizable<peta> : true_type {};
//
//template <>
//struct ratio_string_id<peta> : integral_constant<int,15> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<peta, CharT> :
ratio_detail::ratio_string_static<peta,CharT>
{};
#else
template <>
struct ratio_string<peta, char>
{
static std::string short_name() {return std::string(1, 'P');}
static std::string long_name() {return std::string("peta");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<peta, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'P');}
static std::u16string long_name() {return std::u16string(u"peta");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<peta, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'P');}
static std::u32string long_name() {return std::u32string(U"peta");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<peta, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'P');}
static std::wstring long_name() {return std::wstring(L"peta");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
// exa
//template <>
//struct ratio_string_is_localizable<exa> : true_type {};
//
//template <>
//struct ratio_string_id<exa> : integral_constant<int,18> {};
#ifdef BOOST_RATIO_HAS_STATIC_STRING
template <typename CharT>
struct ratio_string<exa, CharT> :
ratio_detail::ratio_string_static<exa,CharT>
{};
#else
template <>
struct ratio_string<exa, char>
{
static std::string short_name() {return std::string(1, 'E');}
static std::string long_name() {return std::string("exa");}
static std::string symbol() {return short_name();}
static std::string prefix() {return long_name();}
};
#if BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_string<exa, char16_t>
{
static std::u16string short_name() {return std::u16string(1, u'E');}
static std::u16string long_name() {return std::u16string(u"exa");}
static std::u16string symbol() {return short_name();}
static std::u16string prefix() {return long_name();}
};
template <>
struct ratio_string<exa, char32_t>
{
static std::u32string short_name() {return std::u32string(1, U'E');}
static std::u32string long_name() {return std::u32string(U"exa");}
static std::u32string symbol() {return short_name();}
static std::u32string prefix() {return long_name();}
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_string<exa, wchar_t>
{
static std::wstring short_name() {return std::wstring(1, L'E');}
static std::wstring long_name() {return std::wstring(L"exa");}
static std::wstring symbol() {return short_name();}
static std::wstring prefix() {return long_name();}
};
#endif
#endif
}
#endif // BOOST_RATIO_RATIO_IO_HPP
| 28.978011
| 191
| 0.675266
|
importlib
|
9ef4f8167cb9e25833b85487b6024e71ebe4882e
| 1,571
|
cpp
|
C++
|
models/cache/mcp-cache/coherence/sharers.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 8
|
2016-01-22T18:28:48.000Z
|
2021-05-07T02:27:21.000Z
|
models/cache/mcp-cache/coherence/sharers.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 3
|
2016-04-15T02:58:58.000Z
|
2017-01-19T17:07:34.000Z
|
models/cache/mcp-cache/coherence/sharers.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 10
|
2015-12-11T04:16:55.000Z
|
2019-05-25T20:58:13.000Z
|
#include "sharers.h"
namespace manifold {
namespace mcp_cache_namespace {
/** @brief sharers
*
* @todo: document this function
*/
sharers::sharers(size_t size) : data(size)
{
}
/** @brief ~sharers
*
* @todo: document this function
*/
sharers::~sharers()
{
}
/** @brief get
*
* Get the status of a cache represented by the given index.
*/
bool sharers::get(int index)
{
if (index >= data.size()) {
data.resize(index + 1);
data[index] = false;
}
return data[index];
}
/** @brief size
*
* @todo: document this function
*/
int sharers::size() const
{
return data.size();
}
/** @brief count
*
* @todo: counts the number of 1's
*/
int sharers::count() const
{
int count = 0;
for (int i = 0; i < data.size(); i++)
{
if (data[i]) count++;
}
return count;
}
/** @brief clear
*
* @todo: document this function
*/
void sharers::clear()
{
data.clear();
}
/** @brief set
*
* @todo: document this function
*/
void sharers::set(int index)
{
if (index >= data.size())
data.resize(index + 1);
data[index] = true;
}
/** @brief reset
*
* @todo: document this function
*/
void sharers::reset(int index)
{
if (index >= data.size())
data.resize(index + 1);
data[index] = false;
}
/** @brief ones
*
* @todo: document this function
*/
void sharers::ones(std::vector<int>& ret)
{
for (int i = 0; i < data.size(); i++)
{
if (data[i]) ret.push_back(i);
}
}
} //namespace mcp_cache_namespace
} //namespace manifold
| 14.412844
| 61
| 0.565882
|
Basseuph
|
9ef8259611d7e67c3566eaa3ae7425665c2e94e5
| 600
|
hpp
|
C++
|
includes/eeros/sequencer/SequencerUI.hpp
|
RicoPauli/eeros
|
3cc2802253c764b16c6368ad7bdaef1e3c683367
|
[
"Apache-2.0"
] | null | null | null |
includes/eeros/sequencer/SequencerUI.hpp
|
RicoPauli/eeros
|
3cc2802253c764b16c6368ad7bdaef1e3c683367
|
[
"Apache-2.0"
] | null | null | null |
includes/eeros/sequencer/SequencerUI.hpp
|
RicoPauli/eeros
|
3cc2802253c764b16c6368ad7bdaef1e3c683367
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ORG_EEROS_SEQUENCER_SEQUENCERUI_HPP_
#define ORG_EEROS_SEQUENCER_SEQUENCERUI_HPP_
#include <eeros/core/Thread.hpp>
namespace eeros {
namespace sequencer {
void sigPipeHandler(int signum);
// class Sequencer;
class SequencerUI : public eeros::Thread {
public:
SequencerUI();
virtual ~SequencerUI();
virtual void stop();
virtual bool isRunning();
private:
virtual void run();
bool running;
uint16_t port;
double period;
struct hostent *server;
int sockfd;
int newsockfd;
};
};
};
#endif // ORG_EEROS_SEQUENCER_SEQUENCERUI_HPP_
| 18.181818
| 46
| 0.703333
|
RicoPauli
|
9efc0554ce97d02a80dcaf7c5fadb4ee32bf1b1d
| 530
|
cpp
|
C++
|
2.3.cpp
|
sushithreddy75/DATA-STRUCTURES
|
ec948dbaadd0c675596ba1b6fd7c71ef14c9d656
|
[
"MIT"
] | 1
|
2021-07-22T04:19:46.000Z
|
2021-07-22T04:19:46.000Z
|
2.3.cpp
|
sushithreddy75/DATA-STRUCTURES
|
ec948dbaadd0c675596ba1b6fd7c71ef14c9d656
|
[
"MIT"
] | null | null | null |
2.3.cpp
|
sushithreddy75/DATA-STRUCTURES
|
ec948dbaadd0c675596ba1b6fd7c71ef14c9d656
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
union u
{
int x;
char c;
};
int main()
{
int n,i,j=0;
cout<<"ENTER SIZE OF ARRAY: ";
cin>>n;
union u a[n];
union u *l=a,*r=a+n-1;
while(l<=r)
{
cout<<"ENTER 0 TO ENTER INTEGER 1 FOR CHARACTER ";
cin>>i;
if(i==1)
{
cout<<"ENTER CHARACTER: ";
cin>>r->c;
r--;
}
else
{
cout<<"ENTER INTEGER: ";
cin>>l->x;
l++;
j++;
}
}
cout<<"DATA IN ARRAY\n";
for(i=0;i<j;i++)
cout<<a[i].x<<" ";
for(j;j<n;j++)
cout<<a[j].c<<" ";
cout<<endl;
return 0;
}
| 13.25
| 52
| 0.50566
|
sushithreddy75
|
9efd1dae3a7eefaeaa85d7269a5260e45e74697a
| 103
|
cpp
|
C++
|
chap02/Main.cpp
|
HarryLovesCode/Vulkan-API-Book
|
ac552b5d9cba1c4f85d9ec911ec39698b2649c79
|
[
"MIT"
] | 58
|
2016-03-28T18:53:34.000Z
|
2021-12-16T09:04:35.000Z
|
chap03/Main.cpp
|
HarryLovesCode/Vulkan-API-Book
|
ac552b5d9cba1c4f85d9ec911ec39698b2649c79
|
[
"MIT"
] | 9
|
2016-03-24T01:08:31.000Z
|
2021-05-31T10:56:49.000Z
|
chap03/Main.cpp
|
HarryLovesCode/Vulkan-API-Book
|
ac552b5d9cba1c4f85d9ec911ec39698b2649c79
|
[
"MIT"
] | 6
|
2016-11-30T15:42:37.000Z
|
2021-12-16T09:04:34.000Z
|
#include "VulkanExample.hpp"
int main(int argc, char *argv[]) { VulkanExample ve = VulkanExample(); }
| 25.75
| 72
| 0.708738
|
HarryLovesCode
|
9effae0a0aae26af71b3e7680cc52677362e4197
| 10,222
|
cpp
|
C++
|
CViewer.cpp
|
mhoopmann/KojakSpectrumViewer
|
35fe56b3686dfdbe36e4bd5aab6f8d7ee04d6491
|
[
"Apache-2.0"
] | 4
|
2017-06-08T21:28:24.000Z
|
2021-02-25T13:22:00.000Z
|
CViewer.cpp
|
mhoopmann/KojakSpectrumViewer
|
35fe56b3686dfdbe36e4bd5aab6f8d7ee04d6491
|
[
"Apache-2.0"
] | null | null | null |
CViewer.cpp
|
mhoopmann/KojakSpectrumViewer
|
35fe56b3686dfdbe36e4bd5aab6f8d7ee04d6491
|
[
"Apache-2.0"
] | 1
|
2020-10-04T18:10:01.000Z
|
2020-10-04T18:10:01.000Z
|
/*
Copyright 2016, Michael R. Hoopmann, Institute for Systems Biology
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 "CViewer.h"
CViewer::CViewer(){
activeFocus=NULL;
display=NULL;
input=NULL;
state=1;
firstOpen=true;
quitter=false;
focused=true;
}
CViewer::CViewer(CDisplay* d, CInput* inp){
activeFocus=NULL;
display=d;
input=inp;
sg.setDisplay(d);
sg.setInput(inp);
state=1;
firstOpen=true;
quitter=false;
focused=true;
}
CViewer::~CViewer(){
activeFocus=NULL;
display=NULL;
input=NULL;
}
void CViewer::fixLayout(){
int h,w;
display->getWindowSize(w,h);
tb.szX=w;
sliderV.szY=h-tb.szY;
pepBox.szY=h-tb.szY;
msgBox.szY=h-msgBox.posY;
dt.szY=h-dt.posY;
pepBox.szX=w-pepBox.posX;
pepBox.fixLayout();
msgBox.fixLayout();
dt.fixLayout();
fileDlg.fixLayout();
}
void CViewer::init(char* ver, char* bdate){
sg.posY=32;
sg.resize(500,300);
// sg.szX=500;
// sg.szY=300;
#ifdef GCC
gfx.loadGfx("./Fonts/icons.bmp",display->renderer);
#else
gfx.loadGfx("Fonts\\icons.bmp",display->renderer);
#endif
font.setDisplay(display);
#ifdef GCC
font.loadFont("./Fonts/Carlito-Regular.ttf");
#else
font.loadFont("Fonts\\Carlito-Regular.ttf");
#endif
msgBox.setDisplay(display);
msgBox.setFont(&font);
msgBox.posX=0;
msgBox.posY=337;
msgBox.szX=500;
msgBox.szY=263;
msgBox.addText("Testing Message Box");
msgBox.addText("Testing another line.");
msgBox.addText("Testing another really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, long line.");
msgBox.addText("Testing another line.");
dt.setDisplay(display);
dt.setFont(&font);
dt.posX=0;
dt.posY=337;
dt.szX=500;
dt.szY=263;
pepBox.setDisplay(display);
pepBox.setFont(&font);
pepBox.posX=505;
pepBox.posY=32;
pepBox.szX=295;
pepBox.szY=568;
pepBox.init();
fileDlg.setDisplay(display);
fileDlg.setFont(&font);
fileDlg.setGfx(&gfx);
fileDlg.init(ver,bdate);
aboutDlg.setDisplay(display);
aboutDlg.setFont(&font);
aboutDlg.init(ver,bdate);
dataIndex=0;
dt.selected=0;
sg.setFont(&font);
sortDlg.setDisplay(display);
sortDlg.setFont(&font);
sortDlg.setInput(input);
sortDlg.init(&dt);
setDlg.setDisplay(display);
setDlg.setFont(&font);
setDlg.setInput(input);
setDlg.init();
tb.setDisplay(display);
tb.setFont(&font);
tb.setGfx(&gfx);
tb.setInput(input);
tb.init();
sliderH.setDisplay(display);
sliderH.setFocus(activeFocus);
sliderH.posX=0;
sliderH.posY=332;
sliderH.szY=5;
sliderH.szX=500;
sliderH.vertical=false;
sliderV.setDisplay(display);
sliderV.setFocus(activeFocus);
sliderV.posX=500;
sliderV.posY=32;
sliderV.szX=5;
sliderV.szY=568;
dt.setDisplay(display);
dt.setFocus(activeFocus);
dt.posX=0;
dt.posY=337;
dt.szX=500;
dt.szY=263;
}
bool CViewer::logic(){
//Master controller of all user interaction
int mouseX;
int mouseY;
int mouseButton=0;
int val;
bool mouseButton1;
char str[64];
if(quitter) return false;
if(!focused) return true;
SDL_GetMouseState(&mouseX,&mouseY);
mouseButton=input->mouseAction();
mouseButton1=input->getButtonState(0);
//intercept for other states
if(state==1){
val=fileDlg.logic(mouseX,mouseY,mouseButton,mouseButton1);
switch(val){
case 1:
if(!firstOpen) state=0;
return true;
case 2:
state=0;
dt.clear();
data.readPepXML(fileDlg.fileName,&dt);
dataIndex=0;
dt.selected=0;
sortDlg.clear();
sortDlg.init(&dt);
resetSpectrum();
firstOpen=false;
return true;
default:
return true;
}
}
if(state==2){
val=sortDlg.logic(mouseX,mouseY,mouseButton,mouseButton1);
switch(val){
case 1:
state=0;
return true;
case 2:
state=0;
dataIndex=dt.selected;
resetSpectrum();
return true;
default:
return true;
}
}
if(state==3){
val=aboutDlg.logic(mouseX, mouseY, mouseButton, mouseButton1);
switch(val){
case 1:
state=0;
return true;
default:
return true;
}
}
if(state==4){
val=setDlg.logic(mouseX, mouseY, mouseButton, mouseButton1);
switch(val){
case 1:
state=0;
return true;
case 2:
state=0;
sg.fontSize=setDlg.sgFontSize;
sg.lineWidth=setDlg.lineWidth;
sg.spectrum.setTolerance(setDlg.tol, setDlg.tolUnit);
if(setDlg.tolUnit==0) sprintf(str, "Tolerance: %g Da",setDlg.tol);
else sprintf(str, "Tolerance: %g ppm", setDlg.tol);
pepBox.metaTol=str;
return true;
default:
return true;
}
}
//only process other components if sliders are not locked
if(!sliderV.checkLocked() && !sliderH.checkLocked()){
switch(dt.logic(mouseX,mouseY,mouseButton,mouseButton1)){
case 1:
return true;
case 2:
dataIndex=dt.selected;
resetSpectrum();
return true;
default:
break;
}
//Process any toolbar actions
switch(tb.logic(mouseX,mouseY,mouseButton)){
case 1: //open button
state=1;
return true;
case 2: //prev button
dataIndex--;
if(dataIndex<0) dataIndex=0;
dt.selected=dataIndex;
resetSpectrum();
return true;
case 3: //next button
dataIndex++;
if(dataIndex==dt.size(false)) dataIndex=(int)(dt.size(false)-1);
dt.selected=dataIndex;
resetSpectrum();
return true;
case 4: //about dialog
state=3;
return true;
case 5: //sort/filter
state=2;
return true;
case 6: //anywhere in the toolbar
return true;
case 7: //settings dialog
state=4;
sg.spectrum.getTolerance(setDlg.tol, setDlg.tolUnit);
return true;
case 8: //export png
sg.exportPNG();
return true;
default:
break;
}
if(pepBox.logic(mouseX,mouseY,mouseButton,mouseButton1)>0) return true;
//if(msgBox.logic(mouseX,mouseY,mouseButton,mouseButton1)>0) return true;
if(sg.logic(mouseX,mouseY,mouseButton,mouseButton1)) {
return true;
}
}
//always check sliders last?
val=sliderV.logic(mouseX, mouseY, mouseButton, mouseButton1);
if(val<10000){
if(val==0) return true;
sg.resize(sg.getSizeX() + val, sg.getSizeY());
//sg.szX+=val;
dt.szX+=val;
dt.fixLayout();
msgBox.szX+=val;
msgBox.fixLayout();
sliderH.szX+=val;
pepBox.posX=sliderV.posX+sliderV.szX;
pepBox.szX-=val;
pepBox.fixLayout();
return true;
}
val=sliderH.logic(mouseX, mouseY, mouseButton, mouseButton1);
if(val<10000){
if(val==0) return true;
sg.resize(sg.getSizeX(), sg.getSizeY()+val);
//sg.szY+=val;
dt.posY+=val;
dt.szY-=val;
dt.fixLayout();
msgBox.posY+=val;
msgBox.szY-=val;
msgBox.fixLayout();
return true;
}
tb.processInput();
/*
int id;
switch(tb.processInput()){
case 1:
id=data.findSpectrum(tb.scanNumber);
if(id>-1){
dataIndex=id;
resetSpectrum();
}
return true;
default:
break;
}
*/
if(input->getKeyState(KEY_Q))return false;
return true;
}
void CViewer::processEvent(SDL_Event& e){
switch(e.window.event){
case SDL_WINDOWEVENT_RESIZED:
fixLayout();
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
focused=true;
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
focused=false;
break;
case SDL_WINDOWEVENT_CLOSE:
quitter=true;
break;
default:
break;
}
}
bool CViewer::render(){
SDL_Rect r;
SDL_RenderClear(display->renderer);
switch(state){
case 1:
fileDlg.render();
return true;
case 2:
sortDlg.render();
return true;
case 3:
aboutDlg.render();
return true;
case 4:
setDlg.render();
return true;
default:
break;
}
//Clear the entire window
SDL_RenderGetViewport(display->renderer,&r);
SDL_SetRenderDrawColor(display->renderer,0,0,0,255);
SDL_RenderFillRect(display->renderer,&r);
tb.render();
sg.render(pepBox);
//render graph sliders
sliderH.render();
sliderV.render();
//msgBox.render();
dt.render();
//Render peaklists
pepBox.render(0,0);
return true;
}
void CViewer::resetSpectrum(){
//fragList.setPeptide(data[dataIndex].peptideA,1);
int tIndex=dt.getPSMID(dataIndex);
if(tIndex<0) {
sg.spectrum.clear();
sg.resetView();
pepBox.clear=true;
return;
}
pepBox.clear=false;
scanNumber = data[tIndex].scanNumber;
pepBox.setPSM(data[tIndex]);
Spectrum spec = data.getSpectrum(tIndex);
pepBox.scanNumber = spec.getScanNumber();
pepBox.mass = data[tIndex].mass;
pepBox.charge = (int)data[tIndex].charge;
sg.spectrum.clear();
for(int i=0;i<spec.size();i++){
if(spec[i].intensity==0) continue;
sg.spectrum.add(spec[i].mz,(double)spec[i].intensity);
}
sg.resetView();
}
void CViewer::setDisplay(CDisplay *d){
display=d;
sg.setDisplay(d);
pepBox.setDisplay(d);
fileDlg.setDisplay(d);
sortDlg.setDisplay(d);
aboutDlg.setDisplay(d);
setDlg.setDisplay(d);
}
void CViewer::setFocus(CActiveFocus* f){
activeFocus=f;
tb.setFocus(f);
pepBox.setFocus(f);
msgBox.setFocus(f);
fileDlg.setFocus(f);
dt.setFocus(f);
sortDlg.setFocus(f);
aboutDlg.setFocus(f);
setDlg.setFocus(f);
}
void CViewer::setInput(CInput* inp){
input=inp;
sg.setInput(inp);
sortDlg.setInput(inp);
setDlg.setInput(inp);
}
bool CViewer::viewerMain(){
//Check logic
if(!logic()) return false;
//render
render();
return true;
}
| 21.076289
| 247
| 0.648699
|
mhoopmann
|
9effedced5b54003e0023eaba910e312ed8ff668
| 1,497
|
cpp
|
C++
|
sdl2/arkanoid/src/source/App.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/arkanoid/src/source/App.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/arkanoid/src/source/App.cpp
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
/*
ArkanoidRemakeSDL
a sample of object-oriented game programming with C++.
version 1.0, May 2016
Copyright (c) 2016 Giovanni Paolo Vigano'
The source code of the SDL library used by ArkanoidRemakeSDL can be found here:
https://www.libsdl.org/
---
ArkanoidRemakeSDL source code is licensed with the same zlib license:
(http://www.gzip.org/zlib/zlib_license.html)
This software is provided 'as-is', without any express or implied warranty. In
no event will the authors be held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software for any purpose, including
commercial applications, and to alter it and redistribute it freely, subject to
the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be appreciated
but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <App.h>
#include <App.h>
// App implementation
//-------------------------------------------------------------
App::App()
{
mQuit=false;
}
bool App::Run()
{
if (!Init()) return false;
Start();
while (!mQuit) Update();
Stop();
CleanUp();
return true;
}
| 26.732143
| 80
| 0.708083
|
pdpdds
|
7300451101ebda19476d1d6e158e7b8e30ed3994
| 3,744
|
cpp
|
C++
|
src/support/win32/locale_win32.cpp
|
baggio63446333/libcxx
|
fd596ad2a2a848159385d4b2b0f97b379e1b6245
|
[
"MIT"
] | 1
|
2019-01-02T16:14:19.000Z
|
2019-01-02T16:14:19.000Z
|
libxx/libcxx/support/win32/locale_win32.cpp
|
scott-eddy/libcxx
|
ff3918c28d405ef619716fd69260b5ca026db2d0
|
[
"MIT"
] | 6
|
2019-01-02T16:13:43.000Z
|
2019-01-06T12:31:45.000Z
|
libxx/libcxx/support/win32/locale_win32.cpp
|
scott-eddy/libcxx
|
ff3918c28d405ef619716fd69260b5ca026db2d0
|
[
"MIT"
] | 2
|
2019-08-09T09:14:31.000Z
|
2019-09-24T05:28:09.000Z
|
// -*- C++ -*-
//===-------------------- support/win32/locale_win32.cpp ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <locale>
#include <cstdarg> // va_start, va_end
#include <memory>
#include <type_traits>
typedef _VSTD::remove_pointer<locale_t>::type __locale_struct;
typedef _VSTD::unique_ptr<__locale_struct, decltype(&uselocale)> __locale_raii;
// FIXME: base currently unused. Needs manual work to construct the new locale
locale_t newlocale( int mask, const char * locale, locale_t /*base*/ )
{
return _create_locale( mask, locale );
}
locale_t uselocale( locale_t newloc )
{
locale_t old_locale = _get_current_locale();
if ( newloc == NULL )
return old_locale;
// uselocale sets the thread's locale by definition, so unconditionally use thread-local locale
_configthreadlocale( _ENABLE_PER_THREAD_LOCALE );
// uselocale sets all categories
setlocale( LC_ALL, newloc->locinfo->lc_category[LC_ALL].locale );
// uselocale returns the old locale_t
return old_locale;
}
lconv *localeconv_l( locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return localeconv();
}
size_t mbrlen_l( const char *__restrict s, size_t n,
mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrlen( s, n, ps );
}
size_t mbsrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsrtowcs( dst, src, len, ps );
}
size_t wcrtomb_l( char *__restrict s, wchar_t wc, mbstate_t *__restrict ps,
locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcrtomb( s, wc, ps );
}
size_t mbrtowc_l( wchar_t *__restrict pwc, const char *__restrict s,
size_t n, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrtowc( pwc, s, n, ps );
}
size_t mbsnrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t nms, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsnrtowcs( dst, src, nms, len, ps );
}
size_t wcsnrtombs_l( char *__restrict dst, const wchar_t **__restrict src,
size_t nwc, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcsnrtombs( dst, src, nwc, len, ps );
}
wint_t btowc_l( int c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return btowc( c );
}
int wctob_l( wint_t c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wctob( c );
}
int snprintf_l(char *ret, size_t n, locale_t loc, const char *format, ...)
{
__locale_raii __current( uselocale(loc), uselocale );
va_list ap;
va_start( ap, format );
int result = vsnprintf( ret, n, format, ap );
va_end(ap);
return result;
}
int asprintf_l( char **ret, locale_t loc, const char *format, ... )
{
va_list ap;
va_start( ap, format );
int result = vasprintf_l( ret, loc, format, ap );
va_end(ap);
return result;
}
int vasprintf_l( char **ret, locale_t loc, const char *format, va_list ap )
{
__locale_raii __current( uselocale(loc), uselocale );
return vasprintf( ret, format, ap );
}
| 33.72973
| 99
| 0.657853
|
baggio63446333
|
730573d2d88d24486374b280c1196ba532a9ae1d
| 2,269
|
inl
|
C++
|
samples/sine.inl
|
kibergus/LidarVox
|
ac66dfe94b0e11534aa22bfd64293c614ba19d1c
|
[
"WTFPL"
] | null | null | null |
samples/sine.inl
|
kibergus/LidarVox
|
ac66dfe94b0e11534aa22bfd64293c614ba19d1c
|
[
"WTFPL"
] | null | null | null |
samples/sine.inl
|
kibergus/LidarVox
|
ac66dfe94b0e11534aa22bfd64293c614ba19d1c
|
[
"WTFPL"
] | null | null | null |
static const dacsample_t dac_buffer_sine[] = {
2047, 2082, 2118, 2154, 2189, 2225, 2260, 2296, 2331, 2367, 2402, 2437,
2472, 2507, 2542, 2576, 2611, 2645, 2679, 2713, 2747, 2780, 2813, 2846,
2879, 2912, 2944, 2976, 3008, 3039, 3070, 3101, 3131, 3161, 3191, 3221,
3250, 3278, 3307, 3335, 3362, 3389, 3416, 3443, 3468, 3494, 3519, 3544,
3568, 3591, 3615, 3637, 3660, 3681, 3703, 3723, 3744, 3763, 3782, 3801,
3819, 3837, 3854, 3870, 3886, 3902, 3917, 3931, 3944, 3958, 3970, 3982,
3993, 4004, 4014, 4024, 4033, 4041, 4049, 4056, 4062, 4068, 4074, 4078,
4082, 4086, 4089, 4091, 4092, 4093, 4094, 4093, 4092, 4091, 4089, 4086,
4082, 4078, 4074, 4068, 4062, 4056, 4049, 4041, 4033, 4024, 4014, 4004,
3993, 3982, 3970, 3958, 3944, 3931, 3917, 3902, 3886, 3870, 3854, 3837,
3819, 3801, 3782, 3763, 3744, 3723, 3703, 3681, 3660, 3637, 3615, 3591,
3568, 3544, 3519, 3494, 3468, 3443, 3416, 3389, 3362, 3335, 3307, 3278,
3250, 3221, 3191, 3161, 3131, 3101, 3070, 3039, 3008, 2976, 2944, 2912,
2879, 2846, 2813, 2780, 2747, 2713, 2679, 2645, 2611, 2576, 2542, 2507,
2472, 2437, 2402, 2367, 2331, 2296, 2260, 2225, 2189, 2154, 2118, 2082,
2047, 2012, 1976, 1940, 1905, 1869, 1834, 1798, 1763, 1727, 1692, 1657,
1622, 1587, 1552, 1518, 1483, 1449, 1415, 1381, 1347, 1314, 1281, 1248,
1215, 1182, 1150, 1118, 1086, 1055, 1024, 993, 963, 933, 903, 873,
844, 816, 787, 759, 732, 705, 678, 651, 626, 600, 575, 550,
526, 503, 479, 457, 434, 413, 391, 371, 350, 331, 312, 293,
275, 257, 240, 224, 208, 192, 177, 163, 150, 136, 124, 112,
101, 90, 80, 70, 61, 53, 45, 38, 32, 26, 20, 16,
12, 8, 5, 3, 2, 1, 0, 1, 2, 3, 5, 8,
12, 16, 20, 26, 32, 38, 45, 53, 61, 70, 80, 90,
101, 112, 124, 136, 150, 163, 177, 192, 208, 224, 240, 257,
275, 293, 312, 331, 350, 371, 391, 413, 434, 457, 479, 503,
526, 550, 575, 600, 626, 651, 678, 705, 732, 759, 787, 816,
844, 873, 903, 933, 963, 993, 1024, 1055, 1086, 1118, 1150, 1182,
1215, 1248, 1281, 1314, 1347, 1381, 1415, 1449, 1483, 1518, 1552, 1587,
1622, 1657, 1692, 1727, 1763, 1798, 1834, 1869, 1905, 1940, 1976, 2012
};
| 68.757576
| 73
| 0.578228
|
kibergus
|
730852aeb662c1e4862b0141a2dcfb8ad66ed5b9
| 9,714
|
cpp
|
C++
|
src/caffe/layers/convolution3d_layer.cpp
|
antran89/New-C3D-Caffe
|
50644ddee7321dcd0a9c754f09672ff6fbf2029f
|
[
"BSD-2-Clause"
] | 11
|
2016-06-06T14:15:53.000Z
|
2021-09-07T03:12:30.000Z
|
src/caffe/layers/convolution3d_layer.cpp
|
antran89/New-C3D-Caffe
|
50644ddee7321dcd0a9c754f09672ff6fbf2029f
|
[
"BSD-2-Clause"
] | 5
|
2016-06-13T06:40:23.000Z
|
2017-01-07T09:49:29.000Z
|
src/caffe/layers/convolution3d_layer.cpp
|
antran89/New-C3D-Caffe
|
50644ddee7321dcd0a9c754f09672ff6fbf2029f
|
[
"BSD-2-Clause"
] | 8
|
2016-06-12T11:26:00.000Z
|
2018-01-04T12:33:33.000Z
|
/*
*
* Copyright (c) 2015, Facebook, Inc. All rights reserved.
*
* Licensed under the Creative Commons Attribution-NonCommercial 3.0
* License (the "License"). You may obtain a copy of the License at
* https://creativecommons.org/licenses/by-nc/3.0/.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*
*/
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/layers/convolution3d_layer.hpp"
#include "caffe/util/vol2col.hpp"
#include "caffe/filler.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void Convolution3DLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top)
{
CHECK_EQ(bottom.size(), 1) << "Conv Layer takes a single blob as input.";
CHECK_EQ(top.size(), 1) << "Conv Layer takes a single blob as output.";
kernel_size_ = this->layer_param_.convolution3d_param().kernel_size();
kernel_depth_ = this->layer_param_.convolution3d_param().kernel_depth();
stride_ = this->layer_param_.convolution3d_param().stride();
temporal_stride_ = this->layer_param_.convolution3d_param().temporal_stride();
pad_ = this->layer_param_.convolution3d_param().pad();
temporal_pad_ = this->layer_param_.convolution3d_param().temporal_pad();
vector<int>bottom_shape = bottom[0]->shape();
num_ = bottom_shape[0];
channels_ = bottom_shape[1];
length_ = bottom_shape[2];
height_ = bottom_shape[3];
width_ = bottom_shape[4];
num_output_ = this->layer_param_.convolution3d_param().num_output();
filter_group_ = this->layer_param_.convolution3d_param().filter_group();
CHECK_GT(num_output_, 0);
// number of output filters must be divided by filter_group
CHECK_EQ(num_output_ % filter_group_, 0);
}
template <typename Dtype>
void Convolution3DLayer<Dtype>::Reshape(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top)
{
// The vol2col result buffer would only hold one image at a time to avoid
// overly large memory usage.
int height_out = (height_ + 2 * pad_ - kernel_size_) / stride_ + 1;
int width_out = (width_ + 2 * pad_ - kernel_size_) / stride_ + 1;
int length_out = (length_ + 2 * temporal_pad_ - kernel_depth_) / temporal_stride_ + 1;
// buffer for one image
vector<int> shape(5);
shape[0] = 1;
shape[1] = channels_ * kernel_depth_ * kernel_size_ * kernel_size_;
shape[2] = length_out;
shape[3] = height_out;
shape[4] = width_out;
col_buffer_.Reshape(shape);
bias_term_ = this->layer_param_.convolution3d_param().bias_term();
// Figure out the dimensions for individual gemms.
M_ = num_output_ / filter_group_; // doing convolution filter_group_ times per volume
K_ = channels_ * kernel_depth_ * kernel_size_ * kernel_size_;
N_ = length_out * height_out * width_out;
// output size
shape[0] = bottom[0]->shape(0);
shape[1] = num_output_;
shape[2] = length_out;
shape[3] = height_out;
shape[4] = width_out;
top[0]->Reshape(shape);
// Check if we need to set up the weights
if (this->blobs_.size() > 0) {
// LOG(INFO) << "Skipping parameter initialization";
} else {
if (bias_term_) {
this->blobs_.resize(2);
} else {
this->blobs_.resize(1);
}
// Initialize the weights
shape[0] = num_output_;
shape[1] = channels_;
shape[2] = kernel_depth_;
shape[3] = kernel_size_;
shape[4] = kernel_size_;
this->blobs_[0].reset(new Blob<Dtype>(shape));
// fill the weights
shared_ptr<Filler<Dtype> > weight_filler(GetFiller<Dtype>(
this->layer_param_.convolution3d_param().weight_filler()));
weight_filler->Fill(this->blobs_[0].get());
// If necessary, initialize and fill the bias term
if (bias_term_) {
shape[0] = 1;
shape[1] = 1;
shape[2] = 1;
shape[3] = 1;
shape[4] = num_output_;
this->blobs_[1].reset(new Blob<Dtype>(shape));
shared_ptr<Filler<Dtype> > bias_filler(GetFiller<Dtype>(
this->layer_param_.convolution3d_param().bias_filler()));
bias_filler->Fill(this->blobs_[1].get());
}
}
// Set up the bias filler
if (bias_term_) {
bias_multiplier_.reset(new SyncedMemory(N_ * sizeof(Dtype)));
Dtype* bias_multiplier_data =
reinterpret_cast<Dtype*>(bias_multiplier_->mutable_cpu_data());
for (int i = 0; i < N_; ++i) {
bias_multiplier_data[i] = 1.;
}
}
}
template <typename Dtype>
void Convolution3DLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
Dtype* col_data = col_buffer_.mutable_cpu_data();
const Dtype* weight = this->blobs_[0]->cpu_data();
int weight_offset = M_ * K_;
int top_offset = M_ * N_;
for (int n = 0; n < num_; ++n) {
// First, im2col
vol2col_cpu(bottom_data + bottom[0]->offset(n), channels_, length_, height_,
width_, kernel_size_, kernel_depth_, pad_, temporal_pad_, stride_, temporal_stride_, col_data);
// Second, inner-product without filter groups
for (int g=0 ; g < filter_group_; ++g) {
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, M_, N_, K_,
(Dtype)1., weight + g * weight_offset, col_data,
(Dtype)0., top_data + top[0]->offset(n) + g * top_offset);
}
// third, add bias
if (bias_term_) {
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num_output_,
N_, 1, (Dtype)1., this->blobs_[1]->cpu_data(),
reinterpret_cast<const Dtype*>(bias_multiplier_->cpu_data()),
(Dtype)1., top_data + top[0]->offset(n));
}
}
}
template <typename Dtype>
void Convolution3DLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* weight = this->blobs_[0]->cpu_data();
Dtype* weight_diff = this->blobs_[0]->mutable_cpu_diff();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
Dtype* col_data = col_buffer_.mutable_cpu_data();
Dtype* col_diff = col_buffer_.mutable_cpu_diff();
// bias gradient if necessary
Dtype* bias_diff = NULL;
if (bias_term_) {
bias_diff = this->blobs_[1]->mutable_cpu_diff();
memset(bias_diff, 0, sizeof(Dtype) * this->blobs_[1]->count());
for (int n = 0; n < num_; ++n) {
caffe_cpu_gemv<Dtype>(CblasNoTrans, num_output_, N_,
1., top_diff + top[0]->offset(n),
reinterpret_cast<const Dtype*>(bias_multiplier_->cpu_data()), 1.,
bias_diff);
}
}
int weight_offset = M_ * K_;
int top_offset = M_ * N_;
memset(weight_diff, 0, sizeof(Dtype) * this->blobs_[0]->count());
for (int n = 0; n < num_; ++n) {
// since we saved memory in the forward pass by not storing all col data,
// we will need to recompute them.
vol2col_cpu(bottom_data + bottom[0]->offset(n), channels_, length_, height_,
width_, kernel_size_, kernel_depth_, pad_, temporal_pad_, stride_,
temporal_stride_, col_data);
// gradient w.r.t. weight. Note that we will accumulate diffs.
for (int g=0; g<filter_group_; ++g){
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, M_, K_, N_,
(Dtype)1., top_diff + top[0]->offset(n) + g * top_offset,
col_data, (Dtype)1.,
weight_diff + g * weight_offset);
}
// gradient w.r.t. bottom data, if necessary
if (propagate_down[0]) {
// compute first filter group -> col_diff
caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, K_, N_, M_,
(Dtype)1., weight,
top_diff + top[0]->offset(n),
(Dtype)0., col_diff);
// accumulate the other filter groups -> col_diff
for (int g=1; g<filter_group_; ++g){
caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, K_, N_, M_,
(Dtype)1., weight + g * weight_offset,
top_diff + top[0]->offset(n) + g * top_offset,
(Dtype)1., col_diff);
}
// vol2im back to the data
col2vol_cpu(col_diff, channels_, length_, height_, width_, kernel_size_, kernel_depth_, pad_,
temporal_pad_, stride_, temporal_stride_, bottom_diff + bottom[0]->offset(n));
}
}
}
#ifdef CPU_ONLY
STUB_GPU(Convolution3DLayer);
#endif
INSTANTIATE_CLASS(Convolution3DLayer);
REGISTER_LAYER_CLASS(Convolution3D);
} // namespace caffe
| 39.327935
| 118
| 0.599341
|
antran89
|
730c4f6691fccc14dcf240041cb240fd1f235002
| 6,787
|
cc
|
C++
|
system_wrappers/source/rtp_to_ntp_estimator.cc
|
airmelody5211/webrtc-clone
|
943843f1da42e47668c22ca758830334167f1b17
|
[
"BSD-3-Clause"
] | 2
|
2019-09-01T23:36:33.000Z
|
2020-04-13T11:40:13.000Z
|
system_wrappers/source/rtp_to_ntp_estimator.cc
|
zhangj1024/webrtc
|
3a6b729a8edaabd2fe324e1f6f830869ec38d5ab
|
[
"BSD-3-Clause"
] | 2
|
2019-04-26T04:57:02.000Z
|
2019-06-11T17:55:16.000Z
|
system_wrappers/source/rtp_to_ntp_estimator.cc
|
zhangj1024/webrtc
|
3a6b729a8edaabd2fe324e1f6f830869ec38d5ab
|
[
"BSD-3-Clause"
] | 4
|
2021-04-22T09:36:05.000Z
|
2022-02-21T01:57:59.000Z
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "system_wrappers/include/rtp_to_ntp_estimator.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#include "system_wrappers/include/clock.h"
namespace webrtc {
namespace {
// Number of RTCP SR reports to use to map between RTP and NTP.
const size_t kNumRtcpReportsToUse = 2;
// Number of parameters samples used to smooth.
const size_t kNumSamplesToSmooth = 20;
// Calculates the RTP timestamp frequency from two pairs of NTP/RTP timestamps.
bool CalculateFrequency(int64_t ntp_ms1,
uint32_t rtp_timestamp1,
int64_t ntp_ms2,
uint32_t rtp_timestamp2,
double* frequency_khz) {
if (ntp_ms1 <= ntp_ms2)
return false;
*frequency_khz = static_cast<double>(rtp_timestamp1 - rtp_timestamp2) /
static_cast<double>(ntp_ms1 - ntp_ms2);
return true;
}
bool Contains(const std::list<RtpToNtpEstimator::RtcpMeasurement>& measurements,
const RtpToNtpEstimator::RtcpMeasurement& other) {
for (const auto& measurement : measurements) {
if (measurement.IsEqual(other))
return true;
}
return false;
}
} // namespace
bool RtpToNtpEstimator::Parameters::operator<(const Parameters& other) const {
if (frequency_khz < other.frequency_khz - 1e-6) {
return true;
} else if (frequency_khz > other.frequency_khz + 1e-6) {
return false;
} else {
return offset_ms < other.offset_ms - 1e-6;
}
}
bool RtpToNtpEstimator::Parameters::operator==(const Parameters& other) const {
return !(other < *this || *this < other);
}
bool RtpToNtpEstimator::Parameters::operator!=(const Parameters& other) const {
return other < *this || *this < other;
}
bool RtpToNtpEstimator::Parameters::operator<=(const Parameters& other) const {
return !(other < *this);
}
RtpToNtpEstimator::RtcpMeasurement::RtcpMeasurement(uint32_t ntp_secs,
uint32_t ntp_frac,
int64_t unwrapped_timestamp)
: ntp_time(ntp_secs, ntp_frac),
unwrapped_rtp_timestamp(unwrapped_timestamp) {}
bool RtpToNtpEstimator::RtcpMeasurement::IsEqual(
const RtcpMeasurement& other) const {
// Use || since two equal timestamps will result in zero frequency and in
// RtpToNtpMs, |rtp_timestamp_ms| is estimated by dividing by the frequency.
return (ntp_time == other.ntp_time) ||
(unwrapped_rtp_timestamp == other.unwrapped_rtp_timestamp);
}
// Class for converting an RTP timestamp to the NTP domain.
RtpToNtpEstimator::RtpToNtpEstimator()
: consecutive_invalid_samples_(0),
smoothing_filter_(kNumSamplesToSmooth),
params_calculated_(false) {}
RtpToNtpEstimator::~RtpToNtpEstimator() {}
void RtpToNtpEstimator::UpdateParameters() {
if (measurements_.size() != kNumRtcpReportsToUse)
return;
Parameters params;
int64_t timestamp_new = measurements_.front().unwrapped_rtp_timestamp;
int64_t timestamp_old = measurements_.back().unwrapped_rtp_timestamp;
int64_t ntp_ms_new = measurements_.front().ntp_time.ToMs();
int64_t ntp_ms_old = measurements_.back().ntp_time.ToMs();
if (!CalculateFrequency(ntp_ms_new, timestamp_new, ntp_ms_old, timestamp_old,
¶ms.frequency_khz)) {
return;
}
params.offset_ms = timestamp_new - params.frequency_khz * ntp_ms_new;
params_calculated_ = true;
smoothing_filter_.Insert(params);
}
bool RtpToNtpEstimator::UpdateMeasurements(uint32_t ntp_secs,
uint32_t ntp_frac,
uint32_t rtp_timestamp,
bool* new_rtcp_sr) {
*new_rtcp_sr = false;
int64_t unwrapped_rtp_timestamp = unwrapper_.Unwrap(rtp_timestamp);
RtcpMeasurement new_measurement(ntp_secs, ntp_frac, unwrapped_rtp_timestamp);
if (Contains(measurements_, new_measurement)) {
// RTCP SR report already added.
return true;
}
if (!new_measurement.ntp_time.Valid())
return false;
int64_t ntp_ms_new = new_measurement.ntp_time.ToMs();
bool invalid_sample = false;
if (!measurements_.empty()) {
int64_t old_rtp_timestamp = measurements_.front().unwrapped_rtp_timestamp;
int64_t old_ntp_ms = measurements_.front().ntp_time.ToMs();
if (ntp_ms_new <= old_ntp_ms) {
invalid_sample = true;
} else if (unwrapped_rtp_timestamp <= old_rtp_timestamp) {
RTC_LOG(LS_WARNING)
<< "Newer RTCP SR report with older RTP timestamp, dropping";
invalid_sample = true;
} else if (unwrapped_rtp_timestamp - old_rtp_timestamp > (1 << 25)) {
// Sanity check. No jumps too far into the future in rtp.
invalid_sample = true;
}
}
if (invalid_sample) {
++consecutive_invalid_samples_;
if (consecutive_invalid_samples_ < kMaxInvalidSamples) {
return false;
}
RTC_LOG(LS_WARNING) << "Multiple consecutively invalid RTCP SR reports, "
"clearing measurements.";
measurements_.clear();
smoothing_filter_.Reset();
params_calculated_ = false;
}
consecutive_invalid_samples_ = 0;
// Insert new RTCP SR report.
if (measurements_.size() == kNumRtcpReportsToUse)
measurements_.pop_back();
measurements_.push_front(new_measurement);
*new_rtcp_sr = true;
// List updated, calculate new parameters.
UpdateParameters();
return true;
}
bool RtpToNtpEstimator::Estimate(int64_t rtp_timestamp,
int64_t* rtp_timestamp_ms) const {
if (!params_calculated_)
return false;
int64_t rtp_timestamp_unwrapped = unwrapper_.Unwrap(rtp_timestamp);
Parameters params = smoothing_filter_.GetFilteredValue();
// params_calculated_ should not be true unless ms params.frequency_khz has
// been calculated to something non zero.
RTC_DCHECK_NE(params.frequency_khz, 0.0);
double rtp_ms =
(static_cast<double>(rtp_timestamp_unwrapped) - params.offset_ms) /
params.frequency_khz +
0.5f;
if (rtp_ms < 0)
return false;
*rtp_timestamp_ms = rtp_ms;
return true;
}
const absl::optional<RtpToNtpEstimator::Parameters> RtpToNtpEstimator::params()
const {
absl::optional<Parameters> res;
if (params_calculated_) {
res.emplace(smoothing_filter_.GetFilteredValue());
}
return res;
}
} // namespace webrtc
| 33.107317
| 80
| 0.690585
|
airmelody5211
|
730caa6ac54a5c03c3a983c822bb35b6993b7c1c
| 1,270
|
cpp
|
C++
|
IOI/IOI14P2.cpp
|
Genius1506/Competitive-Programming
|
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
|
[
"MIT"
] | null | null | null |
IOI/IOI14P2.cpp
|
Genius1506/Competitive-Programming
|
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
|
[
"MIT"
] | null | null | null |
IOI/IOI14P2.cpp
|
Genius1506/Competitive-Programming
|
0fcbd9cd1a2381cf6dcb6e31f4ad0afe7cb98947
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define pb push_back
#define all(x) x.begin(),x.end()
#define pii pair<int,int>
#define f first
#define s second
const int INF = 0x3f3f3f3f;
struct Node{
int mn,mx;
}st[1<<22];
void app(int i, int xl, int xr){
st[i].mn = min(max(st[i].mn,xl),xr);
st[i].mx = min(max(st[i].mx,xl),xr);
}
void psh(int i){
app(i*2,st[i].mn,st[i].mx);
app(i*2+1,st[i].mn,st[i].mx);
st[i].mn=0;
st[i].mx=INF;
}
void update(int l1, int r1, int xl, int xr, int i, int l2, int r2){
if(l1<=l2&&r1>=r2){
app(i,xl,xr);
return;
}
psh(i);
int m = (l2+r2)>>1;
if(l1<=m)
update(l1,r1,xl,xr,i*2,l2,m);
if(r1>m)
update(l1,r1,xl,xr,i*2+1,m+1,r2);
}
void build(int *finalHeight, int l1, int r1, int i){
if(l1==r1){
finalHeight[l1]=st[i].mn;
return;
}
int m = (l1+r1)>>1;
psh(i);
build(finalHeight,l1,m,i*2);
build(finalHeight,m+1,r1,i*2+1);
}
void buildWall(int n, int k, int *op, int *left, int *right, int *height, int *finalHeight){
for(int i = 0; i < k; i++)
update(left[i],right[i],(op[i]==1?height[i]:0),(op[i]==1?INF:height[i]),1,0,n-1);
build(finalHeight,0,n-1,1);
}
| 24.423077
| 92
| 0.555118
|
Genius1506
|
730eebf9c1f946f7c0fb44d36f3e05a98c4193c4
| 1,282
|
hpp
|
C++
|
include/whack/codegen/expressions/factors/floatingpt.hpp
|
onchere/whack
|
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
|
[
"Apache-2.0"
] | 54
|
2018-10-28T07:18:31.000Z
|
2022-03-08T20:30:40.000Z
|
include/whack/codegen/expressions/factors/floatingpt.hpp
|
onchere/whack
|
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
|
[
"Apache-2.0"
] | null | null | null |
include/whack/codegen/expressions/factors/floatingpt.hpp
|
onchere/whack
|
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
|
[
"Apache-2.0"
] | 5
|
2018-10-28T14:43:53.000Z
|
2020-04-26T19:52:58.000Z
|
/**
* Copyright 2018-present Onchere Bironga
*
* 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.
*/
#ifndef WHACK_FLOATINGPT_HPP
#define WHACK_FLOATINGPT_HPP
#pragma once
namespace whack::codegen::expressions::factors {
class FloatingPt final : public Factor {
public:
explicit FloatingPt(const mpc_ast_t* const ast)
: Factor(kFloatingPt), floatingpt_{ast->contents} {}
llvm::Expected<llvm::Value*> codegen(llvm::IRBuilder<>&) const final {
return llvm::ConstantFP::get(BasicTypes["double"], floatingpt_);
}
inline static bool classof(const Factor* const factor) {
return factor->getKind() == kFloatingPt;
}
private:
const llvm::StringRef floatingpt_;
};
} // end namespace whack::codegen::expressions::factors
#endif // WHACK_FLOATINGPT_HPP
| 29.813953
| 75
| 0.73869
|
onchere
|
7310e81a1676f4653d6a3d639e58131b6ab5c47a
| 2,255
|
cpp
|
C++
|
CheckSuperCalls/Result.cpp
|
Neo7k/CheckSuperCalls
|
d799ef9e30988dc39581e63411c9c6061138fb18
|
[
"MIT"
] | null | null | null |
CheckSuperCalls/Result.cpp
|
Neo7k/CheckSuperCalls
|
d799ef9e30988dc39581e63411c9c6061138fb18
|
[
"MIT"
] | null | null | null |
CheckSuperCalls/Result.cpp
|
Neo7k/CheckSuperCalls
|
d799ef9e30988dc39581e63411c9c6061138fb18
|
[
"MIT"
] | null | null | null |
#include "Result.h"
#include "Files.h"
#include "Algorithms.h"
Result::Result(int threads_num)
{
issues.resize(threads_num);
}
Result::~Result()
{
Clear();
}
void Result::AddIssue(Issue* issue, int thread_id)
{
issues[thread_id].push_back(issue);
}
Result::IssuesVec Result::GetAllIssues() const
{
IssuesVec grouped_result;
for (auto& is_v : issues)
for (auto is : is_v)
grouped_result.push_back(is);
for (auto is : cached_issues)
grouped_result.push_back(is);
return grouped_result;
}
void Result::ReadCache(std::ifstream& f)
{
size_t sz;
Deserialize(f, sz);
for (size_t i = 0; i < sz; ++i)
{
auto issue = new Issue;
Deserialize(f, issue->file);
Deserialize(f, issue->line);
Deserialize(f, issue->funcname.name);
Deserialize(f, issue->funcname.namespase);
Deserialize(f, issue->root_funcname.name);
Deserialize(f, issue->root_funcname.namespase);
cached_issues.push_back(issue);
}
}
void Result::WriteCache(std::ofstream& f) const
{
auto issues = GetAllIssues();
Serialize(f, issues.size());
for (auto& issue : issues)
{
Serialize(f, issue->file);
Serialize(f, issue->line);
Serialize(f, issue->funcname.name);
Serialize(f, issue->funcname.namespase);
Serialize(f, issue->root_funcname.name);
Serialize(f, issue->root_funcname.namespase);
}
}
void Result::UpdateCachedData(const CodeFiles& code_files)
{
std::map<fs::path, std::vector<uint>> issues_by_file;
for (uint i = 0; i < (uint)cached_issues.size(); ++i)
issues_by_file[cached_issues[i]->file].push_back(i);
for (auto& file : code_files.changed_source)
{
auto it = issues_by_file.find(file);
if (it == issues_by_file.end())
continue;
for (auto i : it->second)
{
delete cached_issues[i];
cached_issues[i] = nullptr;
}
}
Erase(cached_issues, nullptr);
}
void Result::Clear()
{
for (auto& is_v : issues)
{
for (auto is : is_v)
delete is;
is_v.clear();
}
for (auto& is : cached_issues)
delete is;
cached_issues.clear();
}
void Result::EraseCachedIssues(const FuncName& root_func)
{
auto it = FindIf(cached_issues, [&root_func](auto issue) {return issue->root_funcname == root_func;});
if (it != cached_issues.end())
{
delete *it;
*it = nullptr;
}
Erase(cached_issues, nullptr);
}
| 19.608696
| 103
| 0.687361
|
Neo7k
|
7313adb79dc2ccb1acbe60345aeea61cdbe116d8
| 4,215
|
cpp
|
C++
|
benchmarks/BM_writeInterleaved.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 281
|
2019-06-06T05:58:59.000Z
|
2022-03-06T12:20:09.000Z
|
benchmarks/BM_writeInterleaved.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 590
|
2019-09-22T00:26:10.000Z
|
2022-03-31T19:21:58.000Z
|
benchmarks/BM_writeInterleaved.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 44
|
2019-10-08T08:24:20.000Z
|
2022-02-26T04:21:44.000Z
|
// SPDX-License-Identifier: BSD-2-Clause
// This code is part of the sfizz library and is licensed under a BSD 2-clause
// license. You should have receive a LICENSE.md file along with the code.
// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz
#include "SIMDHelpers.h"
#include "Buffer.h"
#include <benchmark/benchmark.h>
#include <algorithm>
#include <numeric>
#include <absl/types/span.h>
static void Interleaved_Write(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, false);
sfz::writeInterleaved(inputLeft, inputRight, absl::MakeSpan(output));
}
}
static void Interleaved_Write_SSE(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, true);
sfz::writeInterleaved(inputLeft, inputRight, absl::MakeSpan(output));
}
}
static void Unaligned_Interleaved_Write(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, false);
sfz::writeInterleaved(
absl::MakeSpan(inputLeft).subspan(1),
absl::MakeSpan(inputRight).subspan(1),
absl::MakeSpan(output).subspan(2)
);
}
}
static void Unaligned_Interleaved_Write_SSE(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, true);
sfz::writeInterleaved(
absl::MakeSpan(inputLeft).subspan(1),
absl::MakeSpan(inputRight).subspan(1),
absl::MakeSpan(output).subspan(2)
);
}
}
static void Unaligned_Interleaved_Write_2(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, false);
sfz::writeInterleaved(
absl::MakeSpan(inputLeft),
absl::MakeSpan(inputRight).subspan(1),
absl::MakeSpan(output).subspan(2)
);
}
}
static void Unaligned_Interleaved_Write_SSE_2(benchmark::State& state) {
sfz::Buffer<float> inputLeft (state.range(0));
sfz::Buffer<float> inputRight (state.range(0));
sfz::Buffer<float> output (state.range(0) * 2);
std::iota(inputLeft.begin(), inputLeft.end(), 1.0f);
std::iota(inputRight.begin(), inputRight.end(), 1.0f);
for (auto _ : state) {
sfz::setSIMDOpStatus<float>(sfz::SIMDOps::writeInterleaved, true);
sfz::writeInterleaved(
absl::MakeSpan(inputLeft),
absl::MakeSpan(inputRight).subspan(1),
absl::MakeSpan(output).subspan(2)
);
}
}
BENCHMARK(Interleaved_Write)->Range((8<<10), (8<<20));
BENCHMARK(Interleaved_Write_SSE)->Range((8<<10), (8<<20));
BENCHMARK(Unaligned_Interleaved_Write)->Range((8<<10), (8<<20));
BENCHMARK(Unaligned_Interleaved_Write_SSE)->Range((8<<10), (8<<20));
BENCHMARK(Unaligned_Interleaved_Write_2)->Range((8<<10), (8<<20));
BENCHMARK(Unaligned_Interleaved_Write_SSE_2)->Range((8<<10), (8<<20));
BENCHMARK_MAIN();
| 38.318182
| 78
| 0.688731
|
michaelwillis
|
731418d117145f0ad6f2d6a72f319a6057416cfe
| 7,341
|
cpp
|
C++
|
Assignment2/Program2/main.cpp
|
Siddhant628/Prog1_Compressor-Decompressor-In-C
|
94b27155cb03296a6ad2a5989616c6fa78aadb1c
|
[
"MIT"
] | null | null | null |
Assignment2/Program2/main.cpp
|
Siddhant628/Prog1_Compressor-Decompressor-In-C
|
94b27155cb03296a6ad2a5989616c6fa78aadb1c
|
[
"MIT"
] | null | null | null |
Assignment2/Program2/main.cpp
|
Siddhant628/Prog1_Compressor-Decompressor-In-C
|
94b27155cb03296a6ad2a5989616c6fa78aadb1c
|
[
"MIT"
] | null | null | null |
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
#include"main.h"
int main(int argc, char* argv[])
{
if (argc > 1)
{
sscanf(argv[1], "%d", &bitsPerValue);
}
double rootMeanSquaredError;
InitializeFiles();
ProcessMetaData();
CalculateTheNumberOfDataShorts();
RecreateData();
rootMeanSquaredError = CalculateMeanSquaredError();
std::cout << "RMS Value for " << bitsPerValue<< " = " <<rootMeanSquaredError<<std::endl;
CloseFiles();
return 0;
}
void InitializeFiles()
{
char fileName[30];
sprintf(fileName, "compressedVertData%d.bin", bitsPerValue);
// Open the file with compressed binary data in it
compressedVertDataBin = fopen(fileName, "rb");
if (compressedVertDataBin == NULL)
{
std::cout << "Compressed vertex data (binary) not found by decompressor.\n";
exit(0);
}
// Open the file with uncompressed vert data
uncompressedVertDataText = fopen("vertData.txt","r");
if (uncompressedVertDataText == NULL)
{
std::cout << "Uncompressed vertex data not found by decompressor.\n";
exit(0);
}
// Initialize a new file to which the recreated vert data will be copied
recreatedVertDataText = fopen("recreatedVertDataText.txt","w");
}
void ProcessMetaData()
{
// Read meta data from the compressed binary file
// The file's meta data will contain
// The bits used to represent each value (4 bytes)
// The total number of compressed values (4 bytes)
// The minimum floating point value in data set (8 bytes)
// The size of each bucket of storing values (8 bytes)
fread(&bitsPerValue, sizeof(int), 1, compressedVertDataBin);
fread(&numberOfElements, sizeof(int), 1, compressedVertDataBin);
fread(&minimumFloatValue, sizeof(double), 1, compressedVertDataBin);
fread(&bucketSize, sizeof(double), 1, compressedVertDataBin);
}
void CalculateTheNumberOfDataShorts()
{
// Calculate the total number of bits
numberOfShortsToRead = bitsPerValue * numberOfElements;
// Calculate the number of shorts
numberOfShortsToRead = (int) (numberOfShortsToRead / 16);
// Check if there is an additional short at the end
if ((bitsPerValue*numberOfElements) % 16 != 0)
{
numberOfShortsToRead++;
additionalShortPresent = 1;
}
}
void RecreateData()
{
// Takes value 1 in case a short was read successfully from the bit stream
int successfulRead;
// Temporary variable to store a decompressed value
double decompressedValue;
// The last short which was read from the binary file
unsigned short shortFromFile;
unsigned short tempShort, tempShort2;
// A short which contains 1s for the positions corresponding to the size of
unsigned short shortOfBitSizeLength = 0xffff;
shortOfBitSizeLength = shortOfBitSizeLength >> (16 - bitsPerValue);
CalculateBitsOfFinalShort();
// Decompression Loop
while (numberOfShortsToRead > 0 || additionalShortPresent == 1)
{
// In case this is the last short
if (numberOfShortsToRead == 0)
{
// Case: The last short has multiple values in it
if (bitsLeftToBeProcessed > bitsPerValue)
{
tempShort = shortFromFile;
tempShort = tempShort >> (16 - bitsInLastShort + bitsLeftToBeProcessed - bitsPerValue);
tempShort = tempShort & shortOfBitSizeLength;
bitsLeftToBeProcessed -= bitsPerValue;
decompressedValue = DecompressToDouble((int)tempShort);
CalculateNetSquaredError(decompressedValue);
continue;
}
// Case: The last short has only 1 new value in it
else if (bitsLeftToBeProcessed == bitsPerValue)
{
tempShort = shortFromFile;
tempShort = tempShort >> (16 - bitsInLastShort + bitsLeftToBeProcessed - bitsPerValue);
tempShort = tempShort & shortOfBitSizeLength;
bitsLeftToBeProcessed -= bitsPerValue;
decompressedValue = DecompressToDouble((int)tempShort);
CalculateNetSquaredError(decompressedValue);
break;
}
break;
}
// Don't read another short if an additional short was read
if (additionalShortRead)
{
additionalShortRead = 0;
}
// Read the next short in bit stream
else
{
successfulRead = fread(&shortFromFile, sizeof(short), 1, compressedVertDataBin);
if (successfulRead != 1)
{
std::cout << "Binary file read failed by decompressor.\n";
exit(0);
}
numberOfShortsToRead--;
// If the current short is the additional short, continue with loop to handle it separately
if (numberOfShortsToRead == 0 && additionalShortPresent == 1)
{
continue;
}
}
// Extract values from the short
tempShort = shortFromFile;
// While the short has complete values in it, perform the following loop
while (bitsLeftToBeProcessed >= bitsPerValue)
{
tempShort = tempShort >> (bitsLeftToBeProcessed - bitsPerValue);
tempShort = tempShort & shortOfBitSizeLength;
decompressedValue = DecompressToDouble((int)tempShort);
CalculateNetSquaredError(decompressedValue);
// Brings the next set of bits to the left most end
tempShort = shortFromFile;
bitsLeftToBeProcessed -= bitsPerValue;
}
// Case: Entire short has been processed by the above
if (bitsLeftToBeProcessed == 0)
{
bitsLeftToBeProcessed = 16;
// In case the following short is the last one
if (numberOfShortsToRead == 0)
{
bitsLeftToBeProcessed = bitsInLastShort;
}
continue;
}
// Case: Some bits are left in the short which still have to be processed
successfulRead = fread(&shortFromFile, sizeof(short), 1, compressedVertDataBin);
if (successfulRead != 1)
{
std::cout << "Binary file read failed by decompressor.\n";
exit(0);
}
// Store the next short in a temp variable
additionalShortRead = 1;
numberOfShortsToRead--;
tempShort2 = shortFromFile;
// Operations to get the value distributed over the two shorts
tempShort2 = tempShort2 >> bitsLeftToBeProcessed;
tempShort = tempShort << (16 - bitsLeftToBeProcessed);
tempShort2 |= tempShort;
tempShort2 = tempShort2 >> (16 - bitsPerValue);
decompressedValue = DecompressToDouble((int)tempShort2);
CalculateNetSquaredError(decompressedValue);
// Update the number of bits left to be processed
if (numberOfShortsToRead == 0)
{
bitsLeftToBeProcessed = bitsInLastShort - bitsPerValue + bitsLeftToBeProcessed;
continue;
}
bitsLeftToBeProcessed = 16 - bitsPerValue + bitsLeftToBeProcessed;
}
}
void CalculateBitsOfFinalShort()
{
bitsInLastShort = bitsPerValue * numberOfElements;
bitsInLastShort = (bitsInLastShort % 16);
}
double DecompressToDouble(int valueFromFile)
{
double decompressedValue;
decompressedValue = valueFromFile * bucketSize;
decompressedValue += minimumFloatValue;
decompressedValue += (bucketSize / 2);
WriteDecompressedValueToFile(decompressedValue);
return decompressedValue;
}
void WriteDecompressedValueToFile(double decompressedValue)
{
fprintf(recreatedVertDataText, "%.15lf ", decompressedValue);
}
void CalculateNetSquaredError(double decompressedValue)
{
double originalValue, error;
fscanf(uncompressedVertDataText, "%lf", &originalValue);
error = decompressedValue - originalValue;
error *= error;
// Add the error squared to the net error (mean is calculated later)
meanSquaredError += error;
}
double CalculateMeanSquaredError()
{
meanSquaredError /= numberOfElements;
return sqrt(meanSquaredError);
}
void CloseFiles()
{
fclose(compressedVertDataBin);
fclose(recreatedVertDataText);
fclose(uncompressedVertDataText);
}
| 30.715481
| 94
| 0.738183
|
Siddhant628
|
7314771828254f2e8cffa24e852c49cb57046ac7
| 1,953
|
hpp
|
C++
|
modules/memory/include/shard/memory/allocator.hpp
|
ikimol/shard
|
72a72dbebfd247d2b7b300136c489672960b37d8
|
[
"MIT"
] | null | null | null |
modules/memory/include/shard/memory/allocator.hpp
|
ikimol/shard
|
72a72dbebfd247d2b7b300136c489672960b37d8
|
[
"MIT"
] | null | null | null |
modules/memory/include/shard/memory/allocator.hpp
|
ikimol/shard
|
72a72dbebfd247d2b7b300136c489672960b37d8
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 Miklos Molnar. All rights reserved.
#ifndef SHARD_MEMORY_ALLOCATOR_HPP
#define SHARD_MEMORY_ALLOCATOR_HPP
#include <shard/core/non_copyable.hpp>
#include <cassert>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace shard {
namespace memory {
class allocator {
public:
explicit allocator(std::size_t size) noexcept : m_size(size) {}
virtual ~allocator() {
assert(m_used_memory == 0);
assert(m_allocation_count == 0);
}
/// Allocate raw memory respecting the alignment
virtual void* allocate(std::size_t size, std::size_t align) = 0;
/// Deallocate previously allocated memory
virtual void deallocate(void* ptr) = 0;
/// Return the size of the memory the allocator operates on
std::size_t size() const noexcept { return m_size; }
/// Return the total amount of allocated memory in bytes
std::size_t used_memory() const noexcept { return m_used_memory; }
/// Return the number of allocations
std::size_t allocation_count() const noexcept { return m_allocation_count; }
protected:
std::size_t m_size;
std::size_t m_used_memory = 0;
std::size_t m_allocation_count = 0;
};
// helper functions
template <typename T, typename... Args>
T* new_object(allocator& a, Args&&... args) {
return new (a.allocate(sizeof(T), alignof(T))) T(std::forward<Args>(args)...);
}
template <typename T, std::enable_if_t<!std::is_trivially_destructible<T>::value>* = nullptr>
void delete_object(allocator& a, T* object) {
object->~T();
a.deallocate(object);
}
template <typename T, std::enable_if_t<std::is_trivially_destructible<T>::value>* = nullptr>
void delete_object(allocator& a, T* object) {
a.deallocate(object);
}
} // namespace memory
// bring symbols into parent namespace
using memory::allocator;
using memory::delete_object;
using memory::new_object;
} // namespace shard
#endif // SHARD_MEMORY_ALLOCATOR_HPP
| 26.04
| 93
| 0.709165
|
ikimol
|
7315e4b1025e0b42f093611714738c06e06e53cb
| 7,086
|
cpp
|
C++
|
QtFresnelZones/amplitudeplatewindow.cpp
|
Lnd-stoL/fresnel-zones-qt
|
ada6d03e285665eb5281808a55f9b7cc8289710b
|
[
"MIT"
] | 2
|
2015-09-07T19:19:33.000Z
|
2015-09-07T19:19:40.000Z
|
QtFresnelZones/amplitudeplatewindow.cpp
|
Lnd-stoL/fresnel-zones-qt
|
ada6d03e285665eb5281808a55f9b7cc8289710b
|
[
"MIT"
] | null | null | null |
QtFresnelZones/amplitudeplatewindow.cpp
|
Lnd-stoL/fresnel-zones-qt
|
ada6d03e285665eb5281808a55f9b7cc8289710b
|
[
"MIT"
] | null | null | null |
#include "amplitudeplatewindow.h"
#include "ui_amplitudeplatewindow.h"
#include "colortransform.h"
#include "titlewindow.h"
AmplitudePlateWindow::AmplitudePlateWindow (Fresnel *fresnel, TitleWindow *tw) :
QMainWindow (nullptr),
ui (new Ui::AmplitudePlateWindow),
titleWindow (tw),
_fresnel (fresnel)
{
ui->setupUi (this);
_fresnel->setDefaults();
_fresnel->amplitudePlate = true;
_fresnel->phasePlate = false;
_initCheckBoxes();
_setupSlots();
double minWaveLength = Fresnel::wave_min * Fresnel::scale_to_nano_exp;
double maxWaveLength = Fresnel::wave_max * Fresnel::scale_to_nano_exp;
double defaultWaveLength = Fresnel::wave_def * Fresnel::scale_to_nano_exp;
ui->slider_WaveLength->setRange (minWaveLength, maxWaveLength);
ui->slider_WaveLength->setValue (defaultWaveLength);
ui->spin_WaveLength->setRange (minWaveLength, maxWaveLength);
ui->spin_WaveLength->setValue (defaultWaveLength);
ui->widget_spiralGraph->fresnel = _fresnel;
_fresnel->setHoleRadius (Fresnel::radius_max * 0.85);
button_Tune_Pressed();
ui->widget_schemeGraph->fresnel = _fresnel;
ui->widget_schemeGraph->zonesGraph = ui->widget_Zones;
ui->widget_schemeGraph->schemeType = SchemeGraph::SchemeType::AmplitudePlateScheme;
for (unsigned i = 1; i < zoneCheckBoxesNum+1; ++i) _fresnel->setZoneOpenness (i, false);
_fresnel->setZoneOpenness (0, true);
_initialIntensity = _fresnel->intensity() * 0.25;
_progressBarHigh = _initialIntensity * 90;
for (unsigned i = 1; i < zoneCheckBoxesNum+1; ++i) _fresnel->setZoneOpenness (i, true);
ui->progressBar->setTextVisible (false);
_update();
}
void AmplitudePlateWindow::_initCheckBoxes()
{
_zoneCheckBoxes[0] = ui->checkBox_Zone0,
_zoneCheckBoxes[1] = ui->checkBox_Zone1;
_zoneCheckBoxes[2] = ui->checkBox_Zone2;
_zoneCheckBoxes[3] = ui->checkBox_Zone3;
_zoneCheckBoxes[4] = ui->checkBox_Zone4;
_zoneCheckBoxes[5] = ui->checkBox_Zone5;
_zoneCheckBoxes[6] = ui->checkBox_Zone6;
_zoneCheckBoxes[7] = ui->checkBox_Zone7;
_zoneCheckBoxes[8] = ui->checkBox_Zone8;
_zoneLabels[0] = ui->label_zone0,
_zoneLabels[1] = ui->label_zone1;
_zoneLabels[2] = ui->label_zone2;
_zoneLabels[3] = ui->label_zone3;
_zoneLabels[4] = ui->label_zone4;
_zoneLabels[5] = ui->label_zone5;
_zoneLabels[6] = ui->label_zone6;
_zoneLabels[7] = ui->label_zone7;
_zoneLabels[8] = ui->label_zone8;
}
void AmplitudePlateWindow::_setupSlots()
{
connect (ui->pushButton_Back, SIGNAL(clicked()), this, SLOT(button_Back_Pressed()));
connect (ui->pushButton_Next, SIGNAL(clicked()), this, SLOT(button_Next_Pressed()));
connect (ui->pushButton_closeAll, SIGNAL(clicked()), this, SLOT(button_CloseAll_Pressed()));
connect (ui->pushButton_openAll, SIGNAL(clicked()), this, SLOT(button_OpenAll_Pressed()));
connect (ui->pushButton_OpenOdd, SIGNAL(clicked()), this, SLOT(button_OpenOdd_Pressed()));
for (unsigned i = 0; i < zoneCheckBoxesNum; ++i)
connect (_zoneCheckBoxes[i], SIGNAL(clicked()), this, SLOT(_update()));
connect (ui->slider_WaveLength, SIGNAL(valueChanged(int)), this, SLOT(slider_WaveLength_Changed(int)));
connect (ui->spin_WaveLength, SIGNAL(valueChanged(double)), this, SLOT(spin_WaveLength_Changed(double)));
connect (ui->spin_WaveLength, SIGNAL(editingFinished()), this, SLOT(_update()));
connect (ui->slider_WaveLength, SIGNAL(sliderReleased()), this, SLOT(_update()));
}
void AmplitudePlateWindow::_updateFresnel()
{
double newWaveLength = Fresnel::nano_to_scale_exp * ui->spin_WaveLength->value();
_fresnel->setWaveLength (newWaveLength);
unsigned zonesVisible = _fresnel->fresnelNumber() + 1;
for (unsigned i = 0; i < zoneCheckBoxesNum; ++i)
{
bool enabled = i < zonesVisible;
_zoneCheckBoxes[i]->setEnabled (enabled);
_zoneLabels[i]->setEnabled (enabled);
auto f = _zoneLabels[i]->font();
f.setUnderline (_zoneCheckBoxes[i]->isChecked());
_zoneLabels[i]->setFont (f);
_fresnel->setZoneOpenness (i, _zoneCheckBoxes[i]->isChecked());
}
}
void AmplitudePlateWindow::_updateProgressBar()
{
QRect r = ui->progressBar->geometry();
QColor barColor = ColorTransform::getRGBfromLambda (_fresnel->getWaveLength() * Fresnel::scale_to_nano_exp);
QString st = QString (
"QProgressBar::chunk {"
"background-color:rgb(%1,%2,%3);"
"}").arg (QString::number (barColor.red()),
QString::number (barColor.green()),
QString::number (barColor.blue()));
st.append ("QProgressBar {"
"border: 2px solid grey;"
"border-radius: 2px;"
"text-align: center;"
"background: #eeeeee;"
"}");
ui->progressBar->setStyleSheet (st);
ui->progressBar->setGeometry (r.x(), r.y() + 3, r.width(), r.height() - 6);
int progress = round ((_fresnel->intensity() / _progressBarHigh) * 100);
if (progress < 0) progress = -progress;
if (progress > 100) progress = 100;
ui->progressBar->setValue (progress);
ui->label_intensity->setText (QString ("Интенсивность на оси: ") +
QString::number (_fresnel->intensity() / _initialIntensity, 'g', 4) + " Io");
}
AmplitudePlateWindow::~AmplitudePlateWindow()
{
delete ui;
}
void AmplitudePlateWindow::_update()
{
_updateFresnel();
ui->widget_Zones->update (_fresnel);
_fresnel->spiral (ui->widget_spiralGraph->spiralX, ui->widget_spiralGraph->spiralY);
ui->widget_spiralGraph->repaint();
ui->widget_schemeGraph->repaint();
ui->label_intensity->setText("Интенсивность в точке наблюдения: " +
QString::number ((int)round (_fresnel->intensity() / this->_progressBarHigh)) + " Io");
_updateProgressBar();
}
void AmplitudePlateWindow::button_Back_Pressed()
{
this->close();
}
void AmplitudePlateWindow::button_Next_Pressed()
{
this->close();
titleWindow->openPhasePlateWindow();
}
void AmplitudePlateWindow::button_OpenAll_Pressed()
{
for (unsigned i = 0; i < zoneCheckBoxesNum; ++i)
_zoneCheckBoxes[i]->setChecked (true);
_update();
}
void AmplitudePlateWindow::button_CloseAll_Pressed()
{
for (unsigned i = 0; i < zoneCheckBoxesNum; ++i)
_zoneCheckBoxes[i]->setChecked (false);
_update();
}
void AmplitudePlateWindow::button_OpenOdd_Pressed()
{
for (unsigned i = 0; i < zoneCheckBoxesNum; ++i)
_zoneCheckBoxes[i]->setChecked (i % 2 == 0);
_update();
}
void AmplitudePlateWindow::button_Tune_Pressed()
{
_fresnel->setObserverDistance (_fresnel->getObserverDistanceForZone (6));
_update();
}
void AmplitudePlateWindow::slider_WaveLength_Changed (int value)
{
ui->spin_WaveLength->setValue ((double) value);
}
void AmplitudePlateWindow::spin_WaveLength_Changed (double value)
{
ui->slider_WaveLength->setValue (value);
}
| 31.353982
| 120
| 0.673582
|
Lnd-stoL
|
7316a92f7fada4cda64b8093e97d17806aba954d
| 4,458
|
hpp
|
C++
|
include/UnityEngine/Rendering/MeshUpdateFlags.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/Rendering/MeshUpdateFlags.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/Rendering/MeshUpdateFlags.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: UnityEngine.Rendering
namespace UnityEngine::Rendering {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.Rendering.MeshUpdateFlags
// [TokenAttribute] Offset: FFFFFFFF
// [FlagsAttribute] Offset: FFFFFFFF
struct MeshUpdateFlags/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: MeshUpdateFlags
constexpr MeshUpdateFlags(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public UnityEngine.Rendering.MeshUpdateFlags Default
static constexpr const int Default = 0;
// Get static field: static public UnityEngine.Rendering.MeshUpdateFlags Default
static UnityEngine::Rendering::MeshUpdateFlags _get_Default();
// Set static field: static public UnityEngine.Rendering.MeshUpdateFlags Default
static void _set_Default(UnityEngine::Rendering::MeshUpdateFlags value);
// static field const value: static public UnityEngine.Rendering.MeshUpdateFlags DontValidateIndices
static constexpr const int DontValidateIndices = 1;
// Get static field: static public UnityEngine.Rendering.MeshUpdateFlags DontValidateIndices
static UnityEngine::Rendering::MeshUpdateFlags _get_DontValidateIndices();
// Set static field: static public UnityEngine.Rendering.MeshUpdateFlags DontValidateIndices
static void _set_DontValidateIndices(UnityEngine::Rendering::MeshUpdateFlags value);
// static field const value: static public UnityEngine.Rendering.MeshUpdateFlags DontResetBoneBounds
static constexpr const int DontResetBoneBounds = 2;
// Get static field: static public UnityEngine.Rendering.MeshUpdateFlags DontResetBoneBounds
static UnityEngine::Rendering::MeshUpdateFlags _get_DontResetBoneBounds();
// Set static field: static public UnityEngine.Rendering.MeshUpdateFlags DontResetBoneBounds
static void _set_DontResetBoneBounds(UnityEngine::Rendering::MeshUpdateFlags value);
// static field const value: static public UnityEngine.Rendering.MeshUpdateFlags DontNotifyMeshUsers
static constexpr const int DontNotifyMeshUsers = 4;
// Get static field: static public UnityEngine.Rendering.MeshUpdateFlags DontNotifyMeshUsers
static UnityEngine::Rendering::MeshUpdateFlags _get_DontNotifyMeshUsers();
// Set static field: static public UnityEngine.Rendering.MeshUpdateFlags DontNotifyMeshUsers
static void _set_DontNotifyMeshUsers(UnityEngine::Rendering::MeshUpdateFlags value);
// static field const value: static public UnityEngine.Rendering.MeshUpdateFlags DontRecalculateBounds
static constexpr const int DontRecalculateBounds = 8;
// Get static field: static public UnityEngine.Rendering.MeshUpdateFlags DontRecalculateBounds
static UnityEngine::Rendering::MeshUpdateFlags _get_DontRecalculateBounds();
// Set static field: static public UnityEngine.Rendering.MeshUpdateFlags DontRecalculateBounds
static void _set_DontRecalculateBounds(UnityEngine::Rendering::MeshUpdateFlags value);
// Get instance field: public System.Int32 value__
int _get_value__();
// Set instance field: public System.Int32 value__
void _set_value__(int value);
}; // UnityEngine.Rendering.MeshUpdateFlags
#pragma pack(pop)
static check_size<sizeof(MeshUpdateFlags), 0 + sizeof(int)> __UnityEngine_Rendering_MeshUpdateFlagsSizeCheck;
static_assert(sizeof(MeshUpdateFlags) == 0x4);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Rendering::MeshUpdateFlags, "UnityEngine.Rendering", "MeshUpdateFlags");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 57.153846
| 111
| 0.769403
|
marksteward
|
73174e310e79bdb608eeb0c3c24781615a488735
| 1,678
|
cpp
|
C++
|
sdl/Hypergraph/src/HypPrune.cpp
|
sdl-research/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 29
|
2015-01-26T21:49:51.000Z
|
2021-06-18T18:09:42.000Z
|
sdl/Hypergraph/src/HypPrune.cpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 1
|
2015-12-08T15:03:15.000Z
|
2016-01-26T14:31:06.000Z
|
sdl/Hypergraph/src/HypPrune.cpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 4
|
2015-11-21T14:25:38.000Z
|
2017-10-30T22:22:00.000Z
|
// Copyright 2014-2015 SDL plc
// 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.
#define USAGE_HypPrune \
"Print nothing if input hypergraph is empty (i.e., cannot reach final state from start and lexical " \
"leaves); otherwise print input hypergraph with useless states/arcs removed"
#define HG_TRANSFORM_MAIN
#include <sdl/Hypergraph/Prune.hpp>
#include <sdl/Hypergraph/TransformMain.hpp>
namespace sdl {
namespace Hypergraph {
struct HypPrune : TransformMain<HypPrune> {
typedef TransformMain<HypPrune> Base;
HypPrune() : Base("Prune", USAGE_HypPrune) {}
PruneOptions pruneOptions;
Properties properties(int i) const { return kStoreOutArcs; }
void declare_configurable() { this->configurable(&pruneOptions); }
enum { has_inplace_input_transform = true, has_transform1 = false };
bool printFinal() const { return true; }
static bool nbestHypergraphDefault() { return false; }
template <class Arc>
bool inputTransformInplace(IMutableHypergraph<Arc>& hg, int) const {
pruneUnreachable(hg, pruneOptions);
return true;
}
};
}
}
HYPERGRAPH_NAMED_MAIN(Prune)
| 36.478261
| 104
| 0.717521
|
sdl-research
|
73183a28dfa5e628b5284a949a3d2c68a73b745e
| 4,042
|
cpp
|
C++
|
src/pumex/TextureLoaderJPEG.cpp
|
pumexx/pumex
|
86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe
|
[
"MIT"
] | 299
|
2017-07-17T17:07:39.000Z
|
2022-03-27T20:33:20.000Z
|
src/pumex/TextureLoaderJPEG.cpp
|
pumexx/pumex
|
86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe
|
[
"MIT"
] | 9
|
2018-08-09T11:49:37.000Z
|
2020-12-10T03:55:12.000Z
|
src/pumex/TextureLoaderJPEG.cpp
|
pumexx/pumex
|
86fda7fa351d00bd5918ad90899ce2d6bb8b1dfe
|
[
"MIT"
] | 21
|
2017-12-03T16:08:21.000Z
|
2022-01-17T06:34:39.000Z
|
//
// Copyright(c) 2017-2018 Paweł Księżopolski ( pumexx )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include <pumex/TextureLoaderJPEG.h>
#if defined(GLM_ENABLE_EXPERIMENTAL) // hack around redundant GLM_ENABLE_EXPERIMENTAL defined in type.hpp
#undef GLM_ENABLE_EXPERIMENTAL
#define GLM_ENABLE_EXPERIMENTAL_HACK
#endif
#include <gli/texture2d.hpp>
#include <gli/generate_mipmaps.hpp>
#if defined(GLM_ENABLE_EXPERIMENTAL_HACK)
#define GLM_ENABLE_EXPERIMENTAL
#undef GLM_ENABLE_EXPERIMENTAL_HACK
#endif
#include <jpeglib.h>
#include <pumex/utils/ReadFile.h>
#include <pumex/utils/Log.h>
using namespace pumex;
TextureLoaderJPEG::TextureLoaderJPEG()
: TextureLoader{ {"jpg", "jpeg"} }
{
}
std::shared_ptr<gli::texture> TextureLoaderJPEG::load(const std::string& fileName, bool buildMipMaps)
{
std::vector<unsigned char> jpegContents;
readFileToMemory( fileName, jpegContents );
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, jpegContents.data(), jpegContents.size());
int rc = jpeg_read_header(&cinfo, TRUE);
CHECK_LOG_THROW(rc != 1, "Header says, that this is not JPEG file " << fileName);
jpeg_start_decompress(&cinfo);
uint32_t width = cinfo.output_width;
uint32_t height = cinfo.output_height;
uint32_t pixel_size = cinfo.output_components;
gli::format fmt = gli::FORMAT_UNDEFINED;
bool resizeRGB2RGBA = false;
switch (pixel_size)
{
case 1: fmt = gli::FORMAT_R8_UNORM_PACK8; break;
case 2: fmt = gli::FORMAT_RG8_UNORM_PACK8; break;
case 3: resizeRGB2RGBA = true;
case 4: fmt = gli::FORMAT_RGBA8_UNORM_PACK8; break;
default: break;
}
CHECK_LOG_THROW(fmt == gli::FORMAT_UNDEFINED, "Cannot recognize pixel format " << fileName);
gli::texture2d level0(fmt, gli::texture2d::extent_type(width, height), 1);
gli::texture::size_type blockSize = gli::block_size(fmt);
gli::texture::size_type lineSize = blockSize * width;
unsigned char* imageStart = static_cast<unsigned char*>(level0.data());
std::vector<unsigned char> decodedLine;
decodedLine.resize(pixel_size * width);
for( uint32_t i=0; i<height; ++i)
{
unsigned char* readPixels = resizeRGB2RGBA ? decodedLine.data() : imageStart + (height-i-1) * lineSize;
jpeg_read_scanlines(&cinfo, &readPixels, 1);
if (!resizeRGB2RGBA)
continue;
for (uint32_t j=0; j < width; j++)
{
unsigned char* source = decodedLine.data() + 3 * j;
unsigned char* target = imageStart + (height - i - 1) * lineSize + 4 * j;
target[0] = source[0];
target[1] = source[1];
target[2] = source[2];
target[3] = 0xFF;
}
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
std::shared_ptr<gli::texture> texture;
if(buildMipMaps)
texture = std::make_shared<gli::texture2d>(gli::generate_mipmaps(level0, gli::FILTER_LINEAR));
else
texture = std::make_shared<gli::texture2d>(level0);
return texture;
}
| 37.082569
| 107
| 0.729342
|
pumexx
|
7325237252eec7504392fc9c634e9a7d58a2002c
| 968
|
cc
|
C++
|
lib/interception/interception_linux.cc
|
tylerfox/compiler-rt
|
940db39932e702fbc6ced148ff16263562862f5a
|
[
"MIT"
] | null | null | null |
lib/interception/interception_linux.cc
|
tylerfox/compiler-rt
|
940db39932e702fbc6ced148ff16263562862f5a
|
[
"MIT"
] | null | null | null |
lib/interception/interception_linux.cc
|
tylerfox/compiler-rt
|
940db39932e702fbc6ced148ff16263562862f5a
|
[
"MIT"
] | null | null | null |
//===-- interception_linux.cc -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Linux-specific interception methods.
//===----------------------------------------------------------------------===//
// so dirty!
#ifdef __FreeBSD__
#define __linux__
#endif
#ifdef __linux__
#include "interception.h"
#include <stddef.h> // for NULL
#include <dlfcn.h> // for dlsym
namespace __interception {
bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
uptr real, uptr wrapper) {
*func_addr = (uptr)dlsym(RTLD_NEXT, func_name);
return real == wrapper;
}
} // namespace __interception
#endif // __linux__
| 26.888889
| 80
| 0.551653
|
tylerfox
|
7326b4cfa424eb64d5f010cf6a3c9e8425b1b03c
| 1,613
|
cpp
|
C++
|
leetcode/cpp/p216/p216.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | 1
|
2020-08-20T23:27:13.000Z
|
2020-08-20T23:27:13.000Z
|
leetcode/cpp/p216/p216.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | null | null | null |
leetcode/cpp/p216/p216.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | null | null | null |
// Source: https://leetcode.com/problems/combination-sum-iii/
// Date: 12.09.2020
// Solution by: David Luna
// Runtime: 0ms
// Memory usage: 6.4 MB
#include <algorithm>
#include <iostream>
#include <vector>
#include "../lib/vectorUtils/vectorUtils.h"
// Leetcode solution starts
class Solution {
public:
std::vector<std::vector<int>> combinationSum3(int k, int n) {
if (k == 1 && n < 10) {
return {{n}};
}
std::vector<int> temp;
this->k = k;
this->n = n;
for (int i = 1; i < n && i < 10; ++i) {
arr.push_back(i);
completeCombination(i, i);
arr.pop_back();
}
return ans;
}
private:
std::vector<std::vector<int>> ans;
std::vector<int> arr;
int k, n;
void completeCombination(int i, int sum) {
if ((int)arr.size() > k) {
return;
}
if ((int)arr.size() == k && sum == n) {
ans.push_back(arr);
} else {
for (++i; i + sum <= n && i < 10; ++i) {
arr.push_back(i);
completeCombination(i, sum + i);
arr.pop_back();
}
}
}
};
// Leetcode solution ends
template <typename T> void sortMatrix(std::vector<std::vector<T>> &matrix) {
for (std::vector<T> &row : matrix) {
std::sort(row.begin(), row.end());
}
std::sort(matrix.begin(), matrix.end());
}
void makeTest() {
std::vector<std::vector<int>> ans, correctAns;
int k, n;
std::cin >> k >> n;
makeMatrixT(correctAns);
ans = Solution().combinationSum3(k, n);
sortMatrix(correctAns);
sortMatrix(ans);
std::cout << (ans == correctAns ? "pass\n" : "fail\n");
}
int main() {
int numTests;
std::cin >> numTests;
for (int i = 0; i < numTests; i++) {
makeTest();
}
return 0;
}
| 18.976471
| 76
| 0.593304
|
davidlunadeleon
|
7328c6a584e60b42e90d620d4b98842fcdcb9dc8
| 9,446
|
cpp
|
C++
|
emidi_alpha/CMIDIModule.cpp
|
Wohlstand/scc
|
0c22eaa8d52c1339232401ec4d42e1e228253c5f
|
[
"Zlib"
] | 2
|
2018-10-08T19:02:11.000Z
|
2018-10-09T17:18:35.000Z
|
emidi_alpha/CMIDIModule.cpp
|
Wohlstand/scc
|
0c22eaa8d52c1339232401ec4d42e1e228253c5f
|
[
"Zlib"
] | 1
|
2018-10-08T20:33:10.000Z
|
2018-10-08T20:33:10.000Z
|
emidi_alpha/CMIDIModule.cpp
|
Wohlstand/scc
|
0c22eaa8d52c1339232401ec4d42e1e228253c5f
|
[
"Zlib"
] | 1
|
2018-10-08T19:27:04.000Z
|
2018-10-08T19:27:04.000Z
|
#include "CMIDIModule.hpp"
#if defined (_MSC_VER)
#if defined (_DEBUG)
#define new new( _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif
using namespace dsa;
CMIDIModule::CMIDIModule() : m_device(NULL) {}
CMIDIModule::~CMIDIModule() {}
RESULT CMIDIModule::Reset() {
if(m_device==NULL) return FAILURE;
if(!m_device->Reset()) return FAILURE;
m_off_channels.clear();
{
for(int i=0;i<16;i++) {
m_used_channels[i].clear();
m_program[i] = 3;
m_volume[i] = 127;
m_bend[i] = 0;
m_bend_coarse[i] = 0;
m_bend_fine[i] = 0;
m_bend_range[i] = (2<<7);
m_pan[i] = 64;
m_RPN[i] = m_NRPN[i] = 0;
m_drum[i] = 0;
for(int j=0;j<128;j++)
m_keyon_table[i][j] = -1;
}
}
m_drum[9] = 1;
m_entry_mode = 0;
const SoundDeviceInfo &si = m_device->GetDeviceInfo();
{
for(UINT i=0;i<si.max_ch;i++) {
KeyInfo ki;
ki.midi_ch = i;
ki.dev_ch = i;
ki.note = 0;
m_keyon_table[i][0] = 0;
m_off_channels.push_back(ki);
m_used_channels[i].push_back(ki);
}
}
return SUCCESS;
}
void CMIDIModule::Panpot(BYTE midi_ch, bool is_fine, BYTE data) {
if(!is_fine) {
m_pan[midi_ch] = data;
std::deque<KeyInfo>::iterator it;
for(it=m_used_channels[midi_ch].begin(); it!=m_used_channels[midi_ch].end(); it++)
m_device->SetPan((*it).dev_ch, m_pan[midi_ch]);
}
}
void CMIDIModule::UpdatePitchBend(BYTE midi_ch) {
int range = (m_bend_range[midi_ch]>>7);
if(range!=0) {
m_bend_coarse[midi_ch] = (m_bend[midi_ch] * range) / 8192 ; // note offset
m_bend_fine[midi_ch] = ((m_bend[midi_ch]%(8192/range))*100*range)/8192; // cent offset
} else {
m_bend_coarse[midi_ch] = 0;
m_bend_fine[midi_ch] = 0;
}
std::deque<KeyInfo>::iterator it;
for(it=m_used_channels[midi_ch].begin(); it!=m_used_channels[midi_ch].end(); it++)
m_device->SetBend((*it).dev_ch, m_bend_coarse[midi_ch], m_bend_fine[midi_ch]);
}
void CMIDIModule::PitchBend(BYTE midi_ch, BYTE msb, BYTE lsb) {
m_bend[midi_ch] = ((msb&0x7f)|((lsb&0x7f)<<7)) - 8192;
UpdatePitchBend(midi_ch);
}
void CMIDIModule::ChannelPressure(BYTE midi_ch, BYTE velo) {
std::deque<KeyInfo>::iterator it;
for(it=m_used_channels[midi_ch].begin(); it!=m_used_channels[midi_ch].end(); it++)
m_device->SetVelocity((*it).dev_ch,velo);
}
void CMIDIModule::NoteOn(BYTE midi_ch, BYTE note, BYTE velo) {
if(m_drum[midi_ch]) {
m_device->PercSetVelocity(note,velo);
m_device->PercKeyOn(note);
return;
}
if(0<=m_keyon_table[midi_ch][note]) return; //キーオン中なら無視
KeyInfo ki;
if( m_off_channels.empty() ) { // キーオフ中のデバイスチャンネルが無いとき
ki.dev_ch=-1;
for(int i=0;i<16;i++) { // 発音数が規定値より多いMIDIチャンネルを消音
if(m_used_channels[i].size() > 1) {
ki = m_used_channels[i].front();
m_device->KeyOff(ki.dev_ch);
m_keyon_table[i][ki.note] = -1;
m_used_channels[i].pop_front();
break;
}
}
if(ki.dev_ch==-1) { // だめならどこでもいいから消音
for(int i=0;i<16;i++) {
if(!m_used_channels[i].empty()) {
ki = m_used_channels[i].front();
m_device->KeyOff(ki.dev_ch);
m_keyon_table[i][ki.note] = -1;
m_used_channels[i].pop_front();
break;
}
}
}
} else { // キーオフ中のチャンネルがあるときはそれを利用
ki = m_off_channels.front();
m_off_channels.pop_front();
std::deque<KeyInfo>::iterator it;
for(it=m_used_channels[ki.midi_ch].begin();it!=m_used_channels[ki.midi_ch].end();it++) {
if((*it).dev_ch == ki.dev_ch) {
m_used_channels[ki.midi_ch].erase(it);
break;
}
}
}
m_device->SetProgram(ki.dev_ch, 0, m_program[midi_ch]);
m_device->SetVolume(ki.dev_ch, m_volume[midi_ch]);
m_device->SetVelocity(ki.dev_ch, velo);
m_device->SetBend(ki.dev_ch, m_bend_coarse[midi_ch], m_bend_fine[midi_ch]);
m_device->SetPan(ki.dev_ch, m_pan[midi_ch]);
m_device->KeyOn(ki.dev_ch, note);
m_keyon_table[midi_ch][note] = ki.dev_ch;
ki.midi_ch = midi_ch;
ki.note = note;
m_used_channels[midi_ch].push_back(ki);
}
void CMIDIModule::NoteOff(BYTE midi_ch, BYTE note, BYTE velo) {
if(m_drum[midi_ch]) {
m_device->PercKeyOff(note);
}
int dev_ch = m_keyon_table[midi_ch][note];
if( dev_ch < 0 ) return;
m_device->KeyOff(dev_ch);
m_keyon_table[midi_ch][note] = -1;
std::deque<KeyInfo>::iterator it;
KeyInfo ki;
ki.dev_ch = dev_ch;
ki.midi_ch = midi_ch;
ki.note = 0;
m_off_channels.push_back(ki);
}
void CMIDIModule::MainVolume(BYTE midi_ch, bool is_fine, BYTE data) {
if(is_fine) return;
if(m_drum[midi_ch]) {
m_device->PercSetVolume(data);
return;
}
std::deque<KeyInfo>::iterator it;
for(it=m_used_channels[midi_ch].begin(); it!=m_used_channels[midi_ch].end(); it++)
m_device->SetVolume((*it).dev_ch,data);
}
void CMIDIModule::LoadRPN(BYTE midi_ch, WORD data) {
switch(m_RPN[midi_ch]) {
case 0x0000:
m_bend_range[midi_ch] = data;
UpdatePitchBend(midi_ch);
break;
default:
break;
}
}
WORD CMIDIModule::SaveRPN(BYTE midi_ch) {
switch(m_RPN[midi_ch]) {
case 0x0000:
return m_bend_range[midi_ch];
break;
default:
return 0;
break;
}
}
void CMIDIModule::ResetRPN(BYTE midi_ch) {
m_bend_range[midi_ch] = (2<<7);
}
void CMIDIModule::LoadNRPN(BYTE midi_ch, WORD data) {
}
WORD CMIDIModule::SaveNRPN(BYTE midi_ch) {
return 0;
}
void CMIDIModule::ResetNRPN(BYTE midi_ch) {
}
void CMIDIModule::DataEntry(BYTE midi_ch, bool is_fine, BYTE data) {
int entry = m_entry_mode ? SaveNRPN(midi_ch) : SaveRPN(midi_ch);
if (is_fine)
entry = (entry&0x3F80)|(data&0x7F);
else
entry = ((data&0x7F)<<7)|(entry&0x7F);
m_entry_mode?LoadNRPN(midi_ch,entry):LoadRPN(midi_ch,entry);
}
void CMIDIModule::DataIncrement(BYTE midi_ch, BYTE data) {
int entry = m_entry_mode ? SaveNRPN(midi_ch) : SaveRPN(midi_ch);
if (entry < 0x3FFF) entry++;
m_entry_mode?LoadNRPN(midi_ch,entry):LoadRPN(midi_ch,entry);
}
void CMIDIModule::DataDecrement(BYTE midi_ch, BYTE data) {
int entry = m_entry_mode ? SaveNRPN(midi_ch) : SaveRPN(midi_ch);
if (entry > 0) entry--;
m_entry_mode?LoadNRPN(midi_ch,entry):LoadRPN(midi_ch,entry);
}
void CMIDIModule::NRPN(BYTE midi_ch, bool is_lsb, BYTE data) {
if (is_lsb) {
m_NRPN[midi_ch] = (m_NRPN[midi_ch]&0x3F80)|(data&0x7F);
} else {
m_NRPN[midi_ch] = ((data&0x7F)<<7)|(m_NRPN[midi_ch]&0x7F);
}
if(m_NRPN[midi_ch] == 0x3FFF) { // NRPN NULL
ResetNRPN(midi_ch);
}
if(m_entry_mode == 0) {
m_entry_mode = 1; // NRPN MODE
}
}
void CMIDIModule::RPN(BYTE midi_ch, bool is_lsb, BYTE data) {
if (is_lsb) {
m_RPN[midi_ch] = (m_RPN[midi_ch]&0x3F80)|(data&0x7F);
//if(m_RPN[midi_ch] == 0x3FFF) RPN_Reset();
} else {
m_RPN[midi_ch] = ((data&0x7F)<<7)|(m_RPN[midi_ch]&0x7F);
}
if(m_RPN[midi_ch] == 0x3FFF) { // RPN NULL
ResetRPN(midi_ch);
}
if(m_entry_mode == 1) {
m_entry_mode = 0; // RPN MODE
}
}
void CMIDIModule::ControlChange(BYTE midi_ch, BYTE msb, BYTE lsb) {
if(msb<0x40) { // 14-bit
bool is_low = (msb&0x20)?true:false;
switch(msb&0x1F) {
//case 0x00: BankSelect(midi_ch, is_low, lsb); break;
//case 0x01: ModulationDepth(midi_ch, is_low, lsb); break;
//case 0x02: BreathControl(midi_ch, is_low, lsb); break;
//case 0x04: FootControl(midi_ch, is_low, lsb); break;
//case 0x05: PortamentTime(midi_ch, is_low, lsb); break;
case 0x06: DataEntry(midi_ch, is_low, lsb); break;
case 0x07: MainVolume(midi_ch, is_low, lsb); break;
//case 0x08: BalanceControl(midi_ch, is_low, lsb); break;
case 0x0A: Panpot(midi_ch, is_low, lsb); break;
//case 0x11: Expression(midi_ch, is_low, lsb); break;
default: break;
}
} else { // 7-bit
switch(msb) {
case 0x40: break;
case 0x60: DataIncrement(midi_ch, lsb); break;
case 0x61: DataDecrement(midi_ch, lsb); break;
case 0x62: NRPN(midi_ch, 0, lsb); break;
case 0x63: NRPN(midi_ch, 1, lsb); break;
case 0x64: RPN(midi_ch, 0, lsb); break;
case 0x65: RPN(midi_ch, 1, lsb); break;
default: break;
}
}
}
RESULT CMIDIModule::Render(INT32 buf[2]) {
if(m_device == NULL)
return FAILURE;
else
return m_device->Render(buf);
}
RESULT CMIDIModule::SendMIDIMsg(const CMIDIMsg &msg) {
if(m_device == NULL) return FAILURE;
if(msg.m_type == CMIDIMsg::NOTE_OFF) {
NoteOff(msg.m_ch, msg.m_data[0], msg.m_data[1]);
} else if(msg.m_type == CMIDIMsg::NOTE_ON) {
if(msg.m_data[1] == 0)
NoteOff(msg.m_ch, msg.m_data[0], msg.m_data[1]);
else
NoteOn(msg.m_ch, msg.m_data[0], msg.m_data[1]);
} else if(msg.m_type == CMIDIMsg::PROGRAM_CHANGE) {
m_program[msg.m_ch] = msg.m_data[0];
} else if(msg.m_type == CMIDIMsg::CONTROL_CHANGE) {
ControlChange(msg.m_ch, msg.m_data[0], msg.m_data[1]);
} else if(msg.m_type == CMIDIMsg::PITCH_BEND_CHANGE ) {
PitchBend(msg.m_ch, msg.m_data[0], msg.m_data[1]);
} else if(msg.m_type == CMIDIMsg::CHANNEL_PRESSURE ) {
ChannelPressure(msg.m_ch, msg.m_data[0]);
}
return SUCCESS;
}
RESULT CMIDIModule::SetDrumChannel(int midi_ch, int enable) {
m_drum[midi_ch] = enable;
return SUCCESS;
}
| 28.197015
| 93
| 0.627991
|
Wohlstand
|
732b38f10e924e355ecc0e0b37c3ed5c0c819f70
| 40,498
|
cpp
|
C++
|
Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToDWIImageFilter.cpp
|
rfloca/MITK
|
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
|
[
"BSD-3-Clause"
] | null | null | null |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "itkTractsToDWIImageFilter.h"
#include <boost/progress.hpp>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkPolyLine.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkResampleImageFilter.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkCastImageFilter.h>
#include <itkImageFileWriter.h>
#include <itkRescaleIntensityImageFilter.h>
#include <itkWindowedSincInterpolateImageFunction.h>
#include <itkResampleDwiImageFilter.h>
#include <itkKspaceImageFilter.h>
#include <itkDftImageFilter.h>
#include <itkAddImageFilter.h>
#include <itkConstantPadImageFilter.h>
#include <itkCropImageFilter.h>
#include <mitkAstroStickModel.h>
#include <vtkTransform.h>
#include <iostream>
#include <fstream>
#include <itkImageDuplicator.h>
#include <boost/lexical_cast.hpp>
namespace itk
{
template< class PixelType >
TractsToDWIImageFilter< PixelType >::TractsToDWIImageFilter()
: m_CircleDummy(false)
, m_VolumeAccuracy(10)
, m_AddGibbsRinging(false)
, m_NumberOfRepetitions(1)
, m_EnforcePureFiberVoxels(false)
, m_InterpolationShrink(1000)
, m_FiberRadius(0)
, m_SignalScale(25)
, m_kOffset(0)
, m_tLine(1)
, m_UseInterpolation(false)
, m_SimulateRelaxation(true)
, m_tInhom(50)
, m_TE(100)
, m_FrequencyMap(NULL)
, m_EddyGradientStrength(0.001)
, m_SimulateEddyCurrents(false)
, m_Spikes(0)
, m_Wrap(1.0)
, m_NoiseModel(NULL)
, m_SpikeAmplitude(1)
, m_AddMotionArtifact(false)
{
m_Spacing.Fill(2.5); m_Origin.Fill(0.0);
m_DirectionMatrix.SetIdentity();
m_ImageRegion.SetSize(0, 10);
m_ImageRegion.SetSize(1, 10);
m_ImageRegion.SetSize(2, 10);
m_MaxTranslation.Fill(0.0);
m_MaxRotation.Fill(0.0);
m_RandGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
m_RandGen->SetSeed();
}
template< class PixelType >
TractsToDWIImageFilter< PixelType >::~TractsToDWIImageFilter()
{
}
template< class PixelType >
TractsToDWIImageFilter< PixelType >::DoubleDwiType::Pointer TractsToDWIImageFilter< PixelType >::DoKspaceStuff( std::vector< DoubleDwiType::Pointer >& images )
{
// create slice object
ImageRegion<2> sliceRegion;
sliceRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]);
sliceRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]);
Vector< double, 2 > sliceSpacing;
sliceSpacing[0] = m_UpsampledSpacing[0];
sliceSpacing[1] = m_UpsampledSpacing[1];
// frequency map slice
SliceType::Pointer fMapSlice = NULL;
if (m_FrequencyMap.IsNotNull())
{
fMapSlice = SliceType::New();
ImageRegion<2> region;
region.SetSize(0, m_UpsampledImageRegion.GetSize()[0]);
region.SetSize(1, m_UpsampledImageRegion.GetSize()[1]);
fMapSlice->SetLargestPossibleRegion( region );
fMapSlice->SetBufferedRegion( region );
fMapSlice->SetRequestedRegion( region );
fMapSlice->Allocate();
}
DoubleDwiType::Pointer newImage = DoubleDwiType::New();
newImage->SetSpacing( m_Spacing );
newImage->SetOrigin( m_Origin );
newImage->SetDirection( m_DirectionMatrix );
newImage->SetLargestPossibleRegion( m_ImageRegion );
newImage->SetBufferedRegion( m_ImageRegion );
newImage->SetRequestedRegion( m_ImageRegion );
newImage->SetVectorLength( images.at(0)->GetVectorLength() );
newImage->Allocate();
MatrixType transform = m_DirectionMatrix;
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
{
if (j<2)
transform[i][j] *= m_UpsampledSpacing[j];
else
transform[i][j] *= m_Spacing[j];
}
std::vector< unsigned int > spikeVolume;
for (int i=0; i<m_Spikes; i++)
spikeVolume.push_back(rand()%images.at(0)->GetVectorLength());
std::sort (spikeVolume.begin(), spikeVolume.end());
std::reverse (spikeVolume.begin(), spikeVolume.end());
m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n";
m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*";
unsigned long lastTick = 0;
boost::progress_display disp(2*images.at(0)->GetVectorLength()*images.at(0)->GetLargestPossibleRegion().GetSize(2));
for (unsigned int g=0; g<images.at(0)->GetVectorLength(); g++)
{
std::vector< int > spikeSlice;
while (!spikeVolume.empty() && spikeVolume.back()==g)
{
spikeSlice.push_back(rand()%images.at(0)->GetLargestPossibleRegion().GetSize(2));
spikeVolume.pop_back();
}
std::sort (spikeSlice.begin(), spikeSlice.end());
std::reverse (spikeSlice.begin(), spikeSlice.end());
for (unsigned int z=0; z<images.at(0)->GetLargestPossibleRegion().GetSize(2); z++)
{
std::vector< SliceType::Pointer > compartmentSlices;
std::vector< double > t2Vector;
for (unsigned int i=0; i<images.size(); i++)
{
DiffusionSignalModel<double>* signalModel;
if (i<m_FiberModels.size())
signalModel = m_FiberModels.at(i);
else
signalModel = m_NonFiberModels.at(i-m_FiberModels.size());
SliceType::Pointer slice = SliceType::New();
slice->SetLargestPossibleRegion( sliceRegion );
slice->SetBufferedRegion( sliceRegion );
slice->SetRequestedRegion( sliceRegion );
slice->SetSpacing(sliceSpacing);
slice->Allocate();
slice->FillBuffer(0.0);
// extract slice from channel g
for (unsigned int y=0; y<images.at(0)->GetLargestPossibleRegion().GetSize(1); y++)
for (unsigned int x=0; x<images.at(0)->GetLargestPossibleRegion().GetSize(0); x++)
{
SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y;
DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z;
slice->SetPixel(index2D, images.at(i)->GetPixel(index3D)[g]);
if (fMapSlice.IsNotNull() && i==0)
fMapSlice->SetPixel(index2D, m_FrequencyMap->GetPixel(index3D));
}
compartmentSlices.push_back(slice);
t2Vector.push_back(signalModel->GetT2());
}
if (this->GetAbortGenerateData())
return NULL;
// create k-sapce (inverse fourier transform slices)
itk::Size<2> outSize; outSize.SetElement(0, m_ImageRegion.GetSize(0)); outSize.SetElement(1, m_ImageRegion.GetSize(1));
itk::KspaceImageFilter< SliceType::PixelType >::Pointer idft = itk::KspaceImageFilter< SliceType::PixelType >::New();
idft->SetCompartmentImages(compartmentSlices);
idft->SetT2(t2Vector);
idft->SetkOffset(m_kOffset);
idft->SettLine(m_tLine);
idft->SetTE(m_TE);
idft->SetTinhom(m_tInhom);
idft->SetSimulateRelaxation(m_SimulateRelaxation);
idft->SetSimulateEddyCurrents(m_SimulateEddyCurrents);
idft->SetEddyGradientMagnitude(m_EddyGradientStrength);
idft->SetZ((double)z-(double)images.at(0)->GetLargestPossibleRegion().GetSize(2)/2.0);
idft->SetDirectionMatrix(transform);
idft->SetDiffusionGradientDirection(m_FiberModels.at(0)->GetGradientDirection(g));
idft->SetFrequencyMap(fMapSlice);
idft->SetSignalScale(m_SignalScale);
idft->SetOutSize(outSize);
int numSpikes = 0;
while (!spikeSlice.empty() && spikeSlice.back()==z)
{
numSpikes++;
spikeSlice.pop_back();
}
idft->SetSpikes(numSpikes);
idft->SetSpikeAmplitude(m_SpikeAmplitude);
idft->Update();
ComplexSliceType::Pointer fSlice;
fSlice = idft->GetOutput();
++disp;
unsigned long newTick = 50*disp.count()/disp.expected_count();
for (int tick = 0; tick<(newTick-lastTick); tick++)
m_StatusText += "*";
lastTick = newTick;
// fourier transform slice
SliceType::Pointer newSlice;
itk::DftImageFilter< SliceType::PixelType >::Pointer dft = itk::DftImageFilter< SliceType::PixelType >::New();
dft->SetInput(fSlice);
dft->Update();
newSlice = dft->GetOutput();
// put slice back into channel g
for (unsigned int y=0; y<fSlice->GetLargestPossibleRegion().GetSize(1); y++)
for (unsigned int x=0; x<fSlice->GetLargestPossibleRegion().GetSize(0); x++)
{
DoubleDwiType::IndexType index3D; index3D[0]=x; index3D[1]=y; index3D[2]=z;
SliceType::IndexType index2D; index2D[0]=x; index2D[1]=y;
DoubleDwiType::PixelType pix3D = newImage->GetPixel(index3D);
pix3D[g] = newSlice->GetPixel(index2D);
newImage->SetPixel(index3D, pix3D);
}
++disp;
newTick = 50*disp.count()/disp.expected_count();
for (int tick = 0; tick<(newTick-lastTick); tick++)
m_StatusText += "*";
lastTick = newTick;
}
}
m_StatusText += "\n\n";
return newImage;
}
template< class PixelType >
void TractsToDWIImageFilter< PixelType >::GenerateData()
{
m_StartTime = clock();
m_StatusText = "Starting simulation\n";
// check input data
if (m_FiberBundle.IsNull())
itkExceptionMacro("Input fiber bundle is NULL!");
int numFibers = m_FiberBundle->GetNumFibers();
if (numFibers<=0)
itkExceptionMacro("Input fiber bundle contains no fibers!");
if (m_FiberModels.empty())
itkExceptionMacro("No diffusion model for fiber compartments defined!");
if (m_EnforcePureFiberVoxels)
while (m_FiberModels.size()>1)
m_FiberModels.pop_back();
if (m_NonFiberModels.empty())
itkExceptionMacro("No diffusion model for non-fiber compartments defined!");
int baselineIndex = m_FiberModels[0]->GetFirstBaselineIndex();
if (baselineIndex<0)
itkExceptionMacro("No baseline index found!");
// initialize output dwi image
ImageRegion<3> croppedRegion = m_ImageRegion; croppedRegion.SetSize(1, croppedRegion.GetSize(1)*m_Wrap);
itk::Point<double,3> shiftedOrigin = m_Origin; shiftedOrigin[1] += (m_ImageRegion.GetSize(1)-croppedRegion.GetSize(1))*m_Spacing[1]/2;
typename OutputImageType::Pointer outImage = OutputImageType::New();
outImage->SetSpacing( m_Spacing );
outImage->SetOrigin( shiftedOrigin );
outImage->SetDirection( m_DirectionMatrix );
outImage->SetLargestPossibleRegion( croppedRegion );
outImage->SetBufferedRegion( croppedRegion );
outImage->SetRequestedRegion( croppedRegion );
outImage->SetVectorLength( m_FiberModels[0]->GetNumGradients() );
outImage->Allocate();
typename OutputImageType::PixelType temp;
temp.SetSize(m_FiberModels[0]->GetNumGradients());
temp.Fill(0.0);
outImage->FillBuffer(temp);
// ADJUST GEOMETRY FOR FURTHER PROCESSING
// is input slize size a power of two?
unsigned int x=m_ImageRegion.GetSize(0); unsigned int y=m_ImageRegion.GetSize(1);
if ( x%2 == 1 )
m_ImageRegion.SetSize(0, x+1);
if ( y%2 == 1 )
m_ImageRegion.SetSize(1, y+1);
// apply in-plane upsampling
double upsampling = 1;
if (m_AddGibbsRinging)
{
m_StatusText += "Gibbs ringing enabled\n";
MITK_INFO << "Adding ringing artifacts.";
upsampling = 2;
}
m_UpsampledSpacing = m_Spacing;
m_UpsampledSpacing[0] /= upsampling;
m_UpsampledSpacing[1] /= upsampling;
m_UpsampledImageRegion = m_ImageRegion;
m_UpsampledImageRegion.SetSize(0, m_ImageRegion.GetSize()[0]*upsampling);
m_UpsampledImageRegion.SetSize(1, m_ImageRegion.GetSize()[1]*upsampling);
m_UpsampledOrigin = m_Origin;
m_UpsampledOrigin[0] -= m_Spacing[0]/2; m_UpsampledOrigin[0] += m_UpsampledSpacing[0]/2;
m_UpsampledOrigin[1] -= m_Spacing[1]/2; m_UpsampledOrigin[1] += m_UpsampledSpacing[1]/2;
m_UpsampledOrigin[2] -= m_Spacing[2]/2; m_UpsampledOrigin[2] += m_UpsampledSpacing[2]/2;
// generate double images to store the individual compartment signals
std::vector< DoubleDwiType::Pointer > compartments;
for (unsigned int i=0; i<m_FiberModels.size()+m_NonFiberModels.size(); i++)
{
DoubleDwiType::Pointer doubleDwi = DoubleDwiType::New();
doubleDwi->SetSpacing( m_UpsampledSpacing );
doubleDwi->SetOrigin( m_UpsampledOrigin );
doubleDwi->SetDirection( m_DirectionMatrix );
doubleDwi->SetLargestPossibleRegion( m_UpsampledImageRegion );
doubleDwi->SetBufferedRegion( m_UpsampledImageRegion );
doubleDwi->SetRequestedRegion( m_UpsampledImageRegion );
doubleDwi->SetVectorLength( m_FiberModels[0]->GetNumGradients() );
doubleDwi->Allocate();
DoubleDwiType::PixelType pix;
pix.SetSize(m_FiberModels[0]->GetNumGradients());
pix.Fill(0.0);
doubleDwi->FillBuffer(pix);
compartments.push_back(doubleDwi);
}
// initialize volume fraction images
m_VolumeFractions.clear();
for (unsigned int i=0; i<m_FiberModels.size()+m_NonFiberModels.size(); i++)
{
ItkDoubleImgType::Pointer doubleImg = ItkDoubleImgType::New();
doubleImg->SetSpacing( m_UpsampledSpacing );
doubleImg->SetOrigin( m_UpsampledOrigin );
doubleImg->SetDirection( m_DirectionMatrix );
doubleImg->SetLargestPossibleRegion( m_UpsampledImageRegion );
doubleImg->SetBufferedRegion( m_UpsampledImageRegion );
doubleImg->SetRequestedRegion( m_UpsampledImageRegion );
doubleImg->Allocate();
doubleImg->FillBuffer(0);
m_VolumeFractions.push_back(doubleImg);
}
// resample mask image and frequency map to fit upsampled geometry
if (m_AddGibbsRinging)
{
if (m_TissueMask.IsNotNull())
{
// rescale mask image (otherwise there are problems with the resampling)
itk::RescaleIntensityImageFilter<ItkUcharImgType,ItkUcharImgType>::Pointer rescaler = itk::RescaleIntensityImageFilter<ItkUcharImgType,ItkUcharImgType>::New();
rescaler->SetInput(0,m_TissueMask);
rescaler->SetOutputMaximum(100);
rescaler->SetOutputMinimum(0);
rescaler->Update();
// resample mask image
itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::Pointer resampler = itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::New();
resampler->SetInput(rescaler->GetOutput());
resampler->SetOutputParametersFromImage(m_TissueMask);
resampler->SetSize(m_UpsampledImageRegion.GetSize());
resampler->SetOutputSpacing(m_UpsampledSpacing);
resampler->SetOutputOrigin(m_UpsampledOrigin);
resampler->Update();
m_TissueMask = resampler->GetOutput();
}
// resample frequency map
if (m_FrequencyMap.IsNotNull())
{
itk::ResampleImageFilter<ItkDoubleImgType, ItkDoubleImgType>::Pointer resampler = itk::ResampleImageFilter<ItkDoubleImgType, ItkDoubleImgType>::New();
resampler->SetInput(m_FrequencyMap);
resampler->SetOutputParametersFromImage(m_FrequencyMap);
resampler->SetSize(m_UpsampledImageRegion.GetSize());
resampler->SetOutputSpacing(m_UpsampledSpacing);
resampler->SetOutputOrigin(m_UpsampledOrigin);
resampler->Update();
m_FrequencyMap = resampler->GetOutput();
}
}
// no input tissue mask is set -> create default
bool maskImageSet = true;
if (m_TissueMask.IsNull())
{
m_StatusText += "No tissue mask set\n";
MITK_INFO << "No tissue mask set";
m_TissueMask = ItkUcharImgType::New();
m_TissueMask->SetSpacing( m_UpsampledSpacing );
m_TissueMask->SetOrigin( m_UpsampledOrigin );
m_TissueMask->SetDirection( m_DirectionMatrix );
m_TissueMask->SetLargestPossibleRegion( m_UpsampledImageRegion );
m_TissueMask->SetBufferedRegion( m_UpsampledImageRegion );
m_TissueMask->SetRequestedRegion( m_UpsampledImageRegion );
m_TissueMask->Allocate();
m_TissueMask->FillBuffer(1);
maskImageSet = false;
}
else
{
m_StatusText += "Using tissue mask\n";
MITK_INFO << "Using tissue mask";
}
m_ImageRegion = croppedRegion;
x=m_ImageRegion.GetSize(0); y=m_ImageRegion.GetSize(1);
if ( x%2 == 1 )
m_ImageRegion.SetSize(0, x+1);
if ( y%2 == 1 )
m_ImageRegion.SetSize(1, y+1);
// resample fiber bundle for sufficient voxel coverage
m_StatusText += "\n"+this->GetTime()+" > Resampling fibers ...\n";
double segmentVolume = 0.0001;
float minSpacing = 1;
if(m_UpsampledSpacing[0]<m_UpsampledSpacing[1] && m_UpsampledSpacing[0]<m_UpsampledSpacing[2])
minSpacing = m_UpsampledSpacing[0];
else if (m_UpsampledSpacing[1] < m_UpsampledSpacing[2])
minSpacing = m_UpsampledSpacing[1];
else
minSpacing = m_UpsampledSpacing[2];
FiberBundleType fiberBundle = m_FiberBundle->GetDeepCopy();
fiberBundle->ResampleFibers(minSpacing/m_VolumeAccuracy);
double mmRadius = m_FiberRadius/1000;
if (mmRadius>0)
segmentVolume = M_PI*mmRadius*mmRadius*minSpacing/m_VolumeAccuracy;
double interpFact = 2*atan(-0.5*m_InterpolationShrink);
double maxVolume = 0;
double voxelVolume = m_UpsampledSpacing[0]*m_UpsampledSpacing[1]*m_UpsampledSpacing[2];
if (m_AddMotionArtifact)
{
if (m_RandomMotion)
{
m_StatusText += "Adding random motion artifacts:\n";
m_StatusText += "Maximum rotation: +/-" + boost::lexical_cast<std::string>(m_MaxRotation) + "°\n";
m_StatusText += "Maximum translation: +/-" + boost::lexical_cast<std::string>(m_MaxTranslation) + "mm\n";
}
else
{
m_StatusText += "Adding linear motion artifacts:\n";
m_StatusText += "Maximum rotation: " + boost::lexical_cast<std::string>(m_MaxRotation) + "°\n";
m_StatusText += "Maximum translation: " + boost::lexical_cast<std::string>(m_MaxTranslation) + "mm\n";
}
MITK_INFO << "Adding motion artifacts";
MITK_INFO << "Maximum rotation: " << m_MaxRotation;
MITK_INFO << "Maxmimum translation: " << m_MaxTranslation;
}
maxVolume = 0;
m_StatusText += "\n"+this->GetTime()+" > Generating signal of " + boost::lexical_cast<std::string>(m_FiberModels.size()) + " fiber compartments\n";
MITK_INFO << "Generating signal of " << m_FiberModels.size() << " fiber compartments";
boost::progress_display disp(numFibers*m_FiberModels.at(0)->GetNumGradients());
ofstream logFile;
logFile.open("fiberfox_motion.log");
logFile << "0 rotation: 0,0,0; translation: 0,0,0\n";
// get transform for motion artifacts
FiberBundleType fiberBundleTransformed = fiberBundle;
VectorType rotation = m_MaxRotation/m_FiberModels.at(0)->GetNumGradients();
VectorType translation = m_MaxTranslation/m_FiberModels.at(0)->GetNumGradients();
// creat image to hold transformed mask (motion artifact)
ItkUcharImgType::Pointer tempTissueMask = ItkUcharImgType::New();
itk::ImageDuplicator<ItkUcharImgType>::Pointer duplicator = itk::ImageDuplicator<ItkUcharImgType>::New();
duplicator->SetInputImage(m_TissueMask);
duplicator->Update();
tempTissueMask = duplicator->GetOutput();
// second upsampling needed for motion artifacts
ImageRegion<3> upsampledImageRegion = m_UpsampledImageRegion;
itk::Vector<double,3> upsampledSpacing = m_UpsampledSpacing;
upsampledSpacing[0] /= 4;
upsampledSpacing[1] /= 4;
upsampledSpacing[2] /= 4;
upsampledImageRegion.SetSize(0, m_UpsampledImageRegion.GetSize()[0]*4);
upsampledImageRegion.SetSize(1, m_UpsampledImageRegion.GetSize()[1]*4);
upsampledImageRegion.SetSize(2, m_UpsampledImageRegion.GetSize()[2]*4);
itk::Point<double,3> upsampledOrigin = m_UpsampledOrigin;
upsampledOrigin[0] -= m_UpsampledSpacing[0]/2; upsampledOrigin[0] += upsampledSpacing[0]/2;
upsampledOrigin[1] -= m_UpsampledSpacing[1]/2; upsampledOrigin[1] += upsampledSpacing[1]/2;
upsampledOrigin[2] -= m_UpsampledSpacing[2]/2; upsampledOrigin[2] += upsampledSpacing[2]/2;
ItkUcharImgType::Pointer upsampledTissueMask = ItkUcharImgType::New();
itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::Pointer upsampler = itk::ResampleImageFilter<ItkUcharImgType, ItkUcharImgType>::New();
upsampler->SetInput(m_TissueMask);
upsampler->SetOutputParametersFromImage(m_TissueMask);
upsampler->SetSize(upsampledImageRegion.GetSize());
upsampler->SetOutputSpacing(upsampledSpacing);
upsampler->SetOutputOrigin(upsampledOrigin);
itk::NearestNeighborInterpolateImageFunction<ItkUcharImgType>::Pointer nn_interpolator
= itk::NearestNeighborInterpolateImageFunction<ItkUcharImgType>::New();
upsampler->SetInterpolator(nn_interpolator);
upsampler->Update();
upsampledTissueMask = upsampler->GetOutput();
m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n";
m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*";
unsigned int lastTick = 0;
for (int g=0; g<m_FiberModels.at(0)->GetNumGradients(); g++)
{
vtkPolyData* fiberPolyData = fiberBundleTransformed->GetFiberPolyData();
ItkDoubleImgType::Pointer intraAxonalVolume = ItkDoubleImgType::New();
intraAxonalVolume->SetSpacing( m_UpsampledSpacing );
intraAxonalVolume->SetOrigin( m_UpsampledOrigin );
intraAxonalVolume->SetDirection( m_DirectionMatrix );
intraAxonalVolume->SetLargestPossibleRegion( m_UpsampledImageRegion );
intraAxonalVolume->SetBufferedRegion( m_UpsampledImageRegion );
intraAxonalVolume->SetRequestedRegion( m_UpsampledImageRegion );
intraAxonalVolume->Allocate();
intraAxonalVolume->FillBuffer(0);
// generate fiber signal
for( int i=0; i<numFibers; i++ )
{
vtkCell* cell = fiberPolyData->GetCell(i);
int numPoints = cell->GetNumberOfPoints();
vtkPoints* points = cell->GetPoints();
if (numPoints<2)
continue;
for( int j=0; j<numPoints; j++)
{
if (this->GetAbortGenerateData())
{
m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n";
return;
}
double* temp = points->GetPoint(j);
itk::Point<float, 3> vertex = GetItkPoint(temp);
itk::Vector<double> v = GetItkVector(temp);
itk::Vector<double, 3> dir(3);
if (j<numPoints-1)
dir = GetItkVector(points->GetPoint(j+1))-v;
else
dir = v-GetItkVector(points->GetPoint(j-1));
if (dir.GetSquaredNorm()<0.0001 || dir[0]!=dir[0] || dir[1]!=dir[1] || dir[2]!=dir[2])
continue;
itk::Index<3> idx;
itk::ContinuousIndex<float, 3> contIndex;
tempTissueMask->TransformPhysicalPointToIndex(vertex, idx);
tempTissueMask->TransformPhysicalPointToContinuousIndex(vertex, contIndex);
if (!m_UseInterpolation) // use nearest neighbour interpolation
{
if (!tempTissueMask->GetLargestPossibleRegion().IsInside(idx) || tempTissueMask->GetPixel(idx)<=0)
continue;
// generate signal for each fiber compartment
for (unsigned int k=0; k<m_FiberModels.size(); k++)
{
DoubleDwiType::Pointer doubleDwi = compartments.at(k);
m_FiberModels[k]->SetFiberDirection(dir);
DoubleDwiType::PixelType pix = doubleDwi->GetPixel(idx);
pix[g] += segmentVolume*m_FiberModels[k]->SimulateMeasurement(g);
if (pix[g]!=pix[g])
{
std::cout << "pix[g] " << pix[g] << std::endl;
std::cout << "dir " << dir << std::endl;
std::cout << "segmentVolume " << segmentVolume << std::endl;
std::cout << "m_FiberModels[k]->SimulateMeasurement(g) " << m_FiberModels[k]->SimulateMeasurement(g) << std::endl;
}
doubleDwi->SetPixel(idx, pix );
double vol = intraAxonalVolume->GetPixel(idx) + segmentVolume;
intraAxonalVolume->SetPixel(idx, vol );
if (g==0 && vol>maxVolume)
maxVolume = vol;
}
continue;
}
double frac_x = contIndex[0] - idx[0]; double frac_y = contIndex[1] - idx[1]; double frac_z = contIndex[2] - idx[2];
if (frac_x<0)
{
idx[0] -= 1;
frac_x += 1;
}
if (frac_y<0)
{
idx[1] -= 1;
frac_y += 1;
}
if (frac_z<0)
{
idx[2] -= 1;
frac_z += 1;
}
frac_x = atan((0.5-frac_x)*m_InterpolationShrink)/interpFact + 0.5;
frac_y = atan((0.5-frac_y)*m_InterpolationShrink)/interpFact + 0.5;
frac_z = atan((0.5-frac_z)*m_InterpolationShrink)/interpFact + 0.5;
// use trilinear interpolation
itk::Index<3> newIdx;
for (int x=0; x<2; x++)
{
frac_x = 1-frac_x;
for (int y=0; y<2; y++)
{
frac_y = 1-frac_y;
for (int z=0; z<2; z++)
{
frac_z = 1-frac_z;
newIdx[0] = idx[0]+x;
newIdx[1] = idx[1]+y;
newIdx[2] = idx[2]+z;
double frac = frac_x*frac_y*frac_z;
// is position valid?
if (!tempTissueMask->GetLargestPossibleRegion().IsInside(newIdx) || tempTissueMask->GetPixel(newIdx)<=0)
continue;
// generate signal for each fiber compartment
for (unsigned int k=0; k<m_FiberModels.size(); k++)
{
DoubleDwiType::Pointer doubleDwi = compartments.at(k);
m_FiberModels[k]->SetFiberDirection(dir);
DoubleDwiType::PixelType pix = doubleDwi->GetPixel(newIdx);
pix[g] += segmentVolume*frac*m_FiberModels[k]->SimulateMeasurement(g);
doubleDwi->SetPixel(newIdx, pix );
double vol = intraAxonalVolume->GetPixel(idx) + segmentVolume;
intraAxonalVolume->SetPixel(idx, vol );
if (g==0 && vol>maxVolume)
maxVolume = vol;
}
}
}
}
}
++disp;
unsigned long newTick = 50*disp.count()/disp.expected_count();
for (int tick = 0; tick<(newTick-lastTick); tick++)
m_StatusText += "*";
lastTick = newTick;
}
// generate non-fiber signal
ImageRegionIterator<ItkUcharImgType> it3(tempTissueMask, tempTissueMask->GetLargestPossibleRegion());
double fact = 1;
if (m_FiberRadius<0.0001)
fact = voxelVolume/maxVolume;
while(!it3.IsAtEnd())
{
if (it3.Get()>0)
{
DoubleDwiType::IndexType index = it3.GetIndex();
// get fiber volume fraction
DoubleDwiType::Pointer fiberDwi = compartments.at(0);
DoubleDwiType::PixelType fiberPix = fiberDwi->GetPixel(index); // intra axonal compartment
if (fact>1) // auto scale intra-axonal if no fiber radius is specified
{
fiberPix[g] *= fact;
fiberDwi->SetPixel(index, fiberPix);
}
double f = intraAxonalVolume->GetPixel(index)*fact;
if (f>voxelVolume || (f>0.0 && m_EnforcePureFiberVoxels) ) // more fiber than space in voxel?
{
fiberPix[g] *= voxelVolume/f;
fiberDwi->SetPixel(index, fiberPix);
m_VolumeFractions.at(0)->SetPixel(index, 1);
}
else
{
m_VolumeFractions.at(0)->SetPixel(index, f/voxelVolume);
double nonf = voxelVolume-f; // non-fiber volume
double inter = 0;
if (m_FiberModels.size()>1)
inter = nonf * f/voxelVolume; // inter-axonal fraction of non fiber compartment scales linearly with f
double other = nonf - inter; // rest of compartment
double singleinter = inter/(m_FiberModels.size()-1);
// adjust non-fiber and intra-axonal signal
for (unsigned int i=1; i<m_FiberModels.size(); i++)
{
DoubleDwiType::Pointer doubleDwi = compartments.at(i);
DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index);
if (f>0)
pix[g] /= f;
pix[g] *= singleinter;
doubleDwi->SetPixel(index, pix);
m_VolumeFractions.at(i)->SetPixel(index, singleinter/voxelVolume);
}
for (unsigned int i=0; i<m_NonFiberModels.size(); i++)
{
DoubleDwiType::Pointer doubleDwi = compartments.at(i+m_FiberModels.size());
DoubleDwiType::PixelType pix = doubleDwi->GetPixel(index);
// if (dynamic_cast< mitk::AstroStickModel<double>* >(m_NonFiberModels.at(i)))
// {
// mitk::AstroStickModel<double>* model = dynamic_cast< mitk::AstroStickModel<double>* >(m_NonFiberModels.at(i));
// model->SetSeed(8111984);
// }
pix[g] += m_NonFiberModels[i]->SimulateMeasurement(g)*other*m_NonFiberModels[i]->GetWeight();
doubleDwi->SetPixel(index, pix);
m_VolumeFractions.at(i+m_FiberModels.size())->SetPixel(index, other/voxelVolume*m_NonFiberModels[i]->GetWeight());
}
}
}
++it3;
}
// move fibers
if (m_AddMotionArtifact)
{
if (m_RandomMotion)
{
fiberBundleTransformed = fiberBundle->GetDeepCopy();
rotation[0] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[0]*2)-m_MaxRotation[0];
rotation[1] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[1]*2)-m_MaxRotation[1];
rotation[2] = m_RandGen->GetVariateWithClosedRange(m_MaxRotation[2]*2)-m_MaxRotation[2];
translation[0] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[0]*2)-m_MaxTranslation[0];
translation[1] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[1]*2)-m_MaxTranslation[1];
translation[2] = m_RandGen->GetVariateWithClosedRange(m_MaxTranslation[2]*2)-m_MaxTranslation[2];
}
// rotate mask image
if (maskImageSet)
{
ImageRegionIterator<ItkUcharImgType> maskIt(upsampledTissueMask, upsampledTissueMask->GetLargestPossibleRegion());
tempTissueMask->FillBuffer(0);
while(!maskIt.IsAtEnd())
{
if (maskIt.Get()<=0)
{
++maskIt;
continue;
}
DoubleDwiType::IndexType index = maskIt.GetIndex();
itk::Point<double, 3> point;
upsampledTissueMask->TransformIndexToPhysicalPoint(index, point);
if (m_RandomMotion)
point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]);
else
point = fiberBundle->TransformPoint(point.GetVnlVector(), rotation[0]*(g+1),rotation[1]*(g+1),rotation[2]*(g+1),translation[0]*(g+1),translation[1]*(g+1),translation[2]*(g+1));
tempTissueMask->TransformPhysicalPointToIndex(point, index);
if (tempTissueMask->GetLargestPossibleRegion().IsInside(index))
tempTissueMask->SetPixel(index,100);
++maskIt;
}
}
// rotate fibers
logFile << g+1 << " rotation:" << rotation[0] << "," << rotation[1] << "," << rotation[2] << ";";
logFile << " translation:" << translation[0] << "," << translation[1] << "," << translation[2] << "\n";
fiberBundleTransformed->TransformFibers(rotation[0],rotation[1],rotation[2],translation[0],translation[1],translation[2]);
}
}
logFile.close();
m_StatusText += "\n\n";
if (this->GetAbortGenerateData())
{
m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n";
return;
}
// do k-space stuff
DoubleDwiType::Pointer doubleOutImage;
if (m_Spikes>0 || m_FrequencyMap.IsNotNull() || m_kOffset>0 || m_SimulateRelaxation || m_SimulateEddyCurrents || m_AddGibbsRinging || m_Wrap<1.0)
{
m_StatusText += this->GetTime()+" > Adjusting complex signal\n";
MITK_INFO << "Adjusting complex signal";
doubleOutImage = DoKspaceStuff(compartments);
m_SignalScale = 1;
}
else
{
m_StatusText += this->GetTime()+" > Summing compartments\n";
MITK_INFO << "Summing compartments";
doubleOutImage = compartments.at(0);
for (unsigned int i=1; i<compartments.size(); i++)
{
itk::AddImageFilter< DoubleDwiType, DoubleDwiType, DoubleDwiType>::Pointer adder = itk::AddImageFilter< DoubleDwiType, DoubleDwiType, DoubleDwiType>::New();
adder->SetInput1(doubleOutImage);
adder->SetInput2(compartments.at(i));
adder->Update();
doubleOutImage = adder->GetOutput();
}
}
if (this->GetAbortGenerateData())
{
m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n";
return;
}
m_StatusText += this->GetTime()+" > Finalizing image\n";
MITK_INFO << "Finalizing image";
unsigned int window = 0;
unsigned int min = itk::NumericTraits<unsigned int>::max();
ImageRegionIterator<OutputImageType> it4 (outImage, outImage->GetLargestPossibleRegion());
DoubleDwiType::PixelType signal; signal.SetSize(m_FiberModels[0]->GetNumGradients());
boost::progress_display disp2(outImage->GetLargestPossibleRegion().GetNumberOfPixels());
m_StatusText += "0% 10 20 30 40 50 60 70 80 90 100%\n";
m_StatusText += "|----|----|----|----|----|----|----|----|----|----|\n*";
lastTick = 0;
while(!it4.IsAtEnd())
{
if (this->GetAbortGenerateData())
{
m_StatusText += "\n"+this->GetTime()+" > Simulation aborted\n";
return;
}
++disp2;
unsigned long newTick = 50*disp2.count()/disp2.expected_count();
for (int tick = 0; tick<(newTick-lastTick); tick++)
m_StatusText += "*";
lastTick = newTick;
typename OutputImageType::IndexType index = it4.GetIndex();
signal = doubleOutImage->GetPixel(index)*m_SignalScale;
if (m_NoiseModel!=NULL)
{
DoubleDwiType::PixelType accu = signal; accu.Fill(0.0);
for (unsigned int i=0; i<m_NumberOfRepetitions; i++)
{
DoubleDwiType::PixelType temp = signal;
m_NoiseModel->AddNoise(temp);
accu += temp;
}
signal = accu/m_NumberOfRepetitions;
}
for (unsigned int i=0; i<signal.Size(); i++)
{
if (signal[i]>0)
signal[i] = floor(signal[i]+0.5);
else
signal[i] = ceil(signal[i]-0.5);
if (!m_FiberModels.at(0)->IsBaselineIndex(i) && signal[i]>window)
window = signal[i];
if (!m_FiberModels.at(0)->IsBaselineIndex(i) && signal[i]<min)
min = signal[i];
}
it4.Set(signal);
++it4;
}
window -= min;
unsigned int level = window/2 + min;
m_LevelWindow.SetLevelWindow(level, window);
this->SetNthOutput(0, outImage);
m_StatusText += "\n\n";
m_StatusText += "Finished simulation\n";
m_StatusText += "Simulation time: "+GetTime();
}
template< class PixelType >
itk::Point<float, 3> TractsToDWIImageFilter< PixelType >::GetItkPoint(double point[3])
{
itk::Point<float, 3> itkPoint;
itkPoint[0] = point[0];
itkPoint[1] = point[1];
itkPoint[2] = point[2];
return itkPoint;
}
template< class PixelType >
itk::Vector<double, 3> TractsToDWIImageFilter< PixelType >::GetItkVector(double point[3])
{
itk::Vector<double, 3> itkVector;
itkVector[0] = point[0];
itkVector[1] = point[1];
itkVector[2] = point[2];
return itkVector;
}
template< class PixelType >
vnl_vector_fixed<double, 3> TractsToDWIImageFilter< PixelType >::GetVnlVector(double point[3])
{
vnl_vector_fixed<double, 3> vnlVector;
vnlVector[0] = point[0];
vnlVector[1] = point[1];
vnlVector[2] = point[2];
return vnlVector;
}
template< class PixelType >
vnl_vector_fixed<double, 3> TractsToDWIImageFilter< PixelType >::GetVnlVector(Vector<float,3>& vector)
{
vnl_vector_fixed<double, 3> vnlVector;
vnlVector[0] = vector[0];
vnlVector[1] = vector[1];
vnlVector[2] = vector[2];
return vnlVector;
}
template< class PixelType >
std::string TractsToDWIImageFilter< PixelType >::GetTime()
{
unsigned long total = (double)(clock() - m_StartTime)/CLOCKS_PER_SEC;
unsigned long hours = total/3600;
unsigned long minutes = (total%3600)/60;
unsigned long seconds = total%60;
std::string out = "";
out.append(boost::lexical_cast<std::string>(hours));
out.append(":");
out.append(boost::lexical_cast<std::string>(minutes));
out.append(":");
out.append(boost::lexical_cast<std::string>(seconds));
return out;
}
}
| 42.185417
| 200
| 0.591733
|
rfloca
|
73383f8ffdfc68eb51fd4fb298821c7224be93e7
| 774
|
cpp
|
C++
|
codes/Chapter-04/ObjectasArgu.cpp
|
muyuuuu/Cpp-Notes
|
a514559eb4258304768167ea26de1e54f4a792d4
|
[
"MIT"
] | 1
|
2022-03-25T06:07:27.000Z
|
2022-03-25T06:07:27.000Z
|
codes/Chapter-04/ObjectasArgu.cpp
|
muyuuuu/Cpp-Notes
|
a514559eb4258304768167ea26de1e54f4a792d4
|
[
"MIT"
] | null | null | null |
codes/Chapter-04/ObjectasArgu.cpp
|
muyuuuu/Cpp-Notes
|
a514559eb4258304768167ea26de1e54f4a792d4
|
[
"MIT"
] | 1
|
2021-09-24T07:28:17.000Z
|
2021-09-24T07:28:17.000Z
|
#include <iostream>
using std::cout;
using std::endl;
class Circle
{
private:
double radius = 1.3;
public:
Circle();
Circle(double r);
double getArea();
double getRadius() const;
void setRadius(double r);
};
Circle::Circle(){
}
Circle::Circle(double r){
radius = r;
}
double Circle::getArea(){
return (3.14 * radius * radius);
}
// 常函数 不改变对象的状态
double Circle::getRadius() const{
return radius;
}
void Circle::setRadius(double r){
radius = r;
}
/*
void print(Circle c){
cout << c.getArea() << endl;
}
*/
void print(Circle& c){
cout << c.getArea() << endl;
}
void print(Circle* c){
cout << c->getArea() << endl;
}
int main(){
Circle ca[]{1.0, 2.0, 3.0};
print(ca[0]);
print(ca[1]);
print(ca + 2);
}
| 13.821429
| 36
| 0.581395
|
muyuuuu
|
733adeba0b39aaed149347103a1631e04134e63d
| 45,153
|
cpp
|
C++
|
Holo/Il2CppOutputProject/IL2CPP/libil2cpp/vm/MetadataCache.cpp
|
kyungyeon-lee/ExtendedRealitySearchTask
|
cd182ca92a056c068e1b8a7fe8b2f9a1dfa1990b
|
[
"MIT"
] | 1
|
2021-06-01T19:33:53.000Z
|
2021-06-01T19:33:53.000Z
|
Unity-Project/App-HL2/Il2CppOutputProject/IL2CPP/libil2cpp/vm/MetadataCache.cpp
|
JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity
|
6e13b31a0b053443b9c93267d8f174f1554e79dd
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
Unity-Project/App-HL2/Il2CppOutputProject/IL2CPP/libil2cpp/vm/MetadataCache.cpp
|
JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity
|
6e13b31a0b053443b9c93267d8f174f1554e79dd
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
#include "il2cpp-config.h"
#include "MetadataCache.h"
#include "GlobalMetadata.h"
#include <map>
#include <limits>
#include "il2cpp-tabledefs.h"
#include "il2cpp-runtime-stats.h"
#include "gc/GarbageCollector.h"
#include "metadata/ArrayMetadata.h"
#include "metadata/GenericMetadata.h"
#include "metadata/GenericMethod.h"
#include "os/Atomic.h"
#include "os/Mutex.h"
#include "utils/CallOnce.h"
#include "utils/Collections.h"
#include "utils/Il2CppHashSet.h"
#include "utils/Memory.h"
#include "utils/PathUtils.h"
#include "vm/Assembly.h"
#include "vm/Class.h"
#include "vm/ClassInlines.h"
#include "vm/GenericClass.h"
#include "vm/MetadataAlloc.h"
#include "vm/MetadataLoader.h"
#include "vm/MetadataLock.h"
#include "vm/Method.h"
#include "vm/Object.h"
#include "vm/Runtime.h"
#include "vm/String.h"
#include "vm/Type.h"
#include "vm-utils/NativeSymbol.h"
#include "Baselib.h"
#include "Cpp/ReentrantLock.h"
typedef std::map<Il2CppClass*, Il2CppClass*> PointerTypeMap;
typedef Il2CppHashSet<const Il2CppGenericMethod*, il2cpp::metadata::Il2CppGenericMethodHash, il2cpp::metadata::Il2CppGenericMethodCompare> Il2CppGenericMethodSet;
typedef Il2CppGenericMethodSet::const_iterator Il2CppGenericMethodSetIter;
static Il2CppGenericMethodSet s_GenericMethodSet;
struct Il2CppMetadataCache
{
baselib::ReentrantLock m_CacheMutex;
PointerTypeMap m_PointerTypes;
};
static Il2CppMetadataCache s_MetadataCache;
static int32_t s_ImagesCount = 0;
static Il2CppImage* s_ImagesTable = NULL;
static int32_t s_AssembliesCount = 0;
static Il2CppAssembly* s_AssembliesTable = NULL;
typedef Il2CppHashSet<const Il2CppGenericInst*, il2cpp::metadata::Il2CppGenericInstHash, il2cpp::metadata::Il2CppGenericInstCompare> Il2CppGenericInstSet;
static Il2CppGenericInstSet s_GenericInstSet;
typedef il2cpp::vm::Il2CppMethodTableMap::const_iterator Il2CppMethodTableMapIter;
static il2cpp::vm::Il2CppMethodTableMap s_MethodTableMap;
typedef il2cpp::vm::Il2CppUnresolvedSignatureMap::const_iterator Il2CppUnresolvedSignatureMapIter;
static il2cpp::vm::Il2CppUnresolvedSignatureMap *s_pUnresolvedSignatureMap;
typedef Il2CppHashMap<FieldInfo*, int32_t, il2cpp::utils::PointerHash<FieldInfo> > Il2CppThreadLocalStaticOffsetHashMap;
typedef Il2CppThreadLocalStaticOffsetHashMap::iterator Il2CppThreadLocalStaticOffsetHashMapIter;
static Il2CppThreadLocalStaticOffsetHashMap s_ThreadLocalStaticOffsetMap;
static const Il2CppCodeRegistration * s_Il2CppCodeRegistration;
static const Il2CppMetadataRegistration* s_MetadataCache_Il2CppMetadataRegistration;
static const Il2CppCodeGenOptions* s_Il2CppCodeGenOptions;
static il2cpp::vm::WindowsRuntimeTypeNameToClassMap s_WindowsRuntimeTypeNameToClassMap;
static il2cpp::vm::ClassToWindowsRuntimeTypeNameMap s_ClassToWindowsRuntimeTypeNameMap;
struct InteropDataToTypeConverter
{
inline const Il2CppType* operator()(const Il2CppInteropData& interopData) const
{
return interopData.type;
}
};
typedef il2cpp::utils::collections::ArrayValueMap<const Il2CppType*, Il2CppInteropData, InteropDataToTypeConverter, il2cpp::metadata::Il2CppTypeLess, il2cpp::metadata::Il2CppTypeEqualityComparer> InteropDataMap;
static InteropDataMap s_InteropData;
struct WindowsRuntimeFactoryTableEntryToTypeConverter
{
inline const Il2CppType* operator()(const Il2CppWindowsRuntimeFactoryTableEntry& entry) const
{
return entry.type;
}
};
typedef il2cpp::utils::collections::ArrayValueMap<const Il2CppType*, Il2CppWindowsRuntimeFactoryTableEntry, WindowsRuntimeFactoryTableEntryToTypeConverter, il2cpp::metadata::Il2CppTypeLess, il2cpp::metadata::Il2CppTypeEqualityComparer> WindowsRuntimeFactoryTable;
static WindowsRuntimeFactoryTable s_WindowsRuntimeFactories;
template<typename K, typename V>
struct PairToKeyConverter
{
inline const K& operator()(const std::pair<K, V>& pair) const
{
return pair.first;
}
};
typedef il2cpp::utils::collections::ArrayValueMap<const Il2CppGuid*, std::pair<const Il2CppGuid*, Il2CppClass*>, PairToKeyConverter<const Il2CppGuid*, Il2CppClass*> > GuidToClassMap;
static GuidToClassMap s_GuidToNonImportClassMap;
void il2cpp::vm::MetadataCache::Register(const Il2CppCodeRegistration* const codeRegistration, const Il2CppMetadataRegistration* const metadataRegistration, const Il2CppCodeGenOptions* const codeGenOptions)
{
il2cpp::vm::GlobalMetadata::Register(codeRegistration, metadataRegistration, codeGenOptions);
s_Il2CppCodeRegistration = codeRegistration;
s_MetadataCache_Il2CppMetadataRegistration = metadataRegistration;
s_Il2CppCodeGenOptions = codeGenOptions;
}
Il2CppClass* il2cpp::vm::MetadataCache::GetTypeInfoFromTypeIndex(const Il2CppImage *image, TypeIndex index)
{
return il2cpp::vm::GlobalMetadata::GetTypeInfoFromTypeIndex(index);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetAssemblyEntryPoint(const Il2CppImage* image)
{
return il2cpp::vm::GlobalMetadata::GetAssemblyEntryPoint(image);
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetAssemblyTypeHandle(const Il2CppImage* image, AssemblyTypeIndex index)
{
return il2cpp::vm::GlobalMetadata::GetAssemblyTypeHandle(image, index);
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetAssemblyExportedTypeHandle(const Il2CppImage* image, AssemblyExportedTypeIndex index)
{
return il2cpp::vm::GlobalMetadata::GetAssemblyExportedTypeHandle(image, index);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetMethodInfoFromMethodHandle(Il2CppMetadataMethodDefinitionHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetMethodInfoFromMethodHandle(handle);
}
bool il2cpp::vm::MetadataCache::Initialize()
{
if (!il2cpp::vm::GlobalMetadata::Initialize(&s_ImagesCount, &s_AssembliesCount))
{
return false;
}
il2cpp::metadata::GenericMetadata::RegisterGenericClasses(s_MetadataCache_Il2CppMetadataRegistration->genericClasses, s_MetadataCache_Il2CppMetadataRegistration->genericClassesCount);
il2cpp::metadata::GenericMetadata::SetMaximumRuntimeGenericDepth(s_Il2CppCodeGenOptions->maximumRuntimeGenericDepth);
s_GenericInstSet.resize(s_MetadataCache_Il2CppMetadataRegistration->genericInstsCount);
for (int32_t i = 0; i < s_MetadataCache_Il2CppMetadataRegistration->genericInstsCount; i++)
s_GenericInstSet.insert(s_MetadataCache_Il2CppMetadataRegistration->genericInsts[i]);
s_InteropData.assign_external(s_Il2CppCodeRegistration->interopData, s_Il2CppCodeRegistration->interopDataCount);
s_WindowsRuntimeFactories.assign_external(s_Il2CppCodeRegistration->windowsRuntimeFactoryTable, s_Il2CppCodeRegistration->windowsRuntimeFactoryCount);
// Pre-allocate these arrays so we don't need to lock when reading later.
// These arrays hold the runtime metadata representation for metadata explicitly
// referenced during conversion. There is a corresponding table of same size
// in the converted metadata, giving a description of runtime metadata to construct.
s_ImagesTable = (Il2CppImage*)IL2CPP_CALLOC(s_ImagesCount, sizeof(Il2CppImage));
s_AssembliesTable = (Il2CppAssembly*)IL2CPP_CALLOC(s_AssembliesCount, sizeof(Il2CppAssembly));
// setup all the Il2CppImages. There are not many and it avoid locks later on
for (int32_t imageIndex = 0; imageIndex < s_ImagesCount; imageIndex++)
{
Il2CppImage* image = s_ImagesTable + imageIndex;
AssemblyIndex imageAssemblyIndex;
il2cpp::vm::GlobalMetadata::BuildIl2CppImage(image, imageIndex, &imageAssemblyIndex);
image->assembly = const_cast<Il2CppAssembly*>(GetAssemblyFromIndex(imageAssemblyIndex));
std::string nameNoExt = il2cpp::utils::PathUtils::PathNoExtension(image->name);
image->nameNoExt = (char*)IL2CPP_CALLOC(nameNoExt.size() + 1, sizeof(char));
strcpy(const_cast<char*>(image->nameNoExt), nameNoExt.c_str());
for (uint32_t codeGenModuleIndex = 0; codeGenModuleIndex < s_Il2CppCodeRegistration->codeGenModulesCount; ++codeGenModuleIndex)
{
if (strcmp(image->name, s_Il2CppCodeRegistration->codeGenModules[codeGenModuleIndex]->moduleName) == 0)
image->codeGenModule = s_Il2CppCodeRegistration->codeGenModules[codeGenModuleIndex];
}
IL2CPP_ASSERT(image->codeGenModule);
image->dynamic = false;
}
// setup all the Il2CppAssemblies.
for (int32_t assemblyIndex = 0; assemblyIndex < s_ImagesCount; assemblyIndex++)
{
Il2CppAssembly* assembly = s_AssembliesTable + assemblyIndex;
ImageIndex assemblyImageIndex;
il2cpp::vm::GlobalMetadata::BuildIl2CppAssembly(assembly, assemblyIndex, &assemblyImageIndex);
assembly->image = il2cpp::vm::MetadataCache::GetImageFromIndex(assemblyImageIndex);
Assembly::Register(assembly);
}
InitializeUnresolvedSignatureTable();
#if IL2CPP_ENABLE_NATIVE_STACKTRACES
std::vector<MethodDefinitionKey> managedMethods;
il2cpp::vm::GlobalMetadata::GetAllManagedMethods(managedMethods);
il2cpp::utils::NativeSymbol::RegisterMethods(managedMethods);
#endif
return true;
}
void il2cpp::vm::MetadataCache::ExecuteEagerStaticClassConstructors()
{
for (int32_t i = 0; i < s_AssembliesCount; i++)
{
const Il2CppImage* image = s_AssembliesTable[i].image;
if (image->codeGenModule->staticConstructorTypeIndices != NULL)
{
TypeDefinitionIndex* indexPointer = image->codeGenModule->staticConstructorTypeIndices;
while (*indexPointer) // 0 terminated
{
Il2CppMetadataTypeHandle handle = GetTypeHandleFromIndex(image, *indexPointer);
Il2CppClass* klass = GlobalMetadata::GetTypeInfoFromHandle(handle);
Runtime::ClassInit(klass);
indexPointer++;
}
}
}
}
void il2cpp::vm::MetadataCache::ExecuteModuleInitializers()
{
for (int32_t i = 0; i < s_AssembliesCount; i++)
{
const Il2CppImage* image = s_AssembliesTable[i].image;
if (image->codeGenModule->moduleInitializer != NULL)
image->codeGenModule->moduleInitializer();
}
}
void ClearGenericMethodTable()
{
s_MethodTableMap.clear();
}
void ClearWindowsRuntimeTypeNamesTables()
{
s_ClassToWindowsRuntimeTypeNameMap.clear();
}
void il2cpp::vm::MetadataCache::InitializeGuidToClassTable()
{
Il2CppInteropData* interopData = s_Il2CppCodeRegistration->interopData;
uint32_t interopDataCount = s_Il2CppCodeRegistration->interopDataCount;
std::vector<std::pair<const Il2CppGuid*, Il2CppClass*> > guidToNonImportClassMap;
guidToNonImportClassMap.reserve(interopDataCount);
for (uint32_t i = 0; i < interopDataCount; i++)
{
// It's important to check for non-import types because type projections will have identical GUIDs (e.g. IEnumerable<T> and IIterable<T>)
if (interopData[i].guid != NULL)
{
Il2CppClass* klass = il2cpp::vm::Class::FromIl2CppType(interopData[i].type);
if (!klass->is_import_or_windows_runtime)
guidToNonImportClassMap.push_back(std::make_pair(interopData[i].guid, klass));
}
}
s_GuidToNonImportClassMap.assign(guidToNonImportClassMap);
}
// this is called later in the intialization cycle with more systems setup like GC
void il2cpp::vm::MetadataCache::InitializeGCSafe()
{
il2cpp::vm::GlobalMetadata::InitializeStringLiteralTable();
il2cpp::vm::GlobalMetadata::InitializeGenericMethodTable(s_MethodTableMap);
il2cpp::vm::GlobalMetadata::InitializeWindowsRuntimeTypeNamesTables(s_WindowsRuntimeTypeNameToClassMap, s_ClassToWindowsRuntimeTypeNameMap);
InitializeGuidToClassTable();
}
void ClearImageNames()
{
for (int32_t imageIndex = 0; imageIndex < s_ImagesCount; imageIndex++)
{
Il2CppImage* image = s_ImagesTable + imageIndex;
IL2CPP_FREE((void*)image->nameNoExt);
}
}
void il2cpp::vm::MetadataCache::Clear()
{
ClearGenericMethodTable();
ClearWindowsRuntimeTypeNamesTables();
delete s_pUnresolvedSignatureMap;
Assembly::ClearAllAssemblies();
ClearImageNames();
IL2CPP_FREE(s_ImagesTable);
s_ImagesTable = NULL;
s_ImagesCount = 0;
IL2CPP_FREE(s_AssembliesTable);
s_AssembliesTable = NULL;
s_AssembliesCount = 0;
s_GenericMethodSet.clear();
metadata::ArrayMetadata::Clear();
s_GenericInstSet.clear();
s_Il2CppCodeRegistration = NULL;
s_Il2CppCodeGenOptions = NULL;
il2cpp::metadata::GenericMetadata::Clear();
il2cpp::metadata::GenericMethod::ClearStatics();
il2cpp::vm::GlobalMetadata::Clear();
}
void il2cpp::vm::MetadataCache::InitializeUnresolvedSignatureTable()
{
s_pUnresolvedSignatureMap = new Il2CppUnresolvedSignatureMap();
il2cpp::vm::GlobalMetadata::InitializeUnresolvedSignatureTable(*s_pUnresolvedSignatureMap);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetGenericInstanceType(Il2CppClass* genericTypeDefinition, const il2cpp::metadata::Il2CppTypeVector& genericArgumentTypes)
{
const Il2CppGenericInst* inst = il2cpp::vm::MetadataCache::GetGenericInst(genericArgumentTypes);
Il2CppGenericClass* genericClass = il2cpp::metadata::GenericMetadata::GetGenericClass(genericTypeDefinition, inst);
return il2cpp::vm::GenericClass::GetClass(genericClass);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetGenericInstanceMethod(const MethodInfo* genericMethodDefinition, const il2cpp::metadata::Il2CppTypeVector& genericArgumentTypes)
{
Il2CppGenericContext context = { NULL, GetGenericInst(genericArgumentTypes) };
return il2cpp::vm::GlobalMetadata::GetGenericInstanceMethod(genericMethodDefinition, &context);
}
const Il2CppGenericContext* il2cpp::vm::MetadataCache::GetMethodGenericContext(const MethodInfo* method)
{
if (!method->is_inflated)
{
IL2CPP_NOT_IMPLEMENTED(Image::GetMethodGenericContext);
return NULL;
}
return &method->genericMethod->context;
}
const MethodInfo* il2cpp::vm::MetadataCache::GetGenericMethodDefinition(const MethodInfo* method)
{
if (!method->is_inflated)
{
IL2CPP_NOT_IMPLEMENTED(Image::GetGenericMethodDefinition);
return NULL;
}
return method->genericMethod->methodDefinition;
}
Il2CppClass* il2cpp::vm::MetadataCache::GetPointerType(Il2CppClass* type)
{
il2cpp::os::FastAutoLock lock(&s_MetadataCache.m_CacheMutex);
PointerTypeMap::const_iterator i = s_MetadataCache.m_PointerTypes.find(type);
if (i == s_MetadataCache.m_PointerTypes.end())
return NULL;
return i->second;
}
Il2CppClass* il2cpp::vm::MetadataCache::GetWindowsRuntimeClass(const char* fullName)
{
WindowsRuntimeTypeNameToClassMap::iterator it = s_WindowsRuntimeTypeNameToClassMap.find(fullName);
if (it != s_WindowsRuntimeTypeNameToClassMap.end())
return it->second;
return NULL;
}
const char* il2cpp::vm::MetadataCache::GetWindowsRuntimeClassName(const Il2CppClass* klass)
{
ClassToWindowsRuntimeTypeNameMap::iterator it = s_ClassToWindowsRuntimeTypeNameMap.find(klass);
if (it != s_ClassToWindowsRuntimeTypeNameMap.end())
return it->second;
return NULL;
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetWindowsRuntimeFactoryCreationFunction(const char* fullName)
{
Il2CppClass* klass = GetWindowsRuntimeClass(fullName);
if (klass == NULL)
return NULL;
WindowsRuntimeFactoryTable::iterator factoryEntry = s_WindowsRuntimeFactories.find_first(&klass->byval_arg);
if (factoryEntry == s_WindowsRuntimeFactories.end())
return NULL;
return factoryEntry->createFactoryFunction;
}
Il2CppClass* il2cpp::vm::MetadataCache::GetClassForGuid(const Il2CppGuid* guid)
{
IL2CPP_ASSERT(guid != NULL);
GuidToClassMap::iterator it = s_GuidToNonImportClassMap.find_first(guid);
if (it != s_GuidToNonImportClassMap.end())
return it->second;
return NULL;
}
void il2cpp::vm::MetadataCache::AddPointerType(Il2CppClass* type, Il2CppClass* pointerType)
{
il2cpp::os::FastAutoLock lock(&s_MetadataCache.m_CacheMutex);
s_MetadataCache.m_PointerTypes.insert(std::make_pair(type, pointerType));
}
const Il2CppGenericInst* il2cpp::vm::MetadataCache::GetGenericInst(const Il2CppType* const* types, uint32_t typeCount)
{
// temporary inst to lookup a permanent one that may already exist
Il2CppGenericInst inst;
inst.type_argc = typeCount;
inst.type_argv = (const Il2CppType**)alloca(inst.type_argc * sizeof(Il2CppType*));
size_t index = 0;
const Il2CppType* const* typesEnd = types + typeCount;
for (const Il2CppType* const* iter = types; iter != typesEnd; ++iter, ++index)
inst.type_argv[index] = *iter;
il2cpp::os::FastAutoLock lock(&s_MetadataCache.m_CacheMutex);
Il2CppGenericInstSet::const_iterator iter = s_GenericInstSet.find(&inst);
if (iter != s_GenericInstSet.end())
return *iter;
Il2CppGenericInst* newInst = (Il2CppGenericInst*)MetadataMalloc(sizeof(Il2CppGenericInst));
newInst->type_argc = typeCount;
newInst->type_argv = (const Il2CppType**)MetadataMalloc(newInst->type_argc * sizeof(Il2CppType*));
index = 0;
for (const Il2CppType* const* iter = types; iter != typesEnd; ++iter, ++index)
newInst->type_argv[index] = *iter;
s_GenericInstSet.insert(newInst);
++il2cpp_runtime_stats.generic_instance_count;
return newInst;
}
const Il2CppGenericInst* il2cpp::vm::MetadataCache::GetGenericInst(const il2cpp::metadata::Il2CppTypeVector& types)
{
return GetGenericInst(&types[0], static_cast<uint32_t>(types.size()));
}
static baselib::ReentrantLock s_GenericMethodMutex;
const Il2CppGenericMethod* il2cpp::vm::MetadataCache::GetGenericMethod(const MethodInfo* methodDefinition, const Il2CppGenericInst* classInst, const Il2CppGenericInst* methodInst)
{
Il2CppGenericMethod method = { 0 };
method.methodDefinition = methodDefinition;
method.context.class_inst = classInst;
method.context.method_inst = methodInst;
il2cpp::os::FastAutoLock lock(&s_GenericMethodMutex);
Il2CppGenericMethodSet::const_iterator iter = s_GenericMethodSet.find(&method);
if (iter != s_GenericMethodSet.end())
return *iter;
Il2CppGenericMethod* newMethod = MetadataAllocGenericMethod();
newMethod->methodDefinition = methodDefinition;
newMethod->context.class_inst = classInst;
newMethod->context.method_inst = methodInst;
s_GenericMethodSet.insert(newMethod);
return newMethod;
}
static bool IsShareableEnum(const Il2CppType* type)
{
// Base case for recursion - we've found an enum.
if (il2cpp::vm::Type::IsEnum(type))
return true;
if (il2cpp::vm::Type::IsGenericInstance(type))
{
// Recursive case - look "inside" the generic instance type to see if this is a nested enum.
Il2CppClass* definition = il2cpp::vm::GenericClass::GetTypeDefinition(type->data.generic_class);
return IsShareableEnum(il2cpp::vm::Class::GetType(definition));
}
// Base case for recurion - this is not an enum or a generic instance type.
return false;
}
// this logic must match the C# logic in GenericSharingAnalysis.GetSharedTypeForGenericParameter
static const Il2CppGenericInst* GetSharedInst(const Il2CppGenericInst* inst)
{
if (inst == NULL)
return NULL;
il2cpp::metadata::Il2CppTypeVector types;
for (uint32_t i = 0; i < inst->type_argc; ++i)
{
if (il2cpp::vm::Type::IsReference(inst->type_argv[i]))
types.push_back(&il2cpp_defaults.object_class->byval_arg);
else
{
const Il2CppType* type = inst->type_argv[i];
if (s_Il2CppCodeGenOptions->enablePrimitiveValueTypeGenericSharing)
{
if (IsShareableEnum(type))
{
const Il2CppType* underlyingType = il2cpp::vm::Type::GetUnderlyingType(type);
switch (underlyingType->type)
{
case IL2CPP_TYPE_I1:
type = &il2cpp_defaults.sbyte_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_I2:
type = &il2cpp_defaults.int16_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_I4:
type = &il2cpp_defaults.int32_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_I8:
type = &il2cpp_defaults.int64_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_U1:
type = &il2cpp_defaults.byte_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_U2:
type = &il2cpp_defaults.uint16_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_U4:
type = &il2cpp_defaults.uint32_shared_enum->byval_arg;
break;
case IL2CPP_TYPE_U8:
type = &il2cpp_defaults.uint64_shared_enum->byval_arg;
break;
default:
IL2CPP_ASSERT(0 && "Invalid enum underlying type");
break;
}
}
}
if (il2cpp::vm::Type::IsGenericInstance(type))
{
const Il2CppGenericInst* sharedInst = GetSharedInst(type->data.generic_class->context.class_inst);
Il2CppGenericClass* gklass = il2cpp::metadata::GenericMetadata::GetGenericClass(type->data.generic_class->type, sharedInst);
Il2CppClass* klass = il2cpp::vm::GenericClass::GetClass(gklass);
type = &klass->byval_arg;
}
types.push_back(type);
}
}
const Il2CppGenericInst* sharedInst = il2cpp::vm::MetadataCache::GetGenericInst(types);
return sharedInst;
}
InvokerMethod il2cpp::vm::MetadataCache::GetInvokerMethodPointer(const MethodInfo* methodDefinition, const Il2CppGenericContext* context)
{
Il2CppGenericMethod method = { 0 };
method.methodDefinition = const_cast<MethodInfo*>(methodDefinition);
method.context.class_inst = context->class_inst;
method.context.method_inst = context->method_inst;
Il2CppMethodTableMapIter iter = s_MethodTableMap.find(&method);
if (iter != s_MethodTableMap.end())
{
IL2CPP_ASSERT(iter->second->invokerIndex >= 0);
if (static_cast<uint32_t>(iter->second->invokerIndex) < s_Il2CppCodeRegistration->invokerPointersCount)
return s_Il2CppCodeRegistration->invokerPointers[iter->second->invokerIndex];
return NULL;
}
// get the shared version if it exists
method.context.class_inst = GetSharedInst(context->class_inst);
method.context.method_inst = GetSharedInst(context->method_inst);
iter = s_MethodTableMap.find(&method);
if (iter != s_MethodTableMap.end())
{
IL2CPP_ASSERT(iter->second->invokerIndex >= 0);
if (static_cast<uint32_t>(iter->second->invokerIndex) < s_Il2CppCodeRegistration->invokerPointersCount)
return s_Il2CppCodeRegistration->invokerPointers[iter->second->invokerIndex];
return NULL;
}
return NULL;
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetMethodPointer(const MethodInfo* methodDefinition, const Il2CppGenericContext* context)
{
Il2CppGenericMethod method = { 0 };
method.methodDefinition = const_cast<MethodInfo*>(methodDefinition);
method.context.class_inst = context->class_inst;
method.context.method_inst = context->method_inst;
Il2CppMethodTableMapIter iter = s_MethodTableMap.find(&method);
if (iter != s_MethodTableMap.end())
{
IL2CPP_ASSERT(iter->second->invokerIndex >= 0);
if (iter->second->adjustorThunkIndex != -1)
return s_Il2CppCodeRegistration->genericAdjustorThunks[iter->second->adjustorThunkIndex];
if (static_cast<uint32_t>(iter->second->methodIndex) < s_Il2CppCodeRegistration->genericMethodPointersCount)
return s_Il2CppCodeRegistration->genericMethodPointers[iter->second->methodIndex];
return NULL;
}
method.context.class_inst = GetSharedInst(context->class_inst);
method.context.method_inst = GetSharedInst(context->method_inst);
iter = s_MethodTableMap.find(&method);
if (iter != s_MethodTableMap.end())
{
IL2CPP_ASSERT(iter->second->invokerIndex >= 0);
if (iter->second->adjustorThunkIndex != -1)
return s_Il2CppCodeRegistration->genericAdjustorThunks[iter->second->adjustorThunkIndex];
if (static_cast<uint32_t>(iter->second->methodIndex) < s_Il2CppCodeRegistration->genericMethodPointersCount)
return s_Il2CppCodeRegistration->genericMethodPointers[iter->second->methodIndex];
return NULL;
}
return NULL;
}
const Il2CppType* il2cpp::vm::MetadataCache::GetIl2CppTypeFromIndex(const Il2CppImage* image, TypeIndex index)
{
return il2cpp::vm::GlobalMetadata::GetIl2CppTypeFromIndex(index);
}
const Il2CppType* il2cpp::vm::MetadataCache::GetTypeFromRgctxDefinition(const Il2CppRGCTXDefinition* rgctxDef)
{
return il2cpp::vm::GlobalMetadata::GetTypeFromRgctxDefinition(rgctxDef);
}
const Il2CppGenericMethod* il2cpp::vm::MetadataCache::GetGenericMethodFromRgctxDefinition(const Il2CppRGCTXDefinition* rgctxDef)
{
return il2cpp::vm::GlobalMetadata::GetGenericMethodFromRgctxDefinition(rgctxDef);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetMethodInfoFromVTableSlot(const Il2CppClass* klass, int32_t vTableSlot)
{
return il2cpp::vm::GlobalMetadata::GetMethodInfoFromVTableSlot(klass, vTableSlot);
}
static int CompareIl2CppTokenAdjustorThunkPair(const void* pkey, const void* pelem)
{
return (int)(((Il2CppTokenAdjustorThunkPair*)pkey)->token - ((Il2CppTokenAdjustorThunkPair*)pelem)->token);
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetAdjustorThunk(const Il2CppImage* image, uint32_t token)
{
if (image->codeGenModule->adjustorThunkCount == 0)
return NULL;
Il2CppTokenAdjustorThunkPair key;
memset(&key, 0, sizeof(Il2CppTokenAdjustorThunkPair));
key.token = token;
const Il2CppTokenAdjustorThunkPair* result = (const Il2CppTokenAdjustorThunkPair*)bsearch(&key, image->codeGenModule->adjustorThunks,
image->codeGenModule->adjustorThunkCount, sizeof(Il2CppTokenAdjustorThunkPair), CompareIl2CppTokenAdjustorThunkPair);
if (result == NULL)
return NULL;
return result->adjustorThunk;
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetMethodPointer(const Il2CppImage* image, uint32_t token)
{
uint32_t rid = GetTokenRowId(token);
uint32_t table = GetTokenType(token);
if (rid == 0)
return NULL;
IL2CPP_ASSERT(rid <= image->codeGenModule->methodPointerCount);
return image->codeGenModule->methodPointers[rid - 1];
}
InvokerMethod il2cpp::vm::MetadataCache::GetMethodInvoker(const Il2CppImage* image, uint32_t token)
{
uint32_t rid = GetTokenRowId(token);
uint32_t table = GetTokenType(token);
if (rid == 0)
return NULL;
int32_t index = image->codeGenModule->invokerIndices[rid - 1];
if (index == kMethodIndexInvalid)
return NULL;
IL2CPP_ASSERT(index >= 0 && static_cast<uint32_t>(index) < s_Il2CppCodeRegistration->invokerPointersCount);
return s_Il2CppCodeRegistration->invokerPointers[index];
}
const Il2CppInteropData* il2cpp::vm::MetadataCache::GetInteropDataForType(const Il2CppType* type)
{
IL2CPP_ASSERT(type != NULL);
InteropDataMap::iterator interopData = s_InteropData.find_first(type);
if (interopData == s_InteropData.end())
return NULL;
return interopData;
}
static bool MatchTokens(Il2CppTokenIndexMethodTuple key, Il2CppTokenIndexMethodTuple element)
{
return key.token < element.token;
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetReversePInvokeWrapper(const Il2CppImage* image, const MethodInfo* method)
{
if (image->codeGenModule->reversePInvokeWrapperCount == 0)
return NULL;
// For each image (i.e. assembly), the reverse pinvoke wrapper indices are in an array sorted by
// metadata token. Each entry also might have the method metadata pointer, which is used to further
// find methods that have a matching metadata token.
Il2CppTokenIndexMethodTuple key;
memset(&key, 0, sizeof(Il2CppTokenIndexMethodTuple));
key.token = method->token;
// Binary search for a range which matches the metadata token.
auto begin = image->codeGenModule->reversePInvokeWrapperIndices;
auto end = image->codeGenModule->reversePInvokeWrapperIndices + image->codeGenModule->reversePInvokeWrapperCount;
auto matchingRange = std::equal_range(begin, end, key, &MatchTokens);
int32_t index = -1;
auto numberOfMatches = std::distance(matchingRange.first, matchingRange.second);
if (numberOfMatches == 1)
{
// Normal case - we found one non-generic method.
index = matchingRange.first->index;
}
else if (numberOfMatches > 1)
{
// Multiple generic instance methods share the same token, since it is from the generic method definition.
// To find the proper method, look for the one with a matching method metadata pointer.
const Il2CppTokenIndexMethodTuple* currentMatch = matchingRange.first;
const Il2CppTokenIndexMethodTuple* lastMatch = matchingRange.second;
while (currentMatch != lastMatch)
{
// First, check the method metadata, and use it if it has been initialized.
// If not, let's fall back to the generic method.
const MethodInfo* possibleMatch = (const MethodInfo*)*currentMatch->method;
if (!il2cpp::vm::GlobalMetadata::IsRuntimeMetadataInitialized(possibleMatch))
possibleMatch = il2cpp::metadata::GenericMethod::GetMethod(il2cpp::vm::GlobalMetadata::GetGenericMethodFromTokenMethodTuple(currentMatch));
if (possibleMatch == method)
{
index = currentMatch->index;
break;
}
currentMatch++;
}
}
if (index == -1)
return NULL;
IL2CPP_ASSERT(index >= 0 && static_cast<uint32_t>(index) < s_Il2CppCodeRegistration->reversePInvokeWrapperCount);
return s_Il2CppCodeRegistration->reversePInvokeWrappers[index];
}
static const Il2CppType* GetReducedType(const Il2CppType* type)
{
if (type->byref)
return &il2cpp_defaults.object_class->byval_arg;
if (il2cpp::vm::Type::IsEnum(type))
type = il2cpp::vm::Type::GetUnderlyingType(type);
switch (type->type)
{
case IL2CPP_TYPE_BOOLEAN:
return &il2cpp_defaults.sbyte_class->byval_arg;
case IL2CPP_TYPE_CHAR:
return &il2cpp_defaults.int16_class->byval_arg;
case IL2CPP_TYPE_BYREF:
case IL2CPP_TYPE_CLASS:
case IL2CPP_TYPE_OBJECT:
case IL2CPP_TYPE_STRING:
case IL2CPP_TYPE_ARRAY:
case IL2CPP_TYPE_SZARRAY:
return &il2cpp_defaults.object_class->byval_arg;
case IL2CPP_TYPE_GENERICINST:
if (il2cpp::vm::Type::GenericInstIsValuetype(type))
return type;
else
return &il2cpp_defaults.object_class->byval_arg;
default:
return type;
}
}
Il2CppMethodPointer il2cpp::vm::MetadataCache::GetUnresolvedVirtualCallStub(const MethodInfo* method)
{
il2cpp::metadata::Il2CppSignature signature;
signature.Count = method->parameters_count + 1;
signature.Types = (const Il2CppType**)alloca(signature.Count * sizeof(Il2CppType*));
signature.Types[0] = GetReducedType(method->return_type);
for (int i = 0; i < method->parameters_count; ++i)
signature.Types[i + 1] = GetReducedType(method->parameters[i].parameter_type);
Il2CppUnresolvedSignatureMapIter it = s_pUnresolvedSignatureMap->find(signature);
if (it != s_pUnresolvedSignatureMap->end())
return it->second;
return NULL;
}
const Il2CppAssembly* il2cpp::vm::MetadataCache::GetAssemblyFromIndex(AssemblyIndex index)
{
if (index == kGenericContainerIndexInvalid)
return NULL;
IL2CPP_ASSERT(index <= s_AssembliesCount);
return s_AssembliesTable + index;
}
const Il2CppAssembly* il2cpp::vm::MetadataCache::GetAssemblyByName(const char* nameToFind)
{
for (int i = 0; i < s_AssembliesCount; i++)
{
const Il2CppAssembly* assembly = s_AssembliesTable + i;
const char* assemblyName = assembly->aname.name;
if (strcmp(assemblyName, nameToFind) == 0)
return assembly;
}
return NULL;
}
Il2CppImage* il2cpp::vm::MetadataCache::GetImageFromIndex(ImageIndex index)
{
if (index == kGenericContainerIndexInvalid)
return NULL;
IL2CPP_ASSERT(index <= s_ImagesCount);
return s_ImagesTable + index;
}
Il2CppClass* il2cpp::vm::MetadataCache::GetTypeInfoFromType(const Il2CppType* type)
{
if (type == NULL)
return NULL;
return il2cpp::vm::GlobalMetadata::GetTypeInfoFromType(type);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetTypeInfoFromHandle(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetTypeInfoFromHandle(handle);
}
Il2CppMetadataGenericContainerHandle il2cpp::vm::MetadataCache::GetGenericContainerFromGenericClass(const Il2CppImage* image, const Il2CppGenericClass* genericClass)
{
return il2cpp::vm::GlobalMetadata::GetGenericContainerFromGenericClass(genericClass);
}
Il2CppMetadataGenericContainerHandle il2cpp::vm::MetadataCache::GetGenericContainerFromMethod(Il2CppMetadataMethodDefinitionHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericContainerFromMethod(handle);
}
Il2CppMetadataGenericParameterHandle il2cpp::vm::MetadataCache::GetGenericParameterFromType(const Il2CppType* type)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterFromType(type);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetContainerDeclaringType(Il2CppMetadataGenericContainerHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetContainerDeclaringType(handle);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetParameterDeclaringType(Il2CppMetadataGenericParameterHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetParameterDeclaringType(handle);
}
Il2CppMetadataGenericParameterHandle il2cpp::vm::MetadataCache::GetGenericParameterFromIndex(Il2CppMetadataGenericContainerHandle handle, GenericContainerParameterIndex index)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterFromIndex(handle, index);
}
const Il2CppType* il2cpp::vm::MetadataCache::GetGenericParameterConstraintFromIndex(Il2CppMetadataGenericParameterHandle handle, GenericParameterConstraintIndex index)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterConstraintFromIndex(handle, index);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetNestedTypeFromOffset(const Il2CppClass* klass, TypeNestedTypeIndex offset)
{
return il2cpp::vm::GlobalMetadata::GetNestedTypeFromOffset(klass, offset);
}
const Il2CppType* il2cpp::vm::MetadataCache::GetInterfaceFromOffset(const Il2CppClass* klass, TypeInterfaceIndex offset)
{
return il2cpp::vm::GlobalMetadata::GetInterfaceFromOffset(klass, offset);
}
Il2CppInterfaceOffsetInfo il2cpp::vm::MetadataCache::GetInterfaceOffsetInfo(const Il2CppClass* klass, TypeInterfaceOffsetIndex index)
{
return il2cpp::vm::GlobalMetadata::GetInterfaceOffsetInfo(klass, index);
}
static int CompareIl2CppTokenRangePair(const void* pkey, const void* pelem)
{
return (int)(((Il2CppTokenRangePair*)pkey)->token - ((Il2CppTokenRangePair*)pelem)->token);
}
il2cpp::vm::RGCTXCollection il2cpp::vm::MetadataCache::GetRGCTXs(const Il2CppImage* image, uint32_t token)
{
RGCTXCollection collection = { 0, NULL };
if (image->codeGenModule->rgctxRangesCount == 0)
return collection;
Il2CppTokenRangePair key;
memset(&key, 0, sizeof(Il2CppTokenRangePair));
key.token = token;
const Il2CppTokenRangePair* res = (const Il2CppTokenRangePair*)bsearch(&key, image->codeGenModule->rgctxRanges, image->codeGenModule->rgctxRangesCount, sizeof(Il2CppTokenRangePair), CompareIl2CppTokenRangePair);
if (res == NULL)
return collection;
collection.count = res->range.length;
collection.items = image->codeGenModule->rgctxs + res->range.start;
return collection;
}
const uint8_t* il2cpp::vm::MetadataCache::GetFieldDefaultValue(const FieldInfo* field, const Il2CppType** type)
{
return il2cpp::vm::GlobalMetadata::GetFieldDefaultValue(field, type);
}
const uint8_t* il2cpp::vm::MetadataCache::GetParameterDefaultValue(const MethodInfo* method, const ParameterInfo* parameter, const Il2CppType** type, bool* isExplicitySetNullDefaultValue)
{
return il2cpp::vm::GlobalMetadata::GetParameterDefaultValue(method, parameter, type, isExplicitySetNullDefaultValue);
}
int il2cpp::vm::MetadataCache::GetFieldMarshaledSizeForField(const FieldInfo* field)
{
return il2cpp::vm::GlobalMetadata::GetFieldMarshaledSizeForField(field);
}
int32_t il2cpp::vm::MetadataCache::GetFieldOffsetFromIndexLocked(const Il2CppClass* klass, int32_t fieldIndexInType, FieldInfo* field, const il2cpp::os::FastAutoLock& lock)
{
int32_t offset = il2cpp::vm::GlobalMetadata::GetFieldOffset(klass, fieldIndexInType, field);
if (offset < 0)
{
AddThreadLocalStaticOffsetForFieldLocked(field, offset & ~THREAD_LOCAL_STATIC_MASK, lock);
return THREAD_STATIC_FIELD_OFFSET;
}
return offset;
}
void il2cpp::vm::MetadataCache::AddThreadLocalStaticOffsetForFieldLocked(FieldInfo* field, int32_t offset, const il2cpp::os::FastAutoLock& lock)
{
s_ThreadLocalStaticOffsetMap.add(field, offset);
}
int32_t il2cpp::vm::MetadataCache::GetThreadLocalStaticOffsetForField(FieldInfo* field)
{
IL2CPP_ASSERT(field->offset == THREAD_STATIC_FIELD_OFFSET);
il2cpp::os::FastAutoLock lock(&g_MetadataLock);
Il2CppThreadLocalStaticOffsetHashMapIter iter = s_ThreadLocalStaticOffsetMap.find(field);
IL2CPP_ASSERT(iter != s_ThreadLocalStaticOffsetMap.end());
return iter->second;
}
Il2CppMetadataCustomAttributeHandle il2cpp::vm::MetadataCache::GetCustomAttributeTypeToken(const Il2CppImage* image, uint32_t token)
{
return il2cpp::vm::GlobalMetadata::GetCustomAttributeTypeToken(image, token);
}
const Il2CppAssembly* il2cpp::vm::MetadataCache::GetReferencedAssembly(const Il2CppAssembly* assembly, int32_t referencedAssemblyTableIndex)
{
return il2cpp::vm::GlobalMetadata::GetReferencedAssembly(assembly, referencedAssemblyTableIndex, s_AssembliesTable, s_AssembliesCount);
}
CustomAttributesCache* il2cpp::vm::MetadataCache::GenerateCustomAttributesCache(Il2CppMetadataCustomAttributeHandle handle)
{
return il2cpp::vm::GlobalMetadata::GenerateCustomAttributesCache(handle);
}
CustomAttributesCache* il2cpp::vm::MetadataCache::GenerateCustomAttributesCache(const Il2CppImage* image, uint32_t token)
{
return il2cpp::vm::GlobalMetadata::GenerateCustomAttributesCache(image, token);
}
bool il2cpp::vm::MetadataCache::HasAttribute(Il2CppMetadataCustomAttributeHandle token, Il2CppClass* attribute)
{
return il2cpp::vm::GlobalMetadata::HasAttribute(token, attribute);
}
bool il2cpp::vm::MetadataCache::HasAttribute(const Il2CppImage* image, uint32_t token, Il2CppClass* attribute)
{
return il2cpp::vm::GlobalMetadata::HasAttribute(image, token, attribute);
}
void il2cpp::vm::MetadataCache::InitializeAllMethodMetadata()
{
il2cpp::vm::GlobalMetadata::InitializeAllMethodMetadata();
}
void* il2cpp::vm::MetadataCache::InitializeRuntimeMetadata(uintptr_t* metadataPointer)
{
return il2cpp::vm::GlobalMetadata::InitializeRuntimeMetadata(metadataPointer, true);
}
void il2cpp::vm::MetadataCache::WalkPointerTypes(WalkTypesCallback callback, void* context)
{
il2cpp::os::FastAutoLock lock(&s_MetadataCache.m_CacheMutex);
for (PointerTypeMap::iterator it = s_MetadataCache.m_PointerTypes.begin(); it != s_MetadataCache.m_PointerTypes.end(); it++)
{
callback(it->second, context);
}
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetTypeHandleFromIndex(const Il2CppImage* image, TypeDefinitionIndex typeIndex)
{
return il2cpp::vm::GlobalMetadata::GetTypeHandleFromIndex(typeIndex);
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetTypeHandleFromType(const Il2CppType* type)
{
return il2cpp::vm::GlobalMetadata::GetTypeHandleFromType(type);
}
bool il2cpp::vm::MetadataCache::TypeIsNested(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::TypeIsNested(handle);
}
bool il2cpp::vm::MetadataCache::TypeIsValueType(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::TypeIsValueType(handle);
}
bool il2cpp::vm::MetadataCache::StructLayoutPackIsDefault(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::StructLayoutPackIsDefault(handle);
}
int32_t il2cpp::vm::MetadataCache::StructLayoutPack(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::StructLayoutPack(handle);
}
bool il2cpp::vm::MetadataCache::StructLayoutSizeIsDefault(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::StructLayoutSizeIsDefault(handle);
}
std::pair<const char*, const char*> il2cpp::vm::MetadataCache::GetTypeNamespaceAndName(Il2CppMetadataTypeHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetTypeNamespaceAndName(handle);
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetNestedTypes(Il2CppClass *klass, void* *iter)
{
return GetNestedTypes(
klass->typeMetadataHandle,
iter
);
}
Il2CppMetadataTypeHandle il2cpp::vm::MetadataCache::GetNestedTypes(Il2CppMetadataTypeHandle handle, void** iter)
{
return il2cpp::vm::GlobalMetadata::GetNestedTypes(handle, iter);
}
Il2CppMetadataFieldInfo il2cpp::vm::MetadataCache::GetFieldInfo(const Il2CppClass* klass, TypeFieldIndex fieldIndex)
{
return il2cpp::vm::GlobalMetadata::GetFieldInfo(klass, fieldIndex);
}
Il2CppMetadataMethodInfo il2cpp::vm::MetadataCache::GetMethodInfo(const Il2CppClass* klass, TypeMethodIndex index)
{
return il2cpp::vm::GlobalMetadata::GetMethodInfo(klass, index);
}
Il2CppMetadataParameterInfo il2cpp::vm::MetadataCache::GetParameterInfo(const Il2CppClass* klass, Il2CppMetadataMethodDefinitionHandle handle, MethodParameterIndex paramIndex)
{
return il2cpp::vm::GlobalMetadata::GetParameterInfo(klass, handle, paramIndex);
}
Il2CppMetadataPropertyInfo il2cpp::vm::MetadataCache::GetPropertyInfo(const Il2CppClass* klass, TypePropertyIndex index)
{
return il2cpp::vm::GlobalMetadata::GetPropertyInfo(klass, index);
}
Il2CppMetadataEventInfo il2cpp::vm::MetadataCache::GetEventInfo(const Il2CppClass* klass, TypeEventIndex index)
{
return il2cpp::vm::GlobalMetadata::GetEventInfo(klass, index);
}
uint32_t il2cpp::vm::MetadataCache::GetGenericContainerCount(Il2CppMetadataGenericContainerHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericContainerCount(handle);
}
void il2cpp::vm::MetadataCache::MakeGenericArgType(Il2CppMetadataGenericContainerHandle containerHandle, Il2CppMetadataGenericParameterHandle paramHandle, Il2CppType* arg)
{
return il2cpp::vm::GlobalMetadata::MakeGenericArgType(containerHandle, paramHandle, arg);
}
bool il2cpp::vm::MetadataCache::GetGenericContainerIsMethod(Il2CppMetadataGenericContainerHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericContainerIsMethod(handle);
}
int16_t il2cpp::vm::MetadataCache::GetGenericConstraintCount(Il2CppMetadataGenericParameterHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericConstraintCount(handle);
}
const char* il2cpp::vm::MetadataCache::GetGenericParameterName(Il2CppMetadataGenericParameterHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterName(handle);
}
Il2CppGenericParameterInfo il2cpp::vm::MetadataCache::GetGenericParameterInfo(Il2CppMetadataGenericParameterHandle handle)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterInfo(handle);
}
uint16_t il2cpp::vm::MetadataCache::GetGenericParameterFlags(Il2CppMetadataGenericContainerHandle handle, GenericContainerParameterIndex index)
{
return il2cpp::vm::GlobalMetadata::GetGenericParameterFlags(handle, index);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetMethodInfoFromCatchPoint(const Il2CppImage* image, const Il2CppCatchPoint* cp)
{
return il2cpp::vm::GlobalMetadata::GetMethodInfoFromCatchPoint(cp);
}
const MethodInfo* il2cpp::vm::MetadataCache::GetMethodInfoFromSequencePoint(const Il2CppImage* image, const Il2CppSequencePoint* seqPoint)
{
return il2cpp::vm::GlobalMetadata::GetMethodInfoFromSequencePoint(seqPoint);
}
Il2CppClass* il2cpp::vm::MetadataCache::GetTypeInfoFromTypeSourcePair(const Il2CppImage* image, const Il2CppTypeSourceFilePair* pair)
{
return il2cpp::vm::GlobalMetadata::GetTypeInfoFromTypeSourcePair(pair);
}
| 38.7247
| 263
| 0.745111
|
kyungyeon-lee
|
733c8797b7d490c0cb4abba5650afa543337c98c
| 9,867
|
cpp
|
C++
|
code/appLoadingFunctions.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
code/appLoadingFunctions.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
code/appLoadingFunctions.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
/*
File: appLoadingFunctions.cpp
Author: Taylor Robbins
Date: 06\13\2017
Description:
** Includes a collection of functions that manage loading
** various sorts of resources
*/
Texture_t CreateTexture(const u8* bitmapData, i32 width, i32 height, bool pixelated = false, bool repeat = true)
{
Texture_t result = {};
result.width = width;
result.height = height;
glGenTextures(1, &result.id);
glBindTexture(GL_TEXTURE_2D, result.id);
glTexImage2D(
GL_TEXTURE_2D, //bound texture type
0, //image level
GL_RGBA, //internal format
width, //image width
width, //image height
0, //border
GL_RGBA, //format
GL_UNSIGNED_BYTE, //type
bitmapData); //data
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, pixelated ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, pixelated ? GL_NEAREST : GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glGenerateMipmap(GL_TEXTURE_2D);
return result;
}
void DestroyTexture(Texture_t* texturePntr)
{
Assert(texturePntr != nullptr);
glDeleteTextures(1, &texturePntr->id);
ClearPointer(texturePntr);
}
VertexBuffer_t CreateVertexBuffer(const Vertex_t* vertices, u32 numVertices)
{
VertexBuffer_t result = {};
result.numVertices = numVertices;
glGenBuffers(1, &result.id);
glBindBuffer(GL_ARRAY_BUFFER, result.id);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex_t) * numVertices, vertices, GL_STATIC_DRAW);
return result;
}
FrameBuffer_t CreateFrameBuffer(const Texture_t* texture)
{
FrameBuffer_t result = {};
glGenFramebuffers(1, &result.id);
glBindFramebuffer(GL_FRAMEBUFFER, result.id);
glGenRenderbuffers(1, &result.depthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, result.depthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, texture->width, texture->height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, result.depthBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture->id, 0);
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers);
result.renderTexture = texture;
return result;
}
Shader_t LoadShader(const char* vertShaderFileName, const char* fragShaderFileName)
{
Shader_t result = {};
GLint compiled;
int logLength;
char* logBuffer;
Assert(true);
FileInfo_t vertexShaderFile = platform->ReadEntireFile(vertShaderFileName);
FileInfo_t fragmentShaderFile = platform->ReadEntireFile(fragShaderFileName);
result.vertId = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(result.vertId, 1, (const char* const*)&vertexShaderFile.content, NULL);
glCompileShader(result.vertId);
glGetShaderiv(result.vertId, GL_COMPILE_STATUS, &compiled);
glGetShaderiv(result.vertId, GL_INFO_LOG_LENGTH, &logLength);
DEBUG_PrintLine("%s: Compiled %s : %d byte log",
vertShaderFileName, compiled ? "Successfully" : "Unsuccessfully", logLength);
if (logLength > 0)
{
logBuffer = TempString(logLength+1);
logBuffer[logLength] = '\0';
glGetShaderInfoLog(result.vertId, logLength, NULL, logBuffer);
DEBUG_PrintLine("Log: \"%s\"", logBuffer);
}
result.fragId = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(result.fragId, 1, (const char* const*)&fragmentShaderFile.content, NULL);
glCompileShader(result.fragId);
glGetShaderiv(result.fragId, GL_COMPILE_STATUS, &compiled);
glGetShaderiv(result.fragId, GL_INFO_LOG_LENGTH, &logLength);
DEBUG_PrintLine("%s: Compiled %s : %d byte log",
fragShaderFileName, compiled ? "Successfully" : "Unsuccessfully", logLength);
if (logLength > 0)
{
logBuffer = TempString(logLength+1);
logBuffer[logLength] = '\0';
glGetShaderInfoLog(result.fragId, logLength, NULL, logBuffer);
DEBUG_PrintLine("Log: \"%s\"", logBuffer);
}
platform->FreeFileMemory(&vertexShaderFile);
platform->FreeFileMemory(&fragmentShaderFile);
result.programId = glCreateProgram();
glAttachShader(result.programId, result.fragId);
glAttachShader(result.programId, result.vertId);
glLinkProgram(result.programId);
glGetProgramiv(result.programId, GL_LINK_STATUS, &compiled);
glGetProgramiv(result.programId, GL_INFO_LOG_LENGTH, &logLength);
DEBUG_PrintLine("Shader: Linked %s : %d byte log",
compiled ? "Successfully" : "Unsuccessfully", logLength);
if (logLength > 0)
{
logBuffer = TempString(logLength+1);
logBuffer[logLength] = '\0';
glGetProgramInfoLog(result.programId, logLength, NULL, logBuffer);
DEBUG_PrintLine("Log: \"%s\"", logBuffer);
}
result.locations.positionAttrib = glGetAttribLocation(result.programId, "inPosition");
result.locations.colorAttrib = glGetAttribLocation(result.programId, "inColor");
result.locations.texCoordAttrib = glGetAttribLocation(result.programId, "inTexCoord");
result.locations.worldMatrix = glGetUniformLocation(result.programId, "WorldMatrix");
result.locations.viewMatrix = glGetUniformLocation(result.programId, "ViewMatrix");
result.locations.projectionMatrix = glGetUniformLocation(result.programId, "ProjectionMatrix");
result.locations.diffuseTexture = glGetUniformLocation(result.programId, "DiffuseTexture");
result.locations.alphaTexture = glGetUniformLocation(result.programId, "AlphaTexture");
result.locations.diffuseColor = glGetUniformLocation(result.programId, "DiffuseColor");
result.locations.secondaryColor = glGetUniformLocation(result.programId, "SecondaryColor");
result.locations.doGrayscaleGradient = glGetUniformLocation(result.programId, "DoGrayscaleGradient");
result.locations.sourceRectangle = glGetUniformLocation(result.programId, "SourceRectangle");
result.locations.useAlphaTexture = glGetUniformLocation(result.programId, "UseAlphaTexture");
result.locations.textureSize = glGetUniformLocation(result.programId, "TextureSize");
result.locations.circleRadius = glGetUniformLocation(result.programId, "CircleRadius");
result.locations.circleInnerRadius = glGetUniformLocation(result.programId, "CircleInnerRadius");
glGenVertexArrays(1, &result.vertexArray);
glBindVertexArray(result.vertexArray);
glEnableVertexAttribArray(result.locations.positionAttrib);
glEnableVertexAttribArray(result.locations.colorAttrib);
glEnableVertexAttribArray(result.locations.texCoordAttrib);
return result;
}
Texture_t LoadTexture(const char* fileName, bool pixelated = false, bool repeat = true)
{
Texture_t result = {};
FileInfo_t textureFile = platform->ReadEntireFile(fileName);
i32 numChannels;
i32 width, height;
u8* imageData = stbi_load_from_memory(
(u8*)textureFile.content, textureFile.size,
&width, &height, &numChannels, 4);
result = CreateTexture(imageData, width, height, pixelated, repeat);
stbi_image_free(imageData);
platform->FreeFileMemory(&textureFile);
return result;
}
Font_t LoadFont(const char* fileName,
r32 fontSize, i32 bitmapWidth, i32 bitmapHeight,
u8 firstCharacter, u8 numCharacters)
{
Font_t result = {};
FileInfo_t fontFile = platform->ReadEntireFile(fileName);
result.numChars = numCharacters;
result.firstChar = firstCharacter;
result.fontSize = fontSize;
TempPushMark();
u8* grayscaleData = TempArray(u8, bitmapWidth * bitmapHeight);
stbtt_bakedchar* charInfos = TempArray(stbtt_bakedchar, numCharacters);
int bakeResult = stbtt_BakeFontBitmap((u8*)fontFile.content,
0, fontSize,
grayscaleData, bitmapWidth, bitmapHeight,
firstCharacter, numCharacters, charInfos);
DEBUG_PrintLine("STB Bake Result: %d", bakeResult);
for (u8 cIndex = 0; cIndex < numCharacters; cIndex++)
{
result.chars[cIndex].position = NewVec2i(
charInfos[cIndex].x0,
charInfos[cIndex].y0);
result.chars[cIndex].size = NewVec2i(
charInfos[cIndex].x1 - charInfos[cIndex].x0,
charInfos[cIndex].y1 - charInfos[cIndex].y0);
result.chars[cIndex].offset = NewVec2(
charInfos[cIndex].xoff,
charInfos[cIndex].yoff);
result.chars[cIndex].advanceX = charInfos[cIndex].xadvance;
}
u8* bitmapData = TempArray(u8, 4 * bitmapWidth * bitmapHeight);
for (i32 y = 0; y < bitmapHeight; y++)
{
for (i32 x = 0; x < bitmapWidth; x++)
{
u8 grayscaleValue = grayscaleData[y*bitmapWidth + x];
bitmapData[(y*bitmapWidth+x)*4 + 0] = 255;
bitmapData[(y*bitmapWidth+x)*4 + 1] = 255;
bitmapData[(y*bitmapWidth+x)*4 + 2] = 255;
bitmapData[(y*bitmapWidth+x)*4 + 3] = grayscaleValue;
}
}
result.bitmap = CreateTexture(bitmapData, bitmapWidth, bitmapHeight);
TempPopMark();
platform->FreeFileMemory(&fontFile);
//Create information about character sizes
{
v2 maxSize = Vec2_Zero;
v2 extendVertical = Vec2_Zero;
for (u32 cIndex = 0; cIndex < result.numChars; cIndex++)
{
FontCharInfo_t* charInfo = &result.chars[cIndex];
if (charInfo->height > maxSize.y)
maxSize.y = (r32)charInfo->height;
if (-charInfo->offset.y > extendVertical.x)
extendVertical.x = -charInfo->offset.y;
if (charInfo->offset.y + charInfo->height > extendVertical.y)
extendVertical.y = charInfo->offset.y + charInfo->height;
if (charInfo->advanceX > maxSize.x)
maxSize.x = charInfo->advanceX;
}
result.maxCharWidth = maxSize.x;
result.maxCharHeight = maxSize.y;
result.maxExtendUp = extendVertical.x;
result.maxExtendDown = extendVertical.y;
result.lineHeight = result.maxExtendDown + result.maxExtendUp;
}
return result;
}
| 34.5
| 120
| 0.752711
|
robbitay
|
733cf1f9b05d617a436002d68ecd1486efd5695d
| 26,075
|
cc
|
C++
|
engines/ep/tests/module_tests/evp_store_durability_test.cc
|
gsauere/kv_engine
|
233945fe4ddb033c2292e51f5845ab630c33276f
|
[
"BSD-3-Clause"
] | null | null | null |
engines/ep/tests/module_tests/evp_store_durability_test.cc
|
gsauere/kv_engine
|
233945fe4ddb033c2292e51f5845ab630c33276f
|
[
"BSD-3-Clause"
] | null | null | null |
engines/ep/tests/module_tests/evp_store_durability_test.cc
|
gsauere/kv_engine
|
233945fe4ddb033c2292e51f5845ab630c33276f
|
[
"BSD-3-Clause"
] | null | null | null |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "evp_store_durability_test.h"
#include "../mock/mock_synchronous_ep_engine.h"
#include "checkpoint_utils.h"
#include "test_helpers.h"
#include <programs/engine_testapp/mock_server.h>
class DurabilityEPBucketTest : public STParameterizedBucketTest {
protected:
void SetUp() {
STParameterizedBucketTest::SetUp();
// Add an initial replication topology so we can accept SyncWrites.
setVBucketToActiveWithValidTopology();
}
void setVBucketToActiveWithValidTopology(
nlohmann::json topology = nlohmann::json::array({{"active",
"replica"}})) {
setVBucketStateAndRunPersistTask(
vbid, vbucket_state_active, {{"topology", topology}});
}
/// Test that a prepare of a SyncWrite / SyncDelete is correctly persisted
/// to disk.
void testPersistPrepare(DocumentState docState);
/// Test that a prepare of a SyncWrite / SyncDelete, which is then aborted
/// is correctly persisted to disk.
void testPersistPrepareAbort(DocumentState docState);
/**
* Test that if a single key is prepared, aborted & re-prepared it is the
* second Prepare which is kept on disk.
* @param docState State to use for the second prepare (first is always
* state alive).
*/
void testPersistPrepareAbortPrepare(DocumentState docState);
/**
* Test that if a single key is prepared, aborted re-prepared & re-aborted
* it is the second Abort which is kept on disk.
* @param docState State to use for the second prepare (first is always
* state alive).
*/
void testPersistPrepareAbortX2(DocumentState docState);
};
class DurabilityBucketTest : public STParameterizedBucketTest {
protected:
template <typename F>
void testDurabilityInvalidLevel(F& func);
};
void DurabilityEPBucketTest::testPersistPrepare(DocumentState docState) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
auto key = makeStoredDocKey("key");
auto committed = makeCommittedItem(key, "valueA");
ASSERT_EQ(ENGINE_SUCCESS, store->set(*committed, cookie));
auto& vb = *store->getVBucket(vbid);
flushVBucketToDiskIfPersistent(vbid, 1);
ASSERT_EQ(1, vb.getNumItems());
auto pending = makePendingItem(key, "valueB");
if (docState == DocumentState::Deleted) {
pending->setDeleted(DeleteSource::Explicit);
}
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
const auto& ckptMgr = *store->getVBucket(vbid)->checkpointManager;
ASSERT_EQ(1, ckptMgr.getNumItemsForPersistence());
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
ckptMgr);
// Committed and Pending will be split into two checkpoints:
ASSERT_EQ(2, ckptList.size());
const auto& stats = engine->getEpStats();
ASSERT_EQ(1, stats.diskQueueSize);
// Item must be flushed
flushVBucketToDiskIfPersistent(vbid, 1);
// Item must have been removed from the disk queue
EXPECT_EQ(0, ckptMgr.getNumItemsForPersistence());
EXPECT_EQ(0, stats.diskQueueSize);
// The item count must not increase when flushing Pending SyncWrites
EXPECT_EQ(1, vb.getNumItems());
// @TODO RocksDB
// @TODO Durability
// TSan sporadically reports a data race when calling store->get below when
// running this test under RocksDB. Manifests for both full and value
// eviction but only seen after adding full eviction variants for this test.
// Might be the case that running the couchstore full eviction variant
// beforehand is breaking something.
#ifdef THREAD_SANITIZER
auto bucketType = std::get<0>(GetParam());
if (bucketType == "persistentRocksdb") {
return;
}
#endif
// Check the committed item on disk.
auto* store = vb.getShard()->getROUnderlying();
auto gv = store->get(DiskDocKey(key), Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_EQ(*committed, *gv.item);
// Check the Prepare on disk
DiskDocKey prefixedKey(key, true /*prepare*/);
gv = store->get(prefixedKey, Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_TRUE(gv.item->isPending());
EXPECT_EQ(docState == DocumentState::Deleted, gv.item->isDeleted());
}
TEST_P(DurabilityEPBucketTest, PersistPrepareWrite) {
testPersistPrepare(DocumentState::Alive);
}
TEST_P(DurabilityEPBucketTest, PersistPrepareDelete) {
testPersistPrepare(DocumentState::Deleted);
}
void DurabilityEPBucketTest::testPersistPrepareAbort(DocumentState docState) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
auto& vb = *store->getVBucket(vbid);
ASSERT_EQ(0, vb.getNumItems());
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
if (docState == DocumentState::Deleted) {
pending->setDeleted(DeleteSource::Explicit);
}
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
// A Prepare doesn't account in curr-items
ASSERT_EQ(0, vb.getNumItems());
{
auto res = vb.ht.findForWrite(key);
ASSERT_TRUE(res.storedValue);
ASSERT_EQ(CommittedState::Pending, res.storedValue->getCommitted());
ASSERT_EQ(1, res.storedValue->getBySeqno());
}
const auto& stats = engine->getEpStats();
ASSERT_EQ(1, stats.diskQueueSize);
const auto& ckptMgr = *store->getVBucket(vbid)->checkpointManager;
ASSERT_EQ(1, ckptMgr.getNumItemsForPersistence());
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
ckptMgr);
ASSERT_EQ(1, ckptList.size());
ASSERT_EQ(checkpoint_state::CHECKPOINT_OPEN, ckptList.front()->getState());
ASSERT_EQ(1, ckptList.front()->getNumItems());
ASSERT_EQ(1,
(*(--ckptList.front()->end()))->getOperation() ==
queue_op::pending_sync_write);
ASSERT_EQ(ENGINE_SUCCESS,
vb.abort(key,
{} /*abortSeqno*/,
vb.lockCollections(key)));
// We do not deduplicate Prepare and Abort (achieved by inserting them into
// 2 different checkpoints)
ASSERT_EQ(2, ckptList.size());
ASSERT_EQ(checkpoint_state::CHECKPOINT_OPEN, ckptList.back()->getState());
ASSERT_EQ(1, ckptList.back()->getNumItems());
ASSERT_EQ(1,
(*(--ckptList.back()->end()))->getOperation() ==
queue_op::abort_sync_write);
EXPECT_EQ(2, ckptMgr.getNumItemsForPersistence());
EXPECT_EQ(2, stats.diskQueueSize);
// Note: Prepare and Abort are in the same key-space, so they will be
// deduplicated at Flush
flushVBucketToDiskIfPersistent(vbid, 1);
EXPECT_EQ(0, vb.getNumItems());
EXPECT_EQ(0, ckptMgr.getNumItemsForPersistence());
EXPECT_EQ(0, stats.diskQueueSize);
// At persist-dedup, the Abort survives
auto* store = vb.getShard()->getROUnderlying();
DiskDocKey prefixedKey(key, true /*pending*/);
auto gv = store->get(prefixedKey, Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_TRUE(gv.item->isAbort());
EXPECT_TRUE(gv.item->isDeleted());
}
TEST_P(DurabilityEPBucketTest, PersistPrepareWriteAbort) {
testPersistPrepareAbort(DocumentState::Alive);
}
TEST_P(DurabilityEPBucketTest, PersistPrepareDeleteAbort) {
testPersistPrepareAbort(DocumentState::Deleted);
}
void DurabilityEPBucketTest::testPersistPrepareAbortPrepare(
DocumentState docState) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
auto& vb = *store->getVBucket(vbid);
// First prepare (always a SyncWrite) and abort.
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
ASSERT_EQ(ENGINE_SUCCESS,
vb.abort(key,
{} /*abortSeqno*/,
vb.lockCollections(key)));
// Second prepare.
auto pending2 = makePendingItem(key, "value2");
if (docState == DocumentState::Deleted) {
pending2->setDeleted(DeleteSource::Explicit);
}
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending2, cookie));
// We do not deduplicate Prepare and Abort (achieved by inserting them into
// different checkpoints)
const auto& ckptMgr = *store->getVBucket(vbid)->checkpointManager;
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
ckptMgr);
ASSERT_EQ(3, ckptList.size());
ASSERT_EQ(1, ckptList.back()->getNumItems());
ASSERT_EQ(1,
(*(--ckptList.back()->end()))->getOperation() ==
queue_op::pending_sync_write);
EXPECT_EQ(3, ckptMgr.getNumItemsForPersistence());
// Note: Prepare and Abort are in the same key-space, so they will be
// deduplicated at Flush
flushVBucketToDiskIfPersistent(vbid, 1);
// At persist-dedup, the 2nd Prepare survives
auto* store = vb.getShard()->getROUnderlying();
DiskDocKey prefixedKey(key, true /*pending*/);
auto gv = store->get(prefixedKey, Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_TRUE(gv.item->isPending());
EXPECT_EQ(docState == DocumentState::Deleted, gv.item->isDeleted());
EXPECT_EQ(pending2->getBySeqno(), gv.item->getBySeqno());
}
TEST_P(DurabilityEPBucketTest, PersistPrepareAbortPrepare) {
testPersistPrepareAbortPrepare(DocumentState::Alive);
}
TEST_P(DurabilityEPBucketTest, PersistPrepareAbortPrepareDelete) {
testPersistPrepareAbortPrepare(DocumentState::Deleted);
}
void DurabilityEPBucketTest::testPersistPrepareAbortX2(DocumentState docState) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
auto& vb = *store->getVBucket(vbid);
// First prepare and abort.
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
ASSERT_EQ(ENGINE_SUCCESS,
vb.abort(key,
{} /*abortSeqno*/,
vb.lockCollections(key)));
// Second prepare and abort.
auto pending2 = makePendingItem(key, "value2");
if (docState == DocumentState::Deleted) {
pending2->setDeleted(DeleteSource::Explicit);
}
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending2, cookie));
ASSERT_EQ(ENGINE_SUCCESS,
vb.abort(key,
{} /*abortSeqno*/,
vb.lockCollections(key)));
// We do not deduplicate Prepare and Abort (achieved by inserting them into
// different checkpoints)
const auto& ckptMgr = *store->getVBucket(vbid)->checkpointManager;
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
ckptMgr);
ASSERT_EQ(4, ckptList.size());
ASSERT_EQ(1, ckptList.back()->getNumItems());
ASSERT_EQ(1,
(*(--ckptList.back()->end()))->getOperation() ==
queue_op::abort_sync_write);
EXPECT_EQ(4, ckptMgr.getNumItemsForPersistence());
// Note: Prepare and Abort are in the same key-space and hence are
// deduplicated at Flush.
flushVBucketToDiskIfPersistent(vbid, 1);
// At persist-dedup, the 2nd Abort survives
auto* store = vb.getShard()->getROUnderlying();
DiskDocKey prefixedKey(key, true /*pending*/);
auto gv = store->get(prefixedKey, Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_TRUE(gv.item->isAbort());
EXPECT_TRUE(gv.item->isDeleted());
EXPECT_EQ(pending2->getBySeqno() + 1, gv.item->getBySeqno());
}
TEST_P(DurabilityEPBucketTest, PersistPrepareAbortx2) {
testPersistPrepareAbortX2(DocumentState::Alive);
}
TEST_P(DurabilityEPBucketTest, PersistPrepareAbortPrepareDeleteAbort) {
testPersistPrepareAbortX2(DocumentState::Deleted);
}
/// Test persistence of a prepared & committed SyncWrite, followed by a
/// prepared & committed SyncDelete.
TEST_P(DurabilityEPBucketTest, PersistSyncWriteSyncDelete) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
auto& vb = *store->getVBucket(vbid);
// prepare SyncWrite and commit.
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
ASSERT_EQ(ENGINE_SUCCESS,
vb.commit(key,
{} /*commitSeqno*/,
vb.lockCollections(key)));
// We do not deduplicate Prepare and Commit in CheckpointManager (achieved
// by inserting them into different checkpoints)
const auto& ckptMgr = *store->getVBucket(vbid)->checkpointManager;
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
ckptMgr);
ASSERT_EQ(2, ckptList.size());
ASSERT_EQ(1, ckptList.back()->getNumItems());
EXPECT_EQ(2, ckptMgr.getNumItemsForPersistence());
// Note: Prepare and Commit are not in the same key-space and hence are not
// deduplicated at Flush.
flushVBucketToDiskIfPersistent(vbid, 2);
// prepare SyncDelete and commit.
uint64_t cas = 0;
using namespace cb::durability;
auto reqs = Requirements(Level::Majority, {});
mutation_descr_t delInfo;
ASSERT_EQ(
ENGINE_EWOULDBLOCK,
store->deleteItem(key, cas, vbid, cookie, reqs, nullptr, delInfo));
ASSERT_EQ(3, ckptList.size());
ASSERT_EQ(1, ckptList.back()->getNumItems());
EXPECT_EQ(1, ckptMgr.getNumItemsForPersistence());
flushVBucketToDiskIfPersistent(vbid, 1);
ASSERT_EQ(ENGINE_SUCCESS,
vb.commit(key,
{} /*commitSeqno*/,
vb.lockCollections(key)));
ASSERT_EQ(4, ckptList.size());
ASSERT_EQ(1, ckptList.back()->getNumItems());
EXPECT_EQ(1, ckptMgr.getNumItemsForPersistence());
flushVBucketToDiskIfPersistent(vbid, 1);
// At persist-dedup, the 2nd Prepare and Commit survive.
auto* store = vb.getShard()->getROUnderlying();
auto gv = store->get(DiskDocKey(key), Vbid(0));
EXPECT_EQ(ENGINE_SUCCESS, gv.getStatus());
EXPECT_TRUE(gv.item->isCommitted());
EXPECT_TRUE(gv.item->isDeleted());
EXPECT_EQ(delInfo.seqno + 1, gv.item->getBySeqno());
}
TEST_P(DurabilityEPBucketTest, ActiveLocalNotifyPersistedSeqno) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
const cb::durability::Requirements reqs = {
cb::durability::Level::PersistToMajority, {}};
for (uint8_t seqno = 1; seqno <= 3; seqno++) {
auto item = makePendingItem(
makeStoredDocKey("key" + std::to_string(seqno)), "value", reqs);
ASSERT_EQ(ENGINE_EWOULDBLOCK, store->set(*item, cookie));
}
const auto& vb = store->getVBucket(vbid);
const auto& ckptList =
CheckpointManagerTestIntrospector::public_getCheckpointList(
*vb->checkpointManager);
auto checkPending = [&ckptList]() -> void {
ASSERT_EQ(1, ckptList.size());
const auto& ckpt = *ckptList.front();
EXPECT_EQ(3, ckpt.getNumItems());
for (const auto& qi : ckpt) {
if (!qi->isCheckPointMetaItem()) {
EXPECT_EQ(queue_op::pending_sync_write, qi->getOperation());
}
}
};
// No replica has ack'ed yet
checkPending();
// Replica acks disk-seqno
EXPECT_EQ(ENGINE_SUCCESS,
vb->seqnoAcknowledged("replica", 3 /*preparedSeqno*/));
// Active has not persisted, so Durability Requirements not satisfied yet
checkPending();
// Flusher runs on Active. This:
// - persists all pendings
// - and notifies local DurabilityMonitor of persistence
flushVBucketToDiskIfPersistent(vbid, 3);
// When seqno:1 is persisted:
//
// - the Flusher notifies the local DurabilityMonitor
// - seqno:1 is satisfied, so it is committed
// - the open checkpoint containes the seqno:1:prepare, so it is closed and
// seqno:1:committed is enqueued in a new open checkpoint (that is how
// we avoid SyncWrite de-duplication currently)
// - the next committed seqnos are enqueued into the same open checkpoint
//
// So after Flush we have 2 checkpoints: the first (closed) containing only
// pending SWs and the second (open) containing only committed SWs
ASSERT_EQ(2, ckptList.size());
// Remove the closed checkpoint (that makes the check on Committed easier)
bool newOpenCkptCreated{false};
vb->checkpointManager->removeClosedUnrefCheckpoints(*vb,
newOpenCkptCreated);
ASSERT_FALSE(newOpenCkptCreated);
// Durability Requirements satisfied, all committed
ASSERT_EQ(1, ckptList.size());
const auto& ckpt = *ckptList.front();
EXPECT_EQ(3, ckpt.getNumItems());
for (const auto& qi : ckpt) {
if (!qi->isCheckPointMetaItem()) {
EXPECT_EQ(queue_op::commit_sync_write, qi->getOperation());
}
}
}
TEST_P(DurabilityEPBucketTest, SetDurabilityImpossible) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology",
nlohmann::json::array({{"active", nullptr, nullptr}})}});
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
EXPECT_EQ(ENGINE_DURABILITY_IMPOSSIBLE, store->set(*pending, cookie));
auto item = makeCommittedItem(key, "value");
EXPECT_NE(ENGINE_DURABILITY_IMPOSSIBLE, store->set(*item, cookie));
}
TEST_P(DurabilityEPBucketTest, AddDurabilityImpossible) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology",
nlohmann::json::array({{"active", nullptr, nullptr}})}});
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
EXPECT_EQ(ENGINE_DURABILITY_IMPOSSIBLE, store->add(*pending, cookie));
auto item = makeCommittedItem(key, "value");
EXPECT_NE(ENGINE_DURABILITY_IMPOSSIBLE, store->add(*item, cookie));
}
TEST_P(DurabilityEPBucketTest, ReplaceDurabilityImpossible) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology",
nlohmann::json::array({{"active", nullptr, nullptr}})}});
auto key = makeStoredDocKey("key");
auto pending = makePendingItem(key, "value");
EXPECT_EQ(ENGINE_DURABILITY_IMPOSSIBLE, store->replace(*pending, cookie));
auto item = makeCommittedItem(key, "value");
EXPECT_NE(ENGINE_DURABILITY_IMPOSSIBLE, store->replace(*item, cookie));
}
TEST_P(DurabilityEPBucketTest, DeleteDurabilityImpossible) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology",
nlohmann::json::array({{"active", nullptr, nullptr}})}});
auto key = makeStoredDocKey("key");
uint64_t cas = 0;
mutation_descr_t mutation_descr;
cb::durability::Requirements durabilityRequirements;
durabilityRequirements.setLevel(cb::durability::Level::Majority);
EXPECT_EQ(ENGINE_DURABILITY_IMPOSSIBLE,
store->deleteItem(key,
cas,
vbid,
cookie,
durabilityRequirements,
nullptr,
mutation_descr));
durabilityRequirements.setLevel(cb::durability::Level::None);
EXPECT_NE(ENGINE_DURABILITY_IMPOSSIBLE,
store->deleteItem(key,
cas,
vbid,
cookie,
durabilityRequirements,
nullptr,
mutation_descr));
}
template <typename F>
void DurabilityBucketTest::testDurabilityInvalidLevel(F& func) {
setVBucketStateAndRunPersistTask(vbid, vbucket_state_active);
auto key = makeStoredDocKey("key");
using namespace cb::durability;
auto reqs = Requirements(Level::Majority, {});
auto pending = makePendingItem(key, "value", reqs);
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, func(pending, cookie));
reqs = Requirements(Level::MajorityAndPersistOnMaster, {});
pending = makePendingItem(key, "value", reqs);
if (persistent()) {
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, func(pending, cookie));
} else {
EXPECT_EQ(ENGINE_DURABILITY_INVALID_LEVEL, func(pending, cookie));
}
reqs = Requirements(Level::PersistToMajority, {});
pending = makePendingItem(key, "value", reqs);
if (persistent()) {
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, func(pending, cookie));
} else {
EXPECT_EQ(ENGINE_DURABILITY_INVALID_LEVEL, func(pending, cookie));
}
}
TEST_P(DurabilityBucketTest, SetDurabilityInvalidLevel) {
auto op = [this](queued_item pending,
const void* cookie) -> ENGINE_ERROR_CODE {
return store->set(*pending, cookie);
};
testDurabilityInvalidLevel(op);
}
TEST_P(DurabilityBucketTest, AddDurabilityInvalidLevel) {
auto op = [this](queued_item pending,
const void* cookie) -> ENGINE_ERROR_CODE {
return store->add(*pending, cookie);
};
testDurabilityInvalidLevel(op);
}
TEST_P(DurabilityBucketTest, ReplaceDurabilityInvalidLevel) {
auto op = [this](queued_item pending,
const void* cookie) -> ENGINE_ERROR_CODE {
return store->replace(*pending, cookie);
};
testDurabilityInvalidLevel(op);
}
TEST_P(DurabilityBucketTest, DeleteDurabilityInvalidLevel) {
setVBucketStateAndRunPersistTask(vbid, vbucket_state_active);
using namespace cb::durability;
auto durabilityRequirements = Requirements(Level::Majority, {});
auto del = [this](cb::durability::Requirements requirements)
-> ENGINE_ERROR_CODE {
auto key = makeStoredDocKey("key");
uint64_t cas = 0;
mutation_descr_t mutation_descr;
return store->deleteItem(
key, cas, vbid, cookie, requirements, nullptr, mutation_descr);
};
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, del(durabilityRequirements));
durabilityRequirements =
Requirements(Level::MajorityAndPersistOnMaster, {});
if (persistent()) {
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, del(durabilityRequirements));
} else {
EXPECT_EQ(ENGINE_DURABILITY_INVALID_LEVEL, del(durabilityRequirements));
}
durabilityRequirements = Requirements(Level::PersistToMajority, {});
if (persistent()) {
EXPECT_NE(ENGINE_DURABILITY_INVALID_LEVEL, del(durabilityRequirements));
} else {
EXPECT_EQ(ENGINE_DURABILITY_INVALID_LEVEL, del(durabilityRequirements));
}
}
TEST_P(DurabilityBucketTest, TakeoverSendsDurabilityAmbiguous) {
setVBucketStateAndRunPersistTask(
vbid,
vbucket_state_active,
{{"topology", nlohmann::json::array({{"active", "replica"}})}});
// Make pending
auto key = makeStoredDocKey("key");
using namespace cb::durability;
auto pending = makePendingItem(key, "value");
// Store it
EXPECT_EQ(ENGINE_EWOULDBLOCK, store->set(*pending, cookie));
// We don't send EWOULDBLOCK to clients
auto mockCookie = cookie_to_mock_object(cookie);
EXPECT_EQ(ENGINE_SUCCESS, mockCookie->status);
// Set state to dead
EXPECT_EQ(ENGINE_SUCCESS, store->setVBucketState(vbid, vbucket_state_dead));
// We have set state to dead but we have not yet run the notification task
EXPECT_EQ(ENGINE_SUCCESS, mockCookie->status);
auto& lpAuxioQ = *task_executor->getLpTaskQ()[NONIO_TASK_IDX];
runNextTask(lpAuxioQ);
// We should have told client the SyncWrite is ambiguous
EXPECT_EQ(ENGINE_SYNC_WRITE_AMBIGUOUS, mockCookie->status);
}
// Test cases which run against all persistent storage backends.
INSTANTIATE_TEST_CASE_P(
AllBackends,
DurabilityEPBucketTest,
STParameterizedBucketTest::persistentAllBackendsConfigValues(),
STParameterizedBucketTest::PrintToStringParamName);
// Test cases which run against all configurations.
INSTANTIATE_TEST_CASE_P(AllBackends,
DurabilityBucketTest,
STParameterizedBucketTest::allConfigValues(),
STParameterizedBucketTest::PrintToStringParamName);
| 37.356734
| 80
| 0.658792
|
gsauere
|
7341ff8afdb7de4a6cbe03adf5e35ae31d1d225b
| 24,763
|
hpp
|
C++
|
include/boost/parser/detail/printing_impl.hpp
|
tzlaine/parser
|
095aa362d777a480fffef415d27d214cd6ffec4a
|
[
"BSL-1.0"
] | 7
|
2020-08-29T02:10:20.000Z
|
2022-03-29T20:31:59.000Z
|
include/boost/parser/detail/printing_impl.hpp
|
tzlaine/parser
|
095aa362d777a480fffef415d27d214cd6ffec4a
|
[
"BSL-1.0"
] | 16
|
2020-08-29T21:33:08.000Z
|
2022-03-22T03:01:02.000Z
|
include/boost/parser/detail/printing_impl.hpp
|
tzlaine/parser
|
095aa362d777a480fffef415d27d214cd6ffec4a
|
[
"BSL-1.0"
] | 1
|
2021-09-22T08:15:57.000Z
|
2021-09-22T08:15:57.000Z
|
#ifndef BOOST_PARSER_DETAIL_PRINTING_IMPL_HPP
#define BOOST_PARSER_DETAIL_PRINTING_IMPL_HPP
#include <boost/parser/detail/printing.hpp>
#if BOOST_PARSER_USE_BOOST
#include <boost/type_index.hpp>
#else
#include <typeinfo>
#endif
namespace boost { namespace parser { namespace detail {
template<typename T>
auto type_name()
{
#if BOOST_PARSER_USE_BOOST
return typeindex::type_id<T>().pretty_name();
#else
return typeid(T).name();
#endif
}
template<typename Parser>
struct n_aray_parser : std::false_type
{};
template<
typename Parser,
typename DelimiterParser,
typename MinType,
typename MaxType>
struct n_aray_parser<
repeat_parser<Parser, DelimiterParser, MinType, MaxType>>
: std::true_type
{};
template<typename Parser, typename MinType, typename MaxType>
struct n_aray_parser<repeat_parser<Parser, detail::nope, MinType, MaxType>>
: std::false_type
{};
template<typename Parser, typename DelimiterParser>
struct n_aray_parser<delimited_seq_parser<Parser, DelimiterParser>>
: std::true_type
{};
template<typename ParserTuple>
struct n_aray_parser<or_parser<ParserTuple>> : std::true_type
{};
template<typename ParserTuple, typename BacktrackingTuple>
struct n_aray_parser<seq_parser<ParserTuple, BacktrackingTuple>>
: std::true_type
{};
// true iff Parser is an n-ary parser (contains N>2 subparsers).
template<typename Parser>
constexpr bool n_aray_parser_v = n_aray_parser<Parser>::value;
template<typename Context, typename Expected>
void print_expected(
Context const & context,
std::ostream & os,
Expected expected,
bool no_parens = false)
{
if (is_nope_v<Expected>)
return;
if (!no_parens)
os << "(";
detail::print(os, detail::resolve(context, expected));
if (!no_parens)
os << ")";
}
template<
typename Context,
typename Parser,
typename DelimiterParser,
typename MinType,
typename MaxType>
void print_parser(
Context const & context,
repeat_parser<Parser, DelimiterParser, MinType, MaxType> const & parser,
std::ostream & os,
int components)
{
if constexpr (is_nope_v<DelimiterParser>) {
auto const min_ = detail::resolve(context, parser.min_);
auto const max_ = detail::resolve(context, parser.max_);
constexpr bool n_ary_child = n_aray_parser_v<Parser>;
if (min_ == 0 && max_ == Inf) {
os << "*";
if (n_ary_child)
os << "(";
detail::print_parser(
context, parser.parser_, os, components + 1);
if (n_ary_child)
os << ")";
} else if (min_ == 1 && max_ == Inf) {
os << "+";
if (n_ary_child)
os << "(";
detail::print_parser(
context, parser.parser_, os, components + 1);
if (n_ary_child)
os << ")";
} else {
os << "repeat(";
detail::print(os, min_);
if (min_ == max_) {
os << ")[";
} else {
os << ", ";
if (max_ == unbounded)
os << "Inf";
else
detail::print(os, max_);
os << ")[";
}
detail::print_parser(
context, parser.parser_, os, components + 1);
os << "]";
}
} else {
detail::print_parser(context, parser.parser_, os, components + 1);
os << " % ";
detail::print_parser(
context, parser.delimiter_parser_, os, components + 2);
}
}
template<typename Context, typename Parser>
void print_parser(
Context const & context,
opt_parser<Parser> const & parser,
std::ostream & os,
int components)
{
os << "-";
constexpr bool n_ary_child = n_aray_parser_v<Parser>;
if (n_ary_child)
os << "(";
detail::print_parser(context, parser.parser_, os, components + 1);
if (n_ary_child)
os << ")";
}
template<typename Context, typename ParserTuple>
void print_parser(
Context const & context,
or_parser<ParserTuple> const & parser,
std::ostream & os,
int components)
{
int i = 0;
bool printed_ellipsis = false;
hl::for_each(parser.parsers_, [&](auto const & parser) {
if (components == parser_component_limit) {
if (!printed_ellipsis)
os << " | ...";
printed_ellipsis = true;
return;
}
if (i)
os << " | ";
detail::print_parser(context, parser, os, components);
++components;
++i;
});
}
template<typename Context, typename ParserTuple, typename BacktrackingTuple>
void print_parser(
Context const & context,
seq_parser<ParserTuple, BacktrackingTuple> const & parser,
std::ostream & os,
int components)
{
int i = 0;
bool printed_ellipsis = false;
hl::for_each(
hl::zip(parser.parsers_, BacktrackingTuple{}),
[&](auto const & parser_and_backtrack) {
using namespace literals;
auto const & parser = parser::get(parser_and_backtrack, 0_c);
auto const backtrack = parser::get(parser_and_backtrack, 1_c);
if (components == parser_component_limit) {
if (!printed_ellipsis)
os << (backtrack ? " >> ..." : " > ...");
printed_ellipsis = true;
return;
}
if (i)
os << (backtrack ? " >> " : " > ");
detail::print_parser(context, parser, os, components);
++components;
++i;
});
}
template<typename Context, typename Parser, typename Action>
void print_parser(
Context const & context,
action_parser<Parser, Action> const & parser,
std::ostream & os,
int components)
{
detail::print_parser(context, parser.parser_, os, components);
os << "[<<action>>]";
}
template<typename Context, typename Parser>
void print_directive(
Context const & context,
std::string_view name,
Parser const & parser,
std::ostream & os,
int components)
{
os << name << "[";
if (++components == parser_component_limit)
os << "...";
else
detail::print_parser(context, parser, os, components + 1);
os << "]";
}
template<typename Context, typename Parser>
void print_parser(
Context const & context,
omit_parser<Parser> const & parser,
std::ostream & os,
int components)
{
detail::print_directive(
context, "omit", parser.parser_, os, components);
}
template<typename Context, typename Parser>
void print_parser(
Context const & context,
raw_parser<Parser> const & parser,
std::ostream & os,
int components)
{
detail::print_directive(context, "raw", parser.parser_, os, components);
}
template<typename Context, typename Parser>
void print_parser(
Context const & context,
lexeme_parser<Parser> const & parser,
std::ostream & os,
int components)
{
detail::print_directive(
context, "lexeme", parser.parser_, os, components);
}
template<typename Context, typename Parser, typename SkipParser>
void print_parser(
Context const & context,
skip_parser<Parser, SkipParser> const & parser,
std::ostream & os,
int components)
{
if constexpr (is_nope_v<SkipParser>) {
detail::print_directive(
context, "skip", parser.parser_, os, components);
} else {
os << "skip(";
detail::print_parser(
context, parser.skip_parser_.parser_, os, components);
os << ")";
detail::print_directive(
context, "", parser.parser_, os, components + 1);
}
}
template<typename Context, typename Parser, bool FailOnMatch>
void print_parser(
Context const & context,
expect_parser<Parser, FailOnMatch> const & parser,
std::ostream & os,
int components)
{
if (FailOnMatch)
os << "!";
else
os << "&";
constexpr bool n_ary_child = n_aray_parser_v<Parser>;
if (n_ary_child)
os << "(";
detail::print_parser(context, parser.parser_, os, components + 1);
if (n_ary_child)
os << ")";
}
template<
typename Context,
bool UseCallbacks,
typename Parser,
typename Attribute,
typename LocalState,
typename ParamsTuple>
void print_parser(
Context const & context,
rule_parser<
UseCallbacks,
Parser,
Attribute,
LocalState,
ParamsTuple> const & parser,
std::ostream & os,
int components)
{
os << parser.name_;
if constexpr (!is_nope_v<ParamsTuple>) {
os << ".with(";
int i = 0;
hl::for_each(parser.params_, [&](auto const & param) {
if (i++)
os << ", ";
detail::print_expected(context, os, param, true);
});
os << ")";
}
}
template<typename Context, typename T>
void print_parser(
Context const & context,
symbol_parser<T> const & parser,
std::ostream & os,
int components)
{
os << "symbols<" << detail::type_name<T>() << ">";
}
template<typename Context, typename Predicate>
void print_parser(
Context const & context,
eps_parser<Predicate> const & parser,
std::ostream & os,
int components)
{
os << "eps(<<pred>>)";
}
template<typename Context>
void print_parser(
Context const & context,
eps_parser<nope> const & parser,
std::ostream & os,
int components)
{
os << "eps";
}
template<typename Context>
void print_parser(
Context const & context,
eoi_parser const & parser,
std::ostream & os,
int components)
{
os << "eoi";
}
template<typename Context, typename Atribute>
void print_parser(
Context const & context,
attr_parser<Atribute> const & parser,
std::ostream & os,
int components)
{
os << "attr";
detail::print_expected(context, os, parser.attr_);
}
template<
typename Context,
typename ResolvedExpected,
bool Integral = std::is_integral<ResolvedExpected>{},
int SizeofExpected = sizeof(ResolvedExpected)>
struct print_expected_char_impl
{
static void call(
Context const & context,
std::ostream & os,
ResolvedExpected expected)
{
detail::print(os, expected);
}
};
template<typename Context, typename Expected>
struct print_expected_char_impl<Context, Expected, true, 4>
{
static void
call(Context const & context, std::ostream & os, Expected expected)
{
std::array<uint32_t, 1> cps = {{(uint32_t)expected}};
auto const r = text::as_utf8(cps);
os << "'";
for (auto c : r) {
detail::print_char(os, c);
}
os << "'";
}
};
template<typename Context, typename Expected>
void print_expected_char(
Context const & context, std::ostream & os, Expected expected)
{
auto resolved_expected = detail::resolve(context, expected);
detail::print_expected_char_impl<Context, decltype(resolved_expected)>::
call(context, os, resolved_expected);
}
template<typename Context, typename T>
struct char_print_parser_impl
{
static void call(Context const & context, std::ostream & os, T expected)
{
detail::print_expected_char(context, os, expected);
}
};
template<typename Context, typename T, typename U>
struct char_print_parser_impl<Context, char_pair<T, U>>
{
static void call(
Context const & context,
std::ostream & os,
char_pair<T, U> expected)
{
detail::print_expected_char(context, os, expected.lo_);
os << ", ";
detail::print_expected_char(context, os, expected.hi_);
}
};
template<typename Context, typename Iter, typename Sentinel>
struct char_print_parser_impl<Context, char_range<Iter, Sentinel>>
{
static void call(
Context const & context,
std::ostream & os,
char_range<Iter, Sentinel> expected)
{
os << "\"";
auto const r = text::as_utf8(expected.chars_);
for (auto c : r) {
detail::print_char(os, c);
}
os << "\"";
}
};
template<typename Context, typename Expected, typename AttributeType>
void print_parser(
Context const & context,
char_parser<Expected, AttributeType> const & parser,
std::ostream & os,
int components)
{
if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::alnum>>) {
os << "ascii::alnum";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::alpha>>) {
os << "ascii::alpha";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::blank>>) {
os << "ascii::blank";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::cntrl>>) {
os << "ascii::cntrl";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::digit>>) {
os << "ascii::digit";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::graph>>) {
os << "ascii::graph";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::print>>) {
os << "ascii::print";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::punct>>) {
os << "ascii::punct";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::space>>) {
os << "ascii::space";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::xdigit>>) {
os << "ascii::xdigit";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::lower>>) {
os << "ascii::lower";
} else if (std::is_same_v<
Expected,
ascii_char_class<ascii_char_class_t::upper>>) {
os << "ascii::upper";
} else {
if (std::is_same_v<AttributeType, uint32_t>)
os << "cp";
else if (std::is_same_v<AttributeType, char>)
os << "cu";
else
os << "char_";
if constexpr (!is_nope_v<Expected>) {
os << "(";
char_print_parser_impl<Context, Expected>::call(
context, os, parser.expected_);
os << ")";
}
}
}
template<typename Context, typename Expected, typename AttributeType>
void print_parser(
Context const & context,
omit_parser<char_parser<Expected, AttributeType>> const & parser,
std::ostream & os,
int components)
{
if constexpr (is_nope_v<Expected>) {
os << "omit[char_]";
} else {
char_print_parser_impl<Context, Expected>::call(
context, os, parser.parser_.expected_);
}
}
template<typename Context, typename StrIter, typename StrSentinel>
void print_parser(
Context const & context,
string_parser<StrIter, StrSentinel> const & parser,
std::ostream & os,
int components)
{
os << "string(\"";
for (auto c :
text::as_utf8(parser.expected_first_, parser.expected_last_)) {
detail::print_char(os, c);
}
os << "\")";
}
template<typename Context, typename StrIter, typename StrSentinel>
void print_parser(
Context const & context,
omit_parser<string_parser<StrIter, StrSentinel>> const & parser,
std::ostream & os,
int components)
{
os << "\"";
for (auto c : text::as_utf8(
parser.parser_.expected_first_,
parser.parser_.expected_last_)) {
detail::print_char(os, c);
}
os << "\"";
}
template<typename Context>
void print_parser(
Context const & context,
ws_parser<true> const & parser,
std::ostream & os,
int components)
{
os << "eol";
}
template<typename Context>
void print_parser(
Context const & context,
ws_parser<false> const & parser,
std::ostream & os,
int components)
{
os << "ws";
}
template<typename Context>
void print_parser(
Context const & context,
bool_parser const & parser,
std::ostream & os,
int components)
{
os << "bool_";
}
template<
typename Context,
typename T,
int Radix,
int MinDigits,
int MaxDigits,
typename Expected>
void print_parser(
Context const & context,
uint_parser<T, Radix, MinDigits, MaxDigits, Expected> const & parser,
std::ostream & os,
int components)
{
if (MinDigits == 1 && MaxDigits == -1) {
if (std::is_same_v<T, unsigned short>) {
os << "ushort_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (std::is_same_v<T, unsigned int>) {
if (Radix == 2)
os << "bin";
else if (Radix == 8)
os << "oct";
else if (Radix == 16)
os << "hex";
else if (Radix == 10)
os << "uint_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (Radix == 10 && std::is_same_v<T, unsigned long>) {
os << "ulong_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (Radix == 10 && std::is_same_v<T, unsigned long long>) {
os << "ulong_long";
detail::print_expected(context, os, parser.expected_);
return;
}
}
os << "uint<" << detail::type_name<T>() << ", " << Radix << ", "
<< MinDigits << ", " << MaxDigits << ">";
detail::print_expected(context, os, parser.expected_);
}
template<
typename Context,
typename T,
int Radix,
int MinDigits,
int MaxDigits,
typename Expected>
void print_parser(
Context const & context,
int_parser<T, Radix, MinDigits, MaxDigits, Expected> const & parser,
std::ostream & os,
int components)
{
if (Radix == 10 && MinDigits == 1 && MaxDigits == -1) {
if (std::is_same_v<T, short>) {
os << "short_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (std::is_same_v<T, int>) {
os << "int_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (std::is_same_v<T, long>) {
os << "long_";
detail::print_expected(context, os, parser.expected_);
return;
} else if (std::is_same_v<T, long long>) {
os << "long_long";
detail::print_expected(context, os, parser.expected_);
return;
}
}
os << "int<" << detail::type_name<T>() << ", " << Radix << ", "
<< MinDigits << ", " << MaxDigits << ">";
detail::print_expected(context, os, parser.expected_);
}
template<typename Context>
void print_parser(
Context const & context,
int_parser<short> const & parser,
std::ostream & os,
int components)
{
os << "short_";
}
template<typename Context>
void print_parser(
Context const & context,
int_parser<long> const & parser,
std::ostream & os,
int components)
{
os << "long_";
}
template<typename Context>
void print_parser(
Context const & context,
int_parser<long long> const & parser,
std::ostream & os,
int components)
{
os << "long_long";
}
template<typename Context, typename T>
void print_parser(
Context const & context,
float_parser<T> const & parser,
std::ostream & os,
int components)
{
os << "float<" << detail::type_name<T>() << ">";
}
template<typename Context>
void print_parser(
Context const & context,
float_parser<float> const & parser,
std::ostream & os,
int components)
{
os << "float_";
}
template<typename Context>
void print_parser(
Context const & context,
float_parser<double> const & parser,
std::ostream & os,
int components)
{
os << "double_";
}
template<typename Context, typename ParserTuple, typename BacktrackingTuple>
void print_switch_matchers(
Context const & context,
seq_parser<ParserTuple, BacktrackingTuple> const & parser,
std::ostream & os,
int components)
{
using namespace literals;
os << "("
<< detail::resolve(
context, parser::get(parser.parsers_, 0_c).pred_.value_)
<< ", ";
detail::print_parser(
context, parser::get(parser.parsers_, 1_c), os, components);
os << ")";
}
template<typename Context, typename ParserTuple>
void print_switch_matchers(
Context const & context,
or_parser<ParserTuple> const & parser,
std::ostream & os,
int components)
{
using namespace literals;
bool printed_ellipsis = false;
hl::for_each(parser.parsers_, [&](auto const & parser) {
if (components == parser_component_limit) {
if (!printed_ellipsis)
os << "...";
printed_ellipsis = true;
return;
}
detail::print_switch_matchers(context, parser, os, components);
++components;
});
}
template<typename Context, typename SwitchValue, typename OrParser>
void print_parser(
Context const & context,
switch_parser<SwitchValue, OrParser> const & parser,
std::ostream & os,
int components)
{
os << "switch_(";
detail::print(os, detail::resolve(context, parser.switch_value_));
os << ")";
detail::print_switch_matchers(
context, parser.or_parser_, os, components);
}
}}}
#endif
| 30.533909
| 80
| 0.521988
|
tzlaine
|
7343be8c63458715aeb0ac97ad039e989aafe6ee
| 268
|
cpp
|
C++
|
ch02/list_2.21/main.cpp
|
shoeisha-books/dokushu-cpp
|
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
|
[
"MIT"
] | 17
|
2020-01-01T16:44:05.000Z
|
2022-03-31T07:20:13.000Z
|
ch02/list_2.21/main.cpp
|
shoeisha-books/dokushu-cpp
|
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
|
[
"MIT"
] | 1
|
2021-07-04T01:41:53.000Z
|
2021-07-14T19:17:01.000Z
|
ch02/list_2.21/main.cpp
|
shoeisha-books/dokushu-cpp
|
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
|
[
"MIT"
] | 3
|
2019-11-28T14:37:09.000Z
|
2021-05-22T02:55:15.000Z
|
#include <iostream>
int main()
{
int a = 0;
float b = 3.14f; // 変数bはラムダ式の中で使われていないのでコピーされない
auto lambda = [=]() // デフォルトのキャプチャ
{
// OK。aを使っているので、コンパイラーが自動的にaをコピーする
std::cout << a << std::endl;
};
lambda();
}
| 15.764706
| 52
| 0.503731
|
shoeisha-books
|
734558d9c9c239b2ec4a3d04cef6b977ee41cedb
| 1,392
|
cpp
|
C++
|
qipmsg/trunk/src/qipmsg.cpp
|
cuibo10/feige_src
|
1bfd47eaa046d401f83dfae5715b5487283ba343
|
[
"MIT"
] | null | null | null |
qipmsg/trunk/src/qipmsg.cpp
|
cuibo10/feige_src
|
1bfd47eaa046d401f83dfae5715b5487283ba343
|
[
"MIT"
] | null | null | null |
qipmsg/trunk/src/qipmsg.cpp
|
cuibo10/feige_src
|
1bfd47eaa046d401f83dfae5715b5487283ba343
|
[
"MIT"
] | null | null | null |
// This file is part of QIpMsg.
//
// QIpMsg is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// QIpMsg is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with QIpMsg. If not, see <http://www.gnu.org/licenses/>.
//
#include <QApplication>
#include <QUdpSocket>
#include <QMetaType>
#include "qipmsg.h"
#include "helper.h"
#include "systray.h"
#include "user_manager.h"
#include "msg_thread.h"
#include "constants.h"
#include "global.h"
#include "recv_msg.h"
#include "send_msg.h"
#include "send_file_manager.h"
QIpMsg::QIpMsg(QObject *parent)
: QObject(parent)
{
Global::globalInit(Helper::iniPath());
createConnections();
Global::systray->show();
}
QIpMsg::~QIpMsg()
{
// delete global variable and save settings.
Global::globalEnd();
}
void QIpMsg::createConnections()
{
connect(Global::sendFileManager, SIGNAL(transferCountChanged(int)),
Global::systray, SLOT(updateTransferCount(int)));
}
| 25.777778
| 71
| 0.718391
|
cuibo10
|
7345f941688db6d7afad6fdc15f148bb0d5c9c80
| 112,145
|
cpp
|
C++
|
test/line_break_17.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | null | null | null |
test/line_break_17.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | 1
|
2021-03-05T12:56:59.000Z
|
2021-03-05T13:11:53.000Z
|
test/line_break_17.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | 3
|
2019-10-30T18:38:15.000Z
|
2021-03-05T12:10:13.000Z
|
// Warning! This file is autogenerated.
#include <boost/text/line_break.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(line, breaks_17)
{
// × 0021 ÷ 0E01 ÷
// × [0.3] EXCLAMATION MARK (EX) ÷ [999.0] THAI CHARACTER KO KAI (SA_AL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x21, 0xe01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 1);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 1, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 1);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 1, cps.end()).iter - cps.begin(), 2);
}
// × 0021 × 0020 ÷ 0E01 ÷
// × [0.3] EXCLAMATION MARK (EX) × [7.01] SPACE (SP) ÷ [18.0] THAI CHARACTER KO KAI (SA_AL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x21, 0x20, 0xe01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 0021 × 0308 ÷ 0E01 ÷
// × [0.3] EXCLAMATION MARK (EX) × [9.0] COMBINING DIAERESIS (CM1_CM) ÷ [999.0] THAI CHARACTER KO KAI (SA_AL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x21, 0x308, 0xe01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 0021 × 0308 × 0020 ÷ 0E01 ÷
// × [0.3] EXCLAMATION MARK (EX) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] THAI CHARACTER KO KAI (SA_AL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x21, 0x308, 0x20, 0xe01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 0021 × 3041 ÷
// × [0.3] EXCLAMATION MARK (EX) × [21.03] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x21, 0x3041 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 0021 × 0020 ÷ 3041 ÷
// × [0.3] EXCLAMATION MARK (EX) × [7.01] SPACE (SP) ÷ [18.0] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x21, 0x20, 0x3041 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 0021 × 0308 × 3041 ÷
// × [0.3] EXCLAMATION MARK (EX) × [9.0] COMBINING DIAERESIS (CM1_CM) × [21.03] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x21, 0x308, 0x3041 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 0021 × 0308 × 0020 ÷ 3041 ÷
// × [0.3] EXCLAMATION MARK (EX) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0x21, 0x308, 0x20, 0x3041 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 0023 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] NUMBER SIGN (AL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x23 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 0023 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] NUMBER SIGN (AL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x23 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0023 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] NUMBER SIGN (AL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x23 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 0023 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] NUMBER SIGN (AL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x23 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 2014 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] EM DASH (B2) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x2014 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 2014 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] EM DASH (B2) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x2014 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 2014 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] EM DASH (B2) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x2014 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 2014 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] EM DASH (B2) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x2014 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 0009 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] <CHARACTER TABULATION> (BA) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x9 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 0009 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] <CHARACTER TABULATION> (BA) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x9 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0009 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] <CHARACTER TABULATION> (BA) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x9 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 0009 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] <CHARACTER TABULATION> (BA) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x9 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 00B4 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] ACUTE ACCENT (BB) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xb4 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 00B4 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] ACUTE ACCENT (BB) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xb4 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 00B4 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] ACUTE ACCENT (BB) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xb4 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 00B4 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] ACUTE ACCENT (BB) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xb4 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 000B ÷
// × [0.3] NO-BREAK SPACE (GL) × [6.0] <LINE TABULATION> (BK) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xb }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 000B ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [6.0] <LINE TABULATION> (BK) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xb }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 000B ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [6.0] <LINE TABULATION> (BK) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xb }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 000B ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [6.0] <LINE TABULATION> (BK) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xb }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × FFFC ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] OBJECT REPLACEMENT CHARACTER (CB) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xfffc }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ FFFC ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] OBJECT REPLACEMENT CHARACTER (CB) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xfffc }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × FFFC ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] OBJECT REPLACEMENT CHARACTER (CB) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xfffc }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ FFFC ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] OBJECT REPLACEMENT CHARACTER (CB) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xfffc }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 007D ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] RIGHT CURLY BRACKET (CL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x7d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 007D ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [13.02] RIGHT CURLY BRACKET (CL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x7d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 007D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] RIGHT CURLY BRACKET (CL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x7d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 007D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [13.02] RIGHT CURLY BRACKET (CL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x7d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 0029 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] RIGHT PARENTHESIS (CP) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x29 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 0029 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [13.02] RIGHT PARENTHESIS (CP) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x29 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0029 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] RIGHT PARENTHESIS (CP) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x29 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 0029 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [13.02] RIGHT PARENTHESIS (CP) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x29 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 000D ÷
// × [0.3] NO-BREAK SPACE (GL) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xd }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 000D ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xd }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 000D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xd }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 000D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xd }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 0021 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] EXCLAMATION MARK (EX) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x21 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 0021 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x21 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0021 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] EXCLAMATION MARK (EX) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x21 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 0021 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x21 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 00A0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] NO-BREAK SPACE (GL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xa0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 00A0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] NO-BREAK SPACE (GL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xa0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 00A0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] NO-BREAK SPACE (GL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xa0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 00A0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] NO-BREAK SPACE (GL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xa0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × AC00 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xac00 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ AC00 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xac00 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × AC00 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xac00 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ AC00 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xac00 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × AC01 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HANGUL SYLLABLE GAG (H3) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xac01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ AC01 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HANGUL SYLLABLE GAG (H3) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xac01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × AC01 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HANGUL SYLLABLE GAG (H3) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xac01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ AC01 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HANGUL SYLLABLE GAG (H3) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xac01 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 05D0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HEBREW LETTER ALEF (HL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x5d0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 05D0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HEBREW LETTER ALEF (HL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x5d0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 05D0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HEBREW LETTER ALEF (HL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x5d0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 05D0 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HEBREW LETTER ALEF (HL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x5d0 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 002D ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HYPHEN-MINUS (HY) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x2d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 002D ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HYPHEN-MINUS (HY) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x2d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 002D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HYPHEN-MINUS (HY) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x2d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 002D ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HYPHEN-MINUS (HY) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x2d }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 231A ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] WATCH (ID) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x231a }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 231A ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] WATCH (ID) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x231a }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 231A ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] WATCH (ID) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x231a }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 231A ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] WATCH (ID) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x231a }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 2024 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] ONE DOT LEADER (IN) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x2024 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 2024 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] ONE DOT LEADER (IN) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x2024 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 2024 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] ONE DOT LEADER (IN) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x2024 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 2024 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] ONE DOT LEADER (IN) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x2024 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 002C ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] COMMA (IS) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x2c }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 002C ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [13.02] COMMA (IS) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x2c }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 002C ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] COMMA (IS) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x2c }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 002C ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [13.02] COMMA (IS) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x2c }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 1100 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HANGUL CHOSEONG KIYEOK (JL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x1100 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 1100 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HANGUL CHOSEONG KIYEOK (JL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x1100 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 1100 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HANGUL CHOSEONG KIYEOK (JL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x1100 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 1100 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HANGUL CHOSEONG KIYEOK (JL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x1100 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 11A8 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HANGUL JONGSEONG KIYEOK (JT) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x11a8 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 11A8 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HANGUL JONGSEONG KIYEOK (JT) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x11a8 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 11A8 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HANGUL JONGSEONG KIYEOK (JT) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x11a8 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 11A8 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HANGUL JONGSEONG KIYEOK (JT) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x11a8 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 1160 ÷
// × [0.3] NO-BREAK SPACE (GL) × [12.0] HANGUL JUNGSEONG FILLER (JV) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x1160 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 ÷ 1160 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) ÷ [18.0] HANGUL JUNGSEONG FILLER (JV) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x1160 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 2, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 1160 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.0] HANGUL JUNGSEONG FILLER (JV) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x1160 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 ÷ 1160 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HANGUL JUNGSEONG FILLER (JV) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x1160 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 3, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 000A ÷
// × [0.3] NO-BREAK SPACE (GL) × [6.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0xa }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 000A ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [6.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0xa }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 000A ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [6.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0xa }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 000A ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [6.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0xa }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
// × 00A0 × 0085 ÷
// × [0.3] NO-BREAK SPACE (GL) × [6.0] <NEXT LINE (NEL)> (NL) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa0, 0x85 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 2);
}
// × 00A0 × 0020 × 0085 ÷
// × [0.3] NO-BREAK SPACE (GL) × [7.01] SPACE (SP) × [6.0] <NEXT LINE (NEL)> (NL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x20, 0x85 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0085 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [6.0] <NEXT LINE (NEL)> (NL) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa0, 0x308, 0x85 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 3);
}
// × 00A0 × 0308 × 0020 × 0085 ÷
// × [0.3] NO-BREAK SPACE (GL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [6.0] <NEXT LINE (NEL)> (NL) ÷ [0.3]
{
std::array<uint32_t, 4> cps = {{ 0xa0, 0x308, 0x20, 0x85 }};
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 0, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 1, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 2, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 3, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
EXPECT_EQ(boost::text::prev_allowed_line_break(cps.begin(), cps.begin() + 4, cps.end()).iter - cps.begin(), 0);
EXPECT_EQ(boost::text::next_allowed_line_break(cps.begin() + 0, cps.end()).iter - cps.begin(), 4);
}
}
| 74.169974
| 142
| 0.612029
|
eightysquirrels
|
73469628ccd16b0ab0c83e13383f5519f545d01a
| 64,908
|
cpp
|
C++
|
Source/FDMwkbParticleContainer.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Source/FDMwkbParticleContainer.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
Source/FDMwkbParticleContainer.cpp
|
Gosenca/axionyx_1.0
|
7e2a723e00e6287717d6d81b23db32bcf6c3521a
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#ifdef FDM
#include <stdint.h>
#include <complex>
#include "FDMwkbParticleContainer.H"
#include "fdm_F.H"
using namespace amrex;
/// These are helper functions used when initializing from a morton-ordered
/// binary particle file.
namespace {
inline uint64_t split(unsigned int a) {
uint64_t x = a & 0x1fffff;
x = (x | x << 32) & 0x1f00000000ffff;
x = (x | x << 16) & 0x1f0000ff0000ff;
x = (x | x << 8) & 0x100f00f00f00f00f;
x = (x | x << 4) & 0x10c30c30c30c30c3;
x = (x | x << 2) & 0x1249249249249249;
return x;
}
inline uint64_t get_morton_index(unsigned int x,
unsigned int y,
unsigned int z) {
uint64_t morton_index = 0;
morton_index |= split(x) | ( split(y) << 1) | (split(z) << 2);
return morton_index;
}
struct BoxMortonKey {
uint64_t morton_id;
int box_id;
};
struct by_morton_id {
bool operator()(const BoxMortonKey &a, const BoxMortonKey &b) {
return a.morton_id < b.morton_id;
}
};
std::string get_file_name(const std::string& base, int file_num) {
std::stringstream ss;
ss << base << file_num;
return ss.str();
}
struct ParticleMortonFileHeader {
long NP;
int DM;
int NX;
int SZ;
int NF;
};
void ReadHeader(const std::string& dir,
const std::string& file,
ParticleMortonFileHeader& hdr) {
std::string header_filename = dir;
header_filename += "/";
header_filename += file;
Vector<char> fileCharPtr;
ParallelDescriptor::ReadAndBcastFile(header_filename, fileCharPtr);
std::string fileCharPtrString(fileCharPtr.dataPtr());
std::istringstream HdrFile(fileCharPtrString, std::istringstream::in);
HdrFile >> hdr.NP;
HdrFile >> hdr.DM;
HdrFile >> hdr.NX;
HdrFile >> hdr.SZ;
HdrFile >> hdr.NF;
}
}
void
FDMwkbParticleContainer::moveKickDrift (amrex::MultiFab& acceleration,
int lev,
amrex::Real dt,
amrex::Real a_old,
amrex::Real a_half,
int where_width)
{
BL_PROFILE("FDMwkbParticleContainer::moveKickDrift()");
//If there are no particles at this level
if (lev >= this->GetParticles().size())
return;
const Real* dx = Geom(lev).CellSize();
amrex::MultiFab* ac_ptr;
if (this->OnSameGrids(lev, acceleration))
{
ac_ptr = &acceleration;
}
else
{
ac_ptr = new amrex::MultiFab(this->m_gdb->ParticleBoxArray(lev),
this->m_gdb->ParticleDistributionMap(lev),
acceleration.nComp(),acceleration.nGrow());
for (amrex::MFIter mfi(*ac_ptr); mfi.isValid(); ++mfi)
ac_ptr->setVal(0.);
ac_ptr->copy(acceleration,0,0,acceleration.nComp());
ac_ptr->FillBoundary();
}
const Real* plo = Geom(lev).ProbLo();
int do_move = 1;
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MyParIter pti(*this, lev); pti.isValid(); ++pti) {
AoS& particles = pti.GetArrayOfStructs();
int Np = particles.size();
if (Np > 0)
{
const Box& ac_box = (*ac_ptr)[pti].box();
update_fdm_particles_wkb(&Np, particles.data(),
(*ac_ptr)[pti].dataPtr(),
ac_box.loVect(), ac_box.hiVect(),
plo,dx,dt,a_old,a_half,&do_move);
}
}
if (ac_ptr != &acceleration) delete ac_ptr;
ParticleLevel& pmap = this->GetParticles(lev);
if (lev > 0 && sub_cycle)
{
amrex::ParticleLocData pld;
for (auto& kv : pmap) {
AoS& pbox = kv.second.GetArrayOfStructs();
const int n = pbox.size();
#ifdef _OPENMP
#pragma omp parallel for private(pld)
#endif
for (int i = 0; i < n; i++)
{
ParticleType& p = pbox[i];
if (p.id() <= 0) continue;
// Move the particle to the proper ghost cell.
// and remove any *ghost* particles that have gone too far
// Note that this should only negate ghost particles, not real particles.
if (!this->Where(p, pld, lev, lev, where_width))
{
// Assert that the particle being removed is a ghost particle;
// the ghost particle is no longer in relevant ghost cells for this grid.
if (p.id() == amrex::GhostParticleID)
{
p.id() = -1;
}
else
{
std::cout << "Oops -- removing particle " << p.id() << std::endl;
amrex::Error("Trying to get rid of a non-ghost particle in moveKickDrift");
}
}
}
}
}
}
void
FDMwkbParticleContainer::moveKick (MultiFab& acceleration,
int lev,
Real dt,
Real a_new,
Real a_half)
{
BL_PROFILE("FDMwkbParticleContainer::moveKick()");
const Real* dx = Geom(lev).CellSize();
MultiFab* ac_ptr;
if (OnSameGrids(lev,acceleration))
{
ac_ptr = &acceleration;
}
else
{
ac_ptr = new MultiFab(ParticleBoxArray(lev),
ParticleDistributionMap(lev),
acceleration.nComp(),acceleration.nGrow());
for (MFIter mfi(*ac_ptr); mfi.isValid(); ++mfi)
ac_ptr->setVal(0.);
ac_ptr->copy(acceleration,0,0,acceleration.nComp());
ac_ptr->FillBoundary();
}
const Real* plo = Geom(lev).ProbLo();
int do_move = 0;
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MyParIter pti(*this, lev); pti.isValid(); ++pti) {
AoS& particles = pti.GetArrayOfStructs();
int Np = particles.size();
if (Np > 0)
{
const Box& ac_box = (*ac_ptr)[pti].box();
update_fdm_particles_wkb(&Np, particles.data(),
(*ac_ptr)[pti].dataPtr(),
ac_box.loVect(), ac_box.hiVect(),
plo,dx,dt,a_half,a_new,&do_move);
}
}
if (ac_ptr != &acceleration) delete ac_ptr;
}
void
FDMwkbParticleContainer::moveKickDriftFDM (amrex::MultiFab& phi,
int grav_n_grow,
amrex::MultiFab& acceleration,
int lev,
amrex::Real dt,
amrex::Real a_old,
amrex::Real a_half,
int where_width)
{
BL_PROFILE("FDMwkbParticleContainer::moveKickDrift()");
//If there are no particles at this level
if (lev >= this->GetParticles().size())
return;
const Real* dx = Geom(lev).CellSize();
amrex::MultiFab* ac_ptr;
if (this->OnSameGrids(lev, acceleration))
{
ac_ptr = &acceleration;
}
else
{
ac_ptr = new amrex::MultiFab(this->m_gdb->ParticleBoxArray(lev),
this->m_gdb->ParticleDistributionMap(lev),
acceleration.nComp(),acceleration.nGrow());
for (amrex::MFIter mfi(*ac_ptr); mfi.isValid(); ++mfi)
ac_ptr->setVal(0.);
ac_ptr->copy(acceleration,0,0,acceleration.nComp());
ac_ptr->FillBoundary();
}
amrex::MultiFab* phi_ptr;
phi_ptr = new amrex::MultiFab(this->m_gdb->ParticleBoxArray(lev),
this->m_gdb->ParticleDistributionMap(lev),
phi.nComp(),grav_n_grow);
for (amrex::MFIter mfi(*phi_ptr); mfi.isValid(); ++mfi)
phi_ptr->setVal(0.);
phi_ptr->copy(phi,0,0,phi.nComp());
phi_ptr->FillBoundary();
const Real* plo = Geom(lev).ProbLo();
int do_move = 1;
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MyParIter pti(*this, lev); pti.isValid(); ++pti) {
AoS& particles = pti.GetArrayOfStructs();
int Np = particles.size();
if (Np > 0)
{
const Box& ac_box = (*ac_ptr)[pti].box();
const Box& phi_box = (*phi_ptr)[pti].box();
update_gaussian_beams_wkb(&Np, particles.data(),
(*ac_ptr)[pti].dataPtr(),
ac_box.loVect(), ac_box.hiVect(),
(*phi_ptr)[pti].dataPtr(),
phi_box.loVect(), phi_box.hiVect(),
plo,dx,dt,a_old,a_half,&do_move);
}
}
if (ac_ptr != &acceleration) delete ac_ptr;
delete phi_ptr;
ParticleLevel& pmap = this->GetParticles(lev);
if (lev > 0 && sub_cycle)
{
amrex::ParticleLocData pld;
for (auto& kv : pmap) {
AoS& pbox = kv.second.GetArrayOfStructs();
const int n = pbox.size();
#ifdef _OPENMP
#pragma omp parallel for private(pld)
#endif
for (int i = 0; i < n; i++)
{
ParticleType& p = pbox[i];
if (p.id() <= 0) continue;
// Move the particle to the proper ghost cell.
// and remove any *ghost* particles that have gone too far
// Note that this should only negate ghost particles, not real particles.
if (!this->Where(p, pld, lev, lev, where_width))
{
// Assert that the particle being removed is a ghost particle;
// the ghost particle is no longer in relevant ghost cells for this grid.
if (p.id() == amrex::GhostParticleID)
{
p.id() = -1;
}
else
{
std::cout << "Oops -- removing particle " << p.id() << std::endl;
amrex::Error("Trying to get rid of a non-ghost particle in moveKickDrift");
}
}
}
}
}
}
void
FDMwkbParticleContainer::moveKickFDM (amrex::MultiFab& phi,
int grav_n_grow,
amrex::MultiFab& acceleration,
int lev,
Real dt,
Real a_new,
Real a_half)
{
BL_PROFILE("FDMwkbParticleContainer::moveKick()");
const Real* dx = Geom(lev).CellSize();
MultiFab* ac_ptr;
if (OnSameGrids(lev,acceleration))
{
ac_ptr = &acceleration;
}
else
{
ac_ptr = new MultiFab(ParticleBoxArray(lev),
ParticleDistributionMap(lev),
acceleration.nComp(),acceleration.nGrow());
for (MFIter mfi(*ac_ptr); mfi.isValid(); ++mfi)
ac_ptr->setVal(0.);
ac_ptr->copy(acceleration,0,0,acceleration.nComp());
ac_ptr->FillBoundary();
}
amrex::MultiFab* phi_ptr;
phi_ptr = new amrex::MultiFab(this->m_gdb->ParticleBoxArray(lev),
this->m_gdb->ParticleDistributionMap(lev),
phi.nComp(),grav_n_grow);
for (amrex::MFIter mfi(*phi_ptr); mfi.isValid(); ++mfi)
phi_ptr->setVal(0.);
phi_ptr->copy(phi,0,0,phi.nComp());
phi_ptr->FillBoundary();
const Real* plo = Geom(lev).ProbLo();
int do_move = 0;
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MyParIter pti(*this, lev); pti.isValid(); ++pti) {
AoS& particles = pti.GetArrayOfStructs();
int Np = particles.size();
if (Np > 0)
{
const Box& ac_box = (*ac_ptr)[pti].box();
const Box& phi_box = (*phi_ptr)[pti].box();
update_gaussian_beams_wkb(&Np, particles.data(),
(*ac_ptr)[pti].dataPtr(),
ac_box.loVect(), ac_box.hiVect(),
(*phi_ptr)[pti].dataPtr(),
phi_box.loVect(), phi_box.hiVect(),
plo,dx,dt,a_half,a_new,&do_move);
}
}
if (ac_ptr != &acceleration) delete ac_ptr;
delete phi_ptr;
}
void
FDMwkbParticleContainer::CreateGhostParticlesFDM (int level, int lev, int nGrow, AoS& ghosts) const
{
BL_PROFILE("FDMwkbParticleContainer::CreateGhostParticlesFDM()");
BL_ASSERT(ghosts.empty());
BL_ASSERT(level < finestLevel());
if (level >= static_cast<int>(GetParticles().size()))
return;
const BoxArray& fine = ParticleBoxArray(lev);
std::vector< std::pair<int,Box> > isects;
const auto& pmap = GetParticles(level);
for (const auto& kv : pmap)
{
const auto& pbox = kv.second.GetArrayOfStructs();
for (auto it = pbox.cbegin(); it != pbox.cend(); ++it)
{
const IntVect& iv = Index(*it, lev);
fine.intersections(Box(iv,iv),isects,true,nGrow);
if(!isects.empty())
{
ParticleType p = *it; // yes, make a copy
p.m_idata.id = GhostParticleID;
ghosts().push_back(p);
}
}
}
}
/*
Particle deposition
*/
void
FDMwkbParticleContainer::DepositFDMParticles(MultiFab& mf_real, MultiFab& mf_imag, int lev, amrex::Real a, amrex::Real theta_fdm, amrex::Real hbaroverm) const
{
BL_PROFILE("FDMwkbParticleContainer::DepositFDMParticles()");
MultiFab* mf_pointer_real;
if (OnSameGrids(lev, mf_real)) {
// If we are already working with the internal mf defined on the
// particle_box_array, then we just work with this.
mf_pointer_real = &mf_real;
}
else {
amrex::Print() <<"FDM:: mf_real different!!\n";
// If mf_real is not defined on the particle_box_array, then we need
// to make a temporary here and copy into mf_real at the end.
mf_pointer_real = new MultiFab(ParticleBoxArray(lev),
ParticleDistributionMap(lev),
1, mf_real.nGrow());
for (MFIter mfi(*mf_pointer_real); mfi.isValid(); ++mfi) {
(*mf_pointer_real)[mfi].setVal(0);
}
}
MultiFab* mf_pointer_imag;
if (OnSameGrids(lev, mf_imag)) {
// If we are already working with the internal mf defined on the
// particle_box_array, then we just work with this.
mf_pointer_imag = &mf_imag;
}
else {
amrex::Print() <<"FDM:: mf_imag different!!\n";
// If mf_imag is not defined on the particle_box_array, then we need
// to make a temporary here and copy into mf_imag at the end.
mf_pointer_imag = new MultiFab(ParticleBoxArray(lev),
ParticleDistributionMap(lev),
1, mf_imag.nGrow());
for (MFIter mfi(*mf_pointer_imag); mfi.isValid(); ++mfi) {
(*mf_pointer_imag)[mfi].setVal(0);
}
}
const Real strttime = amrex::second();
const Geometry& gm = Geom(lev);
const Real* plo = gm.ProbLo();
const Real* dx = gm.CellSize();
for (MyConstParIter pti(*this, lev); pti.isValid(); ++pti) {
const auto& particles = pti.GetArrayOfStructs();
const auto pstruct = particles().data();
const long np = pti.numParticles();
FArrayBox& fab_real = (*mf_pointer_real)[pti];
FArrayBox& fab_imag = (*mf_pointer_imag)[pti];
Array4<Real> const& realarr = fab_real.array();
Array4<Real> const& imagarr = fab_imag.array();
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(int i=0; i<np; ++i)
{
const auto& p = pstruct[i];
if(p.rdata(0)==0.0){
//std::complex<Real> amp(8.9e+5,0.0);
std::complex<Real> amp(p.rdata(5),p.rdata(6));
std::complex<Real> phi(0.0,0.0);
std::complex<Real> iimag(0.0,1.0);
int rad = std::ceil(theta_fdm/sqrt(2.0*p.rdata(7))/dx[0]);
Real kernelsize;
Real lx = (p.pos(0) - plo[0])/dx[0] + 0.5;
Real ly = (p.pos(1) - plo[1])/dx[1] + 0.5;
Real lz = (p.pos(2) - plo[2])/dx[2] + 0.5;
int xint = std::floor(lx);
int yint = std::floor(ly);
int zint = std::floor(lz);
for (int ii=-rad; ii<=rad; ii++)
for (int jj=-rad; jj<=rad; jj++)
for (int kk=-rad; kk<=rad; kk++)
{
kernelsize = ((static_cast<Real>(xint+ii)+1.0-lx)*dx[0]*(static_cast<Real>(xint+ii)+1.0-lx)*dx[0]
+(static_cast<Real>(yint+jj)+1.0-ly)*dx[1]*(static_cast<Real>(yint+jj)+1.0-ly)*dx[1]
+(static_cast<Real>(zint+kk)+1.0-lz)*dx[2]*(static_cast<Real>(zint+kk)+1.0-lz)*dx[2])*p.rdata(7);
if (kernelsize <= (theta_fdm*theta_fdm/2.0)){
phi = amp*std::exp(-kernelsize)*std::exp(iimag*(p.rdata(4)
+p.rdata(1)*a*(static_cast<Real>(xint+ii)+1.0-lx)*dx[0]
+p.rdata(2)*a*(static_cast<Real>(yint+jj)+1.0-ly)*dx[1]
+p.rdata(3)*a*(static_cast<Real>(zint+kk)+1.0-lz)*dx[2] )/hbaroverm);
#ifdef _OPENMP
#pragma omp atomic update
#endif
realarr(xint+ii, yint+jj, zint+kk)+= phi.real();
#ifdef _OPENMP
#pragma omp atomic update
#endif
imagarr(xint+ii, yint+jj, zint+kk)+= phi.imag();
}
}
}
}
}
// If mf_real is not defined on the particle_box_array, then we need
// to copy here from mf_pointer_real into mf_real. I believe that we don't
// need any information in ghost cells so we don't copy those.
if (mf_pointer_real != &mf_real) {
mf_real.copy(*mf_pointer_real,0,0,1);
delete mf_pointer_real;
}
// If mf_imag is not defined on the particle_box_array, then we need
// to copy here from mf_pointer_imag into mf_imag. I believe that we don't
// need any information in ghost cells so we don't copy those.
if (mf_pointer_imag != &mf_imag) {
mf_imag.copy(*mf_pointer_imag,0,0,1);
delete mf_pointer_imag;
}
if (m_verbose > 1) {
Real stoptime = amrex::second() - strttime;
ParallelDescriptor::ReduceRealMax(stoptime,ParallelDescriptor::IOProcessorNumber());
amrex::Print() << "FDMwkbParticleContainer::DepositFDMParticles time: " << stoptime << '\n';
}
}
amrex::Real
FDMwkbParticleContainer::estTimestepFDM(amrex::MultiFab& phi,
amrex::Real a,
int lev,
amrex::Real cfl) const
{
BL_PROFILE("FDMwkbParticleContainer::estTimestep()");
amrex::Real dt = 1e50;
BL_ASSERT(lev >= 0);
if (this->GetParticles().size() == 0)
return dt;
const amrex::Real strttime = amrex::ParallelDescriptor::second();
const amrex::Geometry& geom = this->m_gdb->Geom(lev);
const ParticleLevel& pmap = this->GetParticles(lev);
int tnum = 1;
#ifdef _OPENMP
tnum = omp_get_max_threads();
#endif
amrex::Vector<amrex::Real> ldt(tnum,1e50);
long num_particles_at_level = 0;
amrex::MultiFab* phi_pointer;
if (this->OnSameGrids(lev, phi))
{
phi_pointer = 0;
}
else
{
phi_pointer = new amrex::MultiFab(this->m_gdb->ParticleBoxArray(lev),
this->m_gdb->ParticleDistributionMap(lev),
phi.nComp(), phi.nGrow());
phi_pointer->copy(phi,0,0,1);
phi_pointer->FillBoundary(geom.periodicity()); // DO WE NEED GHOST CELLS FILLED ???
}
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MyConstParIter pti(*this, lev); pti.isValid(); ++pti) {
const int grid = pti.index();
const AoS& pbox = pti.GetArrayOfStructs();
const int n = pbox.size();
const amrex::FArrayBox& phifab = (phi_pointer) ? (*phi_pointer)[grid] : phi[grid];
num_particles_at_level += n;
for (int i = 0; i < n; i++) {
const ParticleType& p = pbox[i];
if (p.id() <= 0) continue;
amrex::Real vel_square = (p.rdata(1)*p.rdata(1)+p.rdata(2)*p.rdata(2)+p.rdata(3)*p.rdata(3));
amrex::Real dt_part = (vel_square > 0) ? (cfl * 2.0 / vel_square) : 1e50;
amrex::IntVect cell = this->Index(p, lev);
const amrex::Real pot = phifab(cell,0);
if (pot > 0)
dt_part = std::min( dt_part, cfl / pot );
// if(p.rdata(0))
// dt_part = std::min( dt_part, p.rdata(0) );
int tid = 0;
#ifdef _OPENMP
tid = omp_get_thread_num();
#endif
ldt[tid] = std::min(dt_part, ldt[tid]);
}
}
if (phi_pointer) delete phi_pointer;
for (int i = 0; i < ldt.size(); i++)
dt = std::min(dt, ldt[i]);
amrex::ParallelDescriptor::ReduceRealMin(dt);
//
// Set dt negative if there are no particles at this level.
//
amrex::ParallelDescriptor::ReduceLongSum(num_particles_at_level);
if (num_particles_at_level == 0) dt = -1.e50;
if (this->m_verbose > 1)
{
amrex::Real stoptime = amrex::ParallelDescriptor::second() - strttime;
amrex::ParallelDescriptor::ReduceRealMax(stoptime,amrex::ParallelDescriptor::IOProcessorNumber());
if (amrex::ParallelDescriptor::IOProcessor())
{
std::cout << "FDMwkbParticleContainer::estTimestep() time: " << stoptime << '\n';
}
}
return dt;
}
void
FDMwkbParticleContainer::InitCosmo1ppcMultiLevel(amrex::Vector<std::unique_ptr<amrex::MultiFab> >& mf,
amrex::Vector<amrex::MultiFab*>& phase,
const Real gamma_ax, const Real particleMass,
BoxArray &baWhereNot, int lev, int nlevs)
{
BL_PROFILE("FDMParticleContainer::InitCosmo1ppcMultiLevel()");
const int MyProc = ParallelDescriptor::MyProc();
const Geometry& geom = m_gdb->Geom(lev);
const Real* dx = geom.CellSize();
/*Only initialize Gauss beams on finest initial level*/
if( lev != (nlevs-1) )
return;
static Vector<int> calls;
calls.resize(nlevs);
calls[lev]++;
if (calls[lev] > 1) return;
Vector<ParticleLevel>& particles = this->GetParticles();
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(nlevs);
ParticleType p;
//
// The mf should be initialized according to the ics...
//
int outside_counter=0;
long outcount[3]={0,0,0};
long outcountminus[3]={0,0,0};
long totalcount=0;
Real Amp;
// for (int lev = 0; lev<nlevs; lev++)
for (MFIter mfi(*(mf[lev])); mfi.isValid(); ++mfi)
{
FArrayBox& myFab = (*(mf[lev]))[mfi];
FArrayBox& phaseFab = (*(phase[lev]))[mfi];
const Box& vbx = mfi.validbox();
const int *fab_lo = vbx.loVect();
const int *fab_hi = vbx.hiVect();
ParticleLocData pld;
for (int kx = fab_lo[2]; kx <= fab_hi[2]; kx++)
{
for (int jx = fab_lo[1]; jx <= fab_hi[1]; jx++)
{
for (int ix = fab_lo[0]; ix <= fab_hi[0]; ix++)
{
IntVect indices(D_DECL(ix, jx, kx));
totalcount++;
if (baWhereNot.contains(indices))
{
continue;
}
for (int n = 0; n < BL_SPACEDIM; n++)
{
//
// Set positions (1 p per cell in the center of the cell)
//
p.pos(n) = geom.ProbLo(n) +
(indices[n]+Real(0.5))*dx[n];
//
// Set velocities
//
p.rdata(n+1) = myFab(indices,n+1);
}
//
// Set the mass of the particle from the input value.
//
p.rdata(0) = particleMass;
p.id() = ParticleType::NextID();
p.cpu() = MyProc;
// Amp = std::sqrt(myFab(indices));
Amp = pow(myFab(indices,0),1.0/3.0)*dx[0]*dx[0]/M_PI;
// Amp = std::sqrt(0.5);
//set phase
p.rdata( 4) = phaseFab(indices,0);
//set amplitude
p.rdata( 5) = pow(gamma_ax*Amp,1.5);
p.rdata( 6) = 0.0;
//set width
p.rdata( 7) = gamma_ax;
//set Jacobian qq
p.rdata( 8) = Amp;
p.rdata( 9) = 0.0;
p.rdata(10) = 0.0;
p.rdata(11) = 0.0;
p.rdata(12) = Amp;
p.rdata(13) = 0.0;
p.rdata(14) = 0.0;
p.rdata(15) = 0.0;
p.rdata(16) = Amp;
//set Jacobian pq
p.rdata(17) = 0.0;
p.rdata(18) = 0.0;
p.rdata(19) = 0.0;
p.rdata(20) = 0.0;
p.rdata(21) = 0.0;
p.rdata(22) = 0.0;
p.rdata(23) = 0.0;
p.rdata(24) = 0.0;
p.rdata(25) = 0.0;
if (!this->Where(p, pld))
{
this->PeriodicShift(p);
if (!this->Where(p, pld))
amrex::Abort("FDMParticleContainer::InitCosmo1ppcMultiLevel():invalid particle");
}
BL_ASSERT(pld.m_lev >= 0 && pld.m_lev <= m_gdb->finestLevel());
//handle particles that ran out of this level into a finer one.
if (baWhereNot.contains(pld.m_cell))
{
outside_counter++;
ParticleType newp[8];
ParticleLocData new_pld;
for (int i=0;i<8;i++)
{
newp[i].rdata(0) = particleMass/8.0;
newp[i].id() = ParticleType::NextID();
newp[i].cpu() = MyProc;
for (int dim=0;dim<BL_SPACEDIM;dim++)
{
newp[i].pos(dim)=p.pos(dim)+(2*((i/(1 << dim)) % 2)-1)*dx[dim]/4.0;
newp[i].rdata(dim+1)=p.rdata(dim+1);
}
if (!this->Where(newp[i], new_pld))
{
this->PeriodicShift(newp[i]);
if (!this->Where(newp[i], new_pld))
amrex::Abort("FDMParticleContainer::InitCosmo1ppcMultiLevel():invalid particle");
}
particles[new_pld.m_lev][std::make_pair(new_pld.m_grid,
new_pld.m_tile)].push_back(newp[i]);
}
}
//
// Add it to the appropriate PBox at the appropriate level.
//
else
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(p);
}
}
}
}
Redistribute();
}
void
FDMwkbParticleContainer::InitCosmo1ppcMultiLevel(MultiFab& vel, MultiFab& phase, MultiFab& dens,
const Real gamma_ax, const Real particleMass,
BoxArray &baWhereNot, int lev, int nlevs)
{
/*Only initialize Gauss beams on finest initial level*/
if( lev != (nlevs-1) )
return;
BL_PROFILE("FDMParticleContainer::InitCosmo1ppcMultiLevel()");
const int MyProc = ParallelDescriptor::MyProc();
const Geometry& geom = m_gdb->Geom(lev);
const Real* dx = geom.CellSize();
static Vector<int> calls;
calls.resize(nlevs);
calls[lev]++;
if (calls[lev] > 1) return;
Vector<ParticleLevel>& particles = this->GetParticles();
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(nlevs);
ParticleType p;
//
// The mf should be initialized according to the ics...
//
int outside_counter=0;
long outcount[3]={0,0,0};
long outcountminus[3]={0,0,0};
long totalcount=0;
Real Amp;
// for (int lev = 0; lev<nlevs; lev++)
for (MFIter mfi(dens); mfi.isValid(); ++mfi)
{
FArrayBox& velFab = vel[mfi];
FArrayBox& phaseFab = phase[mfi];
FArrayBox& densFab = dens[mfi];
const Box& vbx = mfi.validbox();
const int *fab_lo = vbx.loVect();
const int *fab_hi = vbx.hiVect();
ParticleLocData pld;
for (int kx = fab_lo[2]; kx <= fab_hi[2]; kx++)
{
for (int jx = fab_lo[1]; jx <= fab_hi[1]; jx++)
{
for (int ix = fab_lo[0]; ix <= fab_hi[0]; ix++)
{
IntVect indices(D_DECL(ix, jx, kx));
totalcount++;
if (baWhereNot.contains(indices))
{
continue;
}
for (int n = 0; n < BL_SPACEDIM; n++)
{
//
// Set positions (1 p per cell in the center of the cell)
//
p.pos(n) = geom.ProbLo(n) +
(indices[n]+Real(0.5))*dx[n];
//
// Set velocities
//
p.rdata(n+1) = velFab(indices,n);
}
//
// Set the mass of the particle from the input value.
//
p.rdata(0) = 0.0;//particleMass;
p.id() = ParticleType::NextID();
p.cpu() = MyProc;
// Amp = std::sqrt(myFab(indices));
Amp = pow(densFab(indices,0),1.0/3.0)*dx[0]*dx[0]/M_PI;
// Amp = std::sqrt(0.5);
//set phase
p.rdata( 4) = phaseFab(indices,0);
if(p.rdata( 4)!=p.rdata( 4))
amrex::Abort("Nans in FDM beam phase!!");
//set amplitude
p.rdata( 5) = pow(gamma_ax*Amp,1.5);
p.rdata( 6) = 0.0;
//set width
p.rdata( 7) = gamma_ax;
//set Jacobian qq
p.rdata( 8) = Amp;
p.rdata( 9) = 0.0;
p.rdata(10) = 0.0;
p.rdata(11) = 0.0;
p.rdata(12) = Amp;
p.rdata(13) = 0.0;
p.rdata(14) = 0.0;
p.rdata(15) = 0.0;
p.rdata(16) = Amp;
//set Jacobian pq
p.rdata(17) = 0.0;
p.rdata(18) = 0.0;
p.rdata(19) = 0.0;
p.rdata(20) = 0.0;
p.rdata(21) = 0.0;
p.rdata(22) = 0.0;
p.rdata(23) = 0.0;
p.rdata(24) = 0.0;
p.rdata(25) = 0.0;
if (!this->Where(p, pld))
{
this->PeriodicShift(p);
if (!this->Where(p, pld))
amrex::Abort("FDMParticleContainer::InitCosmo1ppcMultiLevel():invalid particle");
}
BL_ASSERT(pld.m_lev >= 0 && pld.m_lev <= m_gdb->finestLevel());
//handle particles that ran out of this level into a finer one.
if (baWhereNot.contains(pld.m_cell))
{
outside_counter++;
ParticleType newp[8];
ParticleLocData new_pld;
for (int i=0;i<8;i++)
{
newp[i].rdata(0) = particleMass/8.0;
newp[i].id() = ParticleType::NextID();
newp[i].cpu() = MyProc;
for (int dim=0;dim<BL_SPACEDIM;dim++)
{
newp[i].pos(dim)=p.pos(dim)+(2*((i/(1 << dim)) % 2)-1)*dx[dim]/4.0;
newp[i].rdata(dim+1)=p.rdata(dim+1);
}
if (!this->Where(newp[i], new_pld))
{
this->PeriodicShift(newp[i]);
if (!this->Where(newp[i], new_pld))
amrex::Abort("FDMParticleContainer::InitCosmo1ppcMultiLevel():invalid particle");
}
particles[new_pld.m_lev][std::make_pair(new_pld.m_grid,
new_pld.m_tile)].push_back(newp[i]);
}
}
//
// Add it to the appropriate PBox at the appropriate level.
//
else
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(p);
}
}
}
}
Redistribute();
}
void
FDMwkbParticleContainer::InitCosmo1ppc(MultiFab& mf, const Real vel_fac[], const Real particleMass)
{
BL_PROFILE("FDMwkbParticleContainer::InitCosmo1ppc()");
const int MyProc = ParallelDescriptor::MyProc();
const Geometry& geom = m_gdb->Geom(0);
const Real* dx = geom.CellSize();
Vector<ParticleLevel>& particles = this->GetParticles();
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(m_gdb->finestLevel()+1);
for (int lev = 0; lev < particles.size(); lev++)
{
BL_ASSERT(particles[lev].empty());
}
ParticleType p;
ParticleLocData pld;
Real disp[BL_SPACEDIM];
const Real len[BL_SPACEDIM] = { D_DECL(geom.ProbLength(0),
geom.ProbLength(1),
geom.ProbLength(2)) };
//
// The grid should be initialized according to the ics...
//
for (MFIter mfi(mf); mfi.isValid(); ++mfi)
{
FArrayBox& myFab = mf[mfi];
const Box& vbx = mfi.validbox();
const int *fab_lo = vbx.loVect();
const int *fab_hi = vbx.hiVect();
for (int kx = fab_lo[2]; kx <= fab_hi[2]; kx++)
{
for (int jx = fab_lo[1]; jx <= fab_hi[1]; jx++)
{
for (int ix = fab_lo[0]; ix <= fab_hi[0]; ix++)
{
IntVect indices(D_DECL(ix, jx, kx));
for (int n = 0; n < BL_SPACEDIM; n++)
{
disp[n] = myFab(indices,n);
//
// Start with homogeneous distribution (for 1 p per cell in the center of the cell),
// then add the displacement (input values weighted by domain length).
//
p.pos(n) = geom.ProbLo(n) +
(indices[n]+Real(0.5))*dx[n] +
disp[n] * len[n];
//
// Set the velocities.
//
p.rdata(n+1) = disp[n] * vel_fac[n];
}
//
// Set the mass of the particle from the input value.
//
p.rdata(0) = particleMass;
p.id() = ParticleType::NextID();
p.cpu() = MyProc;
if (!this->Where(p, pld))
{
this->PeriodicShift(p);
if (!this->Where(p, pld))
amrex::Abort("FDMwkbParticleContainer::InitCosmo1ppc(): invalid particle");
}
BL_ASSERT(pld.m_lev >= 0 && pld.m_lev <= this->finestLevel());
//
// Add it to the appropriate PBox at the appropriate level.
//
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(p);
}
}
}
}
}
void
FDMwkbParticleContainer::InitCosmo(
MultiFab& mf, const Real vel_fac[], const Vector<int> n_part, const Real particleMass)
{
Real shift[] = {0,0,0};
InitCosmo(mf, vel_fac, n_part, particleMass, shift);
}
void
FDMwkbParticleContainer::InitCosmo(
MultiFab& mf, const Real vel_fac[], const Vector<int> n_part, const Real particleMass, const Real shift[])
{
BL_PROFILE("FDMwkbParticleContainer::InitCosmo()");
const int MyProc = ParallelDescriptor::MyProc();
const int IOProc = ParallelDescriptor::IOProcessorNumber();
const Real strttime = ParallelDescriptor::second();
const Geometry& geom = m_gdb->Geom(0);
Vector<ParticleLevel>& particles = this->GetParticles();
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(m_gdb->finestLevel()+1);
for (int lev = 0; lev < particles.size(); lev++)
{
BL_ASSERT(particles[lev].empty());
}
const Real len[BL_SPACEDIM] = { D_DECL(geom.ProbLength(0),
geom.ProbLength(1),
geom.ProbLength(2)) };
//
// Print the grids as a sanity check.
//
for (MFIter mfi(mf); mfi.isValid(); ++mfi)
{
const Box& vbx = mfi.validbox();
const int *fab_lo = vbx.loVect();
const int *fab_hi = vbx.hiVect();
if (vbx.isEmpty())
{
std::cout << "...bad grid lo " << fab_lo[0] << " " << fab_lo[1] << " " << fab_lo[2] << '\n';
std::cout << "...bad grid hi " << fab_hi[0] << " " << fab_hi[1] << " " << fab_hi[2] << '\n';
amrex::Error("Empty box in InitCosmo ");
}
if (!geom.Domain().contains(vbx))
{
std::cout << "...bad grid lo " << fab_lo[0] << " " << fab_lo[1] << " " << fab_lo[2] << '\n';
std::cout << "...bad grid hi " << fab_hi[0] << " " << fab_hi[1] << " " << fab_hi[2] << '\n';
amrex::Error("Box in InitCosmo not contained in domain");
}
}
//
// We will need one ghost cell, so check wether we have one.
//
if (mf.nGrow() < 1)
amrex::Abort("FDMwkbParticleContainer::InitCosmo: mf needs at least one correctly filled ghost zone!");
if ( !(n_part[0] == n_part[1] && n_part[1] == n_part[2]) )
{
std::cout << '\n' << '\n';
std::cout << "Your particle lattice will have different spacings in the spatial directions!" << '\n';
std::cout << "You might want to change the particle number or the algorithm... ;)" << '\n';
std::cout << '\n' << '\n';
}
//
// Place the particles evenly spaced in the problem domain.
// Not perfectly fast - but easy
//
Real pos[BL_SPACEDIM];
ParticleType p;
for (MFIter mfi(mf); mfi.isValid(); ++mfi)
{
const Box& box = mfi.validbox();
RealBox gridloc = RealBox(box, geom.CellSize(), geom.ProbLo());
const Real* xlo = gridloc.lo();
const Real* xhi = gridloc.hi();
ParticleLocData pld;
for (int k = 0; k < n_part[2]; k++)
{
for (int j = 0; j < n_part[1]; j++)
{
for (int i = 0; i < n_part[0]; i++)
{
bool isInValidBox = true;
IntVect indices(D_DECL(i, j, k));
for (int n = 0; n < BL_SPACEDIM; n++)
{
pos[n] = geom.ProbLo(n)
+ (indices[n] + Real(0.5))*len[n]/n_part[n]
+ shift[n];
//
// Make sure particle is not on a boundary...
//
pos[n] += 1e-14 * (geom.ProbHi(n) - geom.ProbLo(n));
isInValidBox = isInValidBox
&& (pos[n] > xlo[n])
&& (pos[n] < xhi[n]);
}
if (isInValidBox)
{
D_TERM(p.pos(0) = pos[0];,
p.pos(1) = pos[1];,
p.pos(2) = pos[2];);
//
// Set the mass of the particle.
//
p.rdata(0) = particleMass;
p.id() = ParticleType::NextID();
p.cpu() = MyProc;
if (!this->Where(p, pld))
{
this->PeriodicShift(p);
if (!this->Where(p, pld))
amrex::Abort("FDMwkbParticleContainer::InitCosmo(): invalid particle");
}
BL_ASSERT(pld.m_lev >= 0 && pld.m_lev <= m_gdb->finestLevel());
//
// Add it to the appropriate PBox at the appropriate level.
//
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(p);
}
}
}
}
}
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Done with equidistant placement" << '\n';
}
//
// Let Redistribute() sort out where the particles belong.
//
Redistribute();
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Redistribute done" << '\n';
}
BL_ASSERT(OK());
//
// FIXME: Will we ever need initial particles in grids deeper than 0?!
//
ParticleLevel& pmap = this->GetParticles(0);
//
// Make sure, that mf and m_gdb.boxArray(0) are defined on the same boxarray.
//
ParticleLocData pld;
for (auto& kv : pmap) {
const int grid = kv.first.first;
AoS& pbox = kv.second.GetArrayOfStructs();
const int n = pbox.size();
const FArrayBox& dfab = mf[grid];
#ifdef _OPENMP
#pragma omp parallel for private(pld)
#endif
for (int i = 0; i < n; i++)
{
ParticleType& p = pbox[i];
if (p.id() <= 0) continue;
Real disp[BL_SPACEDIM];
//
// Do CIC interpolation onto the particle positions.
// For CIC we need one ghost cell!
//
ParticleType::GetGravity(dfab, m_gdb->Geom(0), p, disp);
D_TERM(p.pos(0) += len[0]*disp[0];,
p.pos(1) += len[1]*disp[1];,
p.pos(2) += len[2]*disp[2];);
//
// Note: m_data[0] is mass, 1 is v_x, ...
//
D_TERM(p.rdata(1) = vel_fac[0]*disp[0];,
p.rdata(2) = vel_fac[1]*disp[1];,
p.rdata(3) = vel_fac[2]*disp[2];);
if (!this->Where(p, pld))
{
this->PeriodicShift(p);
if (!this->Where(p, pld))
amrex::Abort("FDMwkbParticleContainer::InitCosmo(): invalid particle");
}
this->Reset(p, true);
}
}
//
// Let Redistribute() sort out where the particles now belong.
//
Redistribute();
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Done with particle displacement" << '\n';
}
if (m_verbose > 1)
{
Real runtime = ParallelDescriptor::second() - strttime;
ParallelDescriptor::ReduceRealMax(runtime, IOProc);
if (ParallelDescriptor::IOProcessor())
{
std::cout << "InitCosmo() done time: " << runtime << '\n';
}
}
}
void
FDMwkbParticleContainer::InitFromBinaryMortonFile(const std::string& particle_directory,
int nextra, int skip_factor) {
BL_PROFILE("FDMwkbParticleContainer::InitFromBinaryMortonFile");
ParticleMortonFileHeader hdr;
ReadHeader(particle_directory, "Header", hdr);
uint64_t num_parts = hdr.NP;
int DM = hdr.DM;
int NX = hdr.NX;
int float_size = hdr.SZ;
int num_files = hdr.NF;
size_t psize = (DM + NX) * float_size;
std::string particle_file_base = particle_directory + "/particles.";
std::vector<std::string> file_names;
for (int i = 0; i < num_files; ++i)
file_names.push_back(get_file_name(particle_file_base, i));
const int lev = 0;
const BoxArray& ba = ParticleBoxArray(lev);
int num_boxes = ba.size();
uint64_t num_parts_per_box = num_parts / num_boxes;
uint64_t num_parts_per_file = num_parts / num_files;
uint64_t num_bytes_per_file = num_parts_per_file * psize;
std::vector<BoxMortonKey> box_morton_keys(num_boxes);
for (int i = 0; i < num_boxes; ++i) {
const Box& box = ba[i];
unsigned int x = box.smallEnd(0);
unsigned int y = box.smallEnd(1);
unsigned int z = box.smallEnd(2);
box_morton_keys[i].morton_id = get_morton_index(x, y, z);
box_morton_keys[i].box_id = i;
}
std::sort(box_morton_keys.begin(), box_morton_keys.end(), by_morton_id());
std::vector<int> file_indices(num_boxes);
for (int i = 0; i < num_boxes; ++i)
file_indices[box_morton_keys[i].box_id] = i;
ParticleType p;
for (MFIter mfi = MakeMFIter(lev, false); mfi.isValid(); ++mfi) { // no tiling
Box tile_box = mfi.tilebox();
const int grid = mfi.index();
const int tile = mfi.LocalTileIndex();
auto& particles = GetParticles(lev);
uint64_t start = file_indices[grid]*num_parts_per_box;
uint64_t stop = start + num_parts_per_box;
int file_num = start / num_parts_per_file;
uint64_t seek_pos = (start * psize ) % num_bytes_per_file;
std::string file_name = file_names[file_num];
std::ifstream ifs;
ifs.open(file_name.c_str(), std::ios::in|std::ios::binary);
if ( not ifs ) {
amrex::Print() << "Failed to open file " << file_name << " for reading. \n";
amrex::Abort();
}
ifs.seekg(seek_pos, std::ios::beg);
for (uint64_t i = start; i < stop; ++i) {
int next_file = i / num_parts_per_file;
if (next_file != file_num) {
file_num = next_file;
file_name = file_names[file_num];
ifs.close();
ifs.open(file_name.c_str(), std::ios::in|std::ios::binary);
if ( not ifs ) {
amrex::Print() << "Failed to open file " << file_name << " for reading. \n";
amrex::Abort();
}
}
float fpos[DM];
float fextra[NX];
ifs.read((char*)&fpos[0], DM*sizeof(float));
ifs.read((char*)&fextra[0], NX*sizeof(float));
if ( (i - start) % skip_factor == 0 ) {
AMREX_D_TERM(p.m_rdata.pos[0] = fpos[0];,
p.m_rdata.pos[1] = fpos[1];,
p.m_rdata.pos[2] = fpos[2];);
for (int comp = 0; comp < NX; comp++)
p.m_rdata.arr[BL_SPACEDIM+comp] = fextra[comp];
p.m_rdata.arr[BL_SPACEDIM] *= skip_factor;
p.m_idata.id = ParticleType::NextID();
p.m_idata.cpu = ParallelDescriptor::MyProc();
particles[std::make_pair(grid, tile)].push_back(p);
}
}
}
Redistribute();
}
void
FDMwkbParticleContainer::InitVarCount (MultiFab& mf, long num_particle_fdm, BoxArray &baWhereNot, int lev, int nlevs)
{
const int MyProc = ParallelDescriptor::MyProc();
const Geometry& geom = m_gdb->Geom(lev);
const Real* dx = geom.CellSize();
static Vector<int> calls;
calls.resize(nlevs);
calls[lev]++;
if (calls[lev] > 1) return;
Vector<ParticleLevel>& particles = this->GetParticles();
int npart;
Real r;
Real factor = mf.norm1(0,0)/num_particle_fdm; //compute density per particle
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(nlevs);
for (int i = 0; i < particles.size(); i++)
{
BL_ASSERT(particles[i].empty());
}
ParticleType p;
amrex::InitRandom(MyProc);
//
// The grid should be initialized according to the ics...
//
for (MFIter mfi(mf); mfi.isValid(); ++mfi)
{
FArrayBox& myFab = mf[mfi];
const Box& vbx = mfi.validbox();
const int *fab_lo = vbx.loVect();
const int *fab_hi = vbx.hiVect();
ParticleLocData pld;
for (int kx = fab_lo[2]; kx <= fab_hi[2]; kx++)
{
for (int jx = fab_lo[1]; jx <= fab_hi[1]; jx++)
{
for (int ix = fab_lo[0]; ix <= fab_hi[0]; ix++)
{
IntVect indices(D_DECL(ix, jx, kx));
//compute the floor of number of particles in the cell
npart = myFab(indices,0)/factor;
//roll dice to decide whether to add another particle -----
r = amrex::Random();
if(r < myFab(indices,0)/factor-npart){
npart++;
}
// --------------------------------------------------------
for (int ipart = 0; ipart < npart; ipart++){
for (int n = 0; n < BL_SPACEDIM; n++)
{
do
{
r = amrex::Random();
}
while (r == 0 || r == 1);
p.pos(n) = geom.ProbLo(n) +
(indices[n]+r)*dx[n];
}
// set mass
p.rdata(0) = factor * dx[0] * dx[1] * dx[2];
// set velocity
for (int n = 0; n < BL_SPACEDIM; n++)
{
p.rdata(n+1) = myFab(indices, n+1);
}
p.id() = ParticleType::NextID();
p.cpu() = MyProc;
if (!this->Where(p,pld))
{
this->PeriodicShift(p);
if (!this->Where(p,pld))
amrex::Abort("ParticleContainer<N>::InitVarCount(): invalid particle");
}
BL_ASSERT(pld.m_lev >= 0 && pld.m_lev <= m_gdb->finestLevel());
//handle particles that ran out of this level into a finer one.
if (baWhereNot.contains(pld.m_cell))
{
ParticleLocData new_pld;
if (!this->Where(p, new_pld))
{
this->PeriodicShift(p);
if (!this->Where(p, new_pld))
amrex::Abort("FDMwkbParticleContainer::InitVarCount():invalid particle");
}
particles[new_pld.m_lev][std::make_pair(new_pld.m_grid,
new_pld.m_tile)].push_back(p);
}
//
// Add it to the appropriate PBox at the appropriate level.
//
else
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(p);
}
}
}
}
}
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Done with Gaussian Beam initilization" << '\n';
}
//
// Let Redistribute() sort out where the particles belong.
//
Redistribute();
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Redistribute done" << '\n';
}
}
void
FDMwkbParticleContainer::InitGaussianBeams (long num_particle_fdm, int lev, int nlevs, const Real hbaroverm, const Real sigma_ax, const Real gamma_ax, const Real fact, const Real alpha, const Real a)
{
const int MyProc = ParallelDescriptor::MyProc();
const int nprocs = ParallelDescriptor::NProcs();
const Geometry& geom = m_gdb->Geom(lev);
const Real* dx = geom.CellSize();
static Vector<int> calls;
calls.resize(nlevs);
calls[lev]++;
if (calls[lev] > 1) return;
Vector<ParticleLevel>& particles = this->GetParticles();
int npart = num_particle_fdm;
int npart_tot = nprocs*npart; //Each processor initializes num_particle_fdm beams
Real q[] = {(geom.ProbHi(0)+geom.ProbLo(0))/2.0, (geom.ProbHi(1)+geom.ProbLo(1))/2.0, (geom.ProbHi(2)+geom.ProbLo(2))/2.0};
Real p[] = {0.0,0.0,0.0};
Real q0[] = {(geom.ProbHi(0)+geom.ProbLo(0))/2.0, (geom.ProbHi(1)+geom.ProbLo(1))/2.0, (geom.ProbHi(2)+geom.ProbLo(2))/2.0};
Real p0[] = {0.0,0.0,0.0};
Real phi, Amp;
Real sigma = 0.5/sqrt(alpha);
particles.reserve(15); // So we don't ever have to do any copying on a resize.
particles.resize(nlevs);
for (int i = 0; i < particles.size(); i++)
{
BL_ASSERT(particles[i].empty());
}
ParticleType part;
ParticleLocData pld;
amrex::InitRandom(MyProc);
for(int index=0;index<npart;index++){
q[0] = generateGaussianNoise(q0[0],sigma*sqrt(2.0));
q[1] = generateGaussianNoise(q0[1],sigma*sqrt(2.0));
q[2] = generateGaussianNoise(q0[2],sigma*sqrt(2.0));
phi = 0.0;
p[0] = p0[0];
p[1] = p0[1];
p[2] = p0[2];
Amp = pow(100.0*fact/npart_tot/npart_tot,1.0/3.0)/M_PI/(alpha/M_PI);
if(q[0]>geom.ProbLo(0) && q[0]<geom.ProbHi(0) && q[1]>geom.ProbLo(1) && q[1]<geom.ProbHi(1) && q[2]>geom.ProbLo(2) && q[2]<geom.ProbHi(2)){
part.id() = ParticleType::NextID();
part.cpu() = MyProc;
//set position
for (int n = 0; n < BL_SPACEDIM; n++)
part.pos( n) = q[n];
//set mass
part.rdata( 0) = 1.0/(npart_tot * dx[0] * dx[1] * dx[2]);
//set velocity
part.rdata( 1) = p[0]/a;
part.rdata( 2) = p[1]/a;
part.rdata( 3) = p[2]/a;
//set phase
part.rdata( 4) = phi;
//set amplitude
part.rdata( 5) = pow(gamma_ax*Amp,1.5);
part.rdata( 6) = 0.0;
//set width
part.rdata( 7) = gamma_ax;
//set Jacobian qq
part.rdata( 8) = Amp;
part.rdata( 9) = 0.0;
part.rdata(10) = 0.0;
part.rdata(11) = 0.0;
part.rdata(12) = Amp;
part.rdata(13) = 0.0;
part.rdata(14) = 0.0;
part.rdata(15) = 0.0;
part.rdata(16) = Amp;
//set Jacobian pq
part.rdata(17) = 0.0;
part.rdata(18) = 0.0;
part.rdata(19) = 0.0;
part.rdata(20) = 0.0;
part.rdata(21) = 0.0;
part.rdata(22) = 0.0;
part.rdata(23) = 0.0;
part.rdata(24) = 0.0;
part.rdata(25) = 0.0;
if (!this->Where(part,pld))
amrex::Abort("ParticleContainer<N>::InitGaussianBeams(): invalid particle");
//add particle
particles[pld.m_lev][std::make_pair(pld.m_grid, pld.m_tile)].push_back(part);
}
else
index--;
}
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Done with Gaussian Beam initilization" << '\n';
}
//
// Let Redistribute() sort out where the particles belong.
//
Redistribute();
if (ParallelDescriptor::IOProcessor() && m_verbose)
{
std::cout << "Redistribute done" << '\n';
}
}
amrex::Real
FDMwkbParticleContainer::generateGaussianNoise(const amrex::Real &mean, const amrex::Real &stdDev) {
static bool hasSpare = false;
static amrex::Real spare;
if(hasSpare) {
hasSpare = false;
return mean + stdDev * spare;
}
hasSpare = true;
static amrex::Real u, v, s;
do {
u = (rand() / ((amrex::Real) RAND_MAX)) * 2.0 - 1.0;
v = (rand() / ((amrex::Real) RAND_MAX)) * 2.0 - 1.0;
s = u * u + v * v;
}
while( (s >= 1.0) || (s == 0.0) );
s = sqrt(-2.0 * log(s) / s);
spare = v * s;
return mean + stdDev * u * s;
}
#endif /*FDM*/
| 38.248674
| 211
| 0.429285
|
Gosenca
|
734704a2af5c9d6c41855363309c8b701a770744
| 3,725
|
cpp
|
C++
|
src/Objects/Motobug.cpp
|
MainMemory/CuckySonic
|
af8e10f3c05b286b830001e73f79d9a7a8edc84e
|
[
"MIT"
] | 2
|
2020-01-10T06:52:40.000Z
|
2020-12-17T02:57:30.000Z
|
src/Objects/Motobug.cpp
|
MainMemory/CuckySonic
|
af8e10f3c05b286b830001e73f79d9a7a8edc84e
|
[
"MIT"
] | null | null | null |
src/Objects/Motobug.cpp
|
MainMemory/CuckySonic
|
af8e10f3c05b286b830001e73f79d9a7a8edc84e
|
[
"MIT"
] | null | null | null |
#include "../Game.h"
static const uint8_t animationStand[] = {0x0F,0x02,ANICOMMAND_RESTART};
static const uint8_t animationWalk[] = {0x07,0x00,0x01,0x00,0x02,ANICOMMAND_RESTART};
static const uint8_t animationSmoke[] = {0x01,0x03,0x06,0x04,0x06,0x04,0x06,0x04,0x06,0x05,ANICOMMAND_ADVANCE_ROUTINE};
static const uint8_t *animationList[] = {
animationStand,
animationWalk,
animationSmoke,
};
void ObjMotobug(OBJECT *object)
{
//Define and allocate our scratch
struct SCRATCH
{
int8_t time = 0;
int8_t smokeDelay = 0;
};
SCRATCH *scratch = object->Scratch<SCRATCH>();
if (object->routine == 0)
{
//Load graphics
object->texture = gLevel->GetObjectTexture("data/Object/Sonic1Badnik.bmp");
object->mapping.mappings = gLevel->GetObjectMappings("data/Object/Motobug.map");
//Initialize other properties
object->routine++;
object->renderFlags.alignPlane = true;
object->widthPixels = 24;
object->heightPixels = 32;
object->priority = 4;
if (object->anim == 0)
{
//If a motobug, setup our collision
object->xRadius = 8;
object->yRadius = 14;
object->collisionType = COLLISIONTYPE_ENEMY;
object->touchWidth = 20;
object->touchHeight = 16;
}
else
object->routine = 3; //Dust routine
}
switch (object->routine)
{
case 1: //Waiting to spawn
{
//Fall down to the ground
object->MoveAndFall();
//Check for the floor
int16_t distance = object->CheckCollisionDown_1Point(COLLISIONLAYER_NORMAL_TOP, object->x.pos, object->y.pos + object->yRadius, nullptr);
if (distance >= 0)
break;
//Initialize state
object->yVel = 0;
object->routine++;
object->y.pos += distance;
object->status.xFlip ^= 1;
break;
}
case 2: //Moving forwards
{
switch (object->routineSecondary)
{
case 0:
{
if (--scratch->time < 0)
{
//Set state and turn around
object->routineSecondary = 1;
object->status.xFlip ^= 1;
object->anim = 1;
if (object->status.xFlip)
object->xVel = 0x100;
else
object->xVel = -0x100;
}
break;
}
case 1:
{
//Move and check if we're going over an edge
object->Move();
int16_t distance = object->CheckCollisionDown_1Point(COLLISIONLAYER_NORMAL_TOP, object->x.pos, object->y.pos + object->yRadius, nullptr);
if (distance < -8 || distance >= 12)
{
//Set state and wait
object->routineSecondary = 0;
scratch->time = 59;
object->xVel = 0;
object->anim = 0;
break;
}
//Move across ground
object->y.pos += distance;
//Create smoke every 16 frames
if (--scratch->smokeDelay < 0)
{
//Restart timer and create object
scratch->smokeDelay = 15;
OBJECT *newSmoke = new OBJECT(&ObjMotobug);
newSmoke->x.pos = object->x.pos;
newSmoke->y.pos = object->y.pos;
newSmoke->status = object->status;
newSmoke->anim = 2;
gLevel->objectList.link_back(newSmoke);
}
break;
}
}
//Animate and draw
object->Animate_S1(animationList);
object->DrawInstance(object->renderFlags, object->texture, object->mapping, object->highPriority, object->priority, object->mappingFrame, object->x.pos, object->y.pos);
object->UnloadOffscreen(object->x.pos);
break;
}
case 3: //Smoke
{
//Animate and draw
object->Animate_S1(animationList);
object->DrawInstance(object->renderFlags, object->texture, object->mapping, object->highPriority, object->priority, object->mappingFrame, object->x.pos, object->y.pos);
break;
}
case 4: //Smoke deletion
{
//Delete us
object->deleteFlag = true;
break;
}
default:
break;
}
}
| 25.168919
| 171
| 0.638121
|
MainMemory
|
7347dfa1f323a791b26e7004b9f4131f6addf66d
| 10,387
|
cpp
|
C++
|
sdl2-sonic-drivers/src/files/westwood/ADLFile.cpp
|
Raffaello/sdl2-sonic-drivers
|
20584f100ddd7c61f584deaee0b46c5228d8509d
|
[
"Apache-2.0"
] | 3
|
2021-10-31T14:24:00.000Z
|
2022-03-16T08:15:31.000Z
|
sdl2-sonic-drivers/src/files/westwood/ADLFile.cpp
|
Raffaello/sdl2-sonic-drivers
|
20584f100ddd7c61f584deaee0b46c5228d8509d
|
[
"Apache-2.0"
] | 48
|
2020-06-05T11:11:29.000Z
|
2022-02-27T23:58:44.000Z
|
sdl2-sonic-drivers/src/files/westwood/ADLFile.cpp
|
Raffaello/sdl2-sonic-drivers
|
20584f100ddd7c61f584deaee0b46c5228d8509d
|
[
"Apache-2.0"
] | null | null | null |
#include "ADLFile.hpp"
#include <exception>
#include <fstream>
namespace files
{
namespace westwood
{
/***************************************************************************
* Here's the rough structure of ADL files. The player needs only the *
* first part, the driver uses only the second part (all offsets in the *
* programs/instruments tables are relative to the start of _soundData). *
* *
* _trackEntries[] _soundData[] *
* +------------------+ +-----------------+--------------------+------//-+ *
* | subsong->prog.ID | | Program offsets | Instrument offsets | Data... | *
* +------------------+ +-----------------+--------------------+------//-+ *
* v1: 120 bytes 150 words 150 words @720 *
* v2: 120 bytes 250 words 250 words @1120 *
* v3: 250 words 500 words 500 words @2500 *
* *
* The versions can be distinguished by inspecting the table entries. *
***************************************************************************/
constexpr int V1_NUM_HEADER = 120;
constexpr int V2_NUM_HEADER = 120;
constexpr int V3_NUM_HEADER = 250;
constexpr int V1_HEADER_SIZE = V1_NUM_HEADER * sizeof(uint8_t);
constexpr int V2_HEADER_SIZE = V2_NUM_HEADER * sizeof(uint8_t);
constexpr int V3_HEADER_SIZE = V3_NUM_HEADER * sizeof(uint16_t);
constexpr int V1_NUM_TRACK_OFFSETS = 150;
constexpr int V2_NUM_TRACK_OFFSETS = 250;
constexpr int V3_NUM_TRACK_OFFSETS = 500;
constexpr int V1_TRACK_OFFSETS_SIZE = V1_NUM_TRACK_OFFSETS * sizeof(uint16_t);
constexpr int V2_TRACK_OFFSETS_SIZE = V2_NUM_TRACK_OFFSETS * sizeof(uint16_t);
constexpr int V3_TRACK_OFFSETS_SIZE = V3_NUM_TRACK_OFFSETS * sizeof(uint16_t);
constexpr int V1_NUM_INSTRUMENT_OFFSETS = 150;
constexpr int V2_NUM_INSTRUMENT_OFFSETS = 250;
constexpr int V3_NUM_INSTRUMENT_OFFSETS = 500;
constexpr int V1_INSTRUMENT_OFFSETS_SIZE = V1_NUM_INSTRUMENT_OFFSETS * sizeof(uint16_t);
constexpr int V2_INSTRUMENT_OFFSETS_SIZE = V2_NUM_INSTRUMENT_OFFSETS * sizeof(uint16_t);
constexpr int V3_INSTRUMENT_OFFSETS_SIZE = V3_NUM_INSTRUMENT_OFFSETS * sizeof(uint16_t);
constexpr int V1_DATA_HEADER_SIZE = V1_TRACK_OFFSETS_SIZE + V1_INSTRUMENT_OFFSETS_SIZE;
constexpr int V2_DATA_HEADER_SIZE = V2_TRACK_OFFSETS_SIZE + V2_INSTRUMENT_OFFSETS_SIZE;
constexpr int V3_DATA_HEADER_SIZE = V3_TRACK_OFFSETS_SIZE + V3_INSTRUMENT_OFFSETS_SIZE;
constexpr int V1_DATA_OFFSET = V1_DATA_HEADER_SIZE + V1_HEADER_SIZE;
constexpr int V2_DATA_OFFSET = V2_DATA_HEADER_SIZE + V2_HEADER_SIZE;
constexpr int V3_DATA_OFFSET = V3_DATA_HEADER_SIZE + V3_HEADER_SIZE;
constexpr int V1_OFFSET_START = V1_DATA_OFFSET - V1_HEADER_SIZE;
constexpr int V2_OFFSET_START = V2_DATA_OFFSET - V2_HEADER_SIZE;
constexpr int V3_OFFSET_START = V3_DATA_OFFSET - V3_HEADER_SIZE;
constexpr int FILE_SIZE_MIN = V1_DATA_OFFSET;
const ADLFile::meta_version_t mv1 = {
V1_NUM_HEADER,
V1_HEADER_SIZE,
V1_DATA_OFFSET,
V1_NUM_TRACK_OFFSETS,
V1_TRACK_OFFSETS_SIZE,
V1_NUM_INSTRUMENT_OFFSETS,
V1_OFFSET_START,
V1_DATA_HEADER_SIZE
};
const ADLFile::meta_version_t mv2 = {
V2_NUM_HEADER,
V2_HEADER_SIZE,
V2_DATA_OFFSET,
V2_NUM_TRACK_OFFSETS,
V2_TRACK_OFFSETS_SIZE,
V2_NUM_INSTRUMENT_OFFSETS,
V2_OFFSET_START,
V2_DATA_HEADER_SIZE
};
const ADLFile::meta_version_t mv3 = {
V3_NUM_HEADER,
V3_HEADER_SIZE,
V3_DATA_OFFSET,
V3_NUM_TRACK_OFFSETS,
V3_TRACK_OFFSETS_SIZE,
V3_NUM_INSTRUMENT_OFFSETS,
V3_OFFSET_START,
V3_DATA_HEADER_SIZE
};
ADLFile::ADLFile(const std::string& filename) : File(filename)
{
_assertValid(size() >= FILE_SIZE_MIN);
detectVersion();
// validate version with file size
_assertValid(size() > _meta_version.data_offset);
// read Header
seek(0, std::fstream::beg);
readHeaderFromFile(_meta_version.num_headers, _read);
// read Track Offsets
readOffsetsFromFile(_meta_version.num_track_offsets, _track_offsets, _meta_version.header_size);
// read Instrument Offsets
readOffsetsFromFile(
_meta_version.num_instrument_offsets,
_instrument_offsets,
_meta_version.track_offsets_size + _meta_version.header_size
);
readDataFromFile(_meta_version.data_offset, _meta_version.data_header_size);
_num_tracks = count_loop<uint8_t>(0, _header);
_num_track_offsets = count_loop<uint16_t>(_meta_version.offset_start, _track_offsets);
_num_instrument_offsets = count_loop<uint16_t>(_meta_version.offset_start, _instrument_offsets);
// Closing file
close();
// Adjust Offsets
adjust_offsets(_track_offsets);
adjust_offsets(_instrument_offsets);
}
uint8_t ADLFile::getVersion() const noexcept
{
return _version;
}
int ADLFile::getNumTracks() const noexcept
{
return _num_tracks;
}
int ADLFile::getNumTrackOffsets() const noexcept
{
return _num_track_offsets;
}
int ADLFile::getNumInstrumentOffsets() const noexcept
{
return _num_instrument_offsets;
}
uint8_t ADLFile::getTrack(const int track) const
{
return _header.at(track);
}
uint16_t ADLFile::getTrackOffset(const int programId) const
{
return _track_offsets.at(programId);
}
uint16_t ADLFile::getInstrumentOffset(const int instrument) const
{
return _instrument_offsets.at(instrument);
}
uint16_t ADLFile::getProgramOffset(const int progId, const PROG_TYPE prog_type) const
{
switch (prog_type)
{
case PROG_TYPE::TRACK:
return getTrackOffset(progId);
case PROG_TYPE::INSTRUMENT:
return getInstrumentOffset(progId);
default:
// unreachable code
return 0xFFFF;
}
}
uint32_t ADLFile::getDataSize() const noexcept
{
return _dataSize;
}
std::shared_ptr<uint8_t[]> ADLFile::getData() const noexcept
{
return _data;
}
void ADLFile::detectVersion()
{
seek(0, std::fstream::beg);
// detect version 3
_version = 3;
_meta_version = mv3;
_read = std::bind(&ADLFile::readLE16, this);
for (int i = 0; i < V1_HEADER_SIZE; i++)
{
uint16_t v = readLE16();
// For v3 all entries should be below 500 or equal 0xFFFF.
// For other versions
// this will check program offsets (at least 600).
if ((v >= V3_HEADER_SIZE) && (v < 0xFFFF))
{
//v1,2
_version = 2;
_meta_version = mv2;
_read = std::bind(&ADLFile::readU8, this);
break;
}
}
// detect version 1,2
if (_version < 3)
{
seek(V1_HEADER_SIZE, std::fstream::beg);
// validate v1
uint16_t min_w = 0xFFFF;
for (int i = 0; i < V1_NUM_TRACK_OFFSETS; i++)
{
uint16_t w = readLE16();
_assertValid(w >= V1_OFFSET_START || w == 0);
if (min_w > w && w > 0) {
min_w = w;
}
}
// detect
if (min_w < V2_OFFSET_START)
{
_version = 1;
_meta_version = mv1;
_assertValid(min_w == V1_OFFSET_START);
}
else
{
_assertValid(min_w == V2_OFFSET_START);
}
}
}
void ADLFile::readHeaderFromFile(const int header_size, std::function<uint16_t()> read)
{
_header.resize(header_size);
for (int i = 0; i < header_size; i++)
{
_header[i] = read();
}
_assertValid(_header.size() == header_size);
}
void ADLFile::readOffsetsFromFile(const int num_offsets, std::vector<uint16_t>& vec, const int offset_start)
{
_assertValid(tell() == offset_start);
vec.resize(num_offsets);
for (int i = 0; i < num_offsets; i++) {
vec[i] = readLE16();
}
_assertValid(vec.size() == num_offsets);
}
void ADLFile::readDataFromFile(const int data_offsets, const int data_heder_size)
{
_dataSize = size() - data_offsets;
_assertValid(_dataSize > 0);
_assertValid(tell() == data_offsets);
_data.reset(new uint8_t[_dataSize]);
read(_data.get(), _dataSize);
_dataHeaderSize = data_heder_size;
}
void ADLFile::adjust_offsets(std::vector<uint16_t>& vec)
{
for (auto& v : vec)
{
if (v == 0)
v = 0xFFFF;
if (v == 0xFFFF)
continue;
_assertValid(v >= _dataHeaderSize);
v -= _dataHeaderSize;
}
}
}
}
| 36.445614
| 116
| 0.527871
|
Raffaello
|
734c2ece216873560f4c98a964b007476f90325d
| 1,847
|
cpp
|
C++
|
ThreadedModFileCount.cpp
|
jaygarcia/QtModPlayer
|
a71d922b8c7c2928bedb4658f6111d7ab40c3d69
|
[
"MIT"
] | null | null | null |
ThreadedModFileCount.cpp
|
jaygarcia/QtModPlayer
|
a71d922b8c7c2928bedb4658f6111d7ab40c3d69
|
[
"MIT"
] | 7
|
2018-10-04T12:47:04.000Z
|
2018-10-13T09:15:20.000Z
|
ThreadedModFileCount.cpp
|
jaygarcia/QtModPlayer
|
a71d922b8c7c2928bedb4658f6111d7ab40c3d69
|
[
"MIT"
] | null | null | null |
#include "ThreadedModFileCount.h"
// Based on: https://stackoverflow.com/a/16383433
//QString fileChecksum(const QString &fileName) {
// QFile f(fileName);
// QCryptographicHash hash(QCryptographicHash::Algorithm::Md5);
// if (f.open(QFile::ReadOnly)) {
// if (hash.addData(&f)) {
// return QString::fromUtf8(hash.result().toHex());
// }
// }
// return QString::fromUtf8(hash.result().toHex());
//}
ThreadedModFileCount::ThreadedModFileCount(QVector<QString> droppedFiles) {
this->m_droppedFiles = droppedFiles;
}
void ThreadedModFileCount::run() {
// QJsonArray *allFiles = new QJsonArray();
for (int64_t i = 0; i < this->m_droppedFiles.size(); ++i) {
QString droppedFileName = this->m_droppedFiles.at(i);
QFileInfo *droppedFileInfo = new QFileInfo(droppedFileName);
if (droppedFileInfo->isDir()) {
this->searchDirectoryForFiles(droppedFileName);
}
if (droppedFileInfo->isFile()) {
// TODO: >> DEBUG HERE. no files are going into the array :(
// allFiles->push_back(droppedFileName);
this->allFiles.push_back(droppedFileName);
}
}
QJsonArray *allFiles = new QJsonArray();
int size = this->allFiles.size();
for (int i = 0; i < size; i++) {
allFiles->append(this->allFiles.at(i));
}
emit filesCounted(allFiles);
}
void ThreadedModFileCount::searchDirectoryForFiles(QString dirName) {
QDirIterator *iterator = new QDirIterator(dirName, QDirIterator::Subdirectories);
while (iterator->hasNext() && ! QThread::currentThread()->isInterruptionRequested()) {
QString file = iterator->next();
QFileInfo *fileInfo = new QFileInfo(file);
if (fileInfo->isFile()) {
this->allFiles.push_back(file); // pop off the stack
}
if (this->allFiles.size() % 15 == 0) {
emit countingFiles(this->allFiles.size());
}
}
}
| 24.959459
| 88
| 0.667569
|
jaygarcia
|
73516a39d61c424bd8caa4f9430df34671f84092
| 4,417
|
cpp
|
C++
|
sdk_core/src/base/network/win/network_util.cpp
|
turingdriving/Livox-SDK
|
9306596a2bf15c1343bc023b497465ed0a32909d
|
[
"BSD-3-Clause"
] | 345
|
2019-01-16T02:19:08.000Z
|
2022-03-27T14:23:04.000Z
|
sdk_core/src/base/network/win/network_util.cpp
|
turingdriving/Livox-SDK
|
9306596a2bf15c1343bc023b497465ed0a32909d
|
[
"BSD-3-Clause"
] | 152
|
2019-01-31T06:53:01.000Z
|
2022-03-30T18:34:02.000Z
|
sdk_core/src/base/network/win/network_util.cpp
|
turingdriving/Livox-SDK
|
9306596a2bf15c1343bc023b497465ed0a32909d
|
[
"BSD-3-Clause"
] | 171
|
2019-01-24T09:54:32.000Z
|
2022-03-25T22:18:55.000Z
|
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Livox. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifdef WIN32
#include "base/network/network_util.h"
#include <memory>
#include <iphlpapi.h>
#include <string>
#pragma comment(lib,"iphlpapi.lib")
#pragma comment(lib,"ws2_32.lib")
namespace livox {
namespace util {
void CloseSock(socket_t sock) {
closesocket(sock);
}
socket_t CreateSocket(uint16_t port, bool nonblock, bool reuse_port) {
int status = -1;
int on = -1;
int sock = -1;
struct sockaddr_in servaddr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
return -1;
}
if (nonblock) {
status = ioctlsocket(sock, FIONBIO, (u_long *)&on);
if (status != NO_ERROR) {
closesocket(sock);
return -1;
}
}
if (reuse_port) {
status = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &on, sizeof (on));
if (status != 0) {
closesocket(sock);
return -1;
}
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(port);
status = bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if (status != 0) {
closesocket(sock);
return -1;
}
return sock;
}
bool GetAdapterState(const IP_ADAPTER_INFO *pAdapter) {
if(pAdapter == NULL) {
return false;
}
MIB_IFROW info;
memset(&info ,0 ,sizeof(MIB_IFROW));
info.dwIndex = pAdapter->Index;
if (GetIfEntry(&info) != NOERROR) {
return false;
}
if (info.dwOperStatus == IF_OPER_STATUS_NON_OPERATIONAL
|| info.dwOperStatus == IF_OPER_STATUS_UNREACHABLE
|| info.dwOperStatus == IF_OPER_STATUS_DISCONNECTED
|| info.dwOperStatus == IF_OPER_STATUS_CONNECTING)
return false;
return true;
}
bool FindLocalIp(const struct sockaddr_in &client_addr, uint32_t &local_ip) {
bool found = false;
ULONG ulOutbufLen = sizeof(IP_ADAPTER_INFO);
std::unique_ptr<uint8_t[]> pAdapterInfo(new uint8_t[ulOutbufLen]);
DWORD dlRetVal = GetAdaptersInfo(reinterpret_cast<IP_ADAPTER_INFO *>(pAdapterInfo.get()), &ulOutbufLen);
if (dlRetVal == ERROR_BUFFER_OVERFLOW) {
pAdapterInfo.reset(new uint8_t[ulOutbufLen]);
dlRetVal = GetAdaptersInfo(reinterpret_cast<IP_ADAPTER_INFO *>(pAdapterInfo.get()), &ulOutbufLen);
}
IP_ADAPTER_INFO *pAdapter = reinterpret_cast<IP_ADAPTER_INFO *>(pAdapterInfo.get());
if (NO_ERROR == dlRetVal && pAdapter != NULL) {
while (pAdapter != NULL) {
if (GetAdapterState(pAdapter)) {
std::string str_ip = pAdapter->IpAddressList.IpAddress.String;
std::string str_mask = pAdapter->IpAddressList.IpMask.String;
ULONG host_ip = inet_addr(const_cast<char *>(str_ip.c_str()));
ULONG host_mask = inet_addr(const_cast<char *>(str_mask.c_str()));
if ((host_ip & host_mask) ==
(client_addr.sin_addr.S_un.S_addr & host_mask)) {
local_ip = host_ip;
found = true;
break;
}
}
pAdapter = pAdapter->Next;
}
}
return found;
}
size_t RecvFrom(socket_t &sock, void *buff, size_t buf_size, int flag, struct sockaddr *addr, int* addrlen) {
return recvfrom(sock, (char *)buff, buf_size, 0, addr, addrlen);
}
} // namespace util
} // namespace livox
#endif // WIN32
| 31.55
| 110
| 0.689608
|
turingdriving
|
7351bd42175a0ee9d625150e19d5003f128c1d62
| 4,126
|
hpp
|
C++
|
test/testutil/storage/supergenius_trie_printer.hpp
|
GeniusVentures/SuperGenius
|
ae43304f4a2475498ef56c971296175acb88d0ee
|
[
"MIT"
] | 1
|
2021-07-10T21:25:03.000Z
|
2021-07-10T21:25:03.000Z
|
test/testutil/storage/supergenius_trie_printer.hpp
|
GeniusVentures/SuperGenius
|
ae43304f4a2475498ef56c971296175acb88d0ee
|
[
"MIT"
] | null | null | null |
test/testutil/storage/supergenius_trie_printer.hpp
|
GeniusVentures/SuperGenius
|
ae43304f4a2475498ef56c971296175acb88d0ee
|
[
"MIT"
] | null | null | null |
#ifndef SUPERGENIUS_CORE_STORAGE_TRIE_SUPERGENIUS_TRIE_DB_SUPERGENIUS_TRIE_DB_PRINTER_HPP
#define SUPERGENIUS_CORE_STORAGE_TRIE_SUPERGENIUS_TRIE_DB_SUPERGENIUS_TRIE_DB_PRINTER_HPP
#include "storage/trie/supergenius_trie/supergenius_trie.hpp"
///
/// \@notice: This module is meant only for test usage and is not exception-safe
///
namespace sgns::storage::trie {
namespace printer_internal {
inline std::string nibblesToStr(const sgns::base::Buffer &nibbles) {
std::stringstream s;
for (auto nibble : nibbles) {
if (nibble < 10) {
s << static_cast<char>('0' + nibble);
} else {
s << static_cast<char>('a' + (nibble - 10));
}
}
return s.str();
}
template <typename Stream>
class NodePrinter {
public:
explicit NodePrinter(Stream &s) : stream_{s} {}
Stream &printNode(const SuperGeniusTrie::NodePtr &node,
const SuperGeniusTrie &trie,
size_t nest_level = 0) {
using T = SuperGeniusNode::Type;
switch (node->getTrieType()) {
case T::BranchWithValue:
case T::BranchEmptyValue: {
printBranch(std::static_pointer_cast<BranchNode>(node), trie, nest_level);
break;
}
case T::Leaf: {
stream_ << std::setfill('-') << std::setw(nest_level) << ""
<< std::setw(0) << "(leaf) key: <"
<< hex_lower(codec_.nibblesToKey(node->key_nibbles))
<< "> value: " << node->value.get().toHex() << "\n";
break;
}
default:
stream_ << "(invalid node)\n";
}
return stream_;
}
private:
void printBranch(const SuperGeniusTrie::BranchPtr &node,
const SuperGeniusTrie &trie,
size_t nest_level) {
std::string indent(nest_level, '\t');
auto value =
(node->value ? "\"" + node->value.get().toHex() + "\"" : "NONE");
auto branch = std::dynamic_pointer_cast<BranchNode>(node);
stream_ << std::setfill('-') << std::setw(nest_level) << ""
<< std::setw(0) << "(branch) key: <"
<< hex_lower(codec_.nibblesToKey(node->key_nibbles))
<< "> value: " << value << " children: ";
for (size_t i = 0; i < branch->children.size(); i++) {
if (branch->children[i]) {
stream_ << std::hex << i << "|";
}
}
stream_ << "\n";
printEncAndHash(node, nest_level);
for (size_t i = 0; i < branch->children.size(); i++) {
auto child = branch->children.at(i);
if (child) {
if (! child->isDummy()) {
printNode(child, trie, nest_level + 1);
} else {
auto fetched_child = trie.retrieveChild(branch, i).value();
printNode(fetched_child, trie, nest_level + 1);
}
}
}
}
void printEncAndHash(const SuperGeniusTrie::NodePtr &node,
size_t nest_level) {
auto enc = codec_.encodeNode(*node).value();
if (print_enc_) {
stream_ << std::setfill('-') << std::setw(nest_level) << ""
<< std::setw(0) << "enc: " << enc << "\n";
}
if (print_hash_) {
stream_ << std::setfill('-') << std::setw(nest_level) << ""
<< std::setw(0)
<< "hash: " << base::hex_upper(codec_.merkleValue(enc))
<< "\n";
}
}
Stream &stream_;
SuperGeniusCodec codec_;
bool print_enc_;
bool print_hash_;
};
} // namespace printer_internal
template <typename Stream>
Stream &operator<<(Stream &s, const SuperGeniusTrie &trie) {
if (! trie.empty()) {
auto root = trie.getRoot();
printer_internal::NodePrinter p(s);
p.printNode(root, trie);
}
return s;
}
} // namespace sgns::storage::trie
#endif // SUPERGENIUS_CORE_STORAGE_TRIE_SUPERGENIUS_TRIE_DB_SUPERGENIUS_TRIE_DB_PRINTER_HPP
| 33.819672
| 92
| 0.531992
|
GeniusVentures
|
73522a532b9fbf2f19dd5ea732af98bdd1c19e3d
| 1,253
|
cpp
|
C++
|
src/io/nanopolish_fast5_loader.cpp
|
Yufeng98/nanopolish
|
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
|
[
"MIT"
] | 1
|
2021-03-01T08:27:02.000Z
|
2021-03-01T08:27:02.000Z
|
src/io/nanopolish_fast5_loader.cpp
|
Yufeng98/nanopolish
|
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
|
[
"MIT"
] | null | null | null |
src/io/nanopolish_fast5_loader.cpp
|
Yufeng98/nanopolish
|
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
|
[
"MIT"
] | 1
|
2021-03-01T09:33:53.000Z
|
2021-03-01T09:33:53.000Z
|
//---------------------------------------------------------
// Copyright 2019 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_fast5_loader -- A class that manages
// opening and reading from fast5 files
//
#include <omp.h>
#include "nanopolish_fast5_loader.h"
//
Fast5Loader::Fast5Loader()
{
}
//
Fast5Loader::~Fast5Loader()
{
}
Fast5Data Fast5Loader::load_read(const std::string& filename, const std::string& read_name)
{
Fast5Data data;
data.rt.n = 0;
data.rt.raw = NULL;
fast5_file f5_file = fast5_open(filename);
if(!fast5_is_open(f5_file)) {
data.is_valid = false;
return data;
}
data.read_name = read_name;
data.is_valid = true;
// metadata
data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
data.experiment_type = fast5_get_experiment_type(f5_file, read_name);
// raw data
data.channel_params = fast5_get_channel_params(f5_file, read_name);
data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);
data.start_time = fast5_get_start_time(f5_file, read_name);
fast5_close(f5_file);
return data;
}
| 24.096154
| 91
| 0.64166
|
Yufeng98
|
7353cad65db8399f8e3c44fa4bbb3f20fbc2a92a
| 1,631
|
cpp
|
C++
|
freeflow/sys/acceptor.test/accept.cpp
|
flowgrammable/freeflow-legacy
|
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
|
[
"Apache-2.0"
] | 1
|
2017-07-30T04:18:29.000Z
|
2017-07-30T04:18:29.000Z
|
freeflow/sys/acceptor.test/accept.cpp
|
flowgrammable/freeflow-legacy
|
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
|
[
"Apache-2.0"
] | null | null | null |
freeflow/sys/acceptor.test/accept.cpp
|
flowgrammable/freeflow-legacy
|
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2013-2014 Flowgrammable.org
//
// 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 <freeflow/sys/socket.hpp>
#include <freeflow/sys/acceptor.hpp>
#include <freeflow/sys/reactor.hpp>
using namespace freeflow;
struct Echo_server : Socket_handler {
Echo_server(Reactor& r, Socket&& s)
: Socket_handler(r, READ_EVENTS, std::move(s)) { }
bool on_open() {
std::cout << "* service established\n";
return true;
}
bool on_close() {
std::cout << "* service terminated\n";
return true;
}
bool on_read() {
char buf[1024];
System_result res = read(rc(), buf, 1024);
if (res.failed()) {
std::cout << "* error reading socket\n";
return false;
} else if (res.value() == 0) {
return false;
} else {
buf[res.value()] = 0;
std::cout << buf;
return true;
}
}
};
using My_acceptor = Acceptor<Echo_server>;
int main() {
Reactor r;
// Initialize the acceptr.
My_acceptor c(r);
c.listen(Address(Ipv4_addr::any, 9876), Socket::TCP);
// Run the reactor loop.
r.add_handler(&c);
r.run();
}
| 24.712121
| 70
| 0.657879
|
flowgrammable
|
735e060a80f95e6c1c92f08b0bcfb0e092df01c1
| 12,961
|
hpp
|
C++
|
src/shared/pal/src/include/pal/thread.hpp
|
kouvel/diagnostics
|
2269f2d8b5a585fd1d1876debe0124bd54ef4792
|
[
"MIT"
] | null | null | null |
src/shared/pal/src/include/pal/thread.hpp
|
kouvel/diagnostics
|
2269f2d8b5a585fd1d1876debe0124bd54ef4792
|
[
"MIT"
] | null | null | null |
src/shared/pal/src/include/pal/thread.hpp
|
kouvel/diagnostics
|
2269f2d8b5a585fd1d1876debe0124bd54ef4792
|
[
"MIT"
] | null | null | null |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
include/pal/thread.hpp
Abstract:
Header file for thread structures
--*/
#ifndef _PAL_THREAD_HPP_
#define _PAL_THREAD_HPP_
#include "corunix.hpp"
#include "shm.hpp"
#include "cs.hpp"
#include <pthread.h>
#include <sys/syscall.h>
#include "threadsusp.hpp"
#include "threadinfo.hpp"
#include "synchobjects.hpp"
#include <errno.h>
namespace CorUnix
{
enum PalThreadType
{
UserCreatedThread,
PalWorkerThread,
SignalHandlerThread
};
PAL_ERROR
InternalCreateThread(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
PalThreadType eThreadType,
SIZE_T* pThreadId,
HANDLE *phThread
);
PAL_ERROR
InternalGetThreadDataFromHandle(
CPalThread *pThread,
HANDLE hThread,
CPalThread **ppTargetThread,
IPalObject **ppobjThread
);
VOID
InternalEndCurrentThread(
CPalThread *pThread
);
PAL_ERROR
InternalCreateDummyThread(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
CPalThread **ppDummyThread,
HANDLE *phThread
);
PAL_ERROR
CreateThreadData(
CPalThread **ppThread
);
PAL_ERROR
CreateThreadObject(
CPalThread *pThread,
CPalThread *pNewThread,
HANDLE *phThread
);
/* In the windows CRT there is a constant defined for the max width
of a _ecvt conversion. That constant is 348. 348 for the value, plus
the exponent value, decimal, and sign if required. */
#define ECVT_MAX_COUNT_SIZE 348
#define ECVT_MAX_BUFFER_SIZE 357
/*STR_TIME_SIZE is defined as 26 the size of the
return val by ctime_r*/
#define STR_TIME_SIZE 26
class CThreadCRTInfo : public CThreadInfoInitializer
{
public:
CHAR * strtokContext; // Context for strtok function
WCHAR * wcstokContext; // Context for wcstok function
CThreadCRTInfo() :
strtokContext(NULL),
wcstokContext(NULL)
{
};
};
class CPalThread
{
friend
PAL_ERROR
InternalCreateThread(
CPalThread *,
LPSECURITY_ATTRIBUTES,
DWORD,
LPTHREAD_START_ROUTINE,
LPVOID,
DWORD,
PalThreadType,
SIZE_T*,
HANDLE*
);
friend
PAL_ERROR
InternalCreateDummyThread(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
CPalThread **ppDummyThread,
HANDLE *phThread
);
friend
PAL_ERROR
CreateThreadData(
CPalThread **ppThread
);
friend
PAL_ERROR
CreateThreadObject(
CPalThread *pThread,
CPalThread *pNewThread,
HANDLE *phThread
);
private:
CPalThread *m_pNext;
DWORD m_dwExitCode;
BOOL m_fExitCodeSet;
CRITICAL_SECTION m_csLock;
bool m_fLockInitialized;
bool m_fIsDummy;
//
// Minimal reference count, used primarily for cleanup purposes. A
// new thread object has an initial refcount of 1. This initial
// reference is removed by CorUnix::InternalEndCurrentThread.
//
// The only other spot the refcount is touched is from within
// CPalObjectBase::ReleaseReference -- incremented before the
// destructors for an ojbect are called, and decremented afterwords.
// This permits the freeing of the thread structure to happen after
// the freeing of the enclosing thread object has completed.
//
LONG m_lRefCount;
//
// The IPalObject for this thread. The thread will release its reference
// to this object when it exits.
//
IPalObject *m_pThreadObject;
//
// Thread ID info
//
SIZE_T m_threadId;
DWORD m_dwLwpId;
pthread_t m_pthreadSelf;
//
// Start info
//
LPTHREAD_START_ROUTINE m_lpStartAddress;
LPVOID m_lpStartParameter;
BOOL m_bCreateSuspended;
PalThreadType m_eThreadType;
//
// pthread mutex / condition variable for gating thread startup.
// InternalCreateThread waits on the condition variable to determine
// when the new thread has reached passed all failure points in
// the entry routine
//
pthread_mutex_t m_startMutex;
pthread_cond_t m_startCond;
bool m_fStartItemsInitialized;
bool m_fStartStatus;
bool m_fStartStatusSet;
// Base address of the stack of this thread
void* m_stackBase;
// Limit address of the stack of this thread
void* m_stackLimit;
// Signal handler's alternate stack to help with stack overflow
void* m_alternateStack;
//
// The thread entry routine (called from InternalCreateThread)
//
static void* ThreadEntry(void * pvParam);
//
// Data for PAL side-by-side support
//
public:
//
// Embedded information for areas owned by other subsystems
//
CThreadSynchronizationInfo synchronizationInfo;
CThreadSuspensionInfo suspensionInfo;
CThreadCRTInfo crtInfo;
CPalThread()
:
m_pNext(NULL),
m_dwExitCode(STILL_ACTIVE),
m_fExitCodeSet(FALSE),
m_fLockInitialized(FALSE),
m_fIsDummy(FALSE),
m_lRefCount(1),
m_pThreadObject(NULL),
m_threadId(0),
m_dwLwpId(0),
m_pthreadSelf(0),
m_lpStartAddress(NULL),
m_lpStartParameter(NULL),
m_bCreateSuspended(FALSE),
m_eThreadType(UserCreatedThread),
m_fStartItemsInitialized(FALSE),
m_fStartStatus(FALSE),
m_fStartStatusSet(FALSE),
m_stackBase(NULL),
m_stackLimit(NULL)
{
};
virtual ~CPalThread();
PAL_ERROR
RunPreCreateInitializers(
void
);
//
// m_threadId and m_dwLwpId must be set before calling
// RunPostCreateInitializers
//
PAL_ERROR
RunPostCreateInitializers(
void
);
//
// SetStartStatus is called by THREADEntry or InternalSuspendNewThread
// to inform InternalCreateThread of the results of the thread's
// initialization. InternalCreateThread calls WaitForStartStatus to
// obtain this information (and will not return to its caller until
// the info is available).
//
void
SetStartStatus(
bool fStartSucceeded
);
bool
WaitForStartStatus(
void
);
void
Lock(
CPalThread *pThread
)
{
InternalEnterCriticalSection(pThread, &m_csLock);
};
void
Unlock(
CPalThread *pThread
)
{
InternalLeaveCriticalSection(pThread, &m_csLock);
};
//
// The following three methods provide access to the
// native lock used to protect thread native wait data.
//
void
AcquireNativeWaitLock(
void
)
{
synchronizationInfo.AcquireNativeWaitLock();
}
void
ReleaseNativeWaitLock(
void
)
{
synchronizationInfo.ReleaseNativeWaitLock();
}
bool
TryAcquireNativeWaitLock(
void
)
{
return synchronizationInfo.TryAcquireNativeWaitLock();
}
static void
SetLastError(
DWORD dwLastError
)
{
// Reuse errno to store last error
errno = dwLastError;
};
static DWORD
GetLastError(
void
)
{
// Reuse errno to store last error
return errno;
};
void
SetExitCode(
DWORD dwExitCode
)
{
m_dwExitCode = dwExitCode;
m_fExitCodeSet = TRUE;
};
BOOL
GetExitCode(
DWORD *pdwExitCode
)
{
*pdwExitCode = m_dwExitCode;
return m_fExitCodeSet;
};
SIZE_T
GetThreadId(
void
)
{
return m_threadId;
};
DWORD
GetLwpId(
void
)
{
return m_dwLwpId;
};
pthread_t
GetPThreadSelf(
void
)
{
return m_pthreadSelf;
};
LPTHREAD_START_ROUTINE
GetStartAddress(
void
)
{
return m_lpStartAddress;
};
LPVOID
GetStartParameter(
void
)
{
return m_lpStartParameter;
};
BOOL
GetCreateSuspended(
void
)
{
return m_bCreateSuspended;
};
PalThreadType
GetThreadType(
void
)
{
return m_eThreadType;
};
IPalObject *
GetThreadObject(
void
)
{
return m_pThreadObject;
}
BOOL
IsDummy(
void
)
{
return m_fIsDummy;
};
CPalThread*
GetNext(
void
)
{
return m_pNext;
};
void
SetNext(
CPalThread *pNext
)
{
m_pNext = pNext;
};
void
AddThreadReference(
void
);
void
ReleaseThreadReference(
void
);
};
extern "C" CPalThread *CreateCurrentThreadData();
inline CPalThread *GetCurrentPalThread()
{
return reinterpret_cast<CPalThread*>(pthread_getspecific(thObjKey));
}
inline CPalThread *InternalGetCurrentThread()
{
CPalThread *pThread = GetCurrentPalThread();
if (pThread == nullptr)
pThread = CreateCurrentThreadData();
return pThread;
}
/***
$$TODO: These are needed only to support cross-process thread duplication
class CThreadImmutableData
{
public:
DWORD dwProcessId;
};
class CThreadSharedData
{
public:
DWORD dwThreadId;
DWORD dwExitCode;
};
***/
//
// The process local information for a thread is just a pointer
// to the underlying CPalThread object.
//
class CThreadProcessLocalData
{
public:
CPalThread *pThread;
};
extern CObjectType otThread;
}
BOOL
TLSInitialize(
void
);
VOID
TLSCleanup(
void
);
/*++
Macro:
THREADSilentGetCurrentThreadId
Abstract:
Same as GetCurrentThreadId, but it doesn't output any traces.
It is useful for tracing functions to display the thread ID
without generating any new traces.
TODO: how does the perf of pthread_self compare to
InternalGetCurrentThread when we find the thread in the
cache?
If the perf of pthread_self is comparable to that of the stack
bounds based lookaside system, why aren't we using it in the
cache?
In order to match the thread ids that debuggers use at least for
linux we need to use gettid().
--*/
#if defined(__linux__)
#define PlatformGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid)
#elif defined(__APPLE__)
inline SIZE_T PlatformGetCurrentThreadId() {
uint64_t tid;
pthread_threadid_np(pthread_self(), &tid);
return (SIZE_T)tid;
}
#elif defined(__FreeBSD__)
#include <pthread_np.h>
#define PlatformGetCurrentThreadId() (SIZE_T)pthread_getthreadid_np()
#elif defined(__NetBSD__)
#include <lwp.h>
#define PlatformGetCurrentThreadId() (SIZE_T)_lwp_self()
#else
#define PlatformGetCurrentThreadId() (SIZE_T)pthread_self()
#endif
inline SIZE_T THREADSilentGetCurrentThreadId() {
static __thread SIZE_T tid;
if (!tid)
tid = PlatformGetCurrentThreadId();
return tid;
}
#endif // _PAL_THREAD_HPP_
| 22.30809
| 80
| 0.558985
|
kouvel
|
73686483bd969cc670e142087c1cee31e92474f9
| 2,905
|
hpp
|
C++
|
include/dhnet/rtsp/reply_factory.hpp
|
liunian1027/rtspserver_asio
|
692ec1b5c62672bff06c0f3cfb049b1ddc8c074d
|
[
"MIT"
] | null | null | null |
include/dhnet/rtsp/reply_factory.hpp
|
liunian1027/rtspserver_asio
|
692ec1b5c62672bff06c0f3cfb049b1ddc8c074d
|
[
"MIT"
] | null | null | null |
include/dhnet/rtsp/reply_factory.hpp
|
liunian1027/rtspserver_asio
|
692ec1b5c62672bff06c0f3cfb049b1ddc8c074d
|
[
"MIT"
] | 4
|
2018-05-02T09:30:17.000Z
|
2020-05-26T09:23:26.000Z
|
#ifndef RTSP_REPLY_FACTORY_H__
#define RTSP_REPLY_FACTORY_H__
#include <boost/lexical_cast.hpp>
#include <CompLib/RTP/CRTPPacket.h>
#include "http.hpp"
namespace dhnet {
namespace rtsp {
namespace stock_string
{
static char const rtsp_version[] = "RTSP/1.0";
static char const cseq_name[] = "CSeq";
static char const public_name[] = "Public";
static char const session_name[] = "Session";
static char const transport_name[] = "Transport";
static char const cmd_list[] =
"DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE";
}
inline
reply make_options_reply(int cseq)
{
using namespace stock_string;
reply rep(rtsp_version,status_code::ok);
rep.push_header(header(cseq_name, boost::lexical_cast<std::string>(cseq)));
return rep;
}
inline
reply make_describe_reply(int cseq)
{
using namespace stock_string;
std::string sdp =
"v=0\r\n"
"o=StreamingServer 3440750359 111111 IN IP4 10.6.5.56\r\n"
"s=h264.mp4\r\n"
//"u=http:///\r\n"
//"e=admin@\r\n"
"c=IN IP4 0.0.0.0\r\n"
"b=AS:2097172\r\n"
"t=0 0\r\n"
"a=control:*\r\n"
"a=isma-compliance:2,2.0,2\r\n"
"a=range:npt=0-70.00000\r\n"
"m=video 0 RTP/AVP 96\r\n"
"a=3GPP-Adaptation-Support:1\r\n"
"a=rtpmap:96 H264/90000\r\n"
"a=control:trackID=0\r\n"
"a=framesize:96 192-242\r\n"
"a=fmtp:96 packetization-mode=1;"
"profile-level-id=4D400C;"
"sprop-parameter-sets=J01ADKkYYELxCA==,KM4JiA==\r\n"
"a=mpeg4-esid:201\r\n"
;
reply rep(rtsp_version, mime_type::sdp, sdp.begin(), sdp.end());
rep.push_header(header(cseq_name, boost::lexical_cast<std::string>(cseq)));
return rep;
}
inline
reply make_setup_reply(int cseq)
{
using namespace stock_string;
reply rep(rtsp_version, status_code::ok );
rep.push_header(header("Server","DH Server/1.1"));
rep.push_header(header("User-Agent","DH RTSP Server"));
rep.push_header(header(cseq_name, boost::lexical_cast<std::string>(cseq)));
rep.push_header(header(session_name, "111111"));
rep.push_header(header(transport_name, "RTP/AVP/TCP;unicast;interleaved=0-1;ssrc=0c00cdee;mode=PLAY;ssrc=0000001E"));
return rep;
}
inline
reply make_play_reply(int cseq)
{
using namespace stock_string;
reply rep(rtsp_version, status_code::ok );
rep.push_header(header(cseq_name, boost::lexical_cast<std::string>(cseq)));
rep.push_header(header("Range","npt:0-"));
rep.push_header(header(session_name, "111111"));
return rep;
}
inline
reply make_teardown_reply(int cseq)
{
using namespace stock_string;
reply rep(rtsp_version, status_code::ok );
rep.push_header(header(cseq_name, boost::lexical_cast<std::string>(cseq)));
return rep;
}
} // namespace rtsp
} // namespace dhnet
#endif // RTSP_REPLY_FACTORY_H__
| 25.26087
| 121
| 0.658176
|
liunian1027
|
736be5be7618fc59520bc5040190ba07db8afae6
| 1,548
|
cpp
|
C++
|
C++/Different Ways to Add Parentheses/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | 2
|
2016-04-27T11:55:44.000Z
|
2017-02-06T04:15:46.000Z
|
C++/Different Ways to Add Parentheses/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | null | null | null |
C++/Different Ways to Add Parentheses/main.cpp
|
Leobuaa/LeetCode
|
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
unordered_map<string, vector<int>> dpMap;
return computeWithDP(input, dpMap);
}
vector<int> computeWithDP(string input, unordered_map<string, vector<int>> &dpMap) {
vector<int> res;
int len = input.length();
for (int i = 0; i < len; i++) {
if (!isdigit(input[i])) {
string s1 = input.substr(0, i), s2 = input.substr(i + 1);
vector<int> res1, res2;
if (dpMap.find(s1) != dpMap.end()) {
res1 = dpMap[s1];
} else {
res1 = computeWithDP(s1, dpMap);
}
if (dpMap.find(s2) != dpMap.end()) {
res2 = dpMap[s2];
} else {
res2 = computeWithDP(s2, dpMap);
}
for (auto num1 : res1) {
for (auto num2 : res2) {
if (input[i] == '+') {
res.push_back(num1 + num2);
} else if (input[i] == '-') {
res.push_back(num1 - num2);
} else {
res.push_back(num1 * num2);
}
}
}
}
}
if (res.empty()) {
res.push_back(stoi(input));
}
dpMap[input] = res;
return res;
}
};
| 32.93617
| 88
| 0.375323
|
Leobuaa
|
736c5f7da3ede445b2ee188896d356af072f10b6
| 3,932
|
cpp
|
C++
|
ngraph/frontend/onnx/frontend/src/core/model.cpp
|
v-Golubev/openvino
|
26936d1fbb025c503ee43fe74593ee9d7862ab15
|
[
"Apache-2.0"
] | null | null | null |
ngraph/frontend/onnx/frontend/src/core/model.cpp
|
v-Golubev/openvino
|
26936d1fbb025c503ee43fe74593ee9d7862ab15
|
[
"Apache-2.0"
] | 11
|
2021-08-11T19:59:14.000Z
|
2022-02-21T13:11:15.000Z
|
ngraph/frontend/onnx/frontend/src/core/model.cpp
|
v-Golubev/openvino
|
26936d1fbb025c503ee43fe74593ee9d7862ab15
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <onnx/onnx_pb.h>
#include "core/model.hpp"
#include "ngraph/log.hpp"
#include "onnx_framework_node.hpp"
#include "ops_bridge.hpp"
namespace ngraph
{
namespace onnx_import
{
std::string get_node_domain(const ONNX_NAMESPACE::NodeProto& node_proto)
{
return node_proto.has_domain() ? node_proto.domain() : "";
}
std::int64_t get_opset_version(const ONNX_NAMESPACE::ModelProto& model_proto,
const std::string& domain)
{
for (const auto& opset_import : model_proto.opset_import())
{
if (domain == opset_import.domain())
{
return opset_import.version();
}
}
throw ngraph_error("Couldn't find operator set's version for domain: " + domain + ".");
}
Model::Model(std::shared_ptr<ONNX_NAMESPACE::ModelProto> model_proto)
: m_model_proto{model_proto}
{
// Walk through the elements of opset_import field and register operator sets
// for each domain. An exception UnknownDomain() will raise if the domain is
// unknown or invalid.
for (const auto& id : m_model_proto->opset_import())
{
auto domain = id.has_domain() ? id.domain() : "";
m_opset.emplace(domain, OperatorsBridge::get_operator_set(domain, id.version()));
}
// onnx.proto(.3): the empty string ("") for domain or absence of opset_import field
// implies the operator set that is defined as part of the ONNX specification.
const auto dm = m_opset.find("");
if (dm == std::end(m_opset))
{
m_opset.emplace("", OperatorsBridge::get_operator_set("", ONNX_OPSET_VERSION));
}
}
const Operator& Model::get_operator(const std::string& name,
const std::string& domain) const
{
const auto dm = m_opset.find(domain);
if (dm == std::end(m_opset))
{
throw error::UnknownDomain{domain};
}
const auto op = dm->second.find(name);
if (op == std::end(dm->second))
{
throw error::UnknownOperator{name, domain};
}
return op->second;
}
bool Model::is_operator_available(const ONNX_NAMESPACE::NodeProto& node_proto) const
{
const auto dm = m_opset.find(get_node_domain(node_proto));
if (dm == std::end(m_opset))
{
return false;
}
const auto op = dm->second.find(node_proto.op_type());
return (op != std::end(dm->second));
}
void Model::enable_opset_domain(const std::string& domain)
{
// There is no need to 'update' already enabled domain.
// Since this function may be called only during model import,
// (maybe multiple times) the registered domain opset won't differ
// between subsequent calls.
if (m_opset.find(domain) == std::end(m_opset))
{
OperatorSet opset{OperatorsBridge::get_operator_set(domain)};
if (opset.empty())
{
NGRAPH_WARN << "Couldn't enable domain: " << domain
<< " since it hasn't any registered operators.";
return;
}
m_opset.emplace(domain, opset);
}
}
const OpsetImports& Model::get_opset_imports() const
{
return m_model_proto->opset_import();
}
} // namespace onnx_import
} // namespace ngraph
| 35.745455
| 99
| 0.53586
|
v-Golubev
|
736e13c1ada00d73d163c3be0bbbbb80ab8db4b7
| 1,744
|
cpp
|
C++
|
src/armnnTfParser/test/PassThru.cpp
|
VinayKarnam/armnn
|
98525965c7cfecd9bf48297b433b2122cd1b4a1d
|
[
"MIT"
] | 2
|
2021-12-09T15:14:04.000Z
|
2021-12-10T01:37:53.000Z
|
src/armnnTfParser/test/PassThru.cpp
|
VinayKarnam/armnn
|
98525965c7cfecd9bf48297b433b2122cd1b4a1d
|
[
"MIT"
] | null | null | null |
src/armnnTfParser/test/PassThru.cpp
|
VinayKarnam/armnn
|
98525965c7cfecd9bf48297b433b2122cd1b4a1d
|
[
"MIT"
] | 3
|
2022-01-23T11:34:40.000Z
|
2022-02-12T15:51:37.000Z
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <boost/test/unit_test.hpp>
#include "armnnTfParser/ITfParser.hpp"
#include "ParserPrototxtFixture.hpp"
BOOST_AUTO_TEST_SUITE(TensorflowParser)
struct PassThruFixture : public armnnUtils::ParserPrototxtFixture<armnnTfParser::ITfParser>
{
PassThruFixture()
{
m_Prototext = "node {\n"
" name: \"Placeholder\"\n"
" op: \"Placeholder\"\n"
" attr {\n"
" key: \"dtype\"\n"
" value {\n"
" type: DT_FLOAT\n"
" }\n"
" }\n"
" attr {\n"
" key: \"shape\"\n"
" value {\n"
" shape {\n"
" }\n"
" }\n"
" }\n"
"}\n";
SetupSingleInputSingleOutput({ 1, 7 }, "Placeholder", "Placeholder");
}
};
BOOST_FIXTURE_TEST_CASE(ValidateOutput, PassThruFixture)
{
BOOST_TEST(m_Parser->GetNetworkOutputBindingInfo("Placeholder").second.GetNumDimensions() == 2);
BOOST_TEST(m_Parser->GetNetworkOutputBindingInfo("Placeholder").second.GetShape()[0] == 1);
BOOST_TEST(m_Parser->GetNetworkOutputBindingInfo("Placeholder").second.GetShape()[1] == 7);
}
BOOST_FIXTURE_TEST_CASE(RunGraph, PassThruFixture)
{
armnn::TensorInfo inputTensorInfo = m_Parser->GetNetworkInputBindingInfo("Placeholder").second;
auto input = MakeRandomTensor<float, 2>(inputTensorInfo, 378346);
std::vector<float> inputVec;
inputVec.assign(input.data(), input.data() + input.num_elements());
RunTest<2>(inputVec, inputVec); // The passthru network should output the same as the input.
}
BOOST_AUTO_TEST_SUITE_END()
| 32.90566
| 100
| 0.611812
|
VinayKarnam
|
7376aa55a89d5dcd75fc0e3fd0a7c6f287d5c2bc
| 913
|
cpp
|
C++
|
C++/Vector-Sort/vector-sort.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 108
|
2021-03-29T05:04:16.000Z
|
2022-03-19T15:11:52.000Z
|
C++/Vector-Sort/vector-sort.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | null | null | null |
C++/Vector-Sort/vector-sort.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 32
|
2021-03-30T03:56:54.000Z
|
2022-03-27T14:41:32.000Z
|
/* Author: Isaac Asante
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/vector-sort/problem
* Original video explanation: https://www.youtube.com/watch?v=augknUhDI6Q
* Last verified on: April 17, 2021
*/
/* IMPORTANT:
* This is the full code for the solution.
* Some headers were removed/modified.
*/
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string n, user_input;
getline(cin, n);
getline(cin, user_input);
stringstream ss(user_input);
vector<int> v(stoi(n));
int v_size = v.size();
int x;
for (int i = 0; i < v_size; i++) {
ss >> x;
v[i] = x;
}
sort(v.begin(), v.end());
for (int i = 0; i < v_size; i++) {
cout << v.at(i) << " ";
}
return 0;
}
| 20.75
| 94
| 0.607886
|
IsaacAsante
|
7378bd6cddc8b13bb30bb20ee735444c0647b60c
| 3,981
|
cpp
|
C++
|
daemon/armnn/ThreadManagementServer.cpp
|
RufUsul/gator
|
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
|
[
"BSD-3-Clause"
] | 118
|
2015-03-24T16:09:42.000Z
|
2022-03-21T09:01:59.000Z
|
daemon/armnn/ThreadManagementServer.cpp
|
RufUsul/gator
|
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
|
[
"BSD-3-Clause"
] | 26
|
2016-03-03T23:24:08.000Z
|
2022-03-21T10:24:43.000Z
|
daemon/armnn/ThreadManagementServer.cpp
|
RufUsul/gator
|
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
|
[
"BSD-3-Clause"
] | 73
|
2015-06-09T09:44:06.000Z
|
2021-12-30T09:49:00.000Z
|
/* Copyright (C) 2019-2021 by Arm Limited. All rights reserved. */
#include "armnn/ThreadManagementServer.h"
#include "Logging.h"
#include <cassert>
namespace armnn {
ThreadManagementServer::ThreadManagementServer(std::unique_ptr<IAcceptor> acceptor)
: mAcceptor {std::move(acceptor)},
mReaperThread {&ThreadManagementServer::reaperLoop, this},
mAcceptorThread {&ThreadManagementServer::acceptLoop, this}
{
}
void ThreadManagementServer::stop()
{
if (mIsRunning) {
// Interrupt the acceptor incase it is blocking
mAcceptor->interrupt();
mAcceptorThread.join();
// Ensure that stopCapture has been called
assert(!mEnabled);
// Shut down the threads
std::unique_lock<std::mutex> lock {mMutex};
closeThreads();
mDone = true;
lock.unlock();
mSessionDiedCV.notify_all();
mReaperThread.join();
mIsRunning = false;
}
}
void ThreadManagementServer::startCapture()
{
std::unique_lock<std::mutex> lock {mMutex};
for (auto & t : mThreads) {
t.session->enableCapture();
}
mEnabled = true;
}
void ThreadManagementServer::stopCapture()
{
std::unique_lock<std::mutex> lock {mMutex};
for (auto & t : mThreads) {
t.session->disableCapture();
}
mEnabled = false;
}
void ThreadManagementServer::addThreadToVector(ThreadData threadData) { mThreads.push_back(std::move(threadData)); }
void ThreadManagementServer::closeThreads()
{
for (auto & t : mThreads) {
t.session->close();
}
}
void ThreadManagementServer::runIndividualThread(ISession & session, bool & done)
{
session.runReadLoop();
std::unique_lock<std::mutex> lock {mMutex};
done = true;
lock.unlock();
mSessionDiedCV.notify_all();
}
void ThreadManagementServer::acceptLoop()
{
while (true) {
auto threadSession = mAcceptor->accept();
if (threadSession) {
std::lock_guard<std::mutex> lock {mMutex};
if (mEnabled) {
threadSession->enableCapture();
}
else {
threadSession->disableCapture();
}
// Create the ThreadData and add it to the vector
std::unique_ptr<bool> done {new bool {false}};
ISession & sessionRef = *threadSession;
bool & doneRef = *done;
std::unique_ptr<std::thread> t {new std::thread {&ThreadManagementServer::runIndividualThread,
this,
std::ref(sessionRef),
std::ref(doneRef)}};
addThreadToVector({std::move(t), std::move(threadSession), std::move(done)});
}
else {
return;
}
}
}
void ThreadManagementServer::reaperLoop()
{
std::unique_lock<std::mutex> lock {mMutex};
removeCompletedThreads();
while (!mDone || !mThreads.empty()) {
// Wait for a Session to die, remove it from the vector
mSessionDiedCV.wait(lock);
// Whem the TMS is done, remove all the threads from the vector
removeCompletedThreads();
}
}
void ThreadManagementServer::removeCompletedThreads()
{
for (auto t = mThreads.begin(); t != mThreads.end();) {
bool isThreadDone = *t->done;
if (isThreadDone) {
t->thread->join();
t = mThreads.erase(t);
}
else {
++t;
}
}
}
}
| 30.860465
| 120
| 0.518212
|
RufUsul
|
7379ca12d99befb2ac773b41a547841e238e0030
| 841
|
cpp
|
C++
|
src/header_src/tcp_header.cpp
|
Maxim-byte/pcap_parser-
|
3f34b824699ec595ff34518d83b278d1cbcdeef5
|
[
"MIT"
] | null | null | null |
src/header_src/tcp_header.cpp
|
Maxim-byte/pcap_parser-
|
3f34b824699ec595ff34518d83b278d1cbcdeef5
|
[
"MIT"
] | null | null | null |
src/header_src/tcp_header.cpp
|
Maxim-byte/pcap_parser-
|
3f34b824699ec595ff34518d83b278d1cbcdeef5
|
[
"MIT"
] | null | null | null |
#include "../header_hpp/tcp_header.hpp"
#include <iostream>
#include "../utility/details.hpp"
tcp_header tcp_header::read_tcp_header(std::istream &stream, std::error_code & ec) {
tcp_header header{};
stream.read(reinterpret_cast<char *>(&header.s_port), sizeof(header.s_port));
stream.read(reinterpret_cast<char *>(&header.d_port), sizeof(header.d_port));
stream.seekg(details::tcp_header_length_bytes - sizeof(header.s_port) - sizeof(header.d_port), std::ios::cur);
if(stream.fail()) {
ec = std::make_error_code(std::errc::io_error);
}
return header;
}
void tcp_header::print_tcp_header(std::ostream &stream, const tcp_header &header) {
stream << "Source port: " << details::swap_endian(header.s_port) << '\n';
stream << "Destination port: " << details::swap_endian(header.d_port) << '\n';
}
| 38.227273
| 114
| 0.692033
|
Maxim-byte
|
737a1960b32f8722bf470d9587b56c3369ff090b
| 26,130
|
cc
|
C++
|
src/resid-dtv/sid.cc
|
swingflip/C64_mini_VICE
|
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
|
[
"Apache-2.0"
] | 2
|
2018-11-15T19:52:34.000Z
|
2022-01-17T19:45:01.000Z
|
src/resid-dtv/sid.cc
|
Classicmods/C64_mini_VICE
|
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
|
[
"Apache-2.0"
] | null | null | null |
src/resid-dtv/sid.cc
|
Classicmods/C64_mini_VICE
|
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
|
[
"Apache-2.0"
] | 3
|
2019-06-30T05:37:04.000Z
|
2021-12-04T17:12:35.000Z
|
// ---------------------------------------------------------------------------
// This file is part of reSID, a MOS6581 SID emulator engine.
// Copyright (C) 2004 Dag Lem <resid@nimrod.no>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ---------------------------------------------------------------------------
// C64 DTV modifications written by
// Daniel Kahlin <daniel@kahlin.net>
// Copyright (C) 2007 Daniel Kahlin <daniel@kahlin.net>
#include "sid.h"
#include <math.h>
#if defined(__MMX__) && (HAVE_MMINTRIN_H==1)
#include <mmintrin.h>
#endif
unsigned int wave_train_lut[4096][128];
unsigned int env_train_lut[256][8];
unsigned int volume_train_lut[16];
static void init_lut() {
/* this table needs 2 MB, but the alternative of doing 32M iterations
* of this inner loop per second is worse. */
for (int wave = 0; wave < 4096; wave ++) {
for (int phase1 = 0; phase1 < 128; phase1 ++) {
unsigned int wavecounter = phase1 * 32;
unsigned int wavetrain = 0;
for (int phase2 = 0; phase2 < 32; phase2 ++) {
wavecounter += wave;
wavetrain <<= 1;
wavetrain |= wavecounter >> 12;
wavecounter &= 0xfff;
}
wave_train_lut[wave][phase1] = wavetrain;
}
}
for (int env = 0; env < 256; env ++) {
for (int phase1 = 0; phase1 < 8; phase1 ++) {
/* we always start envelope on particular phase value out of
* 256, which corresponds to how many clocks we have been
* running. */
unsigned int envcounter = phase1 * 32;
unsigned int envtrain = 0;
for (int phase2 = 0; phase2 < 32; phase2 ++) {
envcounter += env;
envtrain <<= 1;
envtrain |= envcounter >> 8;
envcounter &= 0xff;
}
env_train_lut[env][phase1] = envtrain;
}
}
for (int vol = 0; vol < 16; vol ++) {
unsigned int volcounter = (16 - vol) & 0xf;
unsigned int voltrain = 0;
for (int phase2 = 0; phase2 < 32; phase2 ++) {
volcounter += vol;
voltrain <<= 1;
voltrain |= volcounter >> 4;
volcounter &= 0xf;
}
volume_train_lut[vol] = voltrain;
}
}
namespace reSID
{
// ----------------------------------------------------------------------------
// Constructor.
// ----------------------------------------------------------------------------
SID::SID()
{
static bool tableinit = false;
if (! tableinit) {
init_lut();
tableinit = true;
}
// Initialize pointers.
sample = 0;
fir = 0;
voice[0].set_sync_source(&voice[2]);
voice[1].set_sync_source(&voice[0]);
voice[2].set_sync_source(&voice[1]);
set_sampling_parameters(985248, SAMPLE_FAST, 44100);
bus_value = 0;
master_volume = 0;
}
// ----------------------------------------------------------------------------
// Destructor.
// ----------------------------------------------------------------------------
SID::~SID()
{
delete[] sample;
delete[] fir;
}
// ----------------------------------------------------------------------------
// SID reset.
// ----------------------------------------------------------------------------
void SID::reset()
{
for (int i = 0; i < 3; i++) {
voice[i].reset();
}
filter.reset();
extfilt.reset();
bus_value = 0;
}
// ----------------------------------------------------------------------------
// Read sample from audio output.
// ----------------------------------------------------------------------------
int SID::output()
{
int v = extfilt.output();
const int half = 1 << 15;
if (v >= half) {
v = half - 1;
}
else if (v < -half) {
v = -half;
}
return v;
}
// ----------------------------------------------------------------------------
// Read registers.
//
// Reading a write only register returns the last byte written to any SID
// register. The individual bits in this value start to fade down towards
// zero after a few cycles. All bits reach zero within approximately
// $2000 - $4000 cycles.
// It has been claimed that this fading happens in an orderly fashion, however
// sampling of write only registers reveals that this is not the case.
// NB! This is not correctly modeled.
// The actual use of write only registers has largely been made in the belief
// that all SID registers are readable. To support this belief the read
// would have to be done immediately after a write to the same register
// (remember that an intermediate write to another register would yield that
// value instead). With this in mind we return the last value written to
// any SID register for $2000 cycles without modeling the bit fading.
// ----------------------------------------------------------------------------
reg8 SID::read(reg8 offset)
{
switch (offset) {
case 0x19:
return 0x00;
case 0x1a:
return 0x00;
case 0x1b:
return voice[2].wave.readOSC();
case 0x1c:
return voice[2].envelope.readENV();
default:
return bus_value;
}
}
// ----------------------------------------------------------------------------
// Write registers.
// ----------------------------------------------------------------------------
void SID::write(reg8 offset, reg8 value)
{
bus_value = value;
switch (offset) {
case 0x00:
voice[0].wave.writeFREQ_LO(value);
break;
case 0x01:
voice[0].wave.writeFREQ_HI(value);
break;
case 0x02:
voice[0].wave.writePW_LO(value);
break;
case 0x03:
voice[0].wave.writePW_HI(value);
break;
case 0x04:
voice[0].writeCONTROL_REG(value);
break;
case 0x05:
voice[0].envelope.writeATTACK_DECAY(value);
break;
case 0x06:
voice[0].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x07:
voice[1].wave.writeFREQ_LO(value);
break;
case 0x08:
voice[1].wave.writeFREQ_HI(value);
break;
case 0x09:
voice[1].wave.writePW_LO(value);
break;
case 0x0a:
voice[1].wave.writePW_HI(value);
break;
case 0x0b:
voice[1].writeCONTROL_REG(value);
break;
case 0x0c:
voice[1].envelope.writeATTACK_DECAY(value);
break;
case 0x0d:
voice[1].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x0e:
voice[2].wave.writeFREQ_LO(value);
break;
case 0x0f:
voice[2].wave.writeFREQ_HI(value);
break;
case 0x10:
voice[2].wave.writePW_LO(value);
break;
case 0x11:
voice[2].wave.writePW_HI(value);
break;
case 0x12:
voice[2].writeCONTROL_REG(value);
break;
case 0x13:
voice[2].envelope.writeATTACK_DECAY(value);
break;
case 0x14:
voice[2].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x18:
filter.writeMODE_VOL(value);
master_volume = value & 0xf;
break;
case 0x1e:
voice[0].wave.writeACC_HI(value);
break;
case 0x1f:
voice[1].envelope.writeENV(value);
break;
default:
break;
}
}
// ----------------------------------------------------------------------------
// Constructor.
// ----------------------------------------------------------------------------
SID::State::State()
{
int i;
for (i = 0; i < 0x20; i++) {
sid_register[i] = 0;
}
bus_value = 0;
for (i = 0; i < 3; i++) {
accumulator[i] = 0;
shift_register[i] = 0x7ffff8;
rate_counter[i] = 0;
rate_counter_period[i] = 8;
exponential_counter[i] = 0;
exponential_counter_period[i] = 1;
envelope_counter[i] = 0;
envelope_state[i] = EnvelopeGenerator::RELEASE;
hold_zero[i] = true;
}
}
// ----------------------------------------------------------------------------
// Read state.
// ----------------------------------------------------------------------------
SID::State SID::read_state()
{
State state;
int i, j;
for (i = 0, j = 0; i < 3; i++, j += 7) {
WaveformGenerator& wave = voice[i].wave;
EnvelopeGenerator& envelope = voice[i].envelope;
state.sid_register[j + 0] = wave.freq & 0xff;
state.sid_register[j + 1] = wave.freq >> 8;
state.sid_register[j + 2] = wave.pw & 0xff;
state.sid_register[j + 3] = wave.pw >> 8;
state.sid_register[j + 4] =
(wave.waveform << 4)
| (wave.test ? 0x08 : 0)
| (wave.ring_mod ? 0x04 : 0)
| (wave.sync ? 0x02 : 0)
| (envelope.gate ? 0x01 : 0);
state.sid_register[j + 5] = (envelope.attack << 4) | envelope.decay;
state.sid_register[j + 6] = (envelope.sustain << 4) | envelope.release;
}
state.sid_register[j++] =
(filter.voice3off ? 0x80 : 0)
| filter.vol;
// These registers are superfluous, but included for completeness.
for (; j < 0x1d; j++) {
state.sid_register[j] = read(j);
}
for (; j < 0x20; j++) {
state.sid_register[j] = 0;
}
state.bus_value = bus_value;
for (i = 0; i < 3; i++) {
state.accumulator[i] = voice[i].wave.accumulator;
state.shift_register[i] = voice[i].wave.shift_register;
state.rate_counter[i] = voice[i].envelope.rate_counter;
state.rate_counter_period[i] = voice[i].envelope.rate_period;
state.exponential_counter[i] = voice[i].envelope.exponential_counter;
state.exponential_counter_period[i] = voice[i].envelope.exponential_counter_period;
state.envelope_counter[i] = voice[i].envelope.envelope_counter;
state.envelope_state[i] = voice[i].envelope.state;
state.hold_zero[i] = voice[i].envelope.hold_zero;
}
return state;
}
// ----------------------------------------------------------------------------
// Write state.
// ----------------------------------------------------------------------------
void SID::write_state(const State& state)
{
int i;
for (i = 0; i <= 0x18; i++) {
write(i, state.sid_register[i]);
}
bus_value = state.bus_value;
for (i = 0; i < 3; i++) {
voice[i].wave.accumulator = state.accumulator[i];
voice[i].wave.shift_register = state.shift_register[i];
voice[i].envelope.rate_counter = state.rate_counter[i];
voice[i].envelope.rate_period = state.rate_counter_period[i];
voice[i].envelope.exponential_counter = state.exponential_counter[i];
voice[i].envelope.exponential_counter_period = state.exponential_counter_period[i];
voice[i].envelope.envelope_counter = state.envelope_counter[i];
voice[i].envelope.state = state.envelope_state[i];
voice[i].envelope.hold_zero = state.hold_zero[i];
}
}
// ----------------------------------------------------------------------------
// Enable external filter.
// ----------------------------------------------------------------------------
void SID::enable_external_filter(bool enable)
{
extfilt.enable_filter(enable);
}
// ----------------------------------------------------------------------------
// I0() computes the 0th order modified Bessel function of the first kind.
// This function is originally from resample-1.5/filterkit.c by J. O. Smith.
// ----------------------------------------------------------------------------
double SID::I0(double x)
{
// Max error acceptable in I0.
const double I0e = 1e-10;
double sum, u, halfx, temp;
int n;
sum = u = n = 1;
halfx = x/2.0;
do {
temp = halfx/n++;
u *= temp*temp;
sum += u;
} while (u >= I0e*sum);
return sum;
}
// ----------------------------------------------------------------------------
// Setting of SID sampling parameters.
//
// Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64.
// The default end of passband frequency is pass_freq = 0.9*sample_freq/2
// for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample
// frequencies.
//
// For resampling, the ratio between the clock frequency and the sample
// frequency is limited as follows:
// 125*clock_freq/sample_freq < 16384
// E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not
// be set lower than ~ 8kHz. A lower sample frequency would make the
// resampling code overfill its 16k sample ring buffer.
//
// The end of passband frequency is also limited:
// pass_freq <= 0.9*sample_freq/2
// E.g. for a 44.1kHz sampling rate the end of passband frequency is limited
// to slightly below 20kHz. This constraint ensures that the FIR table is
// not overfilled.
// ----------------------------------------------------------------------------
bool SID::set_sampling_parameters(double clock_freq, sampling_method method,
double sample_freq, double pass_freq,
double filter_scale)
{
cycles_per_sample =
cycle_count(clock_freq/sample_freq*(1 << FIXP_SHIFT) + 0.5);
sample_offset = 0;
sample_prev = 0;
// FIR initialization is only necessary for resampling.
if (method != SAMPLE_RESAMPLE && method != SAMPLE_RESAMPLE_FASTMEM)
{
sampling = method;
delete[] sample;
delete[] fir;
sample = 0;
fir = 0;
return true;
}
const int bits = 16;
if (pass_freq > 20000)
pass_freq = 20000;
if (2*pass_freq/sample_freq > 0.9)
pass_freq = 0.9f*sample_freq/2;
const double pi = 3.1415926535897932385;
// 16 bits -> -96dB stopband attenuation.
const double A = -20*log10(1.0/(1 << bits));
// For calculation of beta and N see the reference for the kaiserord
// function in the MATLAB Signal Processing Toolbox:
// http://www.mathworks.com/access/helpdesk/help/toolbox/signal/kaiserord.html
const double beta = 0.1102*(A - 8.7);
const double I0beta = I0(beta);
double f_samples_per_cycle = sample_freq/clock_freq;
double f_cycles_per_sample = clock_freq/sample_freq;
/* This code utilizes the fact that aliasing back to 20 kHz from
* sample_freq/2 is inaudible. This allows us to define a passband
* wider than normally. We might also consider aliasing back to pass_freq,
* but as this can be less than 20 kHz, it might become audible... */
double aliasing_allowance = sample_freq / 2 - 20000;
if (aliasing_allowance < 0)
aliasing_allowance = 0;
double transition_bandwidth = sample_freq/2 - pass_freq + aliasing_allowance;
{
/* Filter order according to Kaiser's paper. */
int N = int((A - 7.95)/(2 * pi * 2.285 * transition_bandwidth/sample_freq) + 0.5);
N += N & 1;
// The filter length is equal to the filter order + 1.
// The filter length must be an odd number (sinc is symmetric about x = 0).
fir_N = int(N*f_cycles_per_sample) + 1;
fir_N |= 1;
// Check whether the sample ring buffer would overfill.
if (FIR_N > RINGSIZE - 1) {
return false;
}
/* Error is bound by 1.234 / L^2 */
fir_RES = (int) (sqrt(1.234 * (1 << bits)) / f_cycles_per_sample + 0.5);
}
sampling = method;
// Allocate memory for FIR tables.
delete[] fir;
fir = new short[fir_N*fir_RES];
// The cutoff frequency is midway through the transition band.
double wc = (pass_freq + transition_bandwidth/2) / sample_freq * pi * 2;
// Calculate fir_RES FIR tables for linear interpolation.
for (int i = 0; i < fir_RES; i++) {
double j_offset = double(i)/fir_RES;
// Calculate FIR table. This is the sinc function, weighted by the
// Kaiser window.
for (int j = 0; j < fir_N; j++) {
double jx = j - fir_N/2. - j_offset;
double wt = wc*jx/f_cycles_per_sample;
double temp = jx/(fir_N/2);
double Kaiser =
fabs(temp) <= 1 ? I0(beta*sqrt(1 - temp*temp))/I0beta : 0;
double sincwt =
fabs(wt) >= 1e-8 ? sin(wt)/wt : 1;
double val =
(1 << FIR_SHIFT)*filter_scale*f_samples_per_cycle*wc/pi*sincwt*Kaiser;
fir[i * fir_N + j] = short(val + 0.5);
}
}
// Allocate sample buffer.
if (!sample) {
sample = new short[RINGSIZE*2];
}
// Clear sample buffer.
for (int j = 0; j < RINGSIZE*2; j++) {
sample[j] = 0;
}
sample_index = 0;
return true;
}
// ----------------------------------------------------------------------------
// SID clocking - 1 cycle.
// ----------------------------------------------------------------------------
void SID::clock()
{
int i;
// Clock amplitude modulators.
for (i = 0; i < 3; i++) {
voice[i].envelope.clock();
}
// Clock oscillators.
for (i = 0; i < 3; i++) {
voice[i].wave.clock();
}
// Synchronize oscillators.
for (i = 0; i < 3; i++) {
voice[i].wave.synchronize();
}
// Clock filter.
filter.clock(voice[0].output(master_volume), voice[1].output(master_volume), voice[2].output(master_volume));
// Clock external filter.
extfilt.clock(filter.output());
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling.
// Fixpoint arithmetics is used.
//
// The example below shows how to clock the SID a specified amount of cycles
// while producing audio output:
//
// while (delta_t) {
// bufindex += sid.clock(delta_t, buf + bufindex, buflength - bufindex);
// write(dsp, buf, bufindex*2);
// bufindex = 0;
// }
//
// ----------------------------------------------------------------------------
int SID::clock(cycle_count& delta_t, short* buf, int n, int interleave)
{
switch (sampling) {
default:
case SAMPLE_FAST:
case SAMPLE_INTERPOLATE:
return clock_interpolate(delta_t, buf, n, interleave);
case SAMPLE_RESAMPLE:
return clock_resample_interpolate(delta_t, buf, n, interleave);
case SAMPLE_RESAMPLE_FASTMEM:
return clock_resample_fast(delta_t, buf, n, interleave);
}
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling - cycle based with linear sample
// interpolation.
//
// Here the chip is clocked every cycle. This yields higher quality
// sound since the samples are linearly interpolated, and since the
// external filter attenuates frequencies above 16kHz, thus reducing
// sampling noise.
// ----------------------------------------------------------------------------
RESID_INLINE
int SID::clock_interpolate(cycle_count& delta_t, short* buf, int n,
int interleave)
{
int s = 0;
int i;
for (;;) {
cycle_count next_sample_offset = sample_offset + cycles_per_sample;
cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
if (delta_t_sample > delta_t) {
break;
}
if (s >= n) {
return s;
}
for (i = 0; i < delta_t_sample - 1; i++) {
clock();
}
if (i < delta_t_sample) {
sample_prev = output();
clock();
}
delta_t -= delta_t_sample;
sample_offset = next_sample_offset & FIXP_MASK;
short sample_now = output();
buf[s++*interleave] =
sample_prev + (sample_offset*(sample_now - sample_prev) >> FIXP_SHIFT);
sample_prev = sample_now;
}
for (i = 0; i < delta_t - 1; i++) {
clock();
}
if (i < delta_t) {
sample_prev = output();
clock();
}
sample_offset -= delta_t << FIXP_SHIFT;
delta_t = 0;
return s;
}
static inline int convolve(const short *a, const short *b, int n)
{
int out = 0;
#if defined(__MMX__) && (HAVE_MMINTRIN_H==1)
union {
__m64 m64;
int i32[2];
} tmp;
tmp.i32[0] = 0;
tmp.i32[1] = 0;
while (n >= 4) {
tmp.m64 = _mm_add_pi32(tmp.m64,
_mm_madd_pi16(*((__m64 *)a),
*((__m64 *)b)));
a += 4;
b += 4;
n -= 4;
}
out = tmp.i32[0] + tmp.i32[1];
_mm_empty();
#endif
while (n --)
out += (*(a++)) * (*(b++));
return out;
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling - cycle based with audio resampling.
//
// This is the theoretically correct (and computationally intensive) audio
// sample generation. The samples are generated by resampling to the specified
// sampling frequency. The work rate is inversely proportional to the
// percentage of the bandwidth allocated to the filter transition band.
//
// This implementation is based on the paper "A Flexible Sampling-Rate
// Conversion Method", by J. O. Smith and P. Gosset, or rather on the
// expanded tutorial on the "Digital Audio Resampling Home Page":
// http://www-ccrma.stanford.edu/~jos/resample/
//
// By building shifted FIR tables with samples according to the
// sampling frequency, this implementation dramatically reduces the
// computational effort in the filter convolutions, without any loss
// of accuracy. The filter convolutions are also vectorizable on
// current hardware.
//
// Further possible optimizations are:
// * An equiripple filter design could yield a lower filter order, see
// http://www.mwrf.com/Articles/ArticleID/7229/7229.html
// * The Convolution Theorem could be used to bring the complexity of
// convolution down from O(n*n) to O(n*log(n)) using the Fast Fourier
// Transform, see http://en.wikipedia.org/wiki/Convolution_theorem
// * Simply resampling in two steps can also yield computational
// savings, since the transition band will be wider in the first step
// and the required filter order is thus lower in this step.
// Laurent Ganier has found the optimal intermediate sampling frequency
// to be (via derivation of sum of two steps):
// 2 * pass_freq + sqrt [ 2 * pass_freq * orig_sample_freq
// * (dest_sample_freq - 2 * pass_freq) / dest_sample_freq ]
//
// NB! the result of right shifting negative numbers is really
// implementation dependent in the C++ standard.
// ----------------------------------------------------------------------------
RESID_INLINE
int SID::clock_resample_interpolate(cycle_count& delta_t, short* buf, int n,
int interleave)
{
int s = 0;
for (;;) {
cycle_count next_sample_offset = sample_offset + cycles_per_sample;
cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
if (delta_t_sample > delta_t) {
break;
}
if (s >= n) {
return s;
}
for (int i = 0; i < delta_t_sample; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++sample_index;
sample_index &= RINGSIZE - 1;
}
delta_t -= delta_t_sample;
sample_offset = next_sample_offset & FIXP_MASK;
int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
int fir_offset_rmd = sample_offset*fir_RES & FIXP_MASK;
short* fir_start = fir + fir_offset*fir_N;
short* sample_start = sample + sample_index - fir_N + RINGSIZE - 1;
// Convolution with filter impulse response.
int v1 = convolve(sample_start, fir_start, fir_N);
// Use next FIR table, wrap around to first FIR table using
// the next sample.
if (++fir_offset == fir_RES) {
fir_offset = 0;
++sample_start;
}
fir_start = fir + fir_offset*fir_N;
// Convolution with filter impulse response.
int v2 = convolve(sample_start, fir_start, fir_N);
// Linear interpolation.
// fir_offset_rmd is equal for all samples, it can thus be factorized out:
// sum(v1 + rmd*(v2 - v1)) = sum(v1) + rmd*(sum(v2) - sum(v1))
int v = v1 + (fir_offset_rmd*(v2 - v1) >> FIXP_SHIFT);
v >>= FIR_SHIFT;
// Saturated arithmetics to guard against 16 bit sample overflow.
const int half = 1 << 15;
if (v >= half) {
v = half - 1;
}
else if (v < -half) {
v = -half;
}
buf[s++*interleave] = v;
}
for (int i = 0; i < delta_t; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++sample_index;
sample_index &= RINGSIZE - 1;
}
sample_offset -= delta_t << FIXP_SHIFT;
delta_t = 0;
return s;
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling - cycle based with audio resampling.
// ----------------------------------------------------------------------------
RESID_INLINE
int SID::clock_resample_fast(cycle_count& delta_t, short* buf, int n,
int interleave)
{
int s = 0;
for (;;) {
cycle_count next_sample_offset = sample_offset + cycles_per_sample;
cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
if (delta_t_sample > delta_t) {
break;
}
if (s >= n) {
return s;
}
for (int i = 0; i < delta_t_sample; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++sample_index;
sample_index &= RINGSIZE - 1;
}
delta_t -= delta_t_sample;
sample_offset = next_sample_offset & FIXP_MASK;
int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
short* fir_start = fir + fir_offset*fir_N;
short* sample_start = sample + sample_index - fir_N + RINGSIZE;
// Convolution with filter impulse response.
int v = convolve(sample_start, fir_start, fir_N);
v >>= FIR_SHIFT;
// Saturated arithmetics to guard against 16 bit sample overflow.
const int half = 1 << 15;
if (v >= half) {
v = half - 1;
}
else if (v < -half) {
v = -half;
}
buf[s++*interleave] = v;
}
for (int i = 0; i < delta_t; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++sample_index;
sample_index &= RINGSIZE - 1;
}
sample_offset -= delta_t << FIXP_SHIFT;
delta_t = 0;
return s;
}
/* ReSID API adaptation hacks */
void SID::set_chip_model(chip_model model) { }
void SID::set_voice_mask(reg4 mask) { }
void SID::enable_filter(bool enable) { }
void SID::adjust_filter_bias(double bias) { }
void SID::input(short sample) { }
} // namespace reSID
| 30.348432
| 111
| 0.572484
|
swingflip
|
737f88fe060bdbba2b796eef27b29b12f56c1695
| 1,588
|
hpp
|
C++
|
demo/test_events.hpp
|
mashavorob/lfds
|
3890472a8a9996ce35d9a28f185df4c2f219a2bd
|
[
"0BSD"
] | null | null | null |
demo/test_events.hpp
|
mashavorob/lfds
|
3890472a8a9996ce35d9a28f185df4c2f219a2bd
|
[
"0BSD"
] | null | null | null |
demo/test_events.hpp
|
mashavorob/lfds
|
3890472a8a9996ce35d9a28f185df4c2f219a2bd
|
[
"0BSD"
] | null | null | null |
/*
* test_conditions.hpp
*
* Created on: Dec 16, 2014
* Author: masha
*/
#ifndef DEMO_TEST_EVENTS_HPP_
#define DEMO_TEST_EVENTS_HPP_
#include <atomic>
#include <condition_variable>
#include <mutex>
class test_events
{
private:
typedef std::unique_lock<std::mutex> lock_type;
test_events(const test_events&);
test_events& operator=(const test_events&);
public:
class event
{
public:
event(std::condition_variable & cv, bool & flag, std::mutex & mutex) :
m_cv(cv), m_flag(flag), m_mutex(mutex)
{
}
void wait()
{
std::unique_lock < std::mutex > lock(m_mutex);
while (!m_flag)
m_cv.wait(lock);
}
private:
std::condition_variable& m_cv;bool& m_flag;
std::mutex& m_mutex;
};
test_events() :
m_start(false), m_stop(false)
{
}
void go()
{
if (!m_start)
{
std::unique_lock < std::mutex > lock(m_mutex);
m_start = true;
m_cv.notify_all();
}
}
void stop()
{
if (!m_stop.load(std::memory_order_relaxed))
{
go();
m_stop.store(true, std::memory_order_release);
}
}
event get_start_ev()
{
return event(m_cv, m_start, m_mutex);
}
std::atomic<bool> & get_stop_ev()
{
return m_stop;
}
private:
std::condition_variable m_cv;
std::mutex m_mutex;bool m_start;
std::atomic<bool> m_stop;
};
#endif /* DEMO_TEST_EVENTS_HPP_ */
| 18.682353
| 78
| 0.547229
|
mashavorob
|
738074a30258b22809b9167922ef3139c22c13d7
| 2,269
|
cpp
|
C++
|
BeLuEngine/BeLuEngine/src/Renderer/Texture/TextureCubeMap.cpp
|
jocke1995/BeLuEngine
|
7fdca9736c61c03330975380bd1b377985c8ebd3
|
[
"MIT"
] | 1
|
2021-03-16T09:16:03.000Z
|
2021-03-16T09:16:03.000Z
|
BeLuEngine/BeLuEngine/src/Renderer/Texture/TextureCubeMap.cpp
|
jocke1995/BeLuEngine
|
7fdca9736c61c03330975380bd1b377985c8ebd3
|
[
"MIT"
] | null | null | null |
BeLuEngine/BeLuEngine/src/Renderer/Texture/TextureCubeMap.cpp
|
jocke1995/BeLuEngine
|
7fdca9736c61c03330975380bd1b377985c8ebd3
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "TextureCubeMap.h"
#include "../Misc/Log.h"
#include "../GPUMemory/Resource.h"
#include "../CommandInterface.h"
#include "../GPUMemory/ShaderResourceView.h"
#include "../DescriptorHeap.h"
#include "TextureFunctions.h"
TextureCubeMap::TextureCubeMap(const std::wstring& filePath)
: Texture(filePath)
{
m_Type = E_TEXTURE_TYPE::TEXTURECUBEMAP;
m_SubresourceData.resize(6); // 6 Subresources for a cubemap
}
TextureCubeMap::~TextureCubeMap()
{
}
bool TextureCubeMap::Init(ID3D12Device5* device, DescriptorHeap* descriptorHeap)
{
HRESULT hr;
m_pDefaultResource = new Resource();
// DDSLoader uses this data type to load the image data
// converts this to m_pImageData when it is used.
std::unique_ptr<uint8_t[]> m_DdsData;
// Loads the texture and creates a default resource;
hr = DirectX::LoadDDSTextureFromFile(device, m_FilePath.c_str(), (ID3D12Resource**)m_pDefaultResource->GetID3D12Resource1PP(), m_DdsData, m_SubresourceData);
if (FAILED(hr))
{
BL_LOG_CRITICAL("Failed to create texture: \'%s\'.\n", to_string(m_FilePath).c_str());
delete m_pDefaultResource;
m_pDefaultResource = nullptr;
return false;
}
// Set resource desc created in LoadDDSTextureFromFile
m_ResourceDescription = m_pDefaultResource->GetID3D12Resource1()->GetDesc();
m_ImageBytesPerRow = m_SubresourceData[0].RowPitch;
// copy m_DdsData to our BYTE* format
m_pImageData = static_cast<BYTE*>(m_DdsData.get());
m_DdsData.release(); // lose the pointer, let m_pImageData delete the data.
// Footprint
UINT64 textureUploadBufferSize;
device->GetCopyableFootprints(
&m_ResourceDescription,
0, m_ResourceDescription.DepthOrArraySize, 0, // 6
nullptr, nullptr, nullptr,
&textureUploadBufferSize);
// Upload heap
m_pUploadResource = new Resource(device,
textureUploadBufferSize,
RESOURCE_TYPE::UPLOAD,
m_FilePath + L"_UPLOAD_RESOURCE");
// Create srv
D3D12_SHADER_RESOURCE_VIEW_DESC desc = {};
desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
desc.Format = m_ResourceDescription.Format;
desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
desc.TextureCube.MipLevels = 1;
m_pSRV = new ShaderResourceView(
device,
descriptorHeap,
&desc,
m_pDefaultResource);
return true;
}
| 28.3625
| 158
| 0.766417
|
jocke1995
|
73829cba411dc9a16fae422bf22bb0fae83d5e83
| 28,288
|
cpp
|
C++
|
commit.cpp
|
BRL-CAD/repowork
|
d5180d99f1086614301cf4c3db44a2b2dd57ebb3
|
[
"CC0-1.0"
] | null | null | null |
commit.cpp
|
BRL-CAD/repowork
|
d5180d99f1086614301cf4c3db44a2b2dd57ebb3
|
[
"CC0-1.0"
] | null | null | null |
commit.cpp
|
BRL-CAD/repowork
|
d5180d99f1086614301cf4c3db44a2b2dd57ebb3
|
[
"CC0-1.0"
] | null | null | null |
/* C O M M I T . C P P
* BRL-CAD
*
* Published in 2020 by the United States Government.
* This work is in the public domain.
*
*/
/** @file commit.cpp
*
* The majority of the work is in processing
* Git commits.
*
*/
#include "TextFlow.hpp"
#include "repowork.h"
typedef int (*commitcmd_t)(git_commit_data *, std::ifstream &);
commitcmd_t
commit_find_cmd(std::string &line, std::map<std::string, commitcmd_t> &cmdmap)
{
commitcmd_t cc = NULL;
std::map<std::string, commitcmd_t>::iterator c_it;
for (c_it = cmdmap.begin(); c_it != cmdmap.end(); c_it++) {
if (!ficmp(line, c_it->first)) {
cc = c_it->second;
break;
}
}
return cc;
}
int
commit_parse_author(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 7); // Remove "author " prefix
size_t spos = line.find_first_of(">");
if (spos == std::string::npos) {
std::cerr << "Invalid author entry! " << line << "\n";
exit(EXIT_FAILURE);
}
cd->author = line.substr(0, spos+1);
cd->author_timestamp = line.substr(spos+2, std::string::npos);
return 0;
}
int
commit_parse_committer(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 10); // Remove "committer " prefix
size_t spos = line.find_first_of(">");
if (spos == std::string::npos) {
std::cerr << "Invalid committer entry! " << line << "\n";
exit(EXIT_FAILURE);
}
cd->committer = line.substr(0, spos+1);
cd->committer_timestamp = line.substr(spos+2, std::string::npos);
//std::cout << "Committer: " << cd->committer << "\n";
//std::cout << "Committer timestamp: " << cd->committer_timestamp << "\n";
return 0;
}
int
commit_parse_commit(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 7); // Remove "commit " prefix
if (!ficmp(line, std::string("refs/notes/"))) {
// Notes commit - flag accordingly
cd->notes_commit = 1;
return 0;
}
size_t spos = line.find_last_of("/");
line.erase(0, spos+1); // Remove "refs/..." prefix
cd->branch = line;
//std::cout << "Branch: " << cd->branch << "\n";
return 0;
}
int
commit_parse_data(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 5); // Remove "data " prefix
size_t data_len = std::stoi(line);
// This is the commit message - read it in
char *cbuffer = new char [data_len+1];
cbuffer[data_len] = '\0';
infile.read(cbuffer, data_len);
cd->commit_msg = std::string(cbuffer);
delete[] cbuffer;
//std::cout << "Commit message:\n" << cd->commit_msg << "\n";
return 0;
}
int
commit_parse_encoding(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
std::cerr << "TODO - support encoding\n";
exit(EXIT_FAILURE);
return 0;
}
int
commit_parse_from(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 5); // Remove "from " prefix
//std::cout << "from line: " << line << "\n";
int ret = git_parse_commitish(cd->from, cd->s, line);
if (!ret) {
return 0;
}
std::cerr << "TODO - unsupported \"from\" specifier: " << line << "\n";
exit(EXIT_FAILURE);
}
int
commit_parse_mark(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
//std::cout << "mark line: " << line << "\n";
line.erase(0, 5); // Remove "mark " prefix
//std::cout << "mark line: " << line << "\n";
if (line.c_str()[0] != ':') {
std::cerr << "Mark without \":\" character??: " << line << "\n";
return -1;
}
line.erase(0, 1); // Remove ":" prefix
cd->id.mark = cd->s->next_mark(std::stol(line));
//std::cout << "Mark id :" << line << " -> " << cd->id.mark << "\n";
return 0;
}
int
commit_parse_merge(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 6); // Remove "merge " prefix
//std::cout << "merge line: " << line << "\n";
git_commitish merge_id;
int ret = git_parse_commitish(merge_id, cd->s, line);
if (!ret) {
cd->merges.push_back(merge_id);
return 0;
}
std::cerr << "TODO - unsupported \"merge\" specifier: " << line << "\n";
git_parse_commitish(merge_id, cd->s, line);
exit(EXIT_FAILURE);
}
int
commit_parse_original_oid(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 13); // Remove "original-oid " prefix
cd->id.sha1 = line;
cd->s->have_sha1s = true;
if (cd->s->sha12key.find(cd->id.sha1) != cd->s->sha12key.end()) {
std::cout << "Have CVS info for commit " << cd->id.sha1 << "\n";
}
return 0;
}
int
commit_parse_filecopy(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 2); // Remove "C " prefix
size_t spos = line.find_first_of(" ");
if (spos == std::string::npos) {
std::cerr << "Invalid copy specifier: " << line << "\n";
return -1;
}
size_t qpos = line.find_first_of("\"");
if (qpos != std::string::npos) {
std::cerr << "quoted path specifiers currently unsupported:" << line << "\n";
exit(EXIT_FAILURE);
}
git_op op;
op.type = filecopy;
op.path = line.substr(0, spos);
op.dest_path = line.substr(spos+1, std::string::npos);
//std::cout << "filecopy: " << op.path << " -> " << op.dest_path << "\n";
cd->fileops.push_back(op);
return 0;
}
int
commit_parse_filedelete(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 2); // Remove "D " prefix
git_op op;
op.type = filedelete;
op.path = line;
cd->fileops.push_back(op);
//std::cout << "filedelete: " << line << "\n";
return 0;
}
int
commit_parse_filemodify(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 2); // Remove "M " prefix
std::regex fmod("([0-9]+) ([:A-Za-z0-9]+) (.*)");
std::smatch fmodvar;
if (!std::regex_search(line, fmodvar, fmod)) {
std::cerr << "Invalid modification specifier: " << line << "\n";
return -1;
}
git_op op;
op.type = filemodify;
op.mode = std::string(fmodvar[1]);
std::string dataref = std::string(fmodvar[2]);
if (dataref == std::string("inline")) {
std::cerr << "inline data unsupported\n";
exit(EXIT_FAILURE);
}
int ret = git_parse_commitish(op.dataref, cd->s, dataref);
if (ret || (op.dataref.mark == -1 && !op.dataref.sha1.length())) {
std::cerr << "Invalid data ref!: " << dataref << "\n";
}
op.path = std::string(fmodvar[3]);
//std::cout << "filemodify: " << op.mode << "," << op.dataref.index << "," << op.path << "\n";
cd->fileops.push_back(op);
return 0;
}
int
commit_parse_notemodify(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
std::cerr << "notemodify currently unsupported:" << line << "\n";
exit(EXIT_FAILURE);
}
int
commit_parse_filerename(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
line.erase(0, 2); // Remove "R " prefix
size_t spos = line.find_first_of(" ");
if (spos == std::string::npos) {
std::cerr << "Invalid copy specifier: " << line << "\n";
return -1;
}
size_t qpos = line.find_first_of("\"");
if (spos != std::string::npos) {
std::cerr << "quoted path specifiers currently unsupported:" << line << "\n";
exit(EXIT_FAILURE);
}
git_op op;
op.type = filerename;
op.path = line.substr(0, spos);
op.dest_path = line.substr(spos+1, std::string::npos);
//std::cout << "filerename: " << op.path << " -> " << op.dest_path << "\n";
cd->fileops.push_back(op);
return 0;
}
int
commit_parse_deleteall(git_commit_data *cd, std::ifstream &infile)
{
std::string line;
std::getline(infile, line);
if (line != std::string("deleteall")) {
std::cerr << "warning - invalid deleteall specifier:" << line << "\n";
}
git_op op;
op.type = filedeleteall;
cd->fileops.push_back(op);
return 0;
}
int
parse_commit(git_fi_data *fi_data, std::ifstream &infile)
{
//std::cout << "Found command: commit\n";
git_commit_data gcd;
gcd.s = fi_data;
// Tell the commit where it will be in the vector - this
// uniquely identifies this specific commit, regardless of
// its sha1.
gcd.id.index = fi_data->commits.size();
std::map<std::string, commitcmd_t> cmdmap;
// Commit info modification commands
cmdmap[std::string("author")] = commit_parse_author;
cmdmap[std::string("commit ")] = commit_parse_commit; // Note - need space after commit to avoid matching committer!
cmdmap[std::string("committer")] = commit_parse_committer;
cmdmap[std::string("data")] = commit_parse_data;
cmdmap[std::string("encoding")] = commit_parse_encoding;
cmdmap[std::string("from")] = commit_parse_from;
cmdmap[std::string("mark")] = commit_parse_mark;
cmdmap[std::string("merge")] = commit_parse_merge;
cmdmap[std::string("original-oid")] = commit_parse_original_oid;
// tree modification commands
cmdmap[std::string("C ")] = commit_parse_filecopy;
cmdmap[std::string("D ")] = commit_parse_filedelete;
cmdmap[std::string("M ")] = commit_parse_filemodify;
cmdmap[std::string("N ")] = commit_parse_notemodify;
cmdmap[std::string("R ")] = commit_parse_filerename;
cmdmap[std::string("deleteall")] = commit_parse_deleteall;
std::string line;
size_t offset = infile.tellg();
int commit_done = 0;
while (!commit_done && std::getline(infile, line)) {
commitcmd_t cc = commit_find_cmd(line, cmdmap);
// If we found a command, process it. Otherwise, we are done
// with the commit and need to clean up.
if (cc) {
//std::cout << "commit line: " << line << "\n";
infile.seekg(offset);
(*cc)(&gcd, infile);
offset = infile.tellg();
} else {
// Whatever was on that line, it's not a commit input.
// Reset input to allow the parent routine to deal with
// it, and return.
infile.seekg(offset);
commit_done = 1;
}
}
gcd.id.mark = fi_data->next_mark(gcd.id.mark);
fi_data->mark_to_index[gcd.id.mark] = gcd.id.index;
// If we have a sha1 and this is not a notes commit, we need to map it to
// this commit's mark
if (!gcd.notes_commit && gcd.id.sha1.length()) {
fi_data->sha1_to_mark[gcd.id.sha1] = gcd.id.mark;
}
//std::cout << "commit new mark: " << gcd.id.mark << "\n";
// Add the commit to the data
fi_data->commits.push_back(gcd);
return 0;
}
int
parse_splice_commit(git_fi_data *fi_data, std::ifstream &infile)
{
//std::cout << "Found command: commit\n";
git_commit_data gcd;
gcd.s = fi_data;
// Tell the commit where it will be in the vector - this
// uniquely identifies this specific commit, regardless of
// its sha1.
gcd.id.index = fi_data->commits.size() + fi_data->splice_commits.size();
std::map<std::string, commitcmd_t> cmdmap;
// Commit info modification commands
cmdmap[std::string("author")] = commit_parse_author;
cmdmap[std::string("commit ")] = commit_parse_commit; // Note - need space after commit to avoid matching committer!
cmdmap[std::string("committer")] = commit_parse_committer;
cmdmap[std::string("data")] = commit_parse_data;
cmdmap[std::string("encoding")] = commit_parse_encoding;
cmdmap[std::string("from")] = commit_parse_from;
cmdmap[std::string("mark")] = commit_parse_mark;
cmdmap[std::string("merge")] = commit_parse_merge;
cmdmap[std::string("original-oid")] = commit_parse_original_oid;
// tree modification commands
cmdmap[std::string("C ")] = commit_parse_filecopy;
cmdmap[std::string("D ")] = commit_parse_filedelete;
cmdmap[std::string("M ")] = commit_parse_filemodify;
cmdmap[std::string("N ")] = commit_parse_notemodify;
cmdmap[std::string("R ")] = commit_parse_filerename;
cmdmap[std::string("deleteall")] = commit_parse_deleteall;
std::string line;
size_t offset = infile.tellg();
int commit_done = 0;
while (!commit_done && std::getline(infile, line)) {
commitcmd_t cc = commit_find_cmd(line, cmdmap);
// If we found a command, process it. Otherwise, we are done
// with the commit and need to clean up.
if (cc) {
//std::cout << "commit line: " << line << "\n";
infile.seekg(offset);
(*cc)(&gcd, infile);
offset = infile.tellg();
} else {
// Whatever was on that line, it's not a commit input.
// Reset input to allow the parent routine to deal with
// it, and return.
infile.seekg(offset);
commit_done = 1;
}
}
gcd.id.mark = fi_data->next_mark(gcd.id.mark);
fi_data->mark_to_index[gcd.id.mark] = gcd.id.index;
//std::cout << "commit new mark: " << gcd.id.mark << "\n";
// Add the commit to the data
fi_data->splice_commits.push_back(gcd);
// Mark the original commit as having a splice, so we will
// be able to write this out in the correct order for the
// fi file.
if (gcd.from.index < (long)fi_data->commits.size()) {
git_commit_data &oc = fi_data->commits[gcd.from.index];
fi_data->splice_map[oc.id.mark] = gcd.id.mark;
} else {
std::cerr << "TODO: Multi-commit splices\n";
exit(1);
}
// For any commits that listed oc as their from commit, they
// now need to be updated to reference the new one instead.
for (size_t i = 0; i < fi_data->commits.size(); i++) {
git_commit_data &c = fi_data->commits[i];
if (c.from.index == gcd.from.index) {
std::cout << "Updating from id of " << c.id.sha1 << "\n";
c.from = gcd.id;
}
}
return 0;
}
int
parse_replace_commit(git_fi_data *fi_data, std::ifstream &infile)
{
// First, find the existing commit for this sha1. If we don't
// have that, we're out of business.
if (fi_data->sha1_to_mark.find(fi_data->replace_sha1) == fi_data->sha1_to_mark.end()) {
std::cerr << "Trying to process unknown replacement sha1 " << fi_data->replace_sha1 << "\n";
return -1;
}
int index = fi_data->mark_to_index[fi_data->sha1_to_mark[fi_data->replace_sha1]];
git_commit_data &gcd = fi_data->commits[index];
std::map<std::string, commitcmd_t> cmdmap;
// Commit info modification commands
cmdmap[std::string("author")] = commit_parse_author;
cmdmap[std::string("commit ")] = commit_parse_commit; // Note - need space after commit to avoid matching committer!
cmdmap[std::string("committer")] = commit_parse_committer;
cmdmap[std::string("data")] = commit_parse_data;
cmdmap[std::string("encoding")] = commit_parse_encoding;
cmdmap[std::string("from")] = commit_parse_from;
cmdmap[std::string("mark")] = commit_parse_mark;
cmdmap[std::string("merge")] = commit_parse_merge;
cmdmap[std::string("original-oid")] = commit_parse_original_oid;
// tree modification commands
cmdmap[std::string("C ")] = commit_parse_filecopy;
cmdmap[std::string("D ")] = commit_parse_filedelete;
cmdmap[std::string("M ")] = commit_parse_filemodify;
cmdmap[std::string("N ")] = commit_parse_notemodify;
cmdmap[std::string("R ")] = commit_parse_filerename;
cmdmap[std::string("deleteall")] = commit_parse_deleteall;
std::string line;
size_t offset = infile.tellg();
int commit_done = 0;
while (!commit_done && std::getline(infile, line)) {
commitcmd_t cc = commit_find_cmd(line, cmdmap);
// If we found a command, process it. Otherwise, we are done
// with the commit and need to clean up.
if (cc) {
//std::cout << "commit line: " << line << "\n";
infile.seekg(offset);
(*cc)(&gcd, infile);
offset = infile.tellg();
} else {
// Whatever was on that line, it's not a commit input.
// Reset input to allow the parent routine to deal with
// it, and return.
infile.seekg(offset);
commit_done = 1;
}
}
return 0;
}
int
parse_add_commit(git_fi_data *fi_data, std::ifstream &infile)
{
//std::cout << "Found command: commit\n";
git_commit_data gcd;
gcd.s = fi_data;
// Tell the commit where it will be in the vector - this
// uniquely identifies this specific commit, regardless of
// its sha1.
gcd.id.index = fi_data->commits.size();
std::map<std::string, commitcmd_t> cmdmap;
// Commit info modification commands
cmdmap[std::string("author")] = commit_parse_author;
cmdmap[std::string("commit ")] = commit_parse_commit; // Note - need space after commit to avoid matching committer!
cmdmap[std::string("committer")] = commit_parse_committer;
cmdmap[std::string("data")] = commit_parse_data;
cmdmap[std::string("encoding")] = commit_parse_encoding;
cmdmap[std::string("from")] = commit_parse_from;
cmdmap[std::string("mark")] = commit_parse_mark;
cmdmap[std::string("merge")] = commit_parse_merge;
cmdmap[std::string("original-oid")] = commit_parse_original_oid;
// tree modification commands
cmdmap[std::string("C ")] = commit_parse_filecopy;
cmdmap[std::string("D ")] = commit_parse_filedelete;
cmdmap[std::string("M ")] = commit_parse_filemodify;
cmdmap[std::string("N ")] = commit_parse_notemodify;
cmdmap[std::string("R ")] = commit_parse_filerename;
cmdmap[std::string("deleteall")] = commit_parse_deleteall;
std::string line;
size_t offset = infile.tellg();
int commit_done = 0;
while (!commit_done && std::getline(infile, line)) {
commitcmd_t cc = commit_find_cmd(line, cmdmap);
// If we found a command, process it. Otherwise, we are done
// with the commit and need to clean up.
if (cc) {
//std::cout << "commit line: " << line << "\n";
infile.seekg(offset);
(*cc)(&gcd, infile);
offset = infile.tellg();
} else {
// Whatever was on that line, it's not a commit input.
// Reset input to allow the parent routine to deal with
// it, and return.
infile.seekg(offset);
commit_done = 1;
}
}
gcd.id.mark = fi_data->next_mark(gcd.id.mark);
fi_data->mark_to_index[gcd.id.mark] = gcd.id.index;
//std::cout << "commit new mark: " << gcd.id.mark << "\n";
// Add the commit to the data
fi_data->commits.push_back(gcd);
return 0;
}
void
write_op(std::ofstream &outfile, git_op *o, git_fi_data *s)
{
bool written = false;
switch (o->type) {
case filemodify:
if (o->dataref.sha1.length()) {
outfile << "M " << o->mode << " " << o->dataref.sha1 << " " << o->path << "\n";
written = true;
}
if (!written && o->dataref.mark > -1 && s->mark_to_sha1.find(o->dataref.mark) != s->mark_to_sha1.end()) {
outfile << "M " << o->mode << " " << s->mark_to_sha1[o->dataref.mark] << " " << o->path << "\n";
written = true;
}
if (!written && o->dataref.mark > -1) {
outfile << "M " << o->mode << " :" << o->dataref.mark << " " << o->path << "\n";
written = true;
}
if (!written) {
std::cerr << "Invalid filemodify dataref: " << o->dataref.mark << "," << o->dataref.sha1 << "\n";
exit(1);
}
break;
case filedelete:
outfile << "D " << o->path << "\n";
break;
case filecopy:
outfile << "C " << o->path << " " << o->dest_path << "\n";
break;
case filerename:
outfile << "R " << o->path << " " << o->dest_path << "\n";
break;
case filedeleteall:
outfile << "deleteall\n";
break;
case notemodify:
std::cerr << "TODO - write notemodify\n";
break;
}
}
// trim from end (in place) - https://stackoverflow.com/a/217605
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !(std::isspace(ch) || ch == '\n' || ch == '\r');
}).base(), s.end());
}
std::string
commit_msg(git_commit_data *c)
{
int cwidth = c->s->wrap_width;
std::string nmsg;
// Any whitespace at the end of the message, just trim it
if (c->s->trim_whitespace) {
rtrim(c->commit_msg);
}
if (c->s->wrap_commit_lines) {
// Wrap the commit messages - gitk doesn't like long one liners by
// default. Don't know why the line wrap ISN'T on by default, but we
// might as well deal with it while we're here...
size_t pdelim = c->commit_msg.find("\n\n");
if (pdelim == std::string::npos) {
size_t spos = c->commit_msg.find_first_of('\n');
if (spos == std::string::npos) {
std::string wmsg = TextFlow::Column(c->commit_msg).width(cwidth).toString();
c->commit_msg = wmsg;
}
} else {
// Multiple paragraphs - separate them for individual consideration.
std::vector<std::string> paragraphs;
std::string paragraphs_str = c->commit_msg;
while (paragraphs_str.length()) {
std::string para = paragraphs_str.substr(0, pdelim);
std::string remainder = paragraphs_str.substr(pdelim+2, std::string::npos);
paragraphs_str = remainder;
paragraphs.push_back(para);
pdelim = paragraphs_str.find("\n\n");
if (pdelim == std::string::npos) {
// That's it - last line
paragraphs.push_back(paragraphs_str);
paragraphs_str = std::string("");
}
}
bool can_wrap = true;
// If any of the paragraphs delimited by two returns has returns inside of it, we can't
// do anything - the message already has some sort of formatting.
for (size_t i = 0; i < paragraphs.size(); i++) {
size_t spos = paragraphs[i].find_first_of('\n');
if (spos != std::string::npos) {
can_wrap = false;
break;
}
}
if (can_wrap) {
// Wrap each paragraph individually
for (size_t i = 0; i < paragraphs.size(); i++) {
std::string newpara = TextFlow::Column(paragraphs[i]).width(cwidth).toString();
paragraphs[i] = newpara;
}
std::string newcommitmsg;
// Reassemble
for (size_t i = 0; i < paragraphs.size(); i++) {
newcommitmsg.append(paragraphs[i]);
newcommitmsg.append("\n\n");
}
rtrim(newcommitmsg);
c->commit_msg = newcommitmsg;
}
}
}
if (c->notes_string.length()) {
std::string nstr = c->notes_string;
if (c->s->trim_whitespace) rtrim(nstr);
if (c->s->wrap_commit_lines) {
size_t spos = nstr.find_first_of('\n');
if (spos == std::string::npos) {
std::string wmsg = TextFlow::Column(nstr).width(cwidth).toString();
nstr = wmsg;
}
}
if (c->svn_committer.length()) {
std::string committerstr = std::string("svn:account:") + c->svn_committer;
nmsg = c->commit_msg + std::string("\n\n") + nstr + std::string("\n") + committerstr + std::string("\n");
} else {
nmsg = c->commit_msg + std::string("\n\n") + nstr + std::string("\n");
}
} else {
if (c->s->trim_whitespace) {
nmsg = c->commit_msg + std::string("\n");
} else {
nmsg = c->commit_msg;
}
}
// Check for CVS information to add
if (c->s->sha12key.find(c->id.sha1) != c->s->sha12key.end()) {
std::string cvsmsg = nmsg;
std::string key = c->s->sha12key[c->id.sha1];
int have_ret = (c->svn_id.length()) ? 1 : 0;
if (c->s->key2cvsbranch.find(key) != c->s->key2cvsbranch.end()) {
//std::cout << "Found branch: " << c->s->key2cvsbranch[key] << "\n";
if (!have_ret) {
cvsmsg.append("\n");
have_ret = 1;
}
std::string cb = c->s->key2cvsbranch[key];
cvsmsg.append("cvs:branch:");
if (cb == std::string("master")) {
cvsmsg.append("trunk");
} else {
cvsmsg.append(cb);
}
cvsmsg.append("\n");
}
if (c->s->key2cvsauthor.find(key) != c->s->key2cvsauthor.end()) {
//std::cout << "Found author: " << c->s->key2cvsauthor[key] << "\n";
if (!have_ret) {
cvsmsg.append("\n");
}
std::string svnname = std::string("svn:account:") + c->s->key2cvsauthor[key];
std::string cvsaccount = std::string("cvs:account:") + c->s->key2cvsauthor[key];
size_t index = cvsmsg.find(svnname);
if (index != std::string::npos) {
std::cout << "Replacing svn:account\n";
cvsmsg.replace(index, cvsaccount.length(), cvsaccount);
} else {
cvsmsg.append(cvsaccount);
cvsmsg.append("\n");
}
}
nmsg = cvsmsg;
}
return nmsg;
}
int
write_commit(std::ofstream &outfile, git_commit_data *c, git_fi_data *d, std::ifstream &infile)
{
if (!infile.good()) {
return -1;
}
if (c->skip_commit)
return 0;
// If this is a reset commit, it's handled quite differently
if (c->reset_commit) {
outfile << "reset " << c->branch << "\n";
if (c->from.mark != -1) {
outfile << "from :" << c->from.mark << "\n";
}
outfile << "\n";
return 0;
}
#if 0
// If this is a rebuild, write the blobs first
if (c->id.sha1.length()) {
if (c->s->rebuild_commits.find(c->id.sha1) != c->s->rebuild_commits.end()) {
std::cout << "rebuild commit!\n";
std::string sha1blobs = c->id.sha1 + std::string("-blob.fi");
std::ifstream s1b(sha1blobs, std::ifstream::binary | std::ios::ate);
std::streamsize size = s1b.tellg();
s1b.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (s1b.read(buffer.data(), size)) {
outfile.write(reinterpret_cast<char*>(buffer.data()), size);
} else {
std::cerr << "Failed to open rebuild file " << sha1blobs << "\n";
exit(1);
}
s1b.close();
}
}
#endif
// Header
if (c->notes_commit) {
// Don't output notes commits - we're handling things differently.
return 0;
} else {
outfile << "commit refs/heads/" << c->branch << "\n";
}
outfile << "mark :" << c->id.mark << "\n";
#if 0
if (c->id.sha1.length()) {
outfile << "original-oid " << c->id.sha1 << "\n";
}
#endif
if (c->author.length()) {
outfile << "author " << c->author << " " << c->author_timestamp << "\n";
} else {
outfile << "author " << c->committer << " " << c->committer_timestamp << "\n";
}
outfile << "committer " << c->committer << " " << c->committer_timestamp << "\n";
std::string nmsg = commit_msg(c);
outfile << "data " << nmsg.length() << "\n";
outfile << nmsg;
if (c->from.mark != -1) {
// Check to see if a commit was spliced in between this commit and its from commit.
if (d->splice_map.find(c->from.mark) != d->splice_map.end()) {
git_commit_data &cd = d->splice_commits[c->from.mark];
outfile << "from :" << cd.id.mark << "\n";
} else {
outfile << "from :" << c->from.mark << "\n";
}
}
for (size_t i = 0; i < c->merges.size(); i++) {
outfile << "merge :" << c->merges[i].mark << "\n";
}
bool write_ops = true;
if (c->id.sha1.length()) {
if ((c->s->rebuild_commits.find(c->id.sha1) != c->s->rebuild_commits.end()) ||
(c->s->reset_commits.find(c->id.sha1) != c->s->reset_commits.end())) {
write_ops = false;
std::string sha1tree = std::string("trees/") + c->id.sha1 + std::string("-tree.fi");
std::ifstream s1t(sha1tree, std::ifstream::binary | std::ios::ate);
std::streamsize size = s1t.tellg();
s1t.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (s1t.read(buffer.data(), size)) {
outfile.write(reinterpret_cast<char*>(buffer.data()), size);
} else {
std::cerr << "Failed to open rebuild file " << sha1tree << "\n";
exit(1);
}
s1t.close();
}
}
if (write_ops) {
for (size_t i = 0; i < c->fileops.size(); i++) {
write_op(outfile, &c->fileops[i], d);
}
}
outfile << "\n";
// If there is a splice commit that follows this one, write it out now.
if (d->splice_map.find(c->id.mark) != d->splice_map.end()) {
std::cout << "Found splice commit to follow " << c->id.sha1 << "\n";
long s1 = d->mark_to_index[d->splice_map[c->id.mark]];
long scind = s1 - d->commits.size();
if (scind < 0) {
std::cerr << "Couldn't find splice commit\n";
exit(1);
}
git_commit_data *sc = &d->splice_commits[scind];
write_commit(outfile, sc, d, infile);
}
return 0;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 31.642058
| 120
| 0.611602
|
BRL-CAD
|
7382a31e1163f2951bc8af4ecafdc03a15f7606a
| 8,921
|
cpp
|
C++
|
source/xyo-win-inject-hook.cpp
|
g-stefan/xyo-win-inject
|
44ad5fc4f11643f33321532ab4f1eae84b04db33
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/xyo-win-inject-hook.cpp
|
g-stefan/xyo-win-inject
|
44ad5fc4f11643f33321532ab4f1eae84b04db33
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/xyo-win-inject-hook.cpp
|
g-stefan/xyo-win-inject
|
44ad5fc4f11643f33321532ab4f1eae84b04db33
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// XYO Win Inject
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include <windows.h>
#include <stdio.h>
#include "xyo-win-inject-hook.hpp"
#ifdef XYO_APPLICATION_32BIT
#define mPointer(type_,value_,offset_) (type_)((BYTE *)(value_)+(DWORD)(offset_))
#define procSize 4
#define PROCTYPE DWORD
#endif
#ifdef XYO_APPLICATION_64BIT
#define mPointer(type_,value_,offset_) (type_)((BYTE *)(value_)+(DWORD64)(offset_))
#define procSize 8
#define PROCTYPE DWORD64
#endif
namespace XYO {
namespace Win {
namespace Inject {
namespace Hook {
using namespace XYO;
void replaceFunction(HMODULE hModule, HookProc **hookList) {
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_IMPORT_DESCRIPTOR importDescriptor;
PIMAGE_THUNK_DATA thunkData;
DWORD dwOld, dw;
HookProc **scanList;
bool found;
if(hModule != nullptr) {
dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
ntHeaders = mPointer(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);
if(ntHeaders->Signature == IMAGE_NT_SIGNATURE) {
importDescriptor = mPointer(PIMAGE_IMPORT_DESCRIPTOR, dosHeader, ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
if(importDescriptor > (PIMAGE_IMPORT_DESCRIPTOR)ntHeaders) {
for(; importDescriptor->Name; ++importDescriptor) {
for(thunkData = mPointer(PIMAGE_THUNK_DATA, dosHeader, importDescriptor->FirstThunk); thunkData->u1.Function; ++thunkData) {
for(scanList = hookList; *scanList != nullptr; ++scanList) {
if((FARPROC)thunkData->u1.Function == (FARPROC)(*scanList)->originalProc) {
if(VirtualProtect(&thunkData->u1.Function, procSize,
PAGE_EXECUTE_READWRITE, &dwOld)) {
thunkData->u1.Function = (PROCTYPE)(*scanList)->newProc;
VirtualProtect(&thunkData->u1.Function, procSize,
dwOld, &dw);
};
break;
};
};
};
};
};
};
};
};
};
BOOL enumImportTable(HMODULE hModule, IEnumImportModuleName iEnum, PVOID userData) {
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_IMPORT_DESCRIPTOR importDescriptor;
if(hModule != nullptr) {
dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
ntHeaders = mPointer(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);
if(ntHeaders->Signature == IMAGE_NT_SIGNATURE) {
importDescriptor = mPointer(PIMAGE_IMPORT_DESCRIPTOR, dosHeader, ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
if(importDescriptor > (PIMAGE_IMPORT_DESCRIPTOR)ntHeaders) {
for(; importDescriptor->Name; ++importDescriptor) {
if ((*iEnum)(userData, mPointer(LPSTR, dosHeader, importDescriptor->Name))) {
} else {
return TRUE;
}
}
}
}
}
}
return TRUE;
};
LPSTR getProcOrdinal(HMODULE hModule, LPSTR procName) {
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_EXPORT_DIRECTORY exportDescriptor;
DWORD *procNames;
DWORD procIndex;
if(IS_INTRESOURCE(procName)) {
return procName;
};
if(hModule != nullptr) {
dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
ntHeaders = mPointer(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);
if(ntHeaders->Signature == IMAGE_NT_SIGNATURE) {
exportDescriptor = mPointer(PIMAGE_EXPORT_DIRECTORY, dosHeader, ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
if(exportDescriptor > (PIMAGE_EXPORT_DIRECTORY)ntHeaders) {
procNames = mPointer(DWORD *, dosHeader, exportDescriptor->AddressOfNames);
for(procIndex = 0; procIndex < exportDescriptor->NumberOfNames; ++procIndex) {
if(StringCore::compareIgnoreCaseAscii(mPointer(LPSTR, dosHeader, procNames[procIndex]), procName) == 0) {
return MAKEINTRESOURCEA(exportDescriptor->Base + ((mPointer(WORD *, dosHeader, exportDescriptor->AddressOfNameOrdinals))[procIndex]));
};
};
};
};
};
};
return 0;
};
LPSTR getProcName(HMODULE hModule, LPSTR procOrdinal) {
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_EXPORT_DIRECTORY exportDescriptor;
DWORD procIndex;
if(!IS_INTRESOURCE(procOrdinal)) {
return procOrdinal;
};
if(hModule != nullptr) {
dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
ntHeaders = mPointer(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);
if(ntHeaders->Signature == IMAGE_NT_SIGNATURE) {
exportDescriptor = mPointer(PIMAGE_EXPORT_DIRECTORY, dosHeader, ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
if(exportDescriptor > (PIMAGE_EXPORT_DIRECTORY)ntHeaders) {
for(procIndex = 0; procIndex < exportDescriptor->NumberOfNames; ++procIndex) {
if(MAKEINTRESOURCEA(exportDescriptor->Base + ((mPointer(WORD *, dosHeader, exportDescriptor->AddressOfNameOrdinals))[procIndex])) == procOrdinal) {
return mPointer(LPSTR, dosHeader, (mPointer(DWORD *, dosHeader, exportDescriptor->AddressOfNames))[procIndex]);
};
};
};
};
};
};
return 0;
};
void setOriginalFunction(HookProc &hook, LPSTR moduleName, LPSTR procName, FARPROC newProc) {
hook.hModule = nullptr;
hook.newProc = nullptr;
hook.originalProc = nullptr;
hook.procName = nullptr;
hook.procOrdinal = nullptr;
HMODULE hModule = GetModuleHandle(moduleName);
if(hModule == nullptr) {
hModule = LoadLibrary(moduleName);
};
if(hModule != nullptr) {
hook.hModule = hModule;
hook.newProc = newProc;
hook.originalProc = GetProcAddress(hModule, procName);
hook.procName = getProcName(hModule, procName);
hook.procOrdinal = getProcOrdinal(hModule, procName);
};
};
bool processModule(HMODULE hModule, HookProc **hookList, HMODULE *processedList, size_t &processedListIndex, size_t processedListSize, LPSTR *skipList) {
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_IMPORT_DESCRIPTOR importDescriptor;
size_t index;
if(hModule == nullptr) {
return false;
};
for(index = 0; index < processedListIndex; ++index) {
if(hModule == processedList[index]) {
return false;
};
};
processedList[processedListIndex] = hModule;
++processedListIndex;
for(index = 0; skipList[index] != nullptr; ++index) {
if(hModule == GetModuleHandle(skipList[index])) {
return false;
};
};
replaceFunction(hModule, hookList);
dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
ntHeaders = mPointer(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);
if(ntHeaders->Signature == IMAGE_NT_SIGNATURE) {
importDescriptor = mPointer(PIMAGE_IMPORT_DESCRIPTOR, dosHeader, ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
if(importDescriptor > (PIMAGE_IMPORT_DESCRIPTOR)ntHeaders) {
for(; importDescriptor->Name; ++importDescriptor) {
processModule(GetModuleHandle(mPointer(LPSTR, dosHeader, importDescriptor->Name)), hookList, processedList, processedListIndex, processedListSize, skipList);
};
};
};
};
return true;
};
FARPROC getProcAddress(HMODULE hModule, LPCSTR lpProcName, HookProc **hookList) {
HookProc **scanList;
if(IS_INTRESOURCE(lpProcName)) {
for(scanList = hookList; *scanList != nullptr; ++scanList) {
if((*scanList)->hModule == hModule) {
if((*scanList)->procOrdinal == lpProcName) {
return (*scanList)->newProc;
};
};
};
return nullptr;
};
for(scanList = hookList; *scanList != nullptr; ++scanList) {
if((*scanList)->hModule == hModule) {
if(StringCore::compareIgnoreCaseAscii((*scanList)->procName, lpProcName) == 0) {
return (*scanList)->newProc;
};
};
};
return nullptr;
};
};
};
};
};
| 35.26087
| 167
| 0.643986
|
g-stefan
|
73844cafa77d531a00bece37879f9cf9a068d652
| 1,606
|
cpp
|
C++
|
problem8.cpp
|
jurrehart/euler
|
9eca473c056472ecdcce73480ff09dfb8285b4cd
|
[
"MIT"
] | null | null | null |
problem8.cpp
|
jurrehart/euler
|
9eca473c056472ecdcce73480ff09dfb8285b4cd
|
[
"MIT"
] | null | null | null |
problem8.cpp
|
jurrehart/euler
|
9eca473c056472ecdcce73480ff09dfb8285b4cd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#define SEQUENCE_SIZE 13
int main(){
std::string sequence = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450";
unsigned long long largestProduct = 0;
for ( int i = 0; i < sequence.length() - SEQUENCE_SIZE; i++){
unsigned long long product = 1;
std::string parse = sequence.substr(i, SEQUENCE_SIZE);
for ( int c=0; c < parse.length() ; c++){
int fact = parse.at(c) - '0';
product *= fact;
}
if (product > largestProduct){
largestProduct = product;
}
}
std::cout << "largest product of SEQUENCE_SIZE " << largestProduct << std::endl;
return 0;
}
| 34.913043
| 81
| 0.848692
|
jurrehart
|
7384599a1f9c15bd15a25edc5116abbb55dd18dc
| 6,675
|
cc
|
C++
|
src/MissionManager/SpeedSection.cc
|
JeremVincent/qgroundcontrol
|
113907ba991b710f6bf4276e765569a41e6060f2
|
[
"Apache-2.0"
] | null | null | null |
src/MissionManager/SpeedSection.cc
|
JeremVincent/qgroundcontrol
|
113907ba991b710f6bf4276e765569a41e6060f2
|
[
"Apache-2.0"
] | null | null | null |
src/MissionManager/SpeedSection.cc
|
JeremVincent/qgroundcontrol
|
113907ba991b710f6bf4276e765569a41e6060f2
|
[
"Apache-2.0"
] | 2
|
2020-03-30T10:45:13.000Z
|
2020-05-10T11:50:07.000Z
|
/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "SpeedSection.h"
#include "JsonHelper.h"
#include "FirmwarePlugin.h"
#include "SimpleMissionItem.h"
#include "Admin/List_file.h"
const char* SpeedSection::_flightSpeedName = "FlightSpeed";
extern List_file *speedParam;
QMap<QString, FactMetaData*> SpeedSection::_metaDataMap;
SpeedSection::SpeedSection(Vehicle* vehicle, QObject* parent)
: Section (vehicle, parent)
, _available (false)
, _dirty (false)
, _specifyFlightSpeed (true)
, _flightSpeedFact (0, _flightSpeedName, FactMetaData::valueTypeDouble)
{
if (_metaDataMap.isEmpty()) {
_metaDataMap = FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/SpeedSection.FactMetaData.json"), NULL /* metaDataParent */);
}
double flightSpeed = 0;
if (_vehicle->multiRotor()) {
flightSpeed = _vehicle->defaultHoverSpeed();
} else {
flightSpeed = _vehicle->defaultCruiseSpeed();
}
flightSpeed = speedParam->at(1).toDouble();
_metaDataMap[_flightSpeedName]->setRawDefaultValue(flightSpeed);
_flightSpeedFact.setMetaData(_metaDataMap[_flightSpeedName]);
_flightSpeedFact.setRawValue(flightSpeed);
connect(this, &SpeedSection::specifyFlightSpeedChanged, this, &SpeedSection::settingsSpecifiedChanged);
connect(&_flightSpeedFact, &Fact::valueChanged, this, &SpeedSection::_flightSpeedChanged);
connect(this, &SpeedSection::specifyFlightSpeedChanged, this, &SpeedSection::_updateSpecifiedFlightSpeed);
connect(&_flightSpeedFact, &Fact::valueChanged, this, &SpeedSection::_updateSpecifiedFlightSpeed);
}
bool SpeedSection::settingsSpecified(void) const
{
return _specifyFlightSpeed;
}
void SpeedSection::setAvailable(bool available)
{
if (available != _available) {
if (available && (_vehicle->multiRotor() || _vehicle->fixedWing())) {
_available = available;
emit availableChanged(available);
}
}
}
void SpeedSection::setDirty(bool dirty)
{
if (_dirty != dirty) {
_dirty = dirty;
emit dirtyChanged(_dirty);
}
}
void SpeedSection::setSpecifyFlightSpeed(bool specifyFlightSpeed)
{
if (specifyFlightSpeed != _specifyFlightSpeed) {
_specifyFlightSpeed = specifyFlightSpeed;
emit specifyFlightSpeedChanged(specifyFlightSpeed);
setDirty(true);
emit itemCountChanged(itemCount());
}
}
int SpeedSection::itemCount(void) const
{
return _specifyFlightSpeed ? 1: 0;
}
void SpeedSection::appendSectionItems(QList<MissionItem*>& items, QObject* missionItemParent, int& seqNum)
{
// IMPORTANT NOTE: If anything changes here you must also change SpeedSection::scanForSettings
if (_specifyFlightSpeed) {
MissionItem* item = new MissionItem(seqNum++,
MAV_CMD_DO_CHANGE_SPEED,
MAV_FRAME_MISSION,
_vehicle->multiRotor() ? 1 /* groundspeed */ : 0 /* airspeed */, // Change airspeed or groundspeed
_flightSpeedFact.rawValue().toDouble(),
-1, // No throttle change
0, // Absolute speed change
0, 0, 0, // param 5-7 not used
true, // autoContinue
false, // isCurrentItem
missionItemParent);
items.append(item);
}
}
bool SpeedSection::scanForSection(QmlObjectListModel* visualItems, int scanIndex)
{
if (!_available || scanIndex >= visualItems->count()) {
return false;
}
SimpleMissionItem* item = visualItems->value<SimpleMissionItem*>(scanIndex);
if (!item) {
// We hit a complex item, there can't be a speed setting
return false;
}
MissionItem& missionItem = item->missionItem();
// See SpeedSection::appendMissionItems for specs on what consitutes a known speed setting
if (missionItem.command() == MAV_CMD_DO_CHANGE_SPEED && missionItem.param3() == -1 && missionItem.param4() == 0 && missionItem.param5() == 0 && missionItem.param6() == 0 && missionItem.param7() == 0) {
if (_vehicle->multiRotor() && missionItem.param1() != 1) {
return false;
} else if (_vehicle->fixedWing() && missionItem.param1() != 0) {
return false;
}
visualItems->removeAt(scanIndex)->deleteLater();
_flightSpeedFact.setRawValue(missionItem.param2());
setSpecifyFlightSpeed(true);
return true;
}
return false;
}
double SpeedSection::specifiedFlightSpeed(void) const
{
return _specifyFlightSpeed ? _flightSpeedFact.rawValue().toDouble() : std::numeric_limits<double>::quiet_NaN();
}
void SpeedSection::_updateSpecifiedFlightSpeed(void)
{
if (_specifyFlightSpeed) {
emit specifiedFlightSpeedChanged(specifiedFlightSpeed());
}
}
void SpeedSection::_flightSpeedChanged(void)
{
// We only set the dirty bit if specify flight speed it set. This allows us to change defaults for flight speed
// without affecting dirty.
if (_specifyFlightSpeed) {
setDirty(true);
}
}
void SpeedSection::setBoxSpeed (int index) {
// qDebug() << "--------- survey setBoxSpeed" << index;
_flightSpeedFact.setRawValue(speedParam->at(index).toDouble());
}
int SpeedSection::getCruiseSpeedInd () {
// qDebug() << "--------- survey getCruiseSpeedInd" << _cruiseSpeed;
if (speedParam->contains(QString::number(_flightSpeedFact.rawValue().toDouble()))) {
return speedParam->indexOf(QString::number(_flightSpeedFact.rawValue().toDouble()));
}
else return 1;
}
QString SpeedSection::getSpeedTxt () {
return _flightSpeedFact.rawValue().toString() + " m/s";
}
| 37.290503
| 205
| 0.589363
|
JeremVincent
|
73849a3691fece0237af7c024bd17ca50033537c
| 657
|
cpp
|
C++
|
src/Entity/SearchableString.cpp
|
epfremmer/PHP-Weekly-Issue37c
|
48d9907f2c427f1bdb122027975509b52b31b711
|
[
"MIT"
] | null | null | null |
src/Entity/SearchableString.cpp
|
epfremmer/PHP-Weekly-Issue37c
|
48d9907f2c427f1bdb122027975509b52b31b711
|
[
"MIT"
] | null | null | null |
src/Entity/SearchableString.cpp
|
epfremmer/PHP-Weekly-Issue37c
|
48d9907f2c427f1bdb122027975509b52b31b711
|
[
"MIT"
] | null | null | null |
//
// Created by Edward Pfremmer on 1/28/16.
//
#include <string>
#include <iostream>
#include "SearchableString.h"
SearchableString::SearchableString(std::string &value) {
this->value = value;
std::transform(this->value.begin(), this->value.end(), this->value.begin(), ::tolower);
}
int SearchableString::search(const std::string search) {
int result = 0;
std::string input(search);
std::transform(input.begin(), input.end(), input.begin(), ::tolower);
size_t pos = this->value.find(input, 0);
while (pos != std::string::npos) {
pos = this->value.find(input, pos+1);
result++;
}
return result;
}
| 21.9
| 91
| 0.631659
|
epfremmer
|
7385d1402258931e01583346fa4e4d6b7f30d8ed
| 1,495
|
hpp
|
C++
|
Includes/Rosetta/PlayMode/Zones/HandZone.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 62
|
2017-08-21T14:11:00.000Z
|
2018-04-23T16:09:02.000Z
|
Includes/Rosetta/PlayMode/Zones/HandZone.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 37
|
2017-08-21T11:13:07.000Z
|
2018-04-30T08:58:41.000Z
|
Includes/Rosetta/PlayMode/Zones/HandZone.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 10
|
2017-08-21T03:44:12.000Z
|
2018-01-10T22:29:10.000Z
|
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#ifndef ROSETTASTONE_PLAYMODE_HAND_ZONE_HPP
#define ROSETTASTONE_PLAYMODE_HAND_ZONE_HPP
#include <Rosetta/PlayMode/Models/Entity.hpp>
#include <Rosetta/PlayMode/Zones/Zone.hpp>
namespace RosettaStone::PlayMode
{
//!
//! \brief HandZone class.
//!
//! This class is where each player keeps the cards currently available to
//! them. The player can see their hand face-up at the bottom of the screen,
//! while the opponent's hand is shown face-down at the top of the screen.
//!
class HandZone : public PositioningZone<Playable>
{
public:
//! Constructs hand zone with given \p player.
//! \param player The player.
explicit HandZone(Player* player);
//! Adds the specified entity into this zone, at the given position.
//! \param entity The entity.
//! \param zonePos The zone position.
void Add(Playable* entity, int zonePos = -1) override;
//! Removes the specified entity from this zone.
//! \param entity The entity.
//! \return The entity.
Playable* Remove(Playable* entity) override;
//! Expands the size of hand.
//! \param newSize The size of hand to expand.
void Expand(int newSize);
};
} // namespace RosettaStone::PlayMode
#endif // ROSETTASTONE_PLAYMODE_HAND_ZONE_HPP
| 32.5
| 76
| 0.724415
|
Hearthstonepp
|
738cb5d2ccd4e2e7311e97f8447d72d4b7ef3d1e
| 1,356
|
cpp
|
C++
|
Code/UnitTests/FoundationTest/Math/RationalTest.cpp
|
alinoctavian/ezEngine
|
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
|
[
"MIT"
] | 1
|
2021-06-23T14:44:02.000Z
|
2021-06-23T14:44:02.000Z
|
Code/UnitTests/FoundationTest/Math/RationalTest.cpp
|
alinoctavian/ezEngine
|
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
|
[
"MIT"
] | null | null | null |
Code/UnitTests/FoundationTest/Math/RationalTest.cpp
|
alinoctavian/ezEngine
|
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
|
[
"MIT"
] | 1
|
2022-03-28T15:57:46.000Z
|
2022-03-28T15:57:46.000Z
|
#include <FoundationTestPCH.h>
#include <Foundation/Math/Rational.h>
#include <Foundation/Strings/StringBuilder.h>
EZ_CREATE_SIMPLE_TEST(Math, Rational)
{
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Rational")
{
ezRational r1(100, 1);
EZ_TEST_BOOL(r1.IsValid());
EZ_TEST_BOOL(r1.IsIntegral());
ezRational r2(100, 0);
EZ_TEST_BOOL(!r2.IsValid());
EZ_TEST_BOOL(r1 != r2);
ezRational r3(100, 1);
EZ_TEST_BOOL(r3 == r1);
ezRational r4(0, 0);
EZ_TEST_BOOL(r4.IsValid());
ezRational r5(30, 6);
EZ_TEST_BOOL(r5.IsIntegral());
EZ_TEST_INT(r5.GetIntegralResult(), 5);
EZ_TEST_FLOAT(r5.GetFloatingPointResult(), 5, ezMath::SmallEpsilon<double>());
ezRational reducedTest(5, 1);
EZ_TEST_BOOL(r5.ReduceIntegralFraction() == reducedTest);
ezRational r6(31, 6);
EZ_TEST_BOOL(!r6.IsIntegral());
EZ_TEST_FLOAT(r6.GetFloatingPointResult(), 5.16666666666, ezMath::SmallEpsilon<double>());
EZ_TEST_INT(r6.GetDenominator(), 6);
EZ_TEST_INT(r6.GetNumerator(), 31);
}
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Rational String Formatting")
{
ezRational r1(50, 25);
ezStringBuilder sb;
sb.Format("Rational: {}", r1);
EZ_TEST_STRING(sb, "Rational: 2");
ezRational r2(233, 76);
sb.Format("Rational: {}", r2);
EZ_TEST_STRING(sb, "Rational: 233/76");
}
}
| 23.37931
| 94
| 0.671091
|
alinoctavian
|
7391ceecd4ad4c946718103dda945c6223da4bda
| 1,338
|
cpp
|
C++
|
Codeforces/1430/A.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | 2
|
2021-09-14T15:57:24.000Z
|
2022-03-18T14:11:04.000Z
|
Codeforces/1430/A.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | null | null | null |
Codeforces/1430/A.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | null | null | null |
/*
"Do I really belong in this game I ponder, I just wanna play my part."
- Guts over fear, Eminem
*/
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define ff first
#define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ss second
#define all(c) c.begin(),c.end()
#define endl "\n"
#define test() int t; cin>>t; while(t--)
#define fl(i,a,b) for(int i = a ; i <b ;i++)
#define get(a) fl(i,0,a.size()) cin>>a[i];
#define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
#define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl;
const ll INF = 2e18;
const int inf = 2e9;
const int mod1 = 1e9 + 7;
int main(){
Shazam;
vector<pair<int,pair<int,int>>> dp(1004,{-1,{-1,-1}});
dp[3] = {1,{0,0}};
dp[5] = {0,{1,0}};
dp[7] = {0,{0,1}};
for(int i = 3; i < 1004; i++){
if(dp[i].ff==-1) continue;
if(i+3 < 1004) dp[i+3] = {dp[i].ff + 1, {dp[i].ss.ff,dp[i].ss.ss}};
if(i+5 < 1004) dp[i+5] = {dp[i].ff, {dp[i].ss.ff+1,dp[i].ss.ss}};;
if(i+7 < 1004) dp[i+7] = {dp[i].ff , {dp[i].ss.ff,dp[i].ss.ss+1}};;
}
test(){
int i; cin>>i;
if(dp[i].ff==-1) cout<<-1<<endl;
else cout<<dp[i].ff<<" "<<dp[i].ss.ff<<" "<<dp[i].ss.ss<<endl;
}
return 0;
}
| 30.409091
| 81
| 0.532138
|
noobie7
|
7392b76a1b427fefdf472f85efd15ca7ad569c38
| 2,129
|
cpp
|
C++
|
src/WAM/indexing.cpp
|
ThermalSpan/russWAM
|
c237bb782a83f7f6e2ccfa50800a55523ca22f67
|
[
"MIT"
] | null | null | null |
src/WAM/indexing.cpp
|
ThermalSpan/russWAM
|
c237bb782a83f7f6e2ccfa50800a55523ca22f67
|
[
"MIT"
] | null | null | null |
src/WAM/indexing.cpp
|
ThermalSpan/russWAM
|
c237bb782a83f7f6e2ccfa50800a55523ca22f67
|
[
"MIT"
] | null | null | null |
//
// indexing.cpp
// russWAM
//
// Created by Russell Wilhelm Bentley on 12/14/15.
// Copyright (c) 2015 Russell Wilhelm Bentley.
// Distributed under the MIT License
//
#include <unordered_map>
#include "WAM.h"
void WAM::switch_on_term (int V, int C, int L, int S) {
DataCell* cell = deref (getGlobalReg (1));
switch (cell->tag) {
case REF:
if (V == -1) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, V);
}
break;
case CON:
if (C == -1) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, C);
}
break;
case LIS:
if (L == -1) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, L);
}
break;
case STR:
case FUN: // TODO: Is this right?
if (S == -1) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, S);
}
break;
default:
panic ("PANIC: switch_on_term not on term? tag: " + tag2str (cell->tag));
break;
}
}
// These are the same...
// TODO: fix this replication heresy OR find out if they should be different
void WAM::switch_on_constant () {
DataCell* cell = deref (getGlobalReg (1));
auto map = m_functorTable->getSwitchMap (m_functorId);
// Find the dereferenced functor, then set the next instruction, else backtrack,
auto labelIter = map->find (cell->functorId);
if (labelIter == map->end ()) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, labelIter->first);
}
}
void WAM::switch_on_structure () {
DataCell* cell = deref (getGlobalReg (1));
auto map = m_functorTable->getSwitchMap (m_functorId);
// Find the dereferenced functor, then set the next instruction, else backtrack,
auto labelIter = map->find (cell->functorId);
if (labelIter == map->end ()) {
backtrack ();
} else {
m_P = m_functorTable->getLabel (m_functorId, labelIter->first);
}
}
| 26.6125
| 84
| 0.566933
|
ThermalSpan
|
73976fd199445a9bce3917ba16e45a51a9da480d
| 4,125
|
hpp
|
C++
|
include/codegen/include/System/Text/RegularExpressions/RegexMatchTimeoutException.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/System/Text/RegularExpressions/RegexMatchTimeoutException.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/System/Text/RegularExpressions/RegexMatchTimeoutException.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:17 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.TimeoutException
#include "System/TimeoutException.hpp"
// Including type: System.TimeSpan
#include "System/TimeSpan.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
// Forward declaring type: StreamingContext
struct StreamingContext;
}
// Completed forward declares
// Type namespace: System.Text.RegularExpressions
namespace System::Text::RegularExpressions {
// Autogenerated type: System.Text.RegularExpressions.RegexMatchTimeoutException
class RegexMatchTimeoutException : public System::TimeoutException, public System::Runtime::Serialization::ISerializable {
public:
// private System.String regexInput
// Offset: 0x88
::Il2CppString* regexInput;
// private System.String regexPattern
// Offset: 0x90
::Il2CppString* regexPattern;
// private System.TimeSpan matchTimeout
// Offset: 0x98
System::TimeSpan matchTimeout;
// public System.Void .ctor(System.String regexInput, System.String regexPattern, System.TimeSpan matchTimeout)
// Offset: 0x121572C
static RegexMatchTimeoutException* New_ctor(::Il2CppString* regexInput, ::Il2CppString* regexPattern, System::TimeSpan matchTimeout);
// private System.Void Init(System.String input, System.String pattern, System.TimeSpan timeout)
// Offset: 0x1215800
void Init(::Il2CppString* input, ::Il2CppString* pattern, System::TimeSpan timeout);
// public System.Void .ctor()
// Offset: 0x1215848
// Implemented from: System.TimeoutException
// Base method: System.Void TimeoutException::.ctor()
// Base method: System.Void SystemException::.ctor()
// Base method: System.Void Exception::.ctor()
// Base method: System.Void Object::.ctor()
static RegexMatchTimeoutException* New_ctor();
// protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1215970
// Implemented from: System.TimeoutException
// Base method: System.Void TimeoutException::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Base method: System.Void SystemException::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
static RegexMatchTimeoutException* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// private System.Void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1215A9C
// Implemented from: System.Runtime.Serialization.ISerializable
// Base method: System.Void ISerializable::GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context)
void System_Runtime_Serialization_ISerializable_GetObjectData(System::Runtime::Serialization::SerializationInfo* si, System::Runtime::Serialization::StreamingContext context);
// private System.Void Init()
// Offset: 0x12158C8
// Implemented from: System.Exception
// Base method: System.Void Exception::Init()
void Init();
}; // System.Text.RegularExpressions.RegexMatchTimeoutException
}
DEFINE_IL2CPP_ARG_TYPE(System::Text::RegularExpressions::RegexMatchTimeoutException*, "System.Text.RegularExpressions", "RegexMatchTimeoutException");
#pragma pack(pop)
| 57.291667
| 189
| 0.764121
|
Futuremappermydud
|
7399ebe3536abecfb9d9fbed610345d99323aa5d
| 1,127
|
cc
|
C++
|
Mu2eKinKal/src/KKMaterial.cc
|
lborrel/Offline
|
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
|
[
"Apache-2.0"
] | 1
|
2021-06-23T22:09:28.000Z
|
2021-06-23T22:09:28.000Z
|
Mu2eKinKal/src/KKMaterial.cc
|
lborrel/Offline
|
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
|
[
"Apache-2.0"
] | 125
|
2020-04-03T13:44:30.000Z
|
2021-10-15T21:29:57.000Z
|
Mu2eKinKal/src/KKMaterial.cc
|
lborrel/Offline
|
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
|
[
"Apache-2.0"
] | null | null | null |
#include "Mu2eKinKal/inc/KKMaterial.hh"
#include "GeometryService/inc/GeomHandle.hh"
#include "TrackerGeom/inc/Tracker.hh"
#include "GeometryService/inc/GeometryService.hh"
namespace mu2e {
using StrawMaterial = KinKal::StrawMaterial;
using MatDBInfo = MatEnv::MatDBInfo;
KKMaterial::KKMaterial(KKMaterial::Config const& matconfig) :
filefinder_(matconfig.elements(),matconfig.isotopes(),matconfig.materials()),
wallmatname_(matconfig.strawWallMaterialName()),
gasmatname_(matconfig.strawGasMaterialName()),
wirematname_(matconfig.strawWireMaterialName()),
matdbinfo_(0) {}
StrawMaterial const& KKMaterial::strawMaterial() const {
if(matdbinfo_ == 0){
matdbinfo_ = new MatDBInfo(filefinder_);
Tracker const & tracker = *(GeomHandle<Tracker>());
auto const& sprop = tracker.strawProperties();
smat_ = std::make_unique<StrawMaterial>(
sprop._strawOuterRadius, sprop._strawWallThickness, sprop._wireRadius,
matdbinfo_->findDetMaterial(wallmatname_),
matdbinfo_->findDetMaterial(gasmatname_),
matdbinfo_->findDetMaterial(wirematname_));
}
return *smat_;
}
}
| 36.354839
| 81
| 0.751553
|
lborrel
|
739a6f4f141af45a2a085e53288975b7e3d8fa48
| 1,596
|
hpp
|
C++
|
src/Cello/compute_SolverNull.hpp
|
brittonsmith/enzo-e
|
56d8417f2bdfc60f38326ba7208b633bfcea3175
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/Cello/compute_SolverNull.hpp
|
brittonsmith/enzo-e
|
56d8417f2bdfc60f38326ba7208b633bfcea3175
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/Cello/compute_SolverNull.hpp
|
brittonsmith/enzo-e
|
56d8417f2bdfc60f38326ba7208b633bfcea3175
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
// See LICENSE_CELLO file for license and copyright information
/// @file compute_SolverNull.hpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2018-02-26
/// @brief [\ref Compute] Declaration for the SolverNull class
#ifndef COMPUTE_SOLVER_NULL_HPP
#define COMPUTE_SOLVER_NULL_HPP
#include <cstring>
class SolverNull : public Solver
{
/// @class SolverNull
/// @ingroup Compute
/// @brief [\ref SolverNull] Interface to a linear SolverNull
public: // interface
/// Create a new SolverNull
SolverNull (std::string name,
std::string field_x,
std::string field_b,
int monitor_iter,
int restart_cycle,
int solve_type,
int min_level = 0,
int max_level = std::numeric_limits<int>::max()) throw()
: Solver(name,
field_x,
field_b,
monitor_iter,
restart_cycle,
solve_type,
min_level,
max_level)
{}
/// Create an uninitialized SolverNull
SolverNull () throw()
: Solver()
{}
/// Destructor
virtual ~SolverNull() throw()
{}
/// Charm++ PUP::able declarations
PUPable_decl(SolverNull);
SolverNull (CkMigrateMessage *m)
: Solver(m)
{ }
/// CHARM++ Pack / Unpack function
void pup (PUP::er &p);
public: // virtual functions
/// Solve the linear system Ax = b
virtual void apply ( std::shared_ptr<Matrix> A, Block * block) throw();
/// Return the name of this SolverNull
virtual std::string type () const
{ return "null"; }
protected: // functions
protected: // attributes
};
#endif /* COMPUTE_SOLVER_NULL_HPP */
| 21.567568
| 73
| 0.64787
|
brittonsmith
|
739c8494350cf191d9e24c8019930ade06e20f14
| 1,140
|
cpp
|
C++
|
.tutorials/zetcode.com_sources/07_wxWidgets_widgets_I/02_wxBitmapButton/bitmapbutton.cpp
|
Y2Kill/VSCode-wxWidgets-MinGW-W64-template
|
6263a547ddb54b6a2fd4fb0836c91b790f8980d7
|
[
"CC0-1.0"
] | null | null | null |
.tutorials/zetcode.com_sources/07_wxWidgets_widgets_I/02_wxBitmapButton/bitmapbutton.cpp
|
Y2Kill/VSCode-wxWidgets-MinGW-W64-template
|
6263a547ddb54b6a2fd4fb0836c91b790f8980d7
|
[
"CC0-1.0"
] | null | null | null |
.tutorials/zetcode.com_sources/07_wxWidgets_widgets_I/02_wxBitmapButton/bitmapbutton.cpp
|
Y2Kill/VSCode-wxWidgets-MinGW-W64-template
|
6263a547ddb54b6a2fd4fb0836c91b790f8980d7
|
[
"CC0-1.0"
] | null | null | null |
#include "bitmapbutton.h"
BitmapButton::BitmapButton(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(250, 130))
{
wxImage::AddHandler( new wxPNGHandler );
wxPanel *panel = new wxPanel(this);
slider = new wxSlider(panel, ID_SLIDER, 0, 0, 100,
wxPoint(10, 30), wxSize(140, -1));
button = new wxBitmapButton(panel, wxID_ANY, wxBitmap(wxT("audio-volume-muted.png"),
wxBITMAP_TYPE_PNG), wxPoint(180, 20));
Connect(ID_SLIDER, wxEVT_COMMAND_SLIDER_UPDATED,
wxScrollEventHandler(BitmapButton::OnScroll));
Center();
}
void BitmapButton::OnScroll(wxScrollEvent& event)
{
pos = slider->GetValue();
if (pos == 0) {
button->SetBitmapLabel(wxBitmap(wxT("audio-volume-muted.png"), wxBITMAP_TYPE_PNG));
} else if (pos > 0 && pos <= 30 ) {
button->SetBitmapLabel(wxBitmap(wxT("audio-volume-low.png"), wxBITMAP_TYPE_PNG));
} else if (pos > 30 && pos < 80 ) {
button->SetBitmapLabel(wxBitmap(wxT("audio-volume-medium.png"), wxBITMAP_TYPE_PNG));
} else {
button->SetBitmapLabel(wxBitmap(wxT("audio-volume-high.png"), wxBITMAP_TYPE_PNG));
}
}
| 34.545455
| 90
| 0.685088
|
Y2Kill
|
739e12ebecbfb83a18bb111ace63527088490fc2
| 19,377
|
cc
|
C++
|
src/ui/scenic/lib/scenic/session.cc
|
sunshinewithmoonlight/fuchsia-2003
|
02b23026dc7fecbad063210d5d45fa1b17feeb8b
|
[
"BSD-3-Clause"
] | null | null | null |
src/ui/scenic/lib/scenic/session.cc
|
sunshinewithmoonlight/fuchsia-2003
|
02b23026dc7fecbad063210d5d45fa1b17feeb8b
|
[
"BSD-3-Clause"
] | null | null | null |
src/ui/scenic/lib/scenic/session.cc
|
sunshinewithmoonlight/fuchsia-2003
|
02b23026dc7fecbad063210d5d45fa1b17feeb8b
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/scenic/lib/scenic/session.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/async/time.h>
#include <trace/event.h>
namespace scenic_impl {
Session::Session(SessionId id, fidl::InterfaceRequest<fuchsia::ui::scenic::Session> session_request,
fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener,
std::function<void()> destroy_session_function)
: id_(id),
listener_(listener.Bind()),
reporter_(std::make_shared<EventAndErrorReporter>(this)),
binding_(this, std::move(session_request)),
destroy_session_func_(std::move(destroy_session_function)),
weak_factory_(this) {
FXL_DCHECK(!binding_.channel() || binding_.is_bound());
}
Session::~Session() { reporter_->Reset(); }
void Session::set_binding_error_handler(fit::function<void(zx_status_t)> error_handler) {
binding_.set_error_handler(std::move(error_handler));
}
void Session::SetFrameScheduler(
const std::shared_ptr<scheduling::FrameScheduler>& frame_scheduler) {
FXL_DCHECK(frame_scheduler_.expired()) << "Error: FrameScheduler already set";
frame_scheduler_ = frame_scheduler;
// Initialize FrameScheduler callbacks.
// Check validity because frame_scheduler is not always set in tests.
if (frame_scheduler) {
frame_scheduler->SetOnUpdateFailedCallbackForSession(id_,
[weak = weak_factory_.GetWeakPtr()]() {
if (weak) {
// Called to initiate a session close
// when an update fails. Requests the
// destruction of client fidl session
// from scenic, which then triggers the
// actual destruction of this object.
weak->destroy_session_func_();
}
});
frame_scheduler->SetOnFramePresentedCallbackForSession(
id_,
[weak = weak_factory_.GetWeakPtr()](fuchsia::scenic::scheduling::FramePresentedInfo info) {
if (!weak)
return;
// Update and set num_presents_allowed before ultimately calling into the client provided
// callback.
weak->num_presents_allowed_ += (info.presentation_infos.size());
FXL_DCHECK(weak->num_presents_allowed_ <=
scheduling::FrameScheduler::kMaxPresentsInFlight);
info.num_presents_allowed = weak->num_presents_allowed_;
weak->binding_.events().OnFramePresented(std::move(info));
});
}
}
void Session::Enqueue(std::vector<fuchsia::ui::scenic::Command> cmds) {
TRACE_DURATION("gfx", "scenic_impl::Session::Enqueue", "session_id", id(), "num_commands",
cmds.size());
for (auto& cmd : cmds) {
// TODO(SCN-710): This dispatch is far from optimal in terms of performance.
// We need to benchmark it to figure out whether it matters.
System::TypeId type_id = SystemTypeForCmd(cmd);
auto dispatcher = type_id != System::TypeId::kInvalid ? dispatchers_[type_id].get() : nullptr;
if (!dispatcher) {
reporter_->EnqueueEvent(std::move(cmd));
} else if (type_id == System::TypeId::kInput) {
// Input handles commands immediately and doesn't care about present calls.
dispatcher->DispatchCommand(std::move(cmd), /*present_id=*/0);
} else {
commands_pending_present_.emplace_back(std::move(cmd));
}
}
}
bool Session::VerifyPresentType(PresentType present_type) {
if (present_type_ == PresentType::UNSET) {
present_type_ = present_type;
}
return present_type_ == present_type;
}
void Session::Present(uint64_t presentation_time, std::vector<zx::event> acquire_fences,
std::vector<zx::event> release_fences,
scheduling::OnPresentedCallback callback) {
TRACE_DURATION("gfx", "scenic_impl::Session::Present");
if (!VerifyPresentType(PresentType::PRESENT1)) {
reporter_->ERROR() << "Client cannot use Present() and Present2() in the same Session";
destroy_session_func_();
return;
}
TRACE_FLOW_END("gfx", "Session::Present", next_present_trace_id_);
next_present_trace_id_++;
if (--num_presents_allowed_ < 0) {
reporter_->ERROR() << "Present() called with no more present calls allowed.";
}
auto present_callback = [weak = weak_factory_.GetWeakPtr(),
callback = std::move(callback)](fuchsia::images::PresentationInfo info) {
if (!weak)
return;
++(weak->num_presents_allowed_);
FXL_DCHECK(weak->num_presents_allowed_ <= scheduling::FrameScheduler::kMaxPresentsInFlight);
callback(info);
};
SchedulePresentRequest(zx::time(presentation_time), std::move(acquire_fences),
std::move(release_fences), std::move(present_callback));
}
void Session::Present2(fuchsia::ui::scenic::Present2Args args, Present2Callback callback) {
if (!VerifyPresentType(PresentType::PRESENT2)) {
reporter_->ERROR() << "Client cannot use Present() and Present2() in the same Session";
destroy_session_func_();
return;
}
// Kill the Session if they have not set any of the Present2Args fields.
if (!args.has_requested_presentation_time() || !args.has_release_fences() ||
!args.has_acquire_fences() || !args.has_requested_prediction_span()) {
reporter_->ERROR() << "One or more fields not set in Present2Args table";
destroy_session_func_();
return;
}
// Kill the Session if they have no more presents left.
if (--num_presents_allowed_ < 0) {
reporter_->ERROR()
<< "Present2() called with no more present calls allowed. Terminating session.";
destroy_session_func_();
return;
}
// Output requested presentation time in milliseconds.
TRACE_DURATION("gfx", "scenic_impl::Session::Present2", "requested_presentation_time",
args.requested_presentation_time() / 1'000'000);
TRACE_FLOW_END("gfx", "Session::Present", next_present_trace_id_);
next_present_trace_id_++;
// After decrementing |num_presents_allowed_|, fire the immediate callback.
InvokeFuturePresentationTimesCallback(args.requested_prediction_span(), std::move(callback));
// Schedule update: flush commands with present count to track in gfx session
scheduling::Present2Info present2_info(id_);
zx::time present_received_time = zx::time(async_now(async_get_default_dispatcher()));
present2_info.SetPresentReceivedTime(present_received_time);
std::variant<scheduling::OnPresentedCallback, scheduling::Present2Info> present2_info_variant;
present2_info_variant.emplace<scheduling::Present2Info>(std::move(present2_info));
SchedulePresentRequest(
zx::time(args.requested_presentation_time()), std::move(*args.mutable_acquire_fences()),
std::move(*args.mutable_release_fences()), std::move(present2_info_variant));
}
void Session::ProcessQueuedPresents() {
if (presents_to_schedule_.empty() || fence_listener_) {
// The queue is either already being processed or there is nothing in the queue to process.
// If the queue is empty then trace id's should now be matching.
FXL_DCHECK(!presents_to_schedule_.empty() ||
queue_processing_trace_id_begin_ == queue_processing_trace_id_end_);
return;
}
// Handle the first present on the queue.
fence_listener_ = std::make_unique<escher::FenceSetListener>(
std::move(presents_to_schedule_.front().acquire_fences));
presents_to_schedule_.front().acquire_fences.clear();
fence_listener_->WaitReadyAsync([weak = weak_factory_.GetWeakPtr()] {
FXL_CHECK(weak);
weak->ScheduleNextPresent();
// Lambda won't fire if the object is destroyed, but the session can be killed inside of
// SchedulePresent, so we need to guard against that.
if (weak) {
// Keep going until all queued presents have been scheduled.
weak->fence_listener_.reset();
// After we delete the fence listener, this closure may be deleted. In that case, we should no
// longer access closed variables, including the this pointer.
weak->ProcessQueuedPresents();
}
});
}
void Session::SchedulePresentRequest(
zx::time requested_presentation_time, std::vector<zx::event> acquire_fences,
std::vector<zx::event> release_fences,
std::variant<scheduling::OnPresentedCallback, scheduling::Present2Info> presentation_info) {
TRACE_DURATION("gfx", "scenic_impl::Sesssion::SchedulePresentRequest");
{
// Logic verifying client requests presents in-order.
if (requested_presentation_time < last_scheduled_presentation_time_) {
reporter_->ERROR() << "scenic_impl::Session: Present called with out-of-order "
"presentation time. "
<< "requested presentation time=" << requested_presentation_time
<< ", last scheduled presentation time="
<< last_scheduled_presentation_time_ << ".";
destroy_session_func_();
return;
}
}
last_scheduled_presentation_time_ = requested_presentation_time;
if (auto scheduler = frame_scheduler_.lock()) {
const scheduling::PresentId present_id =
scheduler->RegisterPresent(id_, std::move(presentation_info), std::move(release_fences));
// Push present to the back of the queue of presents.
PresentRequest request{.present_id = present_id,
.requested_presentation_time = requested_presentation_time,
.acquire_fences = std::move(acquire_fences),
.commands = std::move(commands_pending_present_)};
presents_to_schedule_.emplace_back(std::move(request));
commands_pending_present_.clear();
TRACE_FLOW_BEGIN("gfx", "wait_for_fences", SESSION_TRACE_ID(id_, present_id));
ProcessQueuedPresents();
} else {
FXL_LOG(WARNING) << "FrameScheduler is missing.";
}
}
void Session::ScheduleNextPresent() {
FXL_DCHECK(!presents_to_schedule_.empty());
auto& present_request = presents_to_schedule_.front();
FXL_DCHECK(present_request.acquire_fences.empty());
TRACE_DURATION("gfx", "scenic_impl::Session::ScheduleNextPresent", "session_id", id_,
"requested time", present_request.requested_presentation_time.get());
TRACE_FLOW_END("gfx", "wait_for_fences", SESSION_TRACE_ID(id_, present_request.present_id));
for (auto& cmd : present_request.commands) {
System::TypeId type_id = SystemTypeForCmd(cmd);
auto dispatcher = type_id != System::TypeId::kInvalid ? dispatchers_[type_id].get() : nullptr;
FXL_DCHECK(dispatcher);
dispatcher->DispatchCommand(std::move(cmd), present_request.present_id);
}
if (auto scheduler = frame_scheduler_.lock()) {
scheduler->ScheduleUpdateForSession(presents_to_schedule_.front().requested_presentation_time,
{id_, presents_to_schedule_.front().present_id});
}
presents_to_schedule_.pop_front();
}
void Session::RequestPresentationTimes(zx_duration_t requested_prediction_span,
RequestPresentationTimesCallback callback) {
TRACE_DURATION("gfx", "scenic_impl::Session::RequestPresentationTimes");
InvokeFuturePresentationTimesCallback(requested_prediction_span, std::move(callback));
}
void Session::InvokeFuturePresentationTimesCallback(zx_duration_t requested_prediction_span,
RequestPresentationTimesCallback callback) {
if (!callback)
return;
if (auto locked_frame_scheduler = frame_scheduler_.lock()) {
locked_frame_scheduler->GetFuturePresentationInfos(
zx::duration(requested_prediction_span),
[weak = weak_factory_.GetWeakPtr(), callback = std::move(callback)](
std::vector<fuchsia::scenic::scheduling::PresentationInfo> presentation_infos) {
callback({std::move(presentation_infos), weak ? weak->num_presents_allowed_ : 0});
});
}
}
void Session::SetCommandDispatchers(
std::array<CommandDispatcherUniquePtr, System::TypeId::kMaxSystems> dispatchers) {
for (size_t i = 0; i < System::TypeId::kMaxSystems; ++i) {
dispatchers_[i] = std::move(dispatchers[i]);
}
}
void Session::SetDebugName(std::string debug_name) {
TRACE_DURATION("gfx", "scenic_impl::Session::SetDebugName", "debug name", debug_name);
for (auto& dispatcher : dispatchers_) {
if (dispatcher)
dispatcher->SetDebugName(debug_name);
}
}
Session::EventAndErrorReporter::EventAndErrorReporter(Session* session)
: session_(session), weak_factory_(this) {
FXL_DCHECK(session_);
}
void Session::EventAndErrorReporter::Reset() { session_ = nullptr; }
void Session::EventAndErrorReporter::PostFlushTask() {
FXL_DCHECK(session_);
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::PostFlushTask");
// If this is the first EnqueueEvent() since the last FlushEvent(), post a
// task to ensure that FlushEvents() is called.
if (buffered_events_.empty()) {
async::PostTask(async_get_default_dispatcher(), [weak = weak_factory_.GetWeakPtr()] {
if (!weak)
return;
weak->FilterRedundantGfxEvents();
weak->FlushEvents();
});
}
}
void Session::EventAndErrorReporter::EnqueueEvent(fuchsia::ui::gfx::Event event) {
if (!session_)
return;
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::EnqueueEvent", "event_type",
"gfx::Event");
PostFlushTask();
fuchsia::ui::scenic::Event scenic_event;
scenic_event.set_gfx(std::move(event));
buffered_events_.push_back(std::move(scenic_event));
}
void Session::EventAndErrorReporter::EnqueueEvent(fuchsia::ui::scenic::Command unhandled_command) {
if (!session_)
return;
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::EnqueueEvent", "event_type",
"UnhandledCommand");
PostFlushTask();
fuchsia::ui::scenic::Event scenic_event;
scenic_event.set_unhandled(std::move(unhandled_command));
buffered_events_.push_back(std::move(scenic_event));
}
void Session::EventAndErrorReporter::EnqueueEvent(fuchsia::ui::input::InputEvent event) {
if (!session_)
return;
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::EnqueueEvent", "event_type",
"input::InputEvent");
// Send input event immediately.
fuchsia::ui::scenic::Event scenic_event;
scenic_event.set_input(std::move(event));
FilterRedundantGfxEvents();
buffered_events_.push_back(std::move(scenic_event));
FlushEvents();
}
void Session::EventAndErrorReporter::FilterRedundantGfxEvents() {
if (buffered_events_.empty())
return;
struct EventCounts {
uint32_t view_attached_to_scene = 0;
uint32_t view_detached_from_scene = 0;
};
std::map</*view_id=*/uint32_t, EventCounts> event_counts;
for (const auto& event : buffered_events_) {
if (event.is_gfx()) {
switch (event.gfx().Which()) {
case fuchsia::ui::gfx::Event::kViewAttachedToScene:
event_counts[event.gfx().view_attached_to_scene().view_id].view_attached_to_scene++;
break;
case fuchsia::ui::gfx::Event::kViewDetachedFromScene:
event_counts[event.gfx().view_detached_from_scene().view_id].view_detached_from_scene++;
break;
default:
break;
}
}
}
if (event_counts.empty())
return;
auto is_view_event = [](uint32_t view_id, const fuchsia::ui::scenic::Event& event) {
return event.is_gfx() && ((event.gfx().is_view_detached_from_scene() &&
(view_id == event.gfx().view_detached_from_scene().view_id)) ||
(event.gfx().is_view_attached_to_scene() &&
(view_id == event.gfx().view_attached_to_scene().view_id)));
};
for (auto [view_id, event_count] : event_counts) {
auto matching_view_event = std::bind(is_view_event, view_id, std::placeholders::_1);
// We expect that multiple attach or detach events aren't fired in a row. Then, remove all
// attach/detach events if we have balanced counts. Otherwise, remove all except last.
if (event_count.view_attached_to_scene == event_count.view_detached_from_scene) {
buffered_events_.erase(
std::remove_if(buffered_events_.begin(), buffered_events_.end(), matching_view_event),
buffered_events_.end());
} else if (event_count.view_attached_to_scene && event_count.view_detached_from_scene) {
auto last_event =
std::find_if(buffered_events_.rbegin(), buffered_events_.rend(), matching_view_event);
buffered_events_.erase(
buffered_events_.rend().base(),
std::remove_if(std::next(last_event), buffered_events_.rend(), matching_view_event)
.base());
}
}
}
void Session::EventAndErrorReporter::FlushEvents() {
if (!session_)
return;
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::FlushEvents");
if (!buffered_events_.empty()) {
if (session_->listener_) {
session_->listener_->OnScenicEvent(std::move(buffered_events_));
} else if (event_callback_) {
// Only use the callback if there is no listener. It is difficult to do
// better because we std::move the argument into OnScenicEvent().
for (auto& evt : buffered_events_) {
event_callback_(std::move(evt));
}
}
buffered_events_.clear();
}
}
void Session::EventAndErrorReporter::ReportError(fxl::LogSeverity severity,
std::string error_string) {
// TODO(SCN-1265): Come up with a better solution to avoid children
// calling into us during destruction.
if (!session_) {
FXL_LOG(ERROR) << "Reporting Scenic Session error after session destroyed: " << error_string;
return;
}
TRACE_DURATION("gfx", "scenic_impl::Session::EventAndErrorReporter::ReportError");
switch (severity) {
case fxl::LOG_INFO:
FXL_LOG(INFO) << error_string;
return;
case fxl::LOG_WARNING:
FXL_LOG(WARNING) << error_string;
return;
case fxl::LOG_ERROR:
FXL_LOG(ERROR) << "Scenic session error (session_id: " << session_->id()
<< "): " << error_string;
if (error_callback_) {
error_callback_(error_string);
}
if (session_->listener_) {
session_->listener_->OnScenicError(std::move(error_string));
}
return;
case fxl::LOG_FATAL:
FXL_LOG(FATAL) << error_string;
return;
default:
// Invalid severity.
FXL_DCHECK(false);
}
}
gfx::Session* Session::GetGfxSession() {
auto& dispatcher = dispatchers_[System::TypeId::kGfx];
return dispatcher ? static_cast<gfx::Session*>(dispatcher.get()) : nullptr;
}
} // namespace scenic_impl
| 40.537657
| 100
| 0.672189
|
sunshinewithmoonlight
|
73a932b1db523bea917aadd851a5c13b16995fe6
| 13,407
|
cc
|
C++
|
src/c++/perf_analyzer/perf_utils.cc
|
BobLiu20/client
|
fb291d78595fe69624f9c220eb6654f98ab4202f
|
[
"BSD-3-Clause"
] | null | null | null |
src/c++/perf_analyzer/perf_utils.cc
|
BobLiu20/client
|
fb291d78595fe69624f9c220eb6654f98ab4202f
|
[
"BSD-3-Clause"
] | null | null | null |
src/c++/perf_analyzer/perf_utils.cc
|
BobLiu20/client
|
fb291d78595fe69624f9c220eb6654f98ab4202f
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "perf_utils.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <algorithm>
#include <iostream>
#include <string>
#include "client_backend/client_backend.h"
namespace triton { namespace perfanalyzer {
cb::ProtocolType
ParseProtocol(const std::string& str)
{
std::string protocol(str);
std::transform(protocol.begin(), protocol.end(), protocol.begin(), ::tolower);
if (protocol == "http") {
return cb::ProtocolType::HTTP;
} else if (protocol == "grpc") {
return cb::ProtocolType::GRPC;
}
return cb::ProtocolType::UNKNOWN;
}
cb::Error
ConvertDTypeFromTFS(const std::string& tf_dtype, std::string* datatype)
{
if (tf_dtype == "DT_HALF") {
*datatype = "FP16";
} else if (tf_dtype == "DT_FLOAT") {
*datatype = "FP32";
} else if (tf_dtype == "DT_DOUBLE") {
*datatype = "FP64";
} else if (tf_dtype == "DT_INT32") {
*datatype = "INT32";
} else if (tf_dtype == "DT_INT16") {
*datatype = "INT16";
} else if (tf_dtype == "DT_UINT16") {
*datatype = "UINT16";
} else if (tf_dtype == "DT_INT8") {
*datatype = "INT8";
} else if (tf_dtype == "DT_UNIT8") {
*datatype = "UINT8";
} else if (tf_dtype == "DT_STRING") {
*datatype = "BYTES";
} else if (tf_dtype == "DT_INT64") {
*datatype = "INT64";
} else if (tf_dtype == "DT_BOOL") {
*datatype = "BOOL";
} else if (tf_dtype == "DT_UINT32") {
*datatype = "UINT32";
} else if (tf_dtype == "DT_UINT64") {
*datatype = "UINT64";
} else {
return cb::Error("unsupported datatype encountered " + tf_dtype);
}
return cb::Error::Success;
}
cb::Error
ReadFile(const std::string& path, std::vector<char>* contents)
{
std::ifstream in(path, std::ios::in | std::ios::binary);
if (!in) {
return cb::Error("failed to open file '" + path + "'");
}
in.seekg(0, std::ios::end);
int file_size = in.tellg();
if (file_size > 0) {
contents->resize(file_size);
in.seekg(0, std::ios::beg);
in.read(&(*contents)[0], contents->size());
}
in.close();
// If size is invalid, report after ifstream is closed
if (file_size < 0) {
return cb::Error("failed to get size for file '" + path + "'");
} else if (file_size == 0) {
return cb::Error("file '" + path + "' is empty");
}
return cb::Error::Success;
}
cb::Error
ReadTextFile(const std::string& path, std::vector<std::string>* contents)
{
std::ifstream in(path);
if (!in) {
return cb::Error("failed to open file '" + path + "'");
}
std::string current_string;
while (std::getline(in, current_string)) {
contents->push_back(current_string);
}
in.close();
if (contents->size() == 0) {
return cb::Error("file '" + path + "' is empty");
}
return cb::Error::Success;
}
cb::Error
ReadTimeIntervalsFile(
const std::string& path, std::vector<std::chrono::nanoseconds>* contents)
{
std::ifstream in(path);
if (!in) {
return cb::Error("failed to open file '" + path + "'");
}
std::string current_string;
while (std::getline(in, current_string)) {
std::chrono::nanoseconds curent_time_interval_ns(
std::stol(current_string) * 1000);
contents->push_back(curent_time_interval_ns);
}
in.close();
if (contents->size() == 0) {
return cb::Error("file '" + path + "' is empty");
}
return cb::Error::Success;
}
bool
IsDirectory(const std::string& path)
{
struct stat s;
if (stat(path.c_str(), &s) == 0 && (s.st_mode & S_IFDIR)) {
return true;
} else {
return false;
}
}
bool
IsFile(const std::string& complete_path)
{
struct stat s;
if (stat(complete_path.c_str(), &s) == 0 && (s.st_mode & S_IFREG)) {
return true;
} else {
return false;
}
}
int64_t
ByteSize(const std::vector<int64_t>& shape, const std::string& datatype)
{
int one_element_size;
if ((datatype.compare("BOOL") == 0) || (datatype.compare("INT8") == 0) ||
(datatype.compare("UINT8") == 0)) {
one_element_size = 1;
} else if (
(datatype.compare("INT16") == 0) || (datatype.compare("UINT16") == 0) ||
(datatype.compare("FP16") == 0)) {
one_element_size = 2;
} else if (
(datatype.compare("INT32") == 0) || (datatype.compare("UINT32") == 0) ||
(datatype.compare("FP32") == 0)) {
one_element_size = 4;
} else if (
(datatype.compare("INT64") == 0) || (datatype.compare("UINT64") == 0) ||
(datatype.compare("FP64") == 0)) {
one_element_size = 8;
} else {
return -1;
}
int64_t count = ElementCount(shape);
if (count < 0) {
return count;
}
return (one_element_size * count);
}
int64_t
ElementCount(const std::vector<int64_t>& shape)
{
int64_t count = 1;
bool is_dynamic = false;
for (const auto dim : shape) {
if (dim == -1) {
is_dynamic = true;
} else {
count *= dim;
}
}
if (is_dynamic) {
count = -1;
}
return count;
}
void
SerializeStringTensor(
std::vector<std::string> string_tensor, std::vector<char>* serialized_data)
{
std::string serialized = "";
for (auto s : string_tensor) {
uint32_t len = s.size();
serialized.append(reinterpret_cast<const char*>(&len), sizeof(uint32_t));
serialized.append(s);
}
std::copy(
serialized.begin(), serialized.end(),
std::back_inserter(*serialized_data));
}
cb::Error
SerializeExplicitTensor(
const rapidjson::Value& tensor, const std::string& dt,
std::vector<char>* decoded_data)
{
if (dt.compare("BYTES") == 0) {
std::string serialized = "";
for (const auto& value : tensor.GetArray()) {
if (!value.IsString()) {
return cb::Error("unable to find string data in json");
}
std::string element(value.GetString());
uint32_t len = element.size();
serialized.append(reinterpret_cast<const char*>(&len), sizeof(uint32_t));
serialized.append(element);
}
std::copy(
serialized.begin(), serialized.end(),
std::back_inserter(*decoded_data));
} else {
for (const auto& value : tensor.GetArray()) {
if (dt.compare("BOOL") == 0) {
if (!value.IsBool()) {
return cb::Error("unable to find bool data in json");
}
bool element(value.GetBool());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(bool));
} else if (dt.compare("UINT8") == 0) {
if (!value.IsUint()) {
return cb::Error("unable to find uint8_t data in json");
}
uint8_t element(static_cast<uint8_t>(value.GetUint()));
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(uint8_t));
} else if (dt.compare("INT8") == 0) {
if (!value.IsInt()) {
return cb::Error("unable to find int8_t data in json");
}
int8_t element(static_cast<int8_t>(value.GetInt()));
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(int8_t));
} else if (dt.compare("UINT16") == 0) {
if (!value.IsUint()) {
return cb::Error("unable to find uint16_t data in json");
}
uint16_t element(static_cast<uint16_t>(value.GetUint()));
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(uint16_t));
} else if (dt.compare("INT16") == 0) {
if (!value.IsInt()) {
return cb::Error("unable to find int16_t data in json");
}
int16_t element(static_cast<int16_t>(value.GetInt()));
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(int16_t));
} else if (dt.compare("FP16") == 0) {
return cb::Error(
"Can not use explicit tensor description for fp16 datatype");
} else if (dt.compare("UINT32") == 0) {
if (!value.IsUint()) {
return cb::Error("unable to find uint32_t data in json");
}
uint32_t element(value.GetUint());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(uint32_t));
} else if (dt.compare("INT32") == 0) {
if (!value.IsInt()) {
return cb::Error("unable to find int32_t data in json");
}
int32_t element(value.GetInt());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(int32_t));
} else if (dt.compare("FP32") == 0) {
if (!value.IsDouble()) {
return cb::Error("unable to find float data in json");
}
float element(value.GetFloat());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(float));
} else if (dt.compare("UINT64") == 0) {
if (!value.IsUint64()) {
return cb::Error("unable to find uint64_t data in json");
}
uint64_t element(value.GetUint64());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(uint64_t));
} else if (dt.compare("INT64") == 0) {
if (!value.IsInt64()) {
return cb::Error("unable to find int64_t data in json");
}
int64_t element(value.GetInt64());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(int64_t));
} else if (dt.compare("FP64") == 0) {
if (!value.IsDouble()) {
return cb::Error("unable to find fp64 data in json");
}
double element(value.GetDouble());
const char* src = reinterpret_cast<const char*>(&element);
decoded_data->insert(decoded_data->end(), src, src + sizeof(double));
}
}
}
return cb::Error::Success;
}
std::string
GetRandomString(const int string_length)
{
std::mt19937_64 gen{std::random_device()()};
std::uniform_int_distribution<size_t> dist{0, character_set.length() - 1};
std::string random_string;
std::generate_n(std::back_inserter(random_string), string_length, [&] {
return character_set[dist(gen)];
});
return random_string;
}
std::string
ShapeVecToString(const std::vector<int64_t> shape_vec, bool skip_first)
{
bool first = true;
std::string str("[");
for (const auto& value : shape_vec) {
if (skip_first) {
skip_first = false;
continue;
}
if (!first) {
str += ",";
}
str += std::to_string(value);
first = false;
}
str += "]";
return str;
}
std::string
ShapeTensorValuesToString(const int* data_ptr, const int count)
{
bool first = true;
std::string str("[");
for (int i = 0; i < count; i++) {
if (!first) {
str += ",";
}
str += std::to_string(*(data_ptr + i));
first = false;
}
str += "]";
return str;
}
template <>
std::function<std::chrono::nanoseconds(std::mt19937&)>
ScheduleDistribution<Distribution::POISSON>(const double request_rate)
{
std::exponential_distribution<> dist =
std::exponential_distribution<>(request_rate);
return [dist](std::mt19937& gen) mutable {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::duration<double>(dist(gen)));
};
}
template <>
std::function<std::chrono::nanoseconds(std::mt19937&)>
ScheduleDistribution<Distribution::CONSTANT>(const double request_rate)
{
std::chrono::nanoseconds period =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::duration<double>(1.0 / request_rate));
return [period](std::mt19937& /*gen*/) { return period; };
}
}} // namespace triton::perfanalyzer
| 31.398126
| 80
| 0.62527
|
BobLiu20
|
73ab1d14780db312299f85e00d2e9565d763bb08
| 8,203
|
cpp
|
C++
|
Source/MediaInfo/Multiple/File_MiXml.cpp
|
meganz/MediaInfoLib
|
bb7dd9d10039074df6ca92527e20b1df25ad8ee9
|
[
"BSD-2-Clause"
] | 7
|
2018-04-07T23:57:00.000Z
|
2021-11-21T19:38:19.000Z
|
Source/MediaInfo/Multiple/File_MiXml.cpp
|
meganz/MediaInfoLib
|
bb7dd9d10039074df6ca92527e20b1df25ad8ee9
|
[
"BSD-2-Clause"
] | null | null | null |
Source/MediaInfo/Multiple/File_MiXml.cpp
|
meganz/MediaInfoLib
|
bb7dd9d10039074df6ca92527e20b1df25ad8ee9
|
[
"BSD-2-Clause"
] | 2
|
2018-12-20T00:00:00.000Z
|
2021-06-10T19:06:27.000Z
|
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MIXML_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_MiXml.h"
#include "MediaInfo/MediaInfo_Config.h"
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#include "ZenLib/FileName.h"
#include "tinyxml2.h"
using namespace tinyxml2;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
File_MiXml::File_MiXml()
:File__Analyze()
{
#if MEDIAINFO_EVENTS
ParserIDs[0]=MediaInfo_Parser_MiXml;
#endif //MEDIAINFO_EVENTS
}
//***************************************************************************
// Buffer - File header
//***************************************************************************
//---------------------------------------------------------------------------
bool File_MiXml::FileHeader_Begin()
{
XMLDocument document;
if (!FileHeader_Begin_XML(document))
return false;
{
XMLElement* Root=document.FirstChildElement("MediaInfo");
if (Root)
{
const char* Attribute = Root->Attribute("xmlns");
if (Attribute == NULL || Ztring().From_UTF8(Attribute) != __T("https://mediaarea.net/mediainfo"))
{
Reject("MiXml");
return false;
}
Accept("MiXml");
XMLElement* Media = Root->FirstChildElement();
while (Media)
{
if (string(Media->Value()) == "media")
{
Attribute = Media->Attribute("ref");
if (Attribute)
{
File_Name.From_UTF8(Attribute);
Config->File_Names.clear();
Fill(Stream_General, 0, General_CompleteName, File_Name, true); //TODO: merge with generic code
Fill(Stream_General, 0, General_FolderName, FileName::Path_Get(File_Name), true);
Fill(Stream_General, 0, General_FileName, FileName::Name_Get(File_Name), true);
Fill(Stream_General, 0, General_FileExtension, FileName::Extension_Get(File_Name), true);
}
XMLElement* Track = Media->FirstChildElement();
while (Track)
{
if (string(Track->Value()) == "track")
{
Attribute = Track->Attribute("type");
if (Attribute)
{
string StreamKind(Attribute);
StreamKind_Last = Stream_Max;
if (StreamKind == "General")
StreamKind_Last = Stream_General;
if (StreamKind == "Video")
Stream_Prepare(Stream_Video);
if (StreamKind == "Audio")
Stream_Prepare(Stream_Audio);
if (StreamKind == "Text")
Stream_Prepare(Stream_Text);
if (StreamKind == "Other")
Stream_Prepare(Stream_Other);
if (StreamKind == "Image")
Stream_Prepare(Stream_Image);
if (StreamKind == "Menu")
Stream_Prepare(Stream_Menu);
if (StreamKind_Last != Stream_Max)
{
XMLElement* Element = Track->FirstChildElement();
while (Element)
{
string Name(Element->Name());
if (Name == "Format_Version")
Fill(StreamKind_Last, StreamPos_Last, Element->Name(), string("Version ")+Element->GetText(), true, true);
else if (MediaInfoLib::Config.Info_Get(StreamKind_Last).Read(Ztring().From_UTF8(Element->Name()), Info_Measure) == __T(" ms"))
{
//Converting seconds to milliseconds while keeping precision
Ztring N;
N.From_UTF8(Element->GetText());
size_t Dot = N.find('.');
size_t Precision = 0;
if (Dot != string::npos)
{
size_t End = N.find_first_not_of(__T("0123456789"), Dot + 1);
if (End == string::npos)
End = N.size();
Precision = End - (Dot + 1);
if (Precision <= 3)
Precision = 0;
else
Precision -= 3;
}
Fill(StreamKind_Last, StreamPos_Last, Element->Name(), N.To_float64()*1000, Precision, true);
}
else if (Name != "extra")
Fill(StreamKind_Last, StreamPos_Last, Element->Name(), Element->GetText(), Unlimited, true, true);
else
{
XMLElement* Extra = Element->FirstChildElement();
while (Extra)
{
Fill(StreamKind_Last, StreamPos_Last, Extra->Name(), Extra->GetText(), Unlimited, true, true);
Extra = Extra->NextSiblingElement();
}
}
Element = Element->NextSiblingElement();
}
}
}
}
Track = Track->NextSiblingElement();
}
}
Media = Media->NextSiblingElement();
}
}
else
{
Reject("MiXml");
return false;
}
}
Element_Offset=File_Size;
//All should be OK...
return true;
}
} //NameSpace
#endif //MEDIAINFO_MiXml_YES
| 43.86631
| 166
| 0.344386
|
meganz
|
73ac5872b13e524dbbafd908d38757145cdb87ab
| 568
|
cpp
|
C++
|
src/sampapi/0.3.7-R3-1/CPlayerInfo.cpp
|
kin4stat/SAMP-API
|
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
|
[
"MIT"
] | 25
|
2020-01-02T06:13:58.000Z
|
2022-03-15T12:23:04.000Z
|
src/sampapi/0.3.7-R3-1/CPlayerInfo.cpp
|
kin4stat/SAMP-API
|
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
|
[
"MIT"
] | null | null | null |
src/sampapi/0.3.7-R3-1/CPlayerInfo.cpp
|
kin4stat/SAMP-API
|
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
|
[
"MIT"
] | 29
|
2019-07-07T15:37:03.000Z
|
2022-02-23T18:36:16.000Z
|
/*
This is a SAMP (0.3.7-R3) API project file.
Developer: LUCHARE <luchare.dev@gmail.com>
See more here https://github.com/LUCHARE/SAMP-API
Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.
*/
#include "sampapi/0.3.7-R3-1/CPlayerInfo.h"
SAMPAPI_BEGIN_V037R3_1
CPlayerInfo::CPlayerInfo(const char* szName, BOOL bIsNPC) {
((void(__thiscall*)(CPlayerInfo*, const char*, BOOL))GetAddress(0x13DE0))(this, szName, bIsNPC);
}
CPlayerInfo::~CPlayerInfo() {
((void(__thiscall*)(CPlayerInfo*))GetAddress(0x13B60))(this);
}
SAMPAPI_END
| 24.695652
| 100
| 0.721831
|
kin4stat
|
73ad273b87962bae0566e756720aa1ba46726f82
| 685
|
cpp
|
C++
|
tests/init.cpp
|
sagerg/cpp-password-reader
|
4298e78247db6c06b1a9aa8035a86f13705d97ca
|
[
"BSD-3-Clause"
] | 1
|
2020-07-24T22:51:36.000Z
|
2020-07-24T22:51:36.000Z
|
tests/init.cpp
|
sagerg/cpp-password-reader
|
4298e78247db6c06b1a9aa8035a86f13705d97ca
|
[
"BSD-3-Clause"
] | null | null | null |
tests/init.cpp
|
sagerg/cpp-password-reader
|
4298e78247db6c06b1a9aa8035a86f13705d97ca
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <fstream>
int main()
{
const char *FILENAME = "test.csv";
const unsigned int ROWSIZE = 5;
std::string users[ROWSIZE] = {"John Doe", "Joe Apple", "Suzan Salo", "Joni Vien", "Apple Tim"};
std::ofstream file(FILENAME);
for (int i = 0; i < ROWSIZE; ++i)
{
if (!i)
{
file << "Usernames,Passwords,Etc\n";
}
std::string tmp = "";
std::string etc = "";
for (int j = 0; j < ROWSIZE; ++j)
{
tmp += 'a' + rand() % 26;
etc += 'a' + rand() % 26;
}
file << users[i] + "," + tmp + "," + etc + "\n";
}
file.close();
return 0;
}
| 25.37037
| 99
| 0.449635
|
sagerg
|
73ae5330a5c3d6288e55ce0f6ac79c7690f1fcd8
| 5,241
|
hpp
|
C++
|
src/thread_src/map_gen.hpp
|
enarvaezrd/vspln-move
|
d24f3854133f97a18e8d01bd9ba0d0c20c72d201
|
[
"MIT"
] | null | null | null |
src/thread_src/map_gen.hpp
|
enarvaezrd/vspln-move
|
d24f3854133f97a18e8d01bd9ba0d0c20c72d201
|
[
"MIT"
] | null | null | null |
src/thread_src/map_gen.hpp
|
enarvaezrd/vspln-move
|
d24f3854133f97a18e8d01bd9ba0d0c20c72d201
|
[
"MIT"
] | null | null | null |
#ifndef MAP_GEN
#define MAP_GEN
#include "uav_ugv_commands.hpp"
class ObstacleMapGen
{
public:
ObstacleMapGen(int map_size_, float scale_, int image_size_, float rad_int_, float rad_ext_, std::string laser_topic_) : MapSize(map_size_ + 1),
max_dimm(scale_),
x_offset(0.23),
k(7),
image_size(image_size_),
rad_ext(rad_ext_),
rad_int(rad_int_),
laser_topic(laser_topic_)
{
toDegrees = 180.0 / 3.141593;
HalfMapSize = (MapSize - 1) / 2;
MapResolution = (MapSize - 1) / (max_dimm * 2.0);
ObstacleMap.resize(MapSize);
for (int i = 0; i < MapSize; i++)
ObstacleMap[i].resize(MapSize);
ObstacleMapV = ObstacleMap; //resize
for (int i = 0; i < MapSize; i++)
for (int j = 0; j < MapSize; j++)
ObstacleMapV[i][j] = 0;
ObstacleMap = ObstacleMapV;
// /opt/ros/kinetic/share/robotnik_sensors/urdf/hokuyo_ust10lx.urdf.xacro //To modify frecuency
//sub_Laser = nh_map_gen.subscribe("/scan", 1, &ObstacleMapGen::Laser_Handler, this); ///robot1/front_laser/scan. REAL
sub_Laser = nh_map_gen.subscribe(laser_topic, 1, &ObstacleMapGen::Laser_Handler, this); ///robot1/front_laser/scan SIMM
map_img_factor = (double)(image_size) / (double)(MapSize); //real size in m of each pixel
start_time = std::chrono::high_resolution_clock::now();
ObstacleMap_Global = ObstacleMapV;
ObstacleOldMaps.push_back(ObstacleMapV);
ObstacleOldMaps.push_back(ObstacleMapV);
}
void Thicken_Map();
void CreateMap();
void Laser_Handler(const sensor_msgs::LaserScan &ls);
int R_to_Cells(double real_point, bool limit);
double Cells_to_Real(float cells_point);
std::vector<VectorInt> get_Map()
{
Map_mtx.lock();
std::vector<VectorInt> MapT = ObstacleMap;
Map_mtx.unlock();
return MapT;
}
std::vector<Position> get_Obs_Points()
{
Pts_mtx.lock();
std::vector<Position> Pts = Obstacle_Points;
Pts_mtx.unlock();
return Pts;
}
std::vector<Position> get_Obs_Points_Thick()
{
Pts_mtx.lock();
std::vector<Position> Pts = Obstacle_Points_Thick;
Pts_mtx.unlock();
return Pts;
}
std::vector<VectorInt> Thicken_Map(std::vector<VectorInt> Obs_Map, std::vector<Position> &obs_positions);
std::vector<VectorInt> Manhattan(std::vector<VectorInt> Obs_Map);
std::vector<VectorInt> Thicken_Map_Manhattan(std::vector<VectorInt> Obs_Map, std::vector<Position> &obs_positions);
std::vector<VectorInt> Thicken_Map_from_Image(cv::Mat Image, std::vector<Position> &obs_positions);
void Get_Obstacle_Points(std::vector<VectorInt> Obs_Map, std::vector<Position> &obs_positions);
void ExpandObstacle_Polar(std::vector<VectorInt> &ObstacleMapT, std::vector<Position> &obs_pos);
void Rect_to_Polar(int x, int y, double &radius, double &angle);
void Expand_Obstacle(double radius, double angle, std::vector<VectorInt> &ObstacleMapT);
void AccumulateObstacleMaps(std::vector<VectorInt> Obs_Map);
void Load_UGV_state(RobotState_ ugv_st)
{
ugv_state_mtx.lock();
UGV_state = ugv_st;
end_time = std::chrono::high_resolution_clock::now();
map_build_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
ugv_state_mtx.unlock();
start_time = std::chrono::high_resolution_clock::now();
return;
}
Printer Print;
std::vector<VectorInt> ObstacleMap, ObstacleMapV,ObstacleMap_Global;
std::deque<std::vector<VectorInt>> ObstacleOldMaps;
float max_dimm;
ros::NodeHandle nh_map_gen;
ros::Subscriber sub_Laser; //Marker pose
LaserDataS LaserData;
float x_offset;
std::mutex Map_mtx;
std::mutex Pts_mtx;
int MapSize;
int HalfMapSize;
double MapResolution;
int k;
double map_img_factor;
int image_size;
std::vector<Position> Obstacle_Points_Thick;
std::vector<Position> Obstacle_Points;
float rad_ext, rad_int;
double toDegrees;
std::string laser_topic;
RobotState_ UGV_state;
std::mutex ugv_state_mtx;
double map_build_milliseconds;
std::chrono::time_point<std::chrono::high_resolution_clock> start_time, end_time;
NumberCorrection num;
};
#endif
| 42.266129
| 150
| 0.564396
|
enarvaezrd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.