hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a22d4c1cc7f16d757453e4eb88c8537cf9153bef
| 224
|
hpp
|
C++
|
cpp/include/mh/concurrency/main_thread.hpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | null | null | null |
cpp/include/mh/concurrency/main_thread.hpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | 4
|
2020-01-04T02:26:00.000Z
|
2020-04-19T10:46:50.000Z
|
cpp/include/mh/concurrency/main_thread.hpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | null | null | null |
#pragma once
#include <thread>
namespace mh
{
inline static const std::thread::id main_thread_id = std::this_thread::get_id();
inline bool is_main_thread()
{
return main_thread_id == std::this_thread::get_id();
}
}
| 16
| 81
| 0.714286
|
PazerOP
|
a2344908796c529df62a337119c9aae152cbd0ea
| 751
|
cc
|
C++
|
c-deps/libroach/cache.cc
|
benlong-transloc/cockroach
|
9a38931424b4b84116da606820d3cde699c90879
|
[
"MIT",
"BSD-3-Clause"
] | 2
|
2020-02-28T02:40:42.000Z
|
2020-02-28T04:08:48.000Z
|
c-deps/libroach/cache.cc
|
benlong-transloc/cockroach
|
9a38931424b4b84116da606820d3cde699c90879
|
[
"MIT",
"BSD-3-Clause"
] | 10
|
2020-09-06T14:29:19.000Z
|
2022-03-02T04:56:13.000Z
|
c-deps/libroach/cache.cc
|
rohany/cockroach
|
12c640b74f8a16a27eb5ba03df9628cec4c99400
|
[
"MIT",
"BSD-3-Clause"
] | 2
|
2019-11-12T13:38:48.000Z
|
2020-02-02T09:38:19.000Z
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
#include "cache.h"
DBCache* DBNewCache(uint64_t size) {
const int num_cache_shard_bits = 4;
DBCache* cache = new DBCache;
cache->rep = rocksdb::NewLRUCache(size, num_cache_shard_bits);
return cache;
}
DBCache* DBRefCache(DBCache* cache) {
DBCache* res = new DBCache;
res->rep = cache->rep;
return res;
}
void DBReleaseCache(DBCache* cache) { delete cache; }
| 27.814815
| 69
| 0.729694
|
benlong-transloc
|
a2384a8034b31e628d6bcb624278352b1066ef01
| 835
|
cpp
|
C++
|
projects/client/visual/scenery/test/source/tests/donut_test.cpp
|
silentorb/mythic-cpp
|
97319d158800d77e1a944c47c13523662bc07e08
|
[
"MIT"
] | null | null | null |
projects/client/visual/scenery/test/source/tests/donut_test.cpp
|
silentorb/mythic-cpp
|
97319d158800d77e1a944c47c13523662bc07e08
|
[
"MIT"
] | null | null | null |
projects/client/visual/scenery/test/source/tests/donut_test.cpp
|
silentorb/mythic-cpp
|
97319d158800d77e1a944c47c13523662bc07e08
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include <glaze/definition/Material.h>
#include <glaze/brushes/GL_Desktop_Brush.h>
#include "glaze_test/utility.h"
using namespace std;
using namespace glaze::definition;
using namespace glaze;
TEST(Box_Test, test_test) {
auto code = load_shader("colored.vertex");
Material material;
material.add_inputs(
{
{types::vec3, "position"},
{types::vec3, "normal"},
{types::vec4, "color"},
});
material.add_uniforms(
{
{types::mat4, "model"},
{types::mat4, "normal_transform"},
{types::vec4, "color_filter"},
});
auto donut = brushes::GL_Desktop_Brush(material);
compare_text(code, donut.vertex);
// EXPECT_EQ(0, 1);
// EXPECT_EQ(30, second->get_cache().y.near);
// EXPECT_EQ(60, third->get_cache().y.near);
}
| 23.857143
| 52
| 0.631138
|
silentorb
|
a23b954d4f083885e3d2212f014d11bba31dab9e
| 7,356
|
cpp
|
C++
|
Src/widget.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 1
|
2018-08-09T23:44:54.000Z
|
2018-08-09T23:44:54.000Z
|
Src/widget.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 2
|
2015-01-20T03:51:53.000Z
|
2020-03-27T04:45:38.000Z
|
Src/widget.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 1
|
2018-09-13T05:07:08.000Z
|
2018-09-13T05:07:08.000Z
|
/*
* omnis.xcomp.widget
* ===================
*
* widget.cpp
* Widget library implementation
*
* Bastiaan Olij
*/
#include "widget.h"
#ifdef iswin32
/* not yet supported */
#else
#include "monitor_mac.h"
#endif
qshort mainlib::major() {
return OMNISSDK;
};
qshort mainlib::minor() {
return 124;
};
ECOmethodEvent widgetStaticFuncs[] = {
// ID, Resource, Flags
9000, 9000, fftList, 0, 0, 0, 0,
};
/* see omnis.xcomp.framework\oXCompLib.h for methods to implement here */
qint mainlib::ecm_connect(void) {
OXFcomponent lvComponent;
addStaticMethods(widgetStaticFuncs, 1);
// add our component definitions here...
lvComponent.componentType = cObjType_NVObject;
lvComponent.componentID = 2000;
lvComponent.bitmapID = 0;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDateTime::newObject);
lvComponent.mProperties = oDateTime::properties();
lvComponent.mMethods = oDateTime::methods();
lvComponent.mEventMethodID = 0;
lvComponent.mEvents = oDateTime::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2001;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oCountButton::newObject);
lvComponent.mProperties = oCountButton::properties();
lvComponent.mMethods = oCountButton::methods();
lvComponent.mEventMethodID = 10000;
lvComponent.mEvents = oCountButton::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2006;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oRoundedButton::newObject);
lvComponent.mProperties = oRoundedButton::properties();
lvComponent.mMethods = oRoundedButton::methods();
lvComponent.mEventMethodID = 10000;
lvComponent.mEvents = oRoundedButton::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2002;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDataList::newObject);
lvComponent.mProperties = oDataList::properties();
lvComponent.mMethods = oDataList::methods();
lvComponent.mEventMethodID = 10010;
lvComponent.mEvents = oDataList::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_DropList;
lvComponent.componentID = 2003;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDropDown::newObject);
lvComponent.mProperties = oDropDown::properties();
lvComponent.mMethods = oDropDown::methods();
lvComponent.mEventMethodID = 10020;
lvComponent.mEvents = oDropDown::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_DropList;
lvComponent.componentID = 2005;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oFontDropDown::newObject);
lvComponent.mProperties = oFontDropDown::properties();
lvComponent.mMethods = oFontDropDown::methods();
lvComponent.mEventMethodID = 10020;
lvComponent.mEvents = oFontDropDown::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_NVObject;
lvComponent.componentID = 2004;
lvComponent.bitmapID = 0;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oImage::newObject);
lvComponent.mProperties = oImage::properties();
lvComponent.mMethods = oImage::methods();
lvComponent.mEventMethodID = 0;
lvComponent.mEvents = oImage::events();
addComponent(lvComponent);
return oXCompLib::ecm_connect();
};
qbool mainlib::ecm_disconnect(void) {
// nothing to do here..
return oXCompLib::ecm_disconnect();
};
#ifdef iswin32
void addActiveWindowToMonitorList(EXTqlist * pMonitorList) {
/* Get some info about the active window */
TCHAR name[250];
qchar qname[250];
RECT position;
HWND hWnd = GetActiveWindow();
int len = GetWindowTextLength(hWnd);
if (len > 0) {
if (len > 249) {
len = 249;
};
GetWindowText(hWnd, name, len+1);
CHRconvFromOs::convFromOs(name, len, qname, 250);
};
GetWindowRect(hWnd, &position);
/* now add it to our list */
EXTfldval colFld;
qlong rowNo = pMonitorList->insertRow();
pMonitorList->getColValRef(rowNo, 1, colFld, qtrue);
colFld.setLong(position.left);
pMonitorList->getColValRef(rowNo, 2, colFld, qtrue);
colFld.setLong(position.top);
pMonitorList->getColValRef(rowNo, 3, colFld, qtrue);
colFld.setLong(position.right);
pMonitorList->getColValRef(rowNo, 4, colFld, qtrue);
colFld.setLong(position.bottom);
if (len > 0) {
pMonitorList->getColValRef(rowNo, 5, colFld, qtrue);
colFld.setChar(qname, len);
};
};
#endif
int mainlib::invokeMethod(qlong pMethodId, EXTCompInfo* pECI) {
switch (pMethodId) {
case 9000: { /* $monitors - get list with monitor info */
EXTfldval result;
EXTqlist * monitorList = new EXTqlist(listVlen);
str255 colName;
/* add some columns */
colName = QTEXT("Left");
monitorList->addCol(1, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Top");
monitorList->addCol(2, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Right");
monitorList->addCol(3, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Bottom");
monitorList->addCol(4, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Name");
monitorList->addCol(5, fftCharacter, dpFcharacter, 250, NULL, &colName);
#ifdef iswin32
/* on windows Omnis is contained within its main window, so we add its dimensions */
addActiveWindowToMonitorList(monitorList);
/* may in due time add the actual monitors to this list as well */
#else
/* lets see if we can call some obj-c */
monitor_mac * moninfo = new monitor_mac();
for (int i = 0; i < moninfo->mNumActiveMonitors; i++) {
EXTfldval colFld;
qlong rowNo = monitorList->insertRow();
monitorList->getColValRef(rowNo, 1, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].left);
monitorList->getColValRef(rowNo, 2, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].top);
monitorList->getColValRef(rowNo, 3, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].right);
monitorList->getColValRef(rowNo, 4, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].bottom);
};
delete moninfo;
#endif
/* and return our list */
result.setList(monitorList, qtrue);
delete monitorList;
ECOaddParam(pECI, &result);
return 1L;
} break;
default: {
return oXCompLib::invokeMethod(pMethodId, pECI);
} break;
}
};
| 31.302128
| 87
| 0.660821
|
BastiaanOlij
|
a23c10157cbcccec5e57087d42760495ea114d95
| 1,008
|
cc
|
C++
|
zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 210
|
2019-02-05T12:45:09.000Z
|
2022-03-28T07:59:06.000Z
|
zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 56
|
2021-06-03T03:16:25.000Z
|
2022-03-20T01:07:44.000Z
|
zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 73
|
2019-03-06T18:55:23.000Z
|
2022-03-26T12:04:51.000Z
|
// Copyright 2020 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 "storage/buffer/vmoid_registry.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace storage {
namespace {
using ::testing::_;
TEST(VmoidTest, Move) {
Vmoid vmoid(1), vmoid2;
vmoid2 = std::move(vmoid);
EXPECT_FALSE(vmoid.IsAttached());
EXPECT_TRUE(vmoid2.IsAttached());
[[maybe_unused]] vmoid_t id = vmoid2.TakeId();
}
TEST(VmoidDeathTest, ForgottenDetachAssertsInDebug) {
#if ZX_DEBUG_ASSERT_IMPLEMENTED
ASSERT_DEATH({ Vmoid vmoid(1); }, _);
#else
Vmoid vmoid(1);
#endif
}
TEST(VmoidDeathTest, MoveToAttachedVmoidAssertsInDebug) {
#if ZX_DEBUG_ASSERT_IMPLEMENTED
ASSERT_DEATH(
{
Vmoid vmoid(1);
Vmoid vmoid2(2);
vmoid = std::move(vmoid2);
},
_);
#else
Vmoid vmoid(1), vmoid2(2);
vmoid = std::move(vmoid2);
#endif
}
} // namespace
} // namespace storage
| 21
| 73
| 0.690476
|
allansrc
|
a24577b30f05e6f83b580fe4ce44fbce0ab7c8da
| 1,834
|
cpp
|
C++
|
collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp
|
daemonslayer/Notebook
|
a9880be9bd86955afd6b8f7352822bc18673eda3
|
[
"Apache-2.0"
] | 1
|
2019-03-24T13:12:01.000Z
|
2019-03-24T13:12:01.000Z
|
collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp
|
daemonslayer/Notebook
|
a9880be9bd86955afd6b8f7352822bc18673eda3
|
[
"Apache-2.0"
] | null | null | null |
collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp
|
daemonslayer/Notebook
|
a9880be9bd86955afd6b8f7352822bc18673eda3
|
[
"Apache-2.0"
] | null | null | null |
/*Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Analysis:
If we can use another array flag, we can assign flag[A[i]-1] = A[i] to present its occurrence.And get the first element from flag that the flag[i-1]!=i as the result. Here A[i]-1 and i-1 because the array is from 0 to n-1 to store 1 to n.
But the question requires that we can not use additional space. So we have to use the original array A, to save the flag.
The idea is as follow:
e.g. 3,2,5,1,7
For each element,
1. Do not consider the element which <=0, or value > length n
2. Swap this element A[i] with the A[A[i]-1], e.g. when we met A[0]=3, we swap A[0] and A[2], then A[0]=5
3. For the current element A[i], if A[i]<=0 or A[i]>length n, or A[i] has already occurred, break. Else go to step 2.
e.g. A[0]=5, swap A[0] and A[5], A[0]=7, break.Now the array A is {7,2,3,1,5}.
Next round, A is {1,2,3,7,5}
4. Scan the array A and find the result. e.g. {1,2,3,7,5}, the A[3]!=3+1, print 3+1, result =4.
*/
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for (int i = 0; i<n;i++){
if ( (A[i]>0)&&(A[i]<=n)){
while (A[i]!=(i+1)){
if ((A[i]>n)||(A[i]<=0)||(A[A[i]-1]==A[i])) {break;}
int tmp;
tmp = A[A[i]-1];
A[A[i]-1]=A[i];
A[i]=tmp;
}
}
}
int i=0;
for (; i<n;i++){
if (A[i]!=(i+1)){
return i+1;
}
}
return i+1;
}
};
| 37.428571
| 238
| 0.531625
|
daemonslayer
|
a245b10013ce2468db678e9bc23521ab7c66b945
| 3,684
|
cc
|
C++
|
algorithms/forculus/forculus_decrypter.cc
|
reMarkable/cobalt
|
3feead337a6bdf620df7a62abb72c910a566a38c
|
[
"BSD-3-Clause"
] | null | null | null |
algorithms/forculus/forculus_decrypter.cc
|
reMarkable/cobalt
|
3feead337a6bdf620df7a62abb72c910a566a38c
|
[
"BSD-3-Clause"
] | null | null | null |
algorithms/forculus/forculus_decrypter.cc
|
reMarkable/cobalt
|
3feead337a6bdf620df7a62abb72c910a566a38c
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2016 The Fuchsia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "algorithms/forculus/forculus_decrypter.h"
#include <functional>
#include <vector>
#include "algorithms/forculus/polynomial_computations.h"
#include "util/crypto_util/cipher.h"
namespace cobalt {
namespace forculus {
using crypto::SymmetricCipher;
ForculusDecrypter::ForculusDecrypter(uint32_t threshold,
std::string ciphertext) :
threshold_(threshold), num_seen_(0), ciphertext_(std::move(ciphertext)) {}
ForculusDecrypter::Status ForculusDecrypter::AddObservation(
const ForculusObservation& obs) {
if (obs.ciphertext() != ciphertext_) {
return kWrongCiphertext;
}
// Keep a copy of y so we can check it its the same as a previously added
// point.
FieldElement y(obs.point_y());
auto result = points_.insert(std::make_pair(FieldElement(obs.point_x()), y));
auto key_value_pair = result.first;
auto success = result.second;
if (!success) {
if (key_value_pair->second != y) {
return kInconsistentPoints;
}
}
num_seen_++;
return kOK;
}
uint32_t ForculusDecrypter::size() {
return points_.size();
}
ForculusDecrypter::Status ForculusDecrypter::Decrypt(
std::string *plain_text_out) {
if (size() < threshold_) {
return kNotEnoughPoints;
}
// Put pointers to the first |threshold_| x and y values into vectors.
std::vector<const FieldElement*> x_values(threshold_);
std::vector<const FieldElement*> y_values(threshold_);
uint32_t point_index = 0;
for (const auto& point : points_) {
if (point_index >= threshold_) {
break;
}
x_values[point_index] = &point.first;
y_values[point_index++] = &point.second;
}
// The decryption key we need is the constant term of the unique polynomial of
// degree (threshold_ - 1) that passes through the points given by the
// x_values and y_values. We can find this using interpolation.
FieldElement c0 = InterpolateConstant(x_values, y_values);
// Now we have the key, decrypt.
SymmetricCipher cipher;
cipher.set_key(c0.KeyBytes());
std::vector<byte> recoverd_text;
// Our encryption scheme uses a zero nonce. (Note that C++11 initializes
// the entire array to 0 with this syntax.)
static const byte kZeroNonce[SymmetricCipher::NONCE_SIZE] = {0};
if (!cipher.Decrypt(kZeroNonce,
reinterpret_cast<const byte*>(ciphertext_.data()),
ciphertext_.size(), &recoverd_text)) {
// TODO(pseudorandom, rudominer) One reason that decryption might fail
// is a ballot suppression attack. An adversary may intentionally flood
// us with bad (x, y) values in order to keep us from decrypting a
// ciphertext. Because we use authenticated encryption, the result of
// invalid (x, y) values will be failure to decrypt. One way to combat
// this attack might be to try different sets of points of size
// |threshold| iteratively until decryption succeeds.
return kDecryptionFailed;
}
plain_text_out->assign(recoverd_text.begin(), recoverd_text.end());
return kOK;
}
} // namespace forculus
} // namespace cobalt
| 35.085714
| 80
| 0.711183
|
reMarkable
|
a24bbd680103c5e0bd7054b3e95aa6a8eb8d8e3e
| 3,303
|
cpp
|
C++
|
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
|
chunseoklee/ONE-1
|
f45d579eb78e7e3cd1d878b4137ed23ab569081b
|
[
"Apache-2.0"
] | null | null | null |
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
|
chunseoklee/ONE-1
|
f45d579eb78e7e3cd1d878b4137ed23ab569081b
|
[
"Apache-2.0"
] | null | null | null |
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
|
chunseoklee/ONE-1
|
f45d579eb78e7e3cd1d878b4137ed23ab569081b
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "luci/Pass/RemoveUnnecessarySplitPass.h"
#include <luci/IR/CircleNodes.h>
#include <gtest/gtest.h>
namespace
{
void create_unnecessary_split_graph(loco::Graph *g, bool remove)
{
assert(g);
auto input = g->nodes()->create<luci::CircleInput>();
auto graph_input = g->inputs()->create();
input->index(graph_input->index());
auto dim = g->nodes()->create<luci::CircleConst>();
dim->dtype(loco::DataType::S32);
dim->size<loco::DataType::S32>(1);
dim->rank(1);
dim->dim(0).set(1);
dim->at<loco::DataType::S32>(0) = 0;
auto split_node = g->nodes()->create<luci::CircleSplit>();
split_node->split_dim(dim);
split_node->input(input);
if (remove)
split_node->num_split(1);
else
split_node->num_split(2);
auto split_out_node0 = g->nodes()->create<luci::CircleSplitOut>();
split_out_node0->input(split_node);
split_out_node0->index(0);
auto output0 = g->nodes()->create<luci::CircleOutput>();
output0->from(split_out_node0);
auto graph_output0 = g->outputs()->create();
output0->index(graph_output0->index());
if (!remove)
{
auto split_out_node1 = g->nodes()->create<luci::CircleSplitOut>();
split_out_node1->input(split_node);
split_out_node1->index(1);
auto output1 = g->nodes()->create<luci::CircleOutput>();
output1->from(split_out_node1);
auto graph_output1 = g->outputs()->create();
output1->index(graph_output1->index());
}
}
} // namespace
TEST(RemoveUnnecessarySplitPass, name)
{
luci::RemoveUnnecessarySplitPass pass;
auto const name = pass.name();
ASSERT_NE(nullptr, name);
}
TEST(RemoveUnnecessarySplitPass, create_unnecessary_split)
{
auto graph = loco::make_graph();
create_unnecessary_split_graph(graph.get(), true);
luci::RemoveUnnecessarySplitPass pass;
while (pass.run(graph.get()))
;
luci::CircleSplit *split_node = nullptr;
for (auto node : loco::active_nodes(loco::output_nodes(graph.get())))
{
auto split = dynamic_cast<luci::CircleSplit *>(node);
if (not split)
continue;
split_node = split;
}
// No Split node is in graph.
ASSERT_EQ(nullptr, split_node);
}
TEST(RemoveUnnecessarySplitPass, create_unnecessary_split_NEG)
{
auto graph = loco::make_graph();
create_unnecessary_split_graph(graph.get(), false);
luci::RemoveUnnecessarySplitPass pass;
while (pass.run(graph.get()))
;
luci::CircleSplit *split_node = nullptr;
for (auto node : loco::active_nodes(loco::output_nodes(graph.get())))
{
auto split = dynamic_cast<luci::CircleSplit *>(node);
if (not split)
continue;
split_node = split;
}
// Split node is in graph.
ASSERT_NE(nullptr, split_node);
}
| 27.991525
| 75
| 0.696942
|
chunseoklee
|
a24bfb0a5c845c9ca80feb2549a6fff554012fcd
| 5,151
|
hpp
|
C++
|
src/helics/cpp98/Endpoint.hpp
|
dnadeau4/HELICS-src
|
cad21acaac68d25b50e08b185d4fe5a1ae054241
|
[
"BSD-3-Clause"
] | null | null | null |
src/helics/cpp98/Endpoint.hpp
|
dnadeau4/HELICS-src
|
cad21acaac68d25b50e08b185d4fe5a1ae054241
|
[
"BSD-3-Clause"
] | null | null | null |
src/helics/cpp98/Endpoint.hpp
|
dnadeau4/HELICS-src
|
cad21acaac68d25b50e08b185d4fe5a1ae054241
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright © 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef HELICS_CPP98_ENDPOINT_HPP_
#define HELICS_CPP98_ENDPOINT_HPP_
#pragma once
#include "../shared_api_library/MessageFederate.h"
#include "helicsExceptions.hpp"
#include <vector>
#include <string>
namespace helicscpp
{
class Endpoint
{
public:
explicit Endpoint (helics_endpoint hep) HELICS_NOTHROW: ep (hep) {}
Endpoint () HELICS_NOTHROW : ep (HELICS_NULL_POINTER){};
Endpoint (const Endpoint &endpoint) HELICS_NOTHROW: ep (endpoint.ep) {}
Endpoint &operator= (const Endpoint &endpoint)
{
ep = endpoint.ep;
return *this;
}
operator helics_endpoint () { return ep; }
helics_endpoint baseObject () const { return ep; }
/* Checks if endpoint has unread messages **/
bool hasMessage () const
{
// returns int, 1 = true, 0 = false
return helicsEndpointHasMessage (ep) > 0;
}
/** set the default destination for an endpoint*/
void setDefaultDestination (const std::string &dest)
{
helicsEndpointSetDefaultDestination (ep, dest.c_str (), hThrowOnError ());
}
/** get the default destination for an endpoint*/
const char *getDefaultDestination () const { return helicsEndpointGetDefaultDestination (ep); }
/** Returns the number of pending receives for endpoint **/
uint64_t pendingMessages () const { return helicsEndpointPendingMessages (ep); }
/** Get a packet from an endpoint **/
helics_message getMessage () { return helicsEndpointGetMessage (ep); }
/** Methods for sending a message **/
void sendMessage (const char *data, size_t len)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const char *data, size_t len)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data, static_cast<int> (len), hThrowOnError ());
}
void sendMessage (const char *data, size_t len, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), time, hThrowOnError ());
}
void sendMessage (const std::string &dest, const char *data, size_t len, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data, static_cast<int> (len), time, hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &data)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()),
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const std::string &data)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()),
hThrowOnError ());
}
void sendMessage (const std::string &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (const std::string &dest, const std::string &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::vector<char> &data)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()),
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const std::vector<char> &data)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()),
hThrowOnError ());
}
void sendMessage (const std::vector<char> &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (const std::string &dest, const std::vector<char> &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (helics_message &message)
{
// returns helicsStatus
helicsEndpointSendMessage (ep, &message, hThrowOnError ());
}
const char *getName () const { return helicsEndpointGetName (ep); }
std::string getType () { return helicsEndpointGetType (ep); }
private:
helics_endpoint ep;
};
} // namespace helicscpp
#endif
| 36.531915
| 115
| 0.635411
|
dnadeau4
|
a2500101143a610b8c7fa14d6da625291270a722
| 22,104
|
cpp
|
C++
|
thirdparty/ULib/src/ulib/ldap/ldap.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
thirdparty/ULib/src/ulib/ldap/ldap.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
thirdparty/ULib/src/ulib/ldap/ldap.cpp
|
liftchampion/nativejson-benchmark
|
6d575ffa4359a5c4230f74b07d994602a8016fb5
|
[
"MIT"
] | null | null | null |
// ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// ldap.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
#include <ulib/url.h>
#include <ulib/ldap/ldap.h>
struct timeval ULDAP::timeOut = { 30L, 0L }; // 30 second connection/search timeout
ULDAPEntry::ULDAPEntry(int num_names, const char** names, int num_entry)
{
U_TRACE_REGISTER_OBJECT(0, ULDAPEntry, "%d,%p,%d", num_names, names, num_entry)
U_INTERNAL_ASSERT_EQUALS(names[num_names], 0)
U_DUMP_ATTRS(names)
n_attr = num_names;
n_entry = num_entry;
attr_name = names;
dn = (char**) UMemoryPool::_malloc(num_entry, sizeof(char*), true);
attr_val = (UString**) UMemoryPool::_malloc(num_entry * num_names, sizeof(UString*), true);
}
ULDAPEntry::~ULDAPEntry()
{
U_TRACE_UNREGISTER_OBJECT(0, ULDAPEntry)
for (int i = 0, j, k = 0; i < n_entry; ++i)
{
if (dn[i])
{
U_INTERNAL_DUMP("dn[%d]: %S", i, dn[i])
ldap_memfree(dn[i]);
for (j = 0; j < n_attr; ++j, ++k)
{
if (attr_val[k])
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S = %V", k, attr_name[j], attr_val[k]->rep)
delete attr_val[k];
}
}
}
}
UMemoryPool::_free(dn, n_entry, sizeof(char*));
UMemoryPool::_free(attr_val, n_entry * n_attr, sizeof(UString*));
}
void ULDAPEntry::set(char* attribute, char** values, int index_entry)
{
U_TRACE(0, "ULDAPEntry::set(%S,%p,%d)", attribute, values, index_entry)
U_DUMP_ATTRS(values)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k)
{
if (strcmp(attr_name[j], attribute) == 0)
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j])
U_NEW(UString, attr_val[k], UString((void*)values[0], u__strlen(values[0], __PRETTY_FUNCTION__)));
for (j = 1; values[j]; ++j)
{
attr_val[k]->append(U_CONSTANT_TO_PARAM("; "));
attr_val[k]->append(values[j]);
}
U_INTERNAL_DUMP("value = %V", attr_val[k]->rep)
break;
}
}
}
void ULDAPEntry::set(char* attribute, char* value, uint32_t len, int index_entry)
{
U_TRACE(0, "ULDAPEntry::set(%S,%.*S,%u,%d)", attribute, len, value, len, index_entry)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k)
{
if (strcmp(attr_name[j], attribute) == 0)
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j])
U_NEW(UString, attr_val[k], UString((void*)value, len));
U_INTERNAL_DUMP("value = %V", attr_val[k]->rep)
break;
}
}
}
UString ULDAPEntry::getString(int index_names, int index_entry)
{
U_TRACE(0, "ULDAPEntry::getString(%d,%d)", index_names, index_entry)
U_INTERNAL_ASSERT_MINOR(index_names, n_attr)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
int k = (index_entry * n_attr) + index_names;
if (attr_val[k])
{
UString str = *(attr_val[k]);
U_RETURN_STRING(str);
}
return UString::getStringNull();
}
const char* ULDAPEntry::getCStr(int index_names, int index_entry)
{
U_TRACE(0, "ULDAPEntry::getCStr(%d,%d)", index_names, index_entry)
U_INTERNAL_ASSERT_MINOR(index_names, n_attr)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
int k = (index_entry * n_attr) + index_names;
if (attr_val[k])
{
const char* str = attr_val[k]->c_str();
U_RETURN(str);
}
U_RETURN("");
}
void ULDAP::clear()
{
U_TRACE_NO_PARAM(1, "ULDAP::clear()")
if (ludpp)
{
# if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
U_SYSCALL_VOID(ldap_free_urldesc, "%p", ludpp);
# else
int i;
if (ludpp->lud_dn) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_dn);
if (ludpp->lud_host) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_host);
if (ludpp->lud_filter) U_SYSCALL_VOID(free, "%p", ludpp->lud_filter);
if (ludpp->lud_attrs)
{
for (i = 0; ludpp->lud_attrs[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs[i]);
U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs);
}
if (ludpp->lud_exts)
{
for (i = 0; ludpp->lud_exts[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_exts[i]);
U_SYSCALL_VOID(free, "%p", ludpp->lud_exts);
}
U_SYSCALL_VOID(free, "%p", ludpp);
# endif
ludpp = 0;
}
if (ld)
{
if (searchResult)
{
U_SYSCALL(ldap_msgfree, "%p", searchResult);
searchResult = 0;
}
U_SYSCALL(ldap_unbind_s, "%p", ld);
ld = 0;
# if defined(HAVE_LDAP_SSL_H) && defined(HAS_NOVELL_LDAPSDK)
if (isSecure) U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
# endif
}
}
void ULDAP::setStatus()
{
U_TRACE_NO_PARAM(0, "ULDAP::setStatus()")
U_CHECK_MEMORY
static const char* errlist[] = {
"LDAP_SUCCESS", // 0 0x00
"LDAP_OPERATIONS_ERROR", // 1 0x01
"LDAP_PROTOCOL_ERROR", // 2 0x02
"LDAP_TIMELIMIT_EXCEEDED", // 3 0x03
"LDAP_SIZELIMIT_EXCEEDED", // 4 0x04
"LDAP_COMPARE_FALSE", // 5 0x05
"LDAP_COMPARE_TRUE", // 6 0x06
"LDAP_STRONG_AUTH_NOT_SUPPORTED", // 7 0x07
"LDAP_STRONG_AUTH_REQUIRED", // 8 0x08
"LDAP_PARTIAL_RESULTS", // 9 0x09
"LDAP_REFERRAL", // 10
"LDAP_ADMINLIMIT_EXCEEDED", // 11
"LDAP_UNAVAILABLE_CRITICAL_EXTENSION", // 12
"LDAP_CONFIDENTIALITY_REQUIRED", // 13
"LDAP_SASL_BIND_IN_PROGRESS", // 14
"", // 15
"LDAP_NO_SUCH_ATTRIBUTE", // 16 0x10
"LDAP_UNDEFINED_TYPE", // 17 0x11
"LDAP_INAPPROPRIATE_MATCHING", // 18 0x12
"LDAP_CONSTRAINT_VIOLATION", // 19 0x13
"LDAP_TYPE_OR_VALUE_EXISTS", // 20 0x14
"LDAP_INVALID_SYNTAX", // 21 0x15
"", // 22
"", // 23
"", // 24
"", // 25
"", // 26
"", // 27
"", // 28
"", // 29
"", // 30
"", // 31
"LDAP_NO_SUCH_OBJECT", // 32 0x20
"LDAP_ALIAS_PROBLEM", // 33 0x21
"LDAP_INVALID_DN_SYNTAX", // 34 0x22
"LDAP_IS_LEAF", // 35 0x23
"LDAP_ALIAS_DEREF_PROBLEM", // 36 0x24
"", // 37
"", // 38
"", // 39
"", // 40
"", // 41
"", // 42
"", // 43
"", // 44
"", // 45
"", // 46
"", // 47
"LDAP_INAPPROPRIATE_AUTH", // 48 0x30
"LDAP_INVALID_CREDENTIALS", // 49 0x31
"LDAP_INSUFFICIENT_ACCESS", // 50 0x32
"LDAP_BUSY", // 51 0x33
"LDAP_UNAVAILABLE", // 52 0x34
"LDAP_UNWILLING_TO_PERFORM", // 53 0x35
"LDAP_LOOP_DETECT", // 54 0x36
"", // 55
"", // 56
"", // 57
"", // 58
"", // 59
"", // 60
"", // 61
"", // 62
"", // 63
"LDAP_NAMING_VIOLATION", // 64 0x40
"LDAP_OBJECT_CLASS_VIOLATION", // 65 0x41
"LDAP_NOT_ALLOWED_ON_NONLEAF", // 66 0x42
"LDAP_NOT_ALLOWED_ON_RDN", // 67 0x43
"LDAP_ALREADY_EXISTS", // 68 0x44
"LDAP_NO_OBJECT_CLASS_MODS", // 69 0x45
"LDAP_RESULTS_TOO_LARGE", // 70 0x46
"LDAP_AFFECTS_MULTIPLE_DSAS", // 71
"", // 72
"", // 73
"", // 74
"", // 75
"", // 76
"", // 77
"", // 78
"", // 79
"LDAP_OTHER", // 80 0x50
"LDAP_SERVER_DOWN", // 81 0x51
"LDAP_LOCAL_ERROR", // 82 0x52
"LDAP_ENCODING_ERROR", // 83 0x53
"LDAP_DECODING_ERROR", // 84 0x54
"LDAP_TIMEOUT", // 85 0x55
"LDAP_AUTH_UNKNOWN", // 86 0x56
"LDAP_FILTER_ERROR", // 87 0x57
"LDAP_USER_CANCELLED", // 88 0x58
"LDAP_PARAM_ERROR", // 89 0x59
"LDAP_NO_MEMORY", // 90 0x5a
"LDAP_CONNECT_ERROR", // 91 0x5b
"LDAP_NOT_SUPPORTED", // 92 0x5c
"LDAP_CONTROL_NOT_FOUND", // 93 0x5d
"LDAP_NO_RESULTS_RETURNED", // 94 0x5e
"LDAP_MORE_RESULTS_TO_RETURN", // 95 0x5f
"LDAP_CLIENT_LOOP", // 96 0x60
"LDAP_REFERRAL_LIMIT_EXCEEDED" // 97 0x61
};
char* descr = ldap_err2string(result);
/**
* get a meaningful error string back from the security library
* this function should be called, if ldap_err2string doesn't
* identify the error code
*/
#if defined(HAVE_LDAP_SSL_H) && !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
if (descr == 0) descr = (char*)ldapssl_err2string(result);
#endif
U_INTERNAL_ASSERT_EQUALS(u_buffer_len, 0)
u_buffer_len = u__snprintf(u_buffer, U_BUFFER_SIZE, U_CONSTANT_TO_PARAM("%s (%d, %s)"), (result >= 0 && result < 97 ? errlist[result] : ""), result, descr);
}
#if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H)
/**
* Split 'str' into strings separated by commas.
*
* Note: res[] points into 'str'
*/
U_NO_EXPORT char** ULDAP::split_str(char* str)
{
U_TRACE(0, "ULDAP::split_str(%S)", str)
int i;
char **res, *s;
for (i = 2, s = strchr(str, ','); s; ++i) s = strchr(++s, ',');
res = (char**)calloc(i, sizeof(char*));
for (i = 0, s = strtok(str, ","); s; s = strtok(0, ","), ++i) res[i] = s;
U_DUMP_ATTRS(res)
return res;
}
#endif
/* Initialize the LDAP session */
bool ULDAP::init(const char* url)
{
U_TRACE(1, "ULDAP::init(%S)", url)
U_CHECK_MEMORY
U_INTERNAL_ASSERT_POINTER(url)
if (ludpp) clear();
#if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
result = U_SYSCALL(ldap_url_parse, "%S,%p", url, &ludpp);
#else
result = LDAP_INVALID_SYNTAX;
/**
* Break apart the pieces of an LDAP URL
*
* Syntax:
* ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
*
* Defined in RFC4516 section 2
*/
Url _url(url, u__strlen(url, __PRETTY_FUNCTION__));
ludpp = (LDAPURLDesc*) calloc(1, sizeof(LDAPURLDesc));
ludpp->lud_host = _url.getHost().c_strdup();
ludpp->lud_port = _url.getPort();
ludpp->lud_dn = _url.getPath().c_strndup(1);
ludpp->lud_scope = LDAP_SCOPE_BASE;
U_INTERNAL_DUMP("host = %S dn = %S", ludpp->lud_host, ludpp->lud_dn)
// parse attributes, skip "??"
UString query = _url.getQuery();
char* p = query.data();
char* q = strchr(p, '?');
if (q) *q++ = '\0';
U_INTERNAL_DUMP("attributes = %S", p)
if (*p && *p != '?') ludpp->lud_attrs = split_str(p);
p = q;
if (!p) goto next;
// parse scope, skip "??"
q = strchr(p, '?');
if (q) *q++ = '\0';
if (*p && *p != '?')
{
if (strncmp(p, U_CONSTANT_TO_PARAM("base")) == 0) ludpp->lud_scope = LDAP_SCOPE_BASE;
else if (strncmp(p, U_CONSTANT_TO_PARAM("one")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL;
else if (strncmp(p, U_CONSTANT_TO_PARAM("onetree")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL;
else if (strncmp(p, U_CONSTANT_TO_PARAM("sub")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE;
else if (strncmp(p, U_CONSTANT_TO_PARAM("subtree")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE;
U_INTERNAL_DUMP("scope = %d %S", ludpp->lud_scope, p)
}
p = q;
if (!p) goto next;
// parse filter
q = strchr(p, '?');
if (q) *q++ = '\0';
if (!*p) goto next;
ludpp->lud_filter = strdup(p);
U_INTERNAL_DUMP("filter = %S", ludpp->lud_filter)
// parse extensions
if (q) ludpp->lud_exts = split_str(q);
result = LDAP_SUCCESS;
next:
#endif
if (result != LDAP_SUCCESS)
{
# ifdef DEBUG
char buffer[1024];
const char* descr = "???";
const char* errstr = "";
switch (result)
{
# if !defined(_MSWINDOWS_) || !defined(HAVE_WINLDAP_H)
case LDAP_INVALID_SYNTAX:
descr = "LDAP_INVALID_SYNTAX";
errstr = "Invalid URL syntax";
break;
case LDAP_URL_ERR_MEM:
descr = "LDAP_URL_ERR_MEM";
errstr = "Cannot allocate memory space";
break;
case LDAP_URL_ERR_PARAM:
descr = "LDAP_URL_ERR_PARAM";
errstr = "Invalid parameter";
break;
case LDAP_URL_ERR_BADSCOPE:
descr = "LDAP_URL_ERR_BADSCOPE";
errstr = "Invalid or missing scope string";
break;
# if defined(HAVE_LDAP_SSL_H)
case LDAP_URL_ERR_NOTLDAP:
descr = "LDAP_URL_ERR_NOTLDAP";
errstr = "URL doesn't begin with \"ldap://\"";
break;
case LDAP_URL_ERR_NODN:
descr = "LDAP_URL_ERR_NODN";
errstr = "URL has no DN (required)";
break;
case LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION:
descr = "LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION";
errstr = "";
break;
# else
case LDAP_URL_ERR_BADSCHEME:
descr = "LDAP_URL_ERR_BADSCHEME";
errstr = "URL doesnt begin with \"ldap[s]://\"";
break;
case LDAP_URL_ERR_BADENCLOSURE:
descr = "LDAP_URL_ERR_BADENCLOSURE";
errstr = "URL is missing trailing \">\"";
break;
case LDAP_URL_ERR_BADURL:
descr = "LDAP_URL_ERR_BADURL";
errstr = "Invalid URL";
break;
case LDAP_URL_ERR_BADHOST:
descr = "LDAP_URL_ERR_BADHOST";
errstr = "Host port is invalid";
break;
case LDAP_URL_ERR_BADATTRS:
descr = "LDAP_URL_ERR_BADATTRS";
errstr = "Invalid or missing attributes";
break;
case LDAP_URL_ERR_BADFILTER:
descr = "LDAP_URL_ERR_BADFILTER";
errstr = "Invalid or missing filter";
break;
case LDAP_URL_ERR_BADEXTS:
descr = "LDAP_URL_ERR_BADEXTS";
errstr = "Invalid or missing extensions";
break;
# endif
# endif
}
U_INTERNAL_DUMP("ldap_url_parse() failed - %.*s", u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("(%d, %s) - %s"), result, descr, errstr), buffer)
# endif
U_RETURN(false);
}
/* Get the URL scheme (either ldap or ldaps) */
#ifdef HAVE_LDAP_SSL_H
if (strncmp(url, U_CONSTANT_TO_PARAM("ldaps:")) == 0)
{
/* Making encrypted connection */
isSecure = true;
# ifdef HAS_NOVELL_LDAPSDK
/**
* Initialize the ssl library. The first parameter of ldapssl_client_init is a certificate file. However, when used
* the file must be a DER encoded file. 0 is passed in for the certificate file because ldapssl_set_verify_mode will be used
* to specify no server certificate verification. ldapssl_client_init is an application level initialization not a
* thread level initilization and should be done once
*/
result = U_SYSCALL(ldapssl_client_init, "%p,%p", 0, /* DER encoded cert file */
0); /* reserved, use 0 */
if (result != LDAP_SUCCESS) U_RETURN(false);
/**
* Configure the LDAP SSL library to not verify the server certificate. The default is LDAPSSL_VERIFY_SERVER which validates all servers
* against the trusted certificates normally passed in during ldapssl_client_init or ldapssl_add_trusted_cert.
*
* WARNING: Setting the verify mode to LDAPSSL_VERIFY_NONE turns off server certificate verification. This means all servers are
* considered trusted. This should be used only in controlled environments where encrypted communication between servers and
* clients is desired but server verification is not necessary
*/
result = U_SYSCALL(ldapssl_set_verify_mode, "%d", LDAPSSL_VERIFY_NONE);
if (result != LDAP_SUCCESS)
{
U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
U_RETURN(false);
}
# endif
/* create a LDAP session handle that is enabled for ssl connection */
ld = (LDAP*) U_SYSCALL(ldapssl_init, "%S,%d,%d", (char*)ludpp->lud_host, /* host name */
(ludpp->lud_port ? ludpp->lud_port : LDAPS_PORT), /* port number */
1); /* 0 - clear text, 1 - enable for ssl */
if (ld == 0)
{
# ifdef HAS_NOVELL_LDAPSDK
U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
# endif
U_RETURN(false);
}
# if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H)
(void) U_SYSCALL(ldap_set_option, "%p,%d,%d", ld, LDAP_OPT_SSL, LDAP_OPT_ON);
# endif
}
else
#endif
{
/* Making clear text connection */
if (init(ludpp->lud_host, ludpp->lud_port) == false) U_RETURN(false);
}
U_RETURN(true);
}
void ULDAP::get(ULDAPEntry& e)
{
U_TRACE(1, "ULDAP::get(%p)", &e)
U_CHECK_MEMORY
U_INTERNAL_ASSERT_POINTER(ld)
U_INTERNAL_ASSERT_POINTER(searchResult)
// Go through the search results by checking entries
int i = 0, j;
char** values;
char* attribute;
LDAPMessage* entry;
BerElement* ber = 0;
char* _attribute;
struct berval** bvs = 0;
for (entry = ldap_first_entry(ld, searchResult); entry;
entry = ldap_next_entry( ld, entry), ++i)
{
e.dn[i] = ldap_get_dn(ld, entry);
U_INTERNAL_DUMP("dn[%d]: %S", i, e.dn[i])
for (attribute = ldap_first_attribute(ld, entry, &ber); attribute;
attribute = ldap_next_attribute( ld, entry, ber))
{
values = ldap_get_values(ld, entry, attribute); /* Get values */
U_INTERNAL_DUMP("values = %p attribute = %S", values, attribute)
if (values)
{
e.set(attribute, values, i);
ldap_value_free(values);
}
else
{
for (j = 0; j < e.n_attr; ++j)
{
// be prepared to the 'attr;binary' versions of 'attr'
_attribute = (char*)e.attr_name[j];
U_INTERNAL_DUMP("e.attr_name[%d] = %S", j, _attribute)
if (strncmp(attribute, _attribute, u__strlen(_attribute, __PRETTY_FUNCTION__)) == 0)
{
bvs = ldap_get_values_len(ld, entry, attribute);
if (bvs)
{
e.set(_attribute, bvs[0]->bv_val, bvs[0]->bv_len, i);
ldap_value_free_len(bvs);
break;
}
}
}
}
ldap_memfree(attribute);
}
ber_free(ber, 0);
}
}
// DEBUG
#if defined(U_STDCPP_ENABLE) && defined(DEBUG)
const char* ULDAPEntry::dump(bool reset) const
{
*UObjectIO::os << "dn " << (void*)dn << '\n'
<< "n_attr " << n_attr << '\n'
<< "n_entry " << n_entry << '\n'
<< "attr_val " << (void*)attr_val << '\n'
<< "attr_name " << (void*)attr_name;
if (reset)
{
UObjectIO::output();
return UObjectIO::buffer_output;
}
return 0;
}
const char* ULDAP::dump(bool reset) const
{
*UObjectIO::os << "ld " << (void*)ld << '\n'
<< "ludpp " << (void*)ludpp << '\n'
<< "result " << result << '\n'
<< "isSecure " << isSecure << '\n'
<< "pTimeOut " << (void*)pTimeOut << '\n'
<< "searchResult " << (void*)searchResult;
if (reset)
{
UObjectIO::output();
return UObjectIO::buffer_output;
}
return 0;
}
#endif
| 30.530387
| 161
| 0.497647
|
liftchampion
|
a2525c82eb57edaf137e876962602c448c65bbc4
| 3,334
|
cpp
|
C++
|
gmsh/Geo/discreteRegion.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | 4
|
2019-05-06T09:35:08.000Z
|
2021-05-14T16:26:45.000Z
|
gmsh/Geo/discreteRegion.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | null | null | null |
gmsh/Geo/discreteRegion.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | 1
|
2019-06-28T09:23:43.000Z
|
2019-06-28T09:23:43.000Z
|
// Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// issues on https://gitlab.onelab.info/gmsh/gmsh/issues.
#include "GmshConfig.h"
#include "discreteRegion.h"
#include "MVertex.h"
#include "GModelIO_GEO.h"
#include "Geo.h"
#include "Context.h"
#if defined(HAVE_MESH)
#include "meshGRegion.h"
#include "meshGRegionDelaunayInsertion.h"
#endif
discreteRegion::discreteRegion(GModel *model, int num) : GRegion(model, num)
{
::Volume *v = CreateVolume(num, MSH_VOLUME_DISCRETE);
Tree_Add(model->getGEOInternals()->Volumes, &v);
}
void discreteRegion::setBoundFaces(const std::set<int> &tagFaces)
{
for(std::set<int>::const_iterator it = tagFaces.begin(); it != tagFaces.end();
++it) {
GFace *face = model()->getFaceByTag(*it);
if(face) {
l_faces.push_back(face);
face->addRegion(this);
}
else {
Msg::Error("Unknown model face %d", *it);
}
}
}
void discreteRegion::setBoundFaces(const std::vector<int> &tagFaces,
const std::vector<int> &signFaces)
{
if(tagFaces.size() != signFaces.size()) {
Msg::Error("Wrong number of face signs in setBoundFaces");
std::set<int> tags;
tags.insert(tagFaces.begin(), tagFaces.end());
setBoundFaces(tags);
}
for(std::size_t i = 0; i != tagFaces.size(); i++) {
GFace *face = model()->getFaceByTag(tagFaces[i]);
if(face) {
l_faces.push_back(face);
face->addRegion(this);
l_dirs.push_back(signFaces[i]);
}
else {
Msg::Error("Unknown model face %d", tagFaces[i]);
}
}
}
void discreteRegion::findFaces(
std::map<MFace, std::vector<int>, Less_Face> &map_faces)
{
std::set<MFace, Less_Face> bound_faces;
for(std::size_t elem = 0; elem < getNumMeshElements(); elem++) {
MElement *e = getMeshElement(elem);
for(int iFace = 0; iFace < e->getNumFaces(); iFace++) {
MFace tmp_face = e->getFace(iFace);
std::set<MFace, Less_Face>::iterator itset = bound_faces.find(tmp_face);
if(itset == bound_faces.end())
bound_faces.insert(tmp_face);
else
bound_faces.erase(itset);
}
}
// for the boundary faces, associate the tag of the discrete face
for(std::set<MFace, Less_Face>::iterator itv = bound_faces.begin();
itv != bound_faces.end(); ++itv) {
std::map<MFace, std::vector<int>, Less_Face>::iterator itmap =
map_faces.find(*itv);
if(itmap == map_faces.end()) {
std::vector<int> tagRegions;
tagRegions.push_back(tag());
map_faces.insert(std::make_pair(*itv, tagRegions));
}
else {
std::vector<int> tagRegions = itmap->second;
tagRegions.push_back(tag());
itmap->second = tagRegions;
}
}
}
void discreteRegion::remesh()
{
#if defined(HAVE_MESH)
bool classify = false;
insertVerticesInRegion(this, 2000000000, classify);
// not functional yet: need boundaries
for(int i = 0; i < std::max(CTX::instance()->mesh.optimize,
CTX::instance()->mesh.optimizeNetgen); i++) {
if(CTX::instance()->mesh.optimize >= i) {
optimizeMeshGRegion opt;
opt(this, true);
}
if(CTX::instance()->mesh.optimizeNetgen >= i) {
optimizeMeshGRegionNetgen opt;
opt(this, true);
}
}
#endif
}
| 28.495726
| 80
| 0.632873
|
Poofee
|
a25812c405b0455b36c0084c8766f1fffafe2b9d
| 6,616
|
cpp
|
C++
|
src/Node.cpp
|
caitp/TimedText
|
7fa0724b3ba99539d17cd0c8be59922676f7114c
|
[
"Unlicense"
] | 2
|
2017-08-01T11:17:43.000Z
|
2022-03-19T21:26:45.000Z
|
src/Node.cpp
|
caitp/TimedText
|
7fa0724b3ba99539d17cd0c8be59922676f7114c
|
[
"Unlicense"
] | null | null | null |
src/Node.cpp
|
caitp/TimedText
|
7fa0724b3ba99539d17cd0c8be59922676f7114c
|
[
"Unlicense"
] | null | null | null |
//
// Copyright (c) 2013 Caitlin Potter and Contributors
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "NodeData.h"
namespace TimedText
{
class EmptyNodeData : public NodeData
{
public:
EmptyNodeData() : NodeData(EmptyNode,NullNode) {}
} emptyNode;
Node::Node()
: d(&emptyNode)
{
d->ref.ref();
}
static bool isInternalNode(NodeElementType type)
{
if(type > FirstNodeElementType && type < LastNodeElementType) {
// There are currently only two leaf nodes...
if(type == TextNode || type == TimestampNode)
return false;
return true;
}
return false;
}
static NodeData *internalNodeData(NodeElementType type)
{
if(isInternalNode(type)) {
if(type == InternalTextNode)
return new InternalNodeData(InternalTextNode);
if(type == VoiceNode)
return new VoiceNodeData();
if(type == LangNode)
return new LangNodeData();
else
return new ElementNodeData(type);
}
return 0;
}
static NodeData *leafNodeData(NodeElementType type)
{
if(type == TextNode)
return new TextNodeData();
if(type == TimestampNode)
return new TimestampNodeData();
return 0;
}
static NodeData *createNodeData(NodeType type, NodeElementType elem)
{
NodeData *d = 0;
if(type == InternalNode && (d = internalNodeData(elem)))
return d;
if(type == LeafNode && (d = leafNodeData(elem)))
return d;
d = &emptyNode;
d->ref.ref();
return d;
}
static NodeData *createNodeData(NodeElementType type)
{
NodeData *d = 0;
if((d = internalNodeData(type)))
return d;
if((d = leafNodeData(type)))
return d;
d = &emptyNode;
d->ref.ref();
return d;
}
Node::Node(NodeType type, NodeElementType elementType)
: d(createNodeData(type,elementType))
{
}
Node::Node(NodeElementType type)
: d(createNodeData(type))
{
}
Node::Node(const Node &other)
: d(other.d)
{
d->ref.ref();
}
Node::~Node()
{
if(!d->ref.deref())
delete d;
}
Node &
Node::operator=(const Node &other)
{
other.d->ref.ref();
if(!d->ref.deref())
delete d;
d = other.d;
return *this;
}
NodeType
Node::type() const
{
return d->type;
}
NodeElementType
Node::elementType() const
{
return d->element;
}
Timestamp
Node::timestamp() const
{
return d->timestamp();
}
String
Node::voice() const
{
return d->voice();
}
String
Node::text() const
{
return d->text();
}
String
Node::lang() const
{
return d->lang();
}
List<String>
Node::applicableClasses() const
{
return d->applicableClasses();
}
bool
Node::setTimestamp(const Timestamp &ts)
{
return d->setTimestamp(ts);
}
bool
Node::setVoice(const String &voice)
{
return d->setVoice(voice);
}
bool
Node::setText(const String &text)
{
return d->setText(text);
}
bool
Node::setLang(const String &lang)
{
return d->setLang(lang);
}
bool
Node::setApplicableClasses(const List<String> &classes)
{
return d->setApplicableClasses(classes);
}
const List<Node> &
Node::children() const
{
return d->children();
}
bool
Node::push(const Node &node)
{
return d->push(node);
}
bool
Node::pop(Node &result)
{
return d->pop(result);
}
bool
Node::unshift(const Node &node)
{
return d->unshift(node);
}
bool
Node::shift(Node &result)
{
return d->shift(result);
}
bool
Node::insert(int i, const Node &node)
{
return d->insert(i, node);
}
bool
Node::take(int i, Node &result)
{
return d->take(i, result);
}
bool
Node::itemAt(int i, Node &result)
{
return d->itemAt(i, result);
}
Node::iterator
Node::begin()
{
return d->begin();
}
Node::iterator
Node::end()
{
return d->end();
}
Node::const_iterator
Node::begin() const
{
const NodeData *x = d;
return x->begin();
}
Node::const_iterator
Node::end() const
{
const NodeData *x = d;
return x->end();
}
int
Node::childCount() const
{
return d->childCount();
}
struct VisitState
{
public:
inline VisitState() : i(0) {}
inline VisitState(const VisitState &v) : n(v.n), i(v.i) {}
inline VisitState(const Node &node) : n(node), i(0) {}
inline VisitState(const Node &node, int pos) : n(node), i(pos) {}
inline bool hasChildren() const { return n.childCount() > 0; }
inline bool isLeaf() const { return n.type() == LeafNode; }
inline bool isInternal() const { return n.type() == InternalNode; }
inline bool isInternalText() const {
return n.element() == InternalTextNode;
}
inline bool isEmpty() const { return n.type() == EmptyNode; }
inline bool next(VisitState &result) {
Node tmp;
if(n.itemAt(i++, tmp)) {
result = VisitState(tmp);
return true;
}
return false;
}
operator Node &() { return n; }
operator const Node &() const { return n; }
Node n;
int i;
};
void
Node::visit(NodeVisitor &visitor)
{
List<VisitState> stack;
stack.push(*this);
VisitState *top;
while(stack.lastPtr(top)) {
VisitState it;
if(top->next(it)) {
// Don't visit empty nodes.
if(it.isEmpty())
continue;
// Visit the item before descending
visitor.visit(it);
// We might need to descend, if it's
if(it.isInternal()) {
if(it.hasChildren() && (it.isInternalText() || visitor.enter(it)))
stack.push(it);
}
} else {
// Notify visitor that we are leaving a branch of the tree
if(!top->isInternalText())
visitor.leave(*top);
stack.pop(it);
}
}
}
} // TimedText
| 19.011494
| 74
| 0.667322
|
caitp
|
a25d5c53b29e80e096b16da7437b5840896c5bae
| 2,684
|
cpp
|
C++
|
examples/file_loader/file_loader.cpp
|
torbjoernk/CTML
|
0eb16c35c591f990db32d41c58bce71d41817b8c
|
[
"MIT"
] | 1
|
2018-08-07T15:07:26.000Z
|
2018-08-07T15:07:26.000Z
|
examples/file_loader/file_loader.cpp
|
torbjoernk/CTML
|
0eb16c35c591f990db32d41c58bce71d41817b8c
|
[
"MIT"
] | null | null | null |
examples/file_loader/file_loader.cpp
|
torbjoernk/CTML
|
0eb16c35c591f990db32d41c58bce71d41817b8c
|
[
"MIT"
] | null | null | null |
#include "CTML.h"
#include "dirent.h"
bool add_files_to_doc(std::string folderPath, CTML::Node* containerNode) {
DIR *directory = NULL;
// open the folder path
directory = opendir(folderPath.c_str());
// return false if it doesn't exist
if (directory == NULL) {
std::cout << "Directory not found!\n";
return false;
}
// the directory entry struct
struct dirent *ent;
while ((ent = readdir(directory)) != NULL)
{
// if the current entry is a file
if (ent->d_type == DT_REG) {
// the file name as a string
std::string fileName = std::string(ent->d_name);
// the content of the document
std::string docContent;
std::ifstream textFile(folderPath + fileName);
std::string line;
// loop through the lines in the file
while (std::getline(textFile, line))
{
// append the line to the doc content
docContent += line + '\n';
}
// hacky way of removing the last new line in the doc content
int lastNewLine = docContent.find_last_of('\n');
if (lastNewLine != std::string::npos)
docContent.erase(docContent.find_last_of('\n'));
// remove the extention from the file name
fileName = fileName.substr(0, fileName.find('.'));
// the container for this file
CTML::Node fileContainer("div.post");
CTML::Node fileTitle("h1", fileName);
CTML::Node fileContent("p", docContent);
// append the title and content to the file container
fileContainer.AppendChild(fileTitle).AppendChild(fileContent);
// append the file container to the root container
containerNode->AppendChild(fileContainer);
}
}
// if we can't close the directory for some reason
if (closedir(directory) < 0) {
std::cout << "Could not close the stream to the directory!\n";
return false;
}
// finished
return true;
}
int main()
{
CTML::Document doc;
doc.AddNodeToHead(CTML::Node("title", "CTML Test"));
// force utf-8 encoding
doc.AddNodeToHead(CTML::Node("meta").SetAttribute("charset", "UTF-8"));
CTML::Node containerNode("div.container");
std::string dir;
// input the directory to look for files
std::cout << "Input the directory name with the files: ";
std::cin >> dir;
bool result = add_files_to_doc(dir, &containerNode);
// add the files container to the body
doc.AddNodeToBody(containerNode);
bool fileWriteResult = false;
// if finding files was successful, try to write to a file
if (result)
fileWriteResult = doc.WriteToFile("index.html", CTML::MULTILINE_BR);
// if we wrote to the file successfully
if (fileWriteResult)
std::cout << "All files in \"" + dir + "\" written to index.html successfully!\n";
else
std::cout << "Writing to index.html was unsuccessful!\n";
return fileWriteResult;
}
| 33.55
| 84
| 0.69076
|
torbjoernk
|
a25dfa61654baf386d71959105626bfe2049567e
| 57
|
cpp
|
C++
|
algorithms/des/info.cpp
|
playahammer/crypto
|
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
|
[
"MIT"
] | null | null | null |
algorithms/des/info.cpp
|
playahammer/crypto
|
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
|
[
"MIT"
] | null | null | null |
algorithms/des/info.cpp
|
playahammer/crypto
|
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
|
[
"MIT"
] | 1
|
2019-04-26T02:23:44.000Z
|
2019-04-26T02:23:44.000Z
|
#include "log.h"
Info::Info()
{
}
QString Info::Info
| 5.7
| 18
| 0.596491
|
playahammer
|
a262f7b192a34e3efee1f74fc4223861f275b0fd
| 4,487
|
cpp
|
C++
|
src/server/protocol/ServerProtocol.cpp
|
zminor/Zony_CPP
|
311c75a3d6acebb7f4265b63813b19eeaa9d8926
|
[
"MIT"
] | null | null | null |
src/server/protocol/ServerProtocol.cpp
|
zminor/Zony_CPP
|
311c75a3d6acebb7f4265b63813b19eeaa9d8926
|
[
"MIT"
] | null | null | null |
src/server/protocol/ServerProtocol.cpp
|
zminor/Zony_CPP
|
311c75a3d6acebb7f4265b63813b19eeaa9d8926
|
[
"MIT"
] | null | null | null |
#include "ServerProtocol.h"
#include "../../utils/Utils.h"
namespace HttpServer
{
ServerProtocol::ServerProtocol(
Socket::Adapter &sock,
const ServerSettings &settings,
ServerControls &controls
) noexcept
: sock(sock), settings(settings), controls(controls)
{
}
ServerProtocol::ServerProtocol(const ServerProtocol &prot) noexcept
: sock(prot.sock), settings(prot.settings), controls(prot.controls)
{
}
DataVariant::DataReceiver *
ServerProtocol::createDataReceiver(
const Transfer::request_data *rd,
const std::unordered_map<std::string,
DataVariant::Abstract *> &variants
) {
auto const it = rd->incoming_headers.find("content-type");
if (rd->incoming_headers.cend() == it) {
return nullptr;
}
// get the value of the header
const std::string &header_value = it->second;
std::string data_variant_name; // name of data query
std::unordered_map<std::string, std::string> content_params;
// to determine whether the data type query additional parameters
size_t delimiter = header_value.find(';');
// if there are additional parameters - remove them
if (std::string::npos != delimiter) {
data_variant_name = header_value.substr(0, delimiter);
Utils::trim(data_variant_name);
for (
size_t str_param_cur = delimiter + 1, str_param_end = 0;
std::string::npos != str_param_end;
str_param_cur = str_param_end + 1
) {
str_param_end = header_value.find(';', str_param_cur);
delimiter = header_value.find('=', str_param_cur);
if (delimiter >= str_param_end) {
std::string param_name = header_value.substr(
str_param_cur,
std::string::npos != str_param_end
? str_param_end - str_param_cur
: std::string::npos
);
Utils::trim(param_name);
content_params.emplace(
std::move(param_name),
std::string()
);
} else {
std::string param_name = header_value.substr(
str_param_cur,
delimiter - str_param_cur
);
Utils::trim(param_name);
++delimiter;
std::string param_value = header_value.substr(
delimiter,
std::string::npos != str_param_end
? str_param_end - delimiter
: std::string::npos
);
Utils::trim(param_value);
content_params.emplace(
std::move(param_name),
std::move(param_value)
);
}
}
} else {
data_variant_name = header_value;
}
auto const variant = variants.find(data_variant_name);
if (variants.cend() == variant) {
return nullptr;
}
const DataVariant::Abstract *data_variant = variant->second;
size_t data_length = 0;
auto const it_len = rd->incoming_headers.find("content-length");
if (rd->incoming_headers.cend() != it_len) {
data_length = std::strtoull(
it_len->second.c_str(),
nullptr,
10
);
}
return new DataVariant::DataReceiver {
data_variant,
data_variant->createStateStruct(rd, content_params),
data_length,
0, 0, nullptr,
};
}
void ServerProtocol::destroyDataReceiver(void *src)
{
DataVariant::DataReceiver *dr = reinterpret_cast<DataVariant::DataReceiver *>(src);
if (dr) {
dr->data_variant->destroyStateStruct(dr->ss);
if (dr->reserved) {
delete reinterpret_cast<std::string *>(dr->reserved);
dr->reserved = nullptr;
}
}
delete dr;
}
void ServerProtocol::runApplication(
struct Request &req,
const ServerApplicationSettings &appSets
) const {
std::vector<char> buf;
buf.reserve(4096);
if (this->packRequestParameters(buf, req, appSets.root_dir) == false) {
return;
}
Transfer::app_request request {
this->sock.get_handle(),
this->sock.get_tls_session(),
buf.data()
};
Transfer::app_response response {
nullptr, 0
};
try {
// Launch application
req.app_exit_code = appSets.application_call(&request, &response);
}
catch (std::exception &exc) {
// TODO: exception output
}
if (response.response_data && response.data_size)
{
if (EXIT_SUCCESS == req.app_exit_code) {
this->unpackResponseParameters(req, response.response_data);
}
// Clear outgoing data of application
try {
appSets.application_clear(response.response_data, response.data_size);
}
catch (std::exception &exc) {
// TODO: exception output
}
}
}
}
| 23.615789
| 86
| 0.640517
|
zminor
|
a264baaa6da8b663d483dfc76c2506d201409a6f
| 2,434
|
hpp
|
C++
|
include/domain/structure/field/svector_center.hpp
|
hyperpower/Nablla
|
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
|
[
"MIT"
] | null | null | null |
include/domain/structure/field/svector_center.hpp
|
hyperpower/Nablla
|
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
|
[
"MIT"
] | null | null | null |
include/domain/structure/field/svector_center.hpp
|
hyperpower/Nablla
|
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
|
[
"MIT"
] | null | null | null |
#ifndef _S_VECTOR_CENTER_HPP_
#define _S_VECTOR_CENTER_HPP_
#include "sfield.hpp"
#include "utility/tinyformat.hpp"
#include "algebra/array/multi_array.hpp"
#include <limits>
namespace carpio{
template<St DIM, class FIELD>
class SVectorCenter_{
public:
typedef SIndex_<DIM> Index;
typedef SGrid_<DIM> GridBase;
typedef SGhost_<DIM> GhostBase;
typedef SOrder_<DIM> OrderBase;
typedef FIELD Field;
typedef typename FIELD::Grid Grid;
typedef typename FIELD::Ghost Ghost;
typedef typename FIELD::Order Order;
typedef std::shared_ptr<SIndex_<DIM> > spIndex;
typedef std::shared_ptr<SGrid_<DIM> > spGrid;
typedef std::shared_ptr<SGhost_<DIM> > spGhost;
typedef std::shared_ptr<SOrder_<DIM> > spOrder;
typedef MultiArrayV_<Vt, DIM> Mat;
typedef typename Mat::reference reference;
typedef typename Mat::const_reference const_reference;
typedef SVectorCenter_<DIM, FIELD> Self;
typedef std::shared_ptr<Field> spField;
protected:
std::array<spField, DIM> _arrs;
public:
SVectorCenter_() {
FOR_EACH_DIM{
_arrs[d] = nullptr;
}
}
SVectorCenter_(
spField u,
spField v = nullptr,
spField w = nullptr){
spField a[] = {u,v,w};
FOR_EACH_DIM{
ASSERT(a[d] != nullptr);
_arrs[d] = a[d];
}
}
void set(Axes a, spField sps){
ASSERT(a < DIM);
_arrs[a] = sps;
}
const Order& order() const {
return _arrs[_X_]->order();
}
const Grid& grid() const {
return _arrs[_X_]->grid();
}
const Ghost& ghost() const {
return _arrs[_X_]->ghost();
}
Field& operator[](St d){
return *(_arrs[d]);
}
const Field& operator[](St d) const{
return *(_arrs[d]);
}
Vt max() const{
Vt m = _arrs[_X_]->max();
for(St d = 1; d< DIM; d++){
Vt md = _arrs[d]->max();
if(m < md){
m = md;
}
}
return m;
}
Vt max_norm2() const{
if(DIM == 1){
return max();
}else if(DIM == 2){
auto sum = SqareSum(*(_arrs[_X_]), *(_arrs[_Y_]));
return std::sqrt(sum.max());
}else{
auto sum = SqareSum(_arrs[_X_], _arrs[_Y_], _arrs[_Z_]);
return std::sqrt(sum.max());
}
}
};
}
#endif
| 21.927928
| 68
| 0.554232
|
hyperpower
|
a26caffc313c3585b461573217a412f2b87ff712
| 3,139
|
cpp
|
C++
|
computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp
|
magic428/subjects_notes
|
6930adbb3f445c11ca9d024abb12a53d6aca19e7
|
[
"MIT"
] | 2
|
2020-03-18T17:13:00.000Z
|
2020-03-25T02:34:03.000Z
|
computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp
|
magic428/subjects_notes
|
6930adbb3f445c11ca9d024abb12a53d6aca19e7
|
[
"MIT"
] | null | null | null |
computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp
|
magic428/subjects_notes
|
6930adbb3f445c11ca9d024abb12a53d6aca19e7
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* Video encoding example
*******************************************************************************/
int main(int argc, char** argv)
{
AVCodec *codec = NULL;
AVCodecContext *codecCtx= NULL;
AVFormatContext *pFormatCtx = NULL;
AVStream * pVideoStream = NULL;
AVFrame *picture = NULL;
int i, x, y, //
ret, // Return value
got_packet_ptr; // Data encoded into packet
// Register all formats and codecs
avcodec_register_all();
av_register_all();
avformat_network_init();
char filename[100] ;
sprintf_s(filename,sizeof(filename),"%s","rtsp://192.168.1.7:8554/live.sdp");
if(argc>1)
{
sprintf_s(filename,sizeof(filename),"%s",argv[1]);
}
printf_s("URL: %s\n", filename);
// allocate context
ret = avformat_alloc_output_context2( &pFormatCtx, NULL, "rtsp", filename );
if ( !pFormatCtx || ret < 0 )
{
fprintf(stderr,"Could not allocate output context" );
}
pFormatCtx->flags |= AVFMT_FLAG_NOBUFFER|AVFMT_FLAG_FLUSH_PACKETS;
pFormatCtx->max_interleave_delta = 1;
pFormatCtx->oformat->video_codec = AV_CODEC_ID_H264;
// Find the codec.
codec = avcodec_find_encoder(pFormatCtx->oformat->video_codec);
if (codec == NULL) {
fprintf(stderr, "Codec not found\n");
return -1;
}
// Add stream to pFormatCtx
pVideoStream = avformat_new_stream(pFormatCtx, codec);
if (!pVideoStream)
{
fprintf(stderr, "Cannot add new video stream\n");
return -1;
}
int framerate = 10;
pVideoStream->id = pFormatCtx->nb_streams-1;
pVideoStream->time_base.den = framerate;
pVideoStream->time_base.num = 1;
// Set context
codecCtx = pVideoStream->codec;
codecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
codecCtx->profile = FF_PROFILE_H264_BASELINE;
// Resolution must be a multiple of two.
codecCtx->width = 320;
codecCtx->height = 240;
codecCtx->bit_rate = 1000000;
codecCtx->time_base.den = framerate;
codecCtx->time_base.num = 1;
codecCtx->gop_size = 12; // emit one intra frame every twelve frames at most
if (pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
// Open the codec.
if (avcodec_open2(codecCtx, codec, NULL) < 0)
{
fprintf(stderr, "Cannot open video codec\n");
return -1;
}
ret = avio_open2(&pFormatCtx->pb, filename, AVIO_FLAG_WRITE, NULL, NULL);
if (ret < 0)
{
// Error "Protocol not found"
av_strerror(ret,errbuf, ERRBUFFLEN);
fprintf(stderr, "avio_open2() fail: %s\n", errbuf);
//return -1;
}
// Write file header. (Gets stuck here)
ret = avformat_write_header(pFormatCtx, NULL);
if ( ret < 0 )
{
fprintf(stderr, "error writing header");
return -1;
}
// ...more code
}
--
Ang
| 30.182692
| 82
| 0.566104
|
magic428
|
a2700571f7e9bf2d6a9e6a83e91970a8e058ad46
| 1,442
|
cpp
|
C++
|
src/code-examples/chapter-10/functors-optional/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
src/code-examples/chapter-10/functors-optional/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
src/code-examples/chapter-10/functors-optional/main.cpp
|
nhatvu148/helpers
|
1a6875017cf39790dfe40ecec9dcee4410b1d89e
|
[
"MIT"
] | null | null | null |
#include <optional>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/filter.hpp>
// We can define a range facade that allows using std::optional
// as if it was a proper range (as in range-v3 library).
// If the optional is empty, the range is empty. If it contains
// a value, it generates a range that contains a single value.
template <typename T1, typename F>
auto transform(const std::optional<T1> &opt, F f)
-> decltype(f(opt.value()))
{
if (opt) {
return f(opt.value());
} else {
return {};
}
}
template <typename T>
class optional_range
: public ranges::v3::view_facade<optional_range<T>> {
public:
optional_range() = default;
explicit optional_range(const std::optional<T> &opt)
: m_opt_ptr(opt ? &opt.value() : nullptr)
{
}
private:
friend ranges::v3::range_access;
const T *m_opt_ptr;
const T & read() const { return *m_opt_ptr; }
bool equal(ranges::v3::default_sentinel) const {
return m_opt_ptr == nullptr;
}
void next() { m_opt_ptr = nullptr; }
};
template <typename T>
optional_range<T> as_range(const std::optional<T> &opt)
{
return optional_range<T>(opt);
}
int main(int argc, char *argv[])
{
std::optional<int> i;
transform(i, isalnum);
auto r = as_range(i) | ranges::v3::view::transform(isalnum);
return 0;
}
| 22.888889
| 64
| 0.653259
|
nhatvu148
|
a27073b60d9cad11e32d5c469bca677e37901975
| 3,951
|
cpp
|
C++
|
src_test/test_utils/TestCase.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_test/test_utils/TestCase.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_test/test_utils/TestCase.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* TestCase.cpp
*
* Created on: 2018/05/06
* Author: iizuka
*/
#include "test_utils/TestCase.h"
#include "test_utils/TestGroup.h"
#include "test_utils/TestGroupActions.h"
#include "test_utils/Check.h"
#include "test_utils/TestEnv.h"
#include "test_utils/TestParams.h"
#include "base/UnicodeString.h"
#include <chrono>
#include "base_io_stream/Writer.h"
using namespace std::chrono;
namespace alinous {
TestCase::TestCase(TestGroup* group, const wchar_t* name, TestGroupActions* setup, const char* file, int line) noexcept {
this->group = group;
this->name = new UnicodeString(name);
this->setup = setup;
this->file = new UnicodeString(file);
this->line = line;
this->checks = new ArrayList<Check>();
this->env = new TestEnv(this);
this->done = false;
this->failed = false;
this->microsec = 0;
this->setup->setNames(group->getName(), this->name);
this->setup->setTestEnv(this->env);
group->addTestCase(this->name, this);
}
TestCase::~TestCase() noexcept {
delete this->name;
delete this->setup;
delete this->file;
this->checks->deleteElements();
delete this->checks;
}
void TestCase::doTest(TestParams* params) {
const char* result = "OK";
setDone();
try{
this->setup->setup();
}catch(...){
setFailed();
if(params->isV()){
printf(" %ls [%ls at %d]... failed in setup()\n", this->name->towString(), this->file->towString(), getLine());
}
return;
}
uint64_t start, end;
try{
Check::getThreadKeyRegistory()->registerTestCase(this);
start = Os::getMicroSec();
testBody();
end = Os::getMicroSec();
}catch(...){
end = Os::getMicroSec();
setFailed();
if(params->isV()){
printf(" !!!!! %ls [%ls at %d]... failed. Exception was thrown on test body.\n", this->name->towString(), this->file->towString(), getLine());
}
}
this->microsec = end - start;
try{
this->setup->teardown();
}
catch(...){
setFailed();
if(params->isV()){
printf(" !!!!! %ls [%ls at %d]... failed in teardown()\n", this->name->towString(), this->file->towString(), getLine());
}
return;
}
if(params->isV()){
if(isFailed()){
result = "Failed!!!!!!!!!!!";
}else{
result = "OK";
}
double milli = ((double)this->microsec) / (double)1000;
printf(" %ls() [%ls at %d]... %s(%lf ms)\n", this->name->towString(), this->file->towString(), getLine(), result, milli);
}
else{
printf(".");
fflush( stdout );
}
}
Check* TestCase::addCheck(Check* check) noexcept {
this->checks->addElement(check);
return check;
}
const TestGroup* TestCase::getGroup() const noexcept {
return this->group;
}
TestEnv* TestCase::getEnv() noexcept {
return this->env;
}
const UnicodeString* TestCase::getName() const noexcept {
return this->name;
}
const UnicodeString* TestCase::getFile() const noexcept {
return this->file;
}
const int TestCase::getLine() const noexcept {
return this->line;
}
bool TestCase::isDone() const noexcept {
return this->done;
}
void TestCase::setDone() noexcept {
this->done = true;
}
bool TestCase::isFailed() const noexcept {
return this->failed;
}
void TestCase::setFailed() noexcept {
this->failed = true;
}
ArrayList<Check>* TestCase::getChecks() const noexcept {
return this->checks;
}
void TestCase::exportJUnitXML(Writer* writer) const {
char buff[255]{};
double sec = ((double)this->microsec) / (double)1000000;
::sprintf(buff, "%lf", sec);
UnicodeString milStr(buff);
UnicodeString caseStr(L" <testcase classname=\"");
caseStr.append(this->group->getName()).append(L"\" name=\"").append(this->name).append(L"\" time=\"")
.append(&milStr).append(L"\">\n");
writer->write(&caseStr);
if(failed){
writer->write(L" <failure>\n");
UnicodeString failure(L"");
failure.append(this->file).append(L" at ").append(this->line).append(L"\n");
writer->write(L" ");
writer->write(&failure);
writer->write(L" </failure>\n");
}
writer->write(L" </testcase>\n");
}
} /* namespace alinous */
| 21.95
| 146
| 0.647684
|
alinous-core
|
a2746799b5f0e0552105b05d98da248b16a6d79b
| 6,463
|
cpp
|
C++
|
lib/dirac_domain_wall.cpp
|
Marcogarofalo/quda
|
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
|
[
"MIT"
] | null | null | null |
lib/dirac_domain_wall.cpp
|
Marcogarofalo/quda
|
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
|
[
"MIT"
] | null | null | null |
lib/dirac_domain_wall.cpp
|
Marcogarofalo/quda
|
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <dirac_quda.h>
#include <dslash_quda.h>
#include <blas_quda.h>
namespace quda {
DiracDomainWall::DiracDomainWall(const DiracParam ¶m) :
DiracWilson(param, 5),
m5(param.m5),
kappa5(0.5 / (5.0 + m5)),
Ls(param.Ls)
{
}
DiracDomainWall::DiracDomainWall(const DiracDomainWall &dirac) :
DiracWilson(dirac),
m5(dirac.m5),
kappa5(0.5 / (5.0 + m5)),
Ls(dirac.Ls)
{
}
DiracDomainWall::~DiracDomainWall() { }
DiracDomainWall& DiracDomainWall::operator=(const DiracDomainWall &dirac)
{
if (&dirac != this) {
DiracWilson::operator=(dirac);
m5 = dirac.m5;
kappa5 = dirac.kappa5;
}
return *this;
}
void DiracDomainWall::checkDWF(const ColorSpinorField &out, const ColorSpinorField &in) const
{
if (in.Ndim() != 5 || out.Ndim() != 5) errorQuda("Wrong number of dimensions\n");
if (in.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, in.X(4));
if (out.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, out.X(4));
}
void DiracDomainWall::Dslash(ColorSpinorField &out, const ColorSpinorField &in,
const QudaParity parity) const
{
checkDWF(out, in);
checkParitySpinor(in, out);
checkSpinorAlias(in, out);
ApplyDomainWall5D(out, in, *gauge, 0.0, mass, in, parity, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls-2)*(in.Volume()/Ls);
long long wall = 2*in.Volume()/Ls;
flops += 1320LL*(long long)in.Volume() + 96LL*bulk + 120LL*wall;
}
void DiracDomainWall::DslashXpay(ColorSpinorField &out, const ColorSpinorField &in,
const QudaParity parity, const ColorSpinorField &x,
const double &k) const
{
checkDWF(out, in);
checkParitySpinor(in, out);
checkSpinorAlias(in, out);
ApplyDomainWall5D(out, in, *gauge, k, mass, x, parity, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls-2)*(in.Volume()/Ls);
long long wall = 2*in.Volume()/Ls;
flops += (1320LL+48LL)*(long long)in.Volume() + 96LL*bulk + 120LL*wall;
}
void DiracDomainWall::M(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkFullSpinor(out, in);
ApplyDomainWall5D(out, in, *gauge, -kappa5, mass, in, QUDA_INVALID_PARITY, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls - 2) * (in.Volume() / Ls);
long long wall = 2 * in.Volume() / Ls;
flops += (1320LL + 48LL) * (long long)in.Volume() + 96LL * bulk + 120LL * wall;
}
void DiracDomainWall::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkFullSpinor(out, in);
bool reset = newTmp(&tmp1, in);
M(*tmp1, in);
Mdag(out, *tmp1);
deleteTmp(&tmp1, reset);
}
void DiracDomainWall::prepare(ColorSpinorField* &src, ColorSpinorField* &sol,
ColorSpinorField &x, ColorSpinorField &b,
const QudaSolutionType solType) const
{
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
errorQuda("Preconditioned solution requires a preconditioned solve_type");
}
src = &b;
sol = &x;
}
void DiracDomainWall::reconstruct(ColorSpinorField &, const ColorSpinorField &, const QudaSolutionType) const
{
// do nothing
}
DiracDomainWallPC::DiracDomainWallPC(const DiracParam ¶m)
: DiracDomainWall(param)
{
}
DiracDomainWallPC::DiracDomainWallPC(const DiracDomainWallPC &dirac)
: DiracDomainWall(dirac)
{
}
DiracDomainWallPC::~DiracDomainWallPC()
{
}
DiracDomainWallPC& DiracDomainWallPC::operator=(const DiracDomainWallPC &dirac)
{
if (&dirac != this) {
DiracDomainWall::operator=(dirac);
}
return *this;
}
// Apply the even-odd preconditioned clover-improved Dirac operator
void DiracDomainWallPC::M(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkDWF(out, in);
double kappa2 = -kappa5*kappa5;
bool reset = newTmp(&tmp1, in);
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
Dslash(*tmp1, in, QUDA_ODD_PARITY);
DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, in, kappa2);
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
Dslash(*tmp1, in, QUDA_EVEN_PARITY);
DslashXpay(out, *tmp1, QUDA_ODD_PARITY, in, kappa2);
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
deleteTmp(&tmp1, reset);
}
void DiracDomainWallPC::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const
{
//M(out, in);
//Mdag(out, out);
bool reset = newTmp(&tmp2, in);
M(*tmp2, in);
Mdag(out, *tmp2);
deleteTmp(&tmp2, reset);
}
void DiracDomainWallPC::prepare(ColorSpinorField* &src, ColorSpinorField* &sol,
ColorSpinorField &x, ColorSpinorField &b,
const QudaSolutionType solType) const
{
// we desire solution to preconditioned system
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
src = &b;
sol = &x;
} else {
// we desire solution to full system
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
// src = b_e + k D_eo b_o
DslashXpay(x.Odd(), b.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5);
src = &(x.Odd());
sol = &(x.Even());
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
// src = b_o + k D_oe b_e
DslashXpay(x.Even(), b.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5);
src = &(x.Even());
sol = &(x.Odd());
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
// here we use final solution to store parity solution and parity source
// b is now up for grabs if we want
}
}
void DiracDomainWallPC::reconstruct(ColorSpinorField &x, const ColorSpinorField &b,
const QudaSolutionType solType) const
{
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
return;
}
// create full solution
checkFullSpinor(x, b);
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
// x_o = b_o + k D_oe x_e
DslashXpay(x.Odd(), x.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5);
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
// x_e = b_e + k D_eo x_o
DslashXpay(x.Even(), x.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5);
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
}
} // namespace quda
| 28.852679
| 111
| 0.63763
|
Marcogarofalo
|
a276a5c5b571915bbb078380db42a824cf878ed6
| 2,822
|
cpp
|
C++
|
modules/core/src/intrinsic.cpp
|
shreddered/imagestego
|
633b41bce2e653a3e8a46b812f05af814088ea51
|
[
"MIT"
] | 2
|
2020-10-10T11:44:40.000Z
|
2020-10-25T01:55:21.000Z
|
modules/core/src/intrinsic.cpp
|
shreddered/imagestego
|
633b41bce2e653a3e8a46b812f05af814088ea51
|
[
"MIT"
] | 9
|
2020-09-21T20:56:58.000Z
|
2021-01-26T13:04:05.000Z
|
modules/core/src/intrinsic.cpp
|
shreddered/imagestego
|
633b41bce2e653a3e8a46b812f05af814088ea51
|
[
"MIT"
] | 2
|
2021-01-24T13:49:51.000Z
|
2021-03-13T23:14:15.000Z
|
/*
* This file is a part of imagestego library.
*
* Copyright (c) 2020-2021 Dmitry Kalinin <x.shreddered.x@gmail.com>
*
* 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.
*/
// imagestego headers
#include "imagestego/core/intrinsic.hpp"
// c++ headers
#include <cstdlib>
#if IMAGESTEGO_MSVC && HAVE_INTRIN_H
#include <intrin.h>
#pragma intrinsic(_BitScanReverse)
#endif
#if IMAGESTEGO_MSVC
#define bswap_32(x) _byteswap_ulong(x)
#elif IMAGESTEGO_ICC
#define bswap_32(x) _bswap(x)
#elif IMAGESTEGO_GCC || (IMAGESTEGO_CLANG && !defined(__APPLE__))
#define bswap_32(x) __builtin_bswap32(x)
#elif defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#define bswap_32(x) OSSwapInt32(x)
#elif defined(__sun) || defined(sun)
#include <sys/byteorder.h>
#define bswap_32(x) BSWAP_32(x)
#elif defined(__FreeBSD__)
#include <sys/endian.h>
#define bswap_32(x) bswap32(x)
#elif defined(__OpenBSD__)
#include <sys/types.h>
#define bswap_32(x) swap32(x)
#elif defined(__NetBSD__)
#include <machine/bswap.h>
#include <sys/types.h>
#if defined(__BSWAP_RENAME) && !defined(__bswap_32)
#define bswap_32(x) bswap32(x)
#endif
#endif
namespace imagestego {
uint8_t log2(uint32_t value) noexcept {
#if IMAGESTEGO_CLANG || IMAGESTEGO_GCC
return value ? 31 - __builtin_clz(value) : 0;
#elif IMAGESTEGO_ICC
uint32_t result = 0;
_BitScanReverse(&result, value);
return result;
#elif IMAGESTEGO_MSVC
unsigned long result = 0;
_BitScanReverse(&result, value);
return result;
#else
uint8_t res = 0;
while (value >>= 1)
++res;
return res;
#endif
}
uint32_t bswap(uint32_t value) noexcept {
#ifdef bswap_32
return bswap_32(value);
#else
char* tmp = reinterpret_cast<char*>(&value);
std::reverse(tmp, tmp + 4);
return value;
#endif
}
} // namespace imagestego
| 30.673913
| 81
| 0.739546
|
shreddered
|
a2771f8c514fe3d60e0124e1404599d1f26d0490
| 12,183
|
cc
|
C++
|
bin/context_engine/context_repository_unittest.cc
|
Acidburn0zzz/peridot
|
9a3b1fb8e834d0315092478d83d0176ef28cb765
|
[
"BSD-3-Clause"
] | 1
|
2018-02-05T23:33:32.000Z
|
2018-02-05T23:33:32.000Z
|
bin/context_engine/context_repository_unittest.cc
|
Acidburn0zzz/peridot
|
9a3b1fb8e834d0315092478d83d0176ef28cb765
|
[
"BSD-3-Clause"
] | null | null | null |
bin/context_engine/context_repository_unittest.cc
|
Acidburn0zzz/peridot
|
9a3b1fb8e834d0315092478d83d0176ef28cb765
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2017 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 "peridot/bin/context_engine/context_repository.h"
#include "gtest/gtest.h"
#include "lib/context/cpp/context_metadata_builder.h"
#include "lib/context/cpp/formatting.h"
#include "lib/context/fidl/context_engine.fidl.h"
namespace maxwell {
namespace {
TEST(ContextGraph, GetChildrenRecursive_GetAncestors) {
ContextGraph graph;
graph.AddEdge("a", "b");
graph.AddEdge("b", "c");
graph.AddEdge("b", "d");
auto children = graph.GetChildrenRecursive("b");
EXPECT_EQ(2lu, children.size());
EXPECT_TRUE(children.find("c") != children.end());
EXPECT_TRUE(children.find("d") != children.end());
children = graph.GetChildrenRecursive("a");
EXPECT_EQ(3lu, children.size());
EXPECT_TRUE(children.find("b") != children.end());
EXPECT_TRUE(children.find("c") != children.end());
EXPECT_TRUE(children.find("d") != children.end());
auto ancestors = graph.GetAncestors("c");
EXPECT_EQ(2lu, ancestors.size());
EXPECT_EQ("a", ancestors[0]);
EXPECT_EQ("b", ancestors[1]);
}
class ContextRepositoryTest : public ::testing::Test {
public:
ContextRepositoryTest() {}
protected:
ContextRepository repository_;
};
class TestListener : public ContextListener {
public:
ContextUpdatePtr last_update;
void OnContextUpdate(ContextUpdatePtr update) override {
last_update = std::move(update);
}
void reset() { last_update.reset(); }
};
ContextValuePtr CreateValue(ContextValueType type,
const std::string& content,
ContextMetadataPtr metadata) {
ContextValuePtr value = ContextValue::New();
value->type = type;
value->content = content;
value->meta = std::move(metadata);
return value;
}
} // namespace
TEST_F(ContextRepositoryTest, GetAddUpdateRemove) {
// This test ensures that we can do basic, synchronous add/update/remove/get
// operations.
// Show that when we set values, we can get them back.
auto id1 = repository_.Add(
CreateValue(ContextValueType::ENTITY, "content", nullptr));
auto value1 = repository_.Get(id1);
ASSERT_TRUE(value1);
ASSERT_FALSE(value1->meta);
EXPECT_EQ(ContextValueType::ENTITY, value1->type);
EXPECT_EQ("content", value1->content);
// Setting another value doesn't affect the original value.
auto id2 = repository_.Add(
CreateValue(ContextValueType::ENTITY, "content2", nullptr));
auto value2 = repository_.Get(id2);
ASSERT_TRUE(value2);
ASSERT_FALSE(value2->meta);
EXPECT_EQ("content2", value2->content);
value1 = repository_.Get(id1);
ASSERT_TRUE(value1);
EXPECT_EQ(ContextValueType::ENTITY, value1->type);
EXPECT_EQ("content", value1->content);
// Let's create metadata.
auto id3 = repository_.Add(
CreateValue(ContextValueType::ENTITY, "content3",
ContextMetadataBuilder().SetStoryId("id3story").Build()));
auto value3 = repository_.Get(id3);
ASSERT_TRUE(value3);
EXPECT_EQ("content3", value3->content);
ASSERT_TRUE(value3->meta);
EXPECT_EQ("id3story", value3->meta->story->id);
// Update one of the previous values.
repository_.Update(
id2,
CreateValue(ContextValueType::ENTITY, "new content2",
ContextMetadataBuilder().SetStoryId("id2story").Build()));
value2 = repository_.Get(id2);
ASSERT_TRUE(value2);
ASSERT_TRUE(value2->meta);
EXPECT_EQ("id2story", value2->meta->story->id);
EXPECT_EQ("new content2", value2->content);
// Now remove id3.
repository_.Remove(id3);
EXPECT_FALSE(repository_.Get(id3));
EXPECT_TRUE(repository_.Get(id1));
EXPECT_TRUE(repository_.Get(id2));
// And the others.
repository_.Remove(id1);
repository_.Remove(id2);
EXPECT_FALSE(repository_.Get(id1));
EXPECT_FALSE(repository_.Get(id2));
}
TEST_F(ContextRepositoryTest, ValuesInheritMetadata) {
// When a value is added as a child of another value, the child inherits the
// metadata of its parent.
ContextMetadataPtr meta1 = ContextMetadataBuilder().SetStoryId("id").Build();
auto id1 = repository_.Add(
CreateValue(ContextValueType::STORY, "s", std::move(meta1)));
ContextMetadataPtr meta2 =
ContextMetadataBuilder().SetModuleUrl("url").Build();
auto id2 = repository_.Add(
id1, CreateValue(ContextValueType::MODULE, "m", std::move(meta2)));
auto value1 = repository_.GetMerged(id1);
ASSERT_TRUE(value1);
// value1's metadata shouldn't have changed.
ASSERT_TRUE(value1->meta);
ASSERT_TRUE(value1->meta->story);
EXPECT_EQ("id", value1->meta->story->id);
ASSERT_FALSE(value1->meta->mod);
auto value2 = repository_.GetMerged(id2);
ASSERT_TRUE(value2);
// value2's metadata should combine both value1's and value2's.
ASSERT_TRUE(value2->meta);
ASSERT_TRUE(value2->meta->story);
EXPECT_EQ("id", value2->meta->story->id);
ASSERT_TRUE(value2->meta->mod);
ASSERT_TRUE(value2->meta->mod->url);
EXPECT_EQ("url", value2->meta->mod->url);
// Changing the parent's metadata value should update the child's also.
meta1 = ContextMetadata::New();
meta1->story = StoryMetadata::New();
meta1->story->id = "newid";
repository_.Update(
id1, CreateValue(ContextValueType::STORY, "s", std::move(meta1)));
value2 = repository_.GetMerged(id2);
ASSERT_TRUE(value2);
ASSERT_TRUE(value2->meta);
ASSERT_TRUE(value2->meta->story);
EXPECT_EQ("newid", value2->meta->story->id);
ASSERT_TRUE(value2->meta->mod);
ASSERT_TRUE(value2->meta->mod->url);
EXPECT_EQ("url", value2->meta->mod->url);
// If a parent contains metadata that the child also contains (they both have
// 'mod' metadata), the parent's takes precendence.
meta1 =
ContextMetadataBuilder(meta1.Clone()).SetModuleUrl("override").Build();
repository_.Update(
id1, CreateValue(ContextValueType::STORY, "s", std::move(meta1)));
value2 = repository_.GetMerged(id2);
ASSERT_TRUE(value2);
ASSERT_TRUE(value2->meta);
ASSERT_FALSE(value2->meta->story);
ASSERT_TRUE(value2->meta->mod);
ASSERT_EQ("override", value2->meta->mod->url);
}
TEST_F(ContextRepositoryTest, ListenersGetUpdates) {
// We want to test these subscription behaviors.
// 1) A value is added but doesn't match our subscription.
// a) It's the wrong type (ie, STORY vs ENTITY)
// b) Its metadata doesn't match.
// 2) A value is added that matches our existing subscription.
// 3) A value is updated that newly matches our subscription.
// 4) When a value is removed, it is no longer returned.
// (1)
auto query = ContextQuery::New();
auto selector = ContextSelector::New();
selector->type = ContextValueType::ENTITY;
selector->meta = ContextMetadataBuilder().SetEntityTopic("topic").Build();
query->selector["a"] = std::move(selector);
TestListener listener;
repository_.AddSubscription(std::move(query), &listener,
SubscriptionDebugInfoPtr());
EXPECT_EQ(0lu, listener.last_update->values["a"].size());
listener.reset();
// (a)
auto value = ContextValue::New();
value->type = ContextValueType::STORY;
value->content = "no match";
value->meta = ContextMetadataBuilder().SetEntityTopic("topic").Build();
repository_.Add(std::move(value));
// No new update because nothing changed for our subscription.
EXPECT_FALSE(listener.last_update);
listener.reset();
// (b)
value = ContextValue::New();
value->type = ContextValueType::ENTITY;
value->content = "no match yet";
value->meta =
ContextMetadataBuilder().SetEntityTopic("not the topic").Build();
auto id = repository_.Add(std::move(value)); // Save id for later.
// No new update because nothing changed for our subscription.
EXPECT_FALSE(listener.last_update);
listener.reset();
// (2)
value = ContextValue::New();
value->type = ContextValueType::ENTITY;
value->content = "match";
value->meta = ContextMetadataBuilder().SetEntityTopic("topic").Build();
repository_.Add(std::move(value));
EXPECT_EQ(1lu, listener.last_update->values["a"].size());
EXPECT_EQ("match", listener.last_update->values["a"][0]->content);
listener.reset();
// (3)
value = ContextValue::New();
value->type = ContextValueType::ENTITY;
value->content = "now it matches";
// Add more metadata than the query is looking for. It shouldn't affect
// the query, because it doesn't express any constraint on 'type'.
value->meta = ContextMetadataBuilder()
.SetEntityTopic("topic")
.AddEntityType("type1")
.AddEntityType("type2")
.Build();
repository_.Update(id, std::move(value));
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(2lu, listener.last_update->values["a"].size());
EXPECT_EQ("now it matches", listener.last_update->values["a"][0]->content);
EXPECT_EQ("match", listener.last_update->values["a"][1]->content);
listener.reset();
// (4)
repository_.Remove(id);
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(1lu, listener.last_update->values["a"].size());
EXPECT_EQ("match", listener.last_update->values["a"][0]->content);
listener.reset();
}
TEST_F(ContextRepositoryTest, ListenersGetUpdates_WhenParentsUpdated) {
// We should see updates to listeners when an update to a node's
// parent causes that node to be matched by a query.
auto query = ContextQuery::New();
auto selector = ContextSelector::New();
selector->type = ContextValueType::ENTITY;
selector->meta = ContextMetadataBuilder().SetStoryId("match").Build();
query->selector["a"] = std::move(selector);
TestListener listener;
repository_.AddSubscription(std::move(query), &listener,
SubscriptionDebugInfoPtr());
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(0lu, listener.last_update->values["a"].size());
listener.reset();
// Add a Story value.
auto story_value = ContextValue::New();
story_value->type = ContextValueType::STORY;
story_value->meta = ContextMetadataBuilder().SetStoryId("no match").Build();
auto first_story_value = story_value.Clone(); // Save for later.
auto story_value_id = repository_.Add(std::move(story_value));
// Expect no update.
EXPECT_FALSE(listener.last_update);
// Add an Entity node, but it still shouldn't match.
auto entity_value = ContextValue::New();
entity_value->type = ContextValueType::ENTITY;
entity_value->content = "content";
repository_.Add(story_value_id, std::move(entity_value));
// Still expect no update.
EXPECT_FALSE(listener.last_update);
// Update the story value so its metadata matches the query, and we should
// see the entity value returned in our update.
story_value = ContextValue::New();
story_value->type = ContextValueType::STORY;
story_value->meta = ContextMetadataBuilder().SetStoryId("match").Build();
auto matching_story_value = story_value.Clone(); // Save for later.
repository_.Update(story_value_id, std::move(story_value));
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(1lu, listener.last_update->values["a"].size());
EXPECT_EQ("content", listener.last_update->values["a"][0]->content);
// Make sure we adopted the parent metadata from the story node.
ASSERT_TRUE(listener.last_update->values["a"][0]->meta->story);
EXPECT_EQ("match", listener.last_update->values["a"][0]->meta->story->id);
listener.reset();
// Set the value back to something that doesn't match, and we should get an
// empty update.
repository_.Update(story_value_id, std::move(first_story_value));
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(0lu, listener.last_update->values["a"].size());
listener.reset();
// Set it back to something that matched, and this time remove the value
// entirely. We should observe it go away.
repository_.Update(story_value_id, std::move(matching_story_value));
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(1lu, listener.last_update->values["a"].size());
listener.reset();
repository_.Remove(story_value_id);
ASSERT_TRUE(listener.last_update);
EXPECT_EQ(0lu, listener.last_update->values["a"].size());
listener.reset();
}
} // namespace maxwell
| 36.044379
| 79
| 0.703111
|
Acidburn0zzz
|
a278813e4ddaccac4036a265740e6d7bd98c0dcc
| 688
|
cpp
|
C++
|
win32/src/Display.cpp
|
deianvn/swt-plus-plus
|
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
|
[
"Apache-2.0"
] | null | null | null |
win32/src/Display.cpp
|
deianvn/swt-plus-plus
|
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
|
[
"Apache-2.0"
] | null | null | null |
win32/src/Display.cpp
|
deianvn/swt-plus-plus
|
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
|
[
"Apache-2.0"
] | null | null | null |
#include "swt/widgets/Display.hpp"
#include <windows.h>
#include <iostream>
namespace swt
{
int Display::readAndDispatch()
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
const std::vector<Shell>& Display::getShells()
{
return shells;
}
Shell* Display::getCurrentShell()
{
return currentShell;
}
void Display::setCurrentShell(Shell* shell)
{
currentShell = shell;
}
void Display::addShell(Shell* shell)
{
shells.push_back(*shell);
}
}
| 17.2
| 50
| 0.55814
|
deianvn
|
a27a370fd9ee3abfa131633d8c39a1198ca07edf
| 416
|
cpp
|
C++
|
alex/chapter5/5.8_max_element.cpp
|
Alexhhhc/gay-school-cpp-homework
|
fa864ce1632367ef0fa269c25030e60d3a0aafac
|
[
"BSD-3-Clause"
] | null | null | null |
alex/chapter5/5.8_max_element.cpp
|
Alexhhhc/gay-school-cpp-homework
|
fa864ce1632367ef0fa269c25030e60d3a0aafac
|
[
"BSD-3-Clause"
] | null | null | null |
alex/chapter5/5.8_max_element.cpp
|
Alexhhhc/gay-school-cpp-homework
|
fa864ce1632367ef0fa269c25030e60d3a0aafac
|
[
"BSD-3-Clause"
] | null | null | null |
//例5.8
//用函数求一个矩阵中的最大元
#include <iostream>
using namespace std;
int main()
{
int max_value(int array[3][4]); //函数声明
int a[3][4]={{11,32,45,67},{22,44,66,88},{15,72,43,37}}; //定义数组并初始化
cout<<"max_value is"<<max_value(a)<<endl; //输出最大值
return 0;
}
int max_value(int array[3][4])
{
int i,j,max;
max=array[0][0];
for(i=0;i<3;i++)
for(j=0;j<4;j++)
if(array[i][j]>max)max=array[i][j];
return max; //返回最大值
}
| 20.8
| 68
| 0.605769
|
Alexhhhc
|
a27f6723c35a56017a2417fdde7b64172e160231
| 5,288
|
cpp
|
C++
|
main/FieldText.cpp
|
liebman/esp32-gps-ntp
|
75a73ee038aa825654ca1d235904e0fa9925be06
|
[
"MIT"
] | 9
|
2020-12-26T23:20:44.000Z
|
2022-03-05T17:55:14.000Z
|
main/FieldText.cpp
|
liebman/esp32-gps-ntp
|
75a73ee038aa825654ca1d235904e0fa9925be06
|
[
"MIT"
] | 1
|
2022-01-27T19:29:57.000Z
|
2022-02-10T13:19:44.000Z
|
main/FieldText.cpp
|
liebman/esp32-gps-ntp
|
75a73ee038aa825654ca1d235904e0fa9925be06
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* Copyright (c) 2020 Christopher B. Liebman
*
* 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 "FieldText.h"
#include "esp_log.h"
static const char* TAG = "FieldText";
LVStyle* FieldText::_container_style;
LVStyle* FieldText::_textarea_style;
LVKeyboard* FieldText::_keyboard;
std::function<void(void)> FieldText::_kb_submit_action;
std::function<void(void)> FieldText::_kb_cancel_action;
FieldText::FieldText(LVBase* parent, const char* label, uint16_t length, const std::function<void(void)> submit, const std::function<void(void)> cancel)
{
if (_container_style == nullptr)
{
_container_style = new LVStyle();
_container_style->setPadInner(LV_STATE_DEFAULT, LV_DPX(2));
_container_style->setPad(LV_STATE_DEFAULT, LV_DPX(1), LV_DPX(1), LV_DPX(1), LV_DPX(1));
_container_style->setMargin(LV_STATE_DEFAULT, 0, 0, 0, 0);
_container_style->setBorderWidth(LV_STATE_DEFAULT, 0);
_container_style->setShadowWidth(LV_STATE_DEFAULT, 0);
}
if (_textarea_style == nullptr)
{
_textarea_style = new LVStyle();
_textarea_style->setPadInner(LV_STATE_DEFAULT, LV_DPX(2));
_textarea_style->setPad(LV_STATE_DEFAULT, LV_DPX(1), LV_DPX(1), LV_DPX(1), LV_DPX(1));
_textarea_style->setMargin(LV_STATE_DEFAULT, 0, 0, 0, 0);
_textarea_style->setBorderWidth(LV_STATE_DEFAULT, 1);
_textarea_style->setShadowWidth(LV_STATE_DEFAULT, 0);
}
if (_keyboard == nullptr)
{
_keyboard = new LVKeyboard(nullptr);
_keyboard->setCurserManage(true);
_keyboard->setHidden(true);
_keyboard->setX(0);
_keyboard->setEventCB([this](lv_event_t event) {
_keyboard->defaultEventCB(event);
//ESP_LOGI(TAG, "_keyboard event: %s", _keyboard->getEventName(event));
switch (event)
{
case LV_EVENT_APPLY:
if (_kb_submit_action)
{
_kb_submit_action();
_kb_submit_action = nullptr;
}
_keyboard->setTextArea(nullptr);
_keyboard->setHidden(true);
break;
case LV_EVENT_CANCEL:
if (_kb_cancel_action)
{
_kb_cancel_action();
_kb_cancel_action = nullptr;
}
_keyboard->setTextArea(nullptr);
_keyboard->setHidden(true);
break;
default:
break;
}
});
}
_cont = new LVContainer(parent);
_cont->addStyle(LV_CONT_PART_MAIN, _container_style);
_cont->setFit(LV_FIT_TIGHT);
//_cont->setLayout(LV_LAYOUT_ROW_MID);
_cont->setDragParent(true);
_label = new LVLabel(_cont);
_label->setStaticText(label);
_label->setDragParent(true);
_label->align(_cont, LV_ALIGN_IN_TOP_LEFT, 0, 0);
_textarea = new LVTextArea(_cont);
_textarea->addStyle(LV_TEXTAREA_PART_BG, _textarea_style);
_textarea->setOneLine(true);
_textarea->setMaxLength(length);
_textarea->setPlaceholderText("");
_textarea->setText("");
_textarea->setCurserHidden(true);
_textarea->align(_label, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
_textarea->setEventCB([this, submit, cancel](lv_event_t event){
switch (event)
{
case LV_EVENT_PRESSED:
ESP_LOGI(TAG, "keyboard points to '%s'", _label->getText());
// setup the kb actions to cancle or save
_kb_submit_action = submit;
_kb_cancel_action = cancel;
_keyboard->setMode(_mode);
_keyboard->setTextArea(_textarea);
_keyboard->setParent(_cont);
_keyboard->alignY(_label, LV_ALIGN_OUT_BOTTOM_LEFT, 0);
_keyboard->setHidden(false);
break;
default:
break;
}
});
}
void FieldText::setText(const char* text)
{
_textarea->setText(text);
}
const char* FieldText::getText()
{
return _textarea->getText();
}
void FieldText::setPasswordMode(bool en)
{
_textarea->setPasswordMode(en);
}
void FieldText::setKeyboardMode(lv_keyboard_mode_t mode)
{
_mode = mode;
}
| 34.562092
| 152
| 0.647126
|
liebman
|
a2839bb0b3aeee53b85e5c825847670f870f5299
| 8,942
|
cpp
|
C++
|
AnalyzerExamples/SpiAnalyzer/SpiAnalyzer.cpp
|
blargony/RFFEAnalyzer
|
24684cee1494f5ac4bd7d9c9f020f42248a06f89
|
[
"MIT"
] | 15
|
2015-06-23T23:28:24.000Z
|
2022-03-12T03:23:31.000Z
|
AnalyzerExamples/SpiAnalyzer/SpiAnalyzer.cpp
|
blargony/RFFEAnalyzer
|
24684cee1494f5ac4bd7d9c9f020f42248a06f89
|
[
"MIT"
] | 3
|
2015-06-23T23:41:48.000Z
|
2022-03-16T22:20:50.000Z
|
AnalyzerExamples/SpiAnalyzer/SpiAnalyzer.cpp
|
blargony/RFFEAnalyzer
|
24684cee1494f5ac4bd7d9c9f020f42248a06f89
|
[
"MIT"
] | 3
|
2015-06-23T23:28:30.000Z
|
2020-07-30T15:46:04.000Z
|
#include "SpiAnalyzer.h"
#include "SpiAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
//enum SpiBubbleType { SpiData, SpiError };
SpiAnalyzer::SpiAnalyzer()
: Analyzer2(),
mSettings( new SpiAnalyzerSettings() ),
mSimulationInitilized( false ),
mMosi( NULL ),
mMiso( NULL ),
mClock( NULL ),
mEnable( NULL )
{
SetAnalyzerSettings( mSettings.get() );
}
SpiAnalyzer::~SpiAnalyzer()
{
KillThread();
}
void SpiAnalyzer::SetupResults()
{
mResults.reset( new SpiAnalyzerResults( this, mSettings.get() ) );
SetAnalyzerResults( mResults.get() );
if( mSettings->mMosiChannel != UNDEFINED_CHANNEL )
mResults->AddChannelBubblesWillAppearOn( mSettings->mMosiChannel );
if( mSettings->mMisoChannel != UNDEFINED_CHANNEL )
mResults->AddChannelBubblesWillAppearOn( mSettings->mMisoChannel );
}
void SpiAnalyzer::WorkerThread()
{
Setup();
AdvanceToActiveEnableEdgeWithCorrectClockPolarity();
for( ; ; )
{
GetWord();
CheckIfThreadShouldExit();
}
}
void SpiAnalyzer::AdvanceToActiveEnableEdgeWithCorrectClockPolarity()
{
mResults->CommitPacketAndStartNewPacket();
mResults->CommitResults();
AdvanceToActiveEnableEdge();
for( ; ; )
{
if( IsInitialClockPolarityCorrect() == true ) //if false, this function moves to the next active enable edge.
break;
}
}
void SpiAnalyzer::Setup()
{
bool allow_last_trailing_clock_edge_to_fall_outside_enable = false;
if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge )
allow_last_trailing_clock_edge_to_fall_outside_enable = true;
if( mSettings->mClockInactiveState == BIT_LOW )
{
if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge )
mArrowMarker = AnalyzerResults::UpArrow;
else
mArrowMarker = AnalyzerResults::DownArrow;
}else
{
if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge )
mArrowMarker = AnalyzerResults::DownArrow;
else
mArrowMarker = AnalyzerResults::UpArrow;
}
if( mSettings->mMosiChannel != UNDEFINED_CHANNEL )
mMosi = GetAnalyzerChannelData( mSettings->mMosiChannel );
else
mMosi = NULL;
if( mSettings->mMisoChannel != UNDEFINED_CHANNEL )
mMiso = GetAnalyzerChannelData( mSettings->mMisoChannel );
else
mMiso = NULL;
mClock = GetAnalyzerChannelData( mSettings->mClockChannel );
if( mSettings->mEnableChannel != UNDEFINED_CHANNEL )
mEnable = GetAnalyzerChannelData( mSettings->mEnableChannel );
else
mEnable = NULL;
}
void SpiAnalyzer::AdvanceToActiveEnableEdge()
{
if( mEnable != NULL )
{
if( mEnable->GetBitState() != mSettings->mEnableActiveState )
{
mEnable->AdvanceToNextEdge();
}else
{
mEnable->AdvanceToNextEdge();
mEnable->AdvanceToNextEdge();
}
mCurrentSample = mEnable->GetSampleNumber();
mClock->AdvanceToAbsPosition( mCurrentSample );
}else
{
mCurrentSample = mClock->GetSampleNumber();
}
}
bool SpiAnalyzer::IsInitialClockPolarityCorrect()
{
if( mClock->GetBitState() == mSettings->mClockInactiveState )
return true;
mResults->AddMarker( mCurrentSample, AnalyzerResults::ErrorSquare, mSettings->mClockChannel );
if( mEnable != NULL )
{
Frame error_frame;
error_frame.mStartingSampleInclusive = mCurrentSample;
mEnable->AdvanceToNextEdge();
mCurrentSample = mEnable->GetSampleNumber();
error_frame.mEndingSampleInclusive = mCurrentSample;
error_frame.mFlags = SPI_ERROR_FLAG | DISPLAY_AS_ERROR_FLAG;
mResults->AddFrame( error_frame );
mResults->CommitResults();
ReportProgress( error_frame.mEndingSampleInclusive );
//move to the next active-going enable edge
mEnable->AdvanceToNextEdge();
mCurrentSample = mEnable->GetSampleNumber();
mClock->AdvanceToAbsPosition( mCurrentSample );
return false;
}else
{
mClock->AdvanceToNextEdge(); //at least start with the clock in the idle state.
mCurrentSample = mClock->GetSampleNumber();
return true;
}
}
bool SpiAnalyzer::WouldAdvancingTheClockToggleEnable()
{
if( mEnable == NULL )
return false;
U64 next_edge = mClock->GetSampleOfNextEdge();
bool enable_will_toggle = mEnable->WouldAdvancingToAbsPositionCauseTransition( next_edge );
if( enable_will_toggle == false )
return false;
else
return true;
}
void SpiAnalyzer::GetWord()
{
//we're assuming we come into this function with the clock in the idle state;
U32 bits_per_transfer = mSettings->mBitsPerTransfer;
DataBuilder mosi_result;
U64 mosi_word = 0;
mosi_result.Reset( &mosi_word, mSettings->mShiftOrder, bits_per_transfer );
DataBuilder miso_result;
U64 miso_word = 0;
miso_result.Reset( &miso_word, mSettings->mShiftOrder, bits_per_transfer );
U64 first_sample = 0;
bool need_reset = false;
mArrowLocations.clear();
ReportProgress( mClock->GetSampleNumber() );
for( U32 i=0; i<bits_per_transfer; i++ )
{
//on every single edge, we need to check that enable doesn't toggle.
//note that we can't just advance the enable line to the next edge, becuase there may not be another edge
if( WouldAdvancingTheClockToggleEnable() == true )
{
AdvanceToActiveEnableEdgeWithCorrectClockPolarity(); //ok, we pretty much need to reset everything and return.
return;
}
mClock->AdvanceToNextEdge();
if( i == 0 )
first_sample = mClock->GetSampleNumber();
if( mSettings->mDataValidEdge == AnalyzerEnums::LeadingEdge )
{
mCurrentSample = mClock->GetSampleNumber();
if( mMosi != NULL )
{
mMosi->AdvanceToAbsPosition( mCurrentSample );
mosi_result.AddBit( mMosi->GetBitState() );
}
if( mMiso != NULL )
{
mMiso->AdvanceToAbsPosition( mCurrentSample );
miso_result.AddBit( mMiso->GetBitState() );
}
mArrowLocations.push_back( mCurrentSample );
}
// ok, the trailing edge is messy -- but only on the very last bit.
// If the trialing edge isn't doesn't represent valid data, we want to allow the enable line to rise before the clock trialing edge -- and still report the frame
if( ( i == ( bits_per_transfer - 1 ) ) && ( mSettings->mDataValidEdge != AnalyzerEnums::TrailingEdge ) )
{
//if this is the last bit, and the trailing edge doesn't represent valid data
if( WouldAdvancingTheClockToggleEnable() == true )
{
//moving to the trailing edge would cause the clock to revert to inactive. jump out, record the frame, and them move to the next active enable edge
need_reset = true;
break;
}
//enable isn't going to go inactive, go ahead and advance the clock as usual. Then we're done, jump out and record the frame.
mClock->AdvanceToNextEdge();
break;
}
//this isn't the very last bit, etc, so proceed as normal
if( WouldAdvancingTheClockToggleEnable() == true )
{
AdvanceToActiveEnableEdgeWithCorrectClockPolarity(); //ok, we pretty much need to reset everything and return.
return;
}
mClock->AdvanceToNextEdge();
if( mSettings->mDataValidEdge == AnalyzerEnums::TrailingEdge )
{
mCurrentSample = mClock->GetSampleNumber();
if( mMosi != NULL )
{
mMosi->AdvanceToAbsPosition( mCurrentSample );
mosi_result.AddBit( mMosi->GetBitState() );
}
if( mMiso != NULL )
{
mMiso->AdvanceToAbsPosition( mCurrentSample );
miso_result.AddBit( mMiso->GetBitState() );
}
mArrowLocations.push_back( mCurrentSample );
}
}
//save the resuls:
U32 count = mArrowLocations.size();
for( U32 i=0; i<count; i++ )
mResults->AddMarker( mArrowLocations[i], mArrowMarker, mSettings->mClockChannel );
Frame result_frame;
result_frame.mStartingSampleInclusive = first_sample;
result_frame.mEndingSampleInclusive = mClock->GetSampleNumber();
result_frame.mData1 = mosi_word;
result_frame.mData2 = miso_word;
result_frame.mFlags = 0;
mResults->AddFrame( result_frame );
mResults->CommitResults();
if( need_reset == true )
AdvanceToActiveEnableEdgeWithCorrectClockPolarity();
}
bool SpiAnalyzer::NeedsRerun()
{
return false;
}
U32 SpiAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
if( mSimulationInitilized == false )
{
mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
mSimulationInitilized = true;
}
return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels );
}
U32 SpiAnalyzer::GetMinimumSampleRateHz()
{
return 10000; //we don't have any idea, depends on the SPI rate, etc.; return the lowest rate.
}
const char* SpiAnalyzer::GetAnalyzerName() const
{
return "SPI";
}
const char* GetAnalyzerName()
{
return "SPI";
}
Analyzer* CreateAnalyzer()
{
return new SpiAnalyzer();
}
void DestroyAnalyzer( Analyzer* analyzer )
{
delete analyzer;
}
| 27.015106
| 164
| 0.708454
|
blargony
|
a2840ffffa6f81dec80b567d6c793b5d06851f60
| 24,378
|
hpp
|
C++
|
include/boost/text/normalize.hpp
|
jan-moeller/text
|
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
|
[
"BSL-1.0"
] | null | null | null |
include/boost/text/normalize.hpp
|
jan-moeller/text
|
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
|
[
"BSL-1.0"
] | null | null | null |
include/boost/text/normalize.hpp
|
jan-moeller/text
|
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
|
[
"BSL-1.0"
] | null | null | null |
#ifndef BOOST_TEXT_NORMALIZE_HPP
#define BOOST_TEXT_NORMALIZE_HPP
#include <boost/text/utility.hpp>
#include <boost/text/detail/normalization_data.hpp>
#include <boost/container/static_vector.hpp>
#include <algorithm>
namespace boost { namespace text {
namespace detail {
template<typename Iter, std::size_t Capacity>
void order_canonically(
Iter first,
Iter last,
container::static_vector<int, Capacity> & cccs) noexcept
{
BOOST_ASSERT(first != last);
std::transform(first, last, cccs.begin(), ccc);
--last;
while (first != last) {
auto it = first;
auto new_last = first;
auto ccc_it = cccs.begin();
while (it != last) {
auto next = std::next(it);
auto ccc_next = std::next(ccc_it);
auto const ccc_a = *ccc_it;
auto const ccc_b = *ccc_next;
if (0 < ccc_b && ccc_b < ccc_a) {
std::iter_swap(it, next);
std::iter_swap(ccc_it, ccc_next);
new_last = it;
}
++it;
++ccc_it;
}
last = new_last;
}
}
template<std::size_t Capacity, typename FlushFunc>
bool flush_buffer(
container::static_vector<uint32_t, Capacity> & buffer,
FlushFunc & flush)
{
container::static_vector<int, Capacity> cccs(buffer.size());
if (!buffer.empty())
order_canonically(buffer.begin(), buffer.end(), cccs);
if (!flush(buffer.begin(), buffer.end()))
return false;
buffer.clear();
return true;
}
template<
typename Iter,
typename Sentinel,
std::size_t Capacity,
typename DecomposeFunc,
typename FlushFunc>
bool normalize_to_decomposed_impl(
Iter first,
Sentinel last,
container::static_vector<uint32_t, Capacity> & buffer,
DecomposeFunc && decompose,
FlushFunc && flush)
{
while (first != last) {
auto const decomp = decompose(*first);
if (!ccc(decomp.storage_[0])) {
if (!detail::flush_buffer(buffer, flush))
return false;
}
buffer.insert(buffer.end(), decomp.begin(), decomp.end());
++first;
}
if (!detail::flush_buffer(buffer, flush))
return false;
return true;
}
template<
typename Iter,
typename Sentinel,
typename OutIter,
typename DecomposeFunc>
OutIter normalize_to_decomposed(
Iter first, Sentinel last, OutIter out, DecomposeFunc && decompose)
{
container::static_vector<uint32_t, 64> buffer;
using buffer_iterator =
container::static_vector<uint32_t, 64>::iterator;
normalize_to_decomposed_impl(
first,
last,
buffer,
decompose,
[&out](buffer_iterator first, buffer_iterator last) {
out = std::copy(first, last, out);
return true;
});
return out;
}
inline constexpr bool hangul_l(uint32_t cp) noexcept
{
return 0x1100 <= cp && cp <= 0x1112;
}
inline constexpr bool hangul_v(uint32_t cp) noexcept
{
return 0x1161 <= cp && cp <= 0x1175;
}
inline constexpr bool hangul_t(uint32_t cp) noexcept
{
return 0x11a8 <= cp && cp <= 0x11c2;
}
template<bool DisallowDiscontiguous, std::size_t Capacity>
void compose(
container::static_vector<uint32_t, Capacity> & buffer,
container::static_vector<int, Capacity> & cccs)
{
BOOST_ASSERT(buffer.size() == cccs.size());
BOOST_ASSERT(2 <= buffer.size());
auto starter_it = buffer.begin();
auto it = std::next(buffer.begin());
auto ccc_it = std::next(cccs.begin());
while (it != buffer.end()) {
// Hangul composition as described in Unicode 11.0 Section 3.12.
auto const hangul_cp0 = *starter_it;
auto const hangul_cp1 = *it;
if (it == starter_it + 1 && hangul_l(hangul_cp0) &&
hangul_v(hangul_cp1)) {
auto const cp2_it = it + 1;
auto const hangul_cp2 =
cp2_it == buffer.end() ? 0 : *cp2_it;
if (hangul_t(hangul_cp2)) {
*starter_it =
compose_hangul(hangul_cp0, hangul_cp1, hangul_cp2);
buffer.erase(it, it + 2);
cccs.erase(ccc_it, ccc_it + 2);
} else {
*starter_it = compose_hangul(hangul_cp0, hangul_cp1);
buffer.erase(it, it + 1);
cccs.erase(ccc_it, ccc_it + 1);
}
} else {
auto const prev_ccc = *std::prev(ccc_it);
auto const ccc = *ccc_it;
uint32_t composition = 0;
if ((it == starter_it + 1 ||
(!DisallowDiscontiguous &&
(prev_ccc != 0 && prev_ccc < ccc))) &&
(composition = compose_unblocked(*starter_it, *it))) {
*starter_it = composition;
buffer.erase(it);
cccs.erase(ccc_it);
} else {
++it;
++ccc_it;
if (it == buffer.end() &&
starter_it < buffer.end() - 2) {
++starter_it;
it = std::next(starter_it);
ccc_it = cccs.begin() + (it - buffer.begin());
}
}
}
}
}
template<
bool DisallowDiscontiguous,
std::size_t Capacity,
typename FlushFunc>
bool compose_and_flush_buffer(
container::static_vector<uint32_t, Capacity> & buffer,
FlushFunc &&
flush) noexcept(noexcept(flush(buffer.begin(), buffer.end())))
{
container::static_vector<int, Capacity> cccs(buffer.size());
if (!buffer.empty())
order_canonically(buffer.begin(), buffer.end(), cccs);
if (2 <= buffer.size())
compose<DisallowDiscontiguous>(buffer, cccs);
if (!flush(buffer.begin(), buffer.end()))
return false;
buffer.clear();
return true;
}
template<std::size_t Capacity>
bool hangul_final_v(
container::static_vector<uint32_t, Capacity> & buffer,
uint32_t cp) noexcept
{
return !buffer.empty() && hangul_l(buffer.back()) && hangul_v(cp);
}
template<std::size_t Capacity>
bool hangul_final_t(
container::static_vector<uint32_t, Capacity> & buffer,
uint32_t cp) noexcept
{
return 2 <= buffer.size() && hangul_l(buffer[buffer.size() - 2]) &&
hangul_v(buffer.back()) && hangul_t(cp);
}
template<
bool DisallowDiscontiguous,
typename Iter,
typename Sentinel,
std::size_t Capacity,
typename DecomposeFunc,
typename QuickCheckFunc,
typename FlushFunc>
bool normalize_to_composed_impl(
Iter first,
Sentinel last,
container::static_vector<uint32_t, Capacity> & buffer,
DecomposeFunc && decompose,
QuickCheckFunc && quick_check_,
FlushFunc && flush) noexcept
{
while (first != last) {
auto const decomp = decompose(*first);
auto const it = std::find_if(
decomp.begin(), decomp.end(), [&quick_check_](uint32_t cp) {
return !ccc(cp) && quick_check_(cp) == quick_check::yes;
});
if (it != decomp.end() && !hangul_final_v(buffer, *it) &&
!hangul_final_t(buffer, *it)) {
buffer.insert(buffer.end(), decomp.begin(), it);
if (!detail::compose_and_flush_buffer<
DisallowDiscontiguous>(buffer, flush)) {
return false;
}
buffer.insert(buffer.end(), it, decomp.end());
} else {
buffer.insert(buffer.end(), decomp.begin(), decomp.end());
}
++first;
}
if (!detail::compose_and_flush_buffer<DisallowDiscontiguous>(
buffer, flush)) {
return false;
}
return true;
}
template<
bool DisallowDiscontiguous,
typename Iter,
typename Sentinel,
typename OutIter,
typename DecomposeFunc,
typename QuickCheckFunc>
OutIter normalize_to_composed(
Iter first,
Sentinel last,
OutIter out,
DecomposeFunc && decompose,
QuickCheckFunc && quick_check_)
{
container::static_vector<uint32_t, 64> buffer;
using buffer_iterator =
container::static_vector<uint32_t, 64>::iterator;
normalize_to_composed_impl<DisallowDiscontiguous>(
first,
last,
buffer,
decompose,
quick_check_,
[&out](buffer_iterator first, buffer_iterator last) {
out = std::copy(first, last, out);
return true;
});
return out;
}
#if 0
// NOTE: The logic in
// http://www.unicode.org/reports/tr15/tr15-45.html#Detecting_Normalization_Forms
// seems to indicate that if a supplementary code point is encountered
// in normalized_quick_check(), then we should proceed as normal for
// this iteration, but then do a double increment of the loop control
// variable. That looks wrong, so I'm leaving that out for now.
bool supplemantary(uint32_t cp)
{
return 0x10000 <= cp && cp <= 0x10FFFF;
}
#endif
// TODO: Experiment with writing out the ccc values for reuse in case
// the result is not quick_check::yes.
template<typename Iter, typename Sentinel, typename QuickCheckFunc>
quick_check normalized_quick_check(
Iter first, Sentinel last, QuickCheckFunc && quick_check_) noexcept
{
quick_check retval = quick_check::yes;
int prev_ccc = 0;
while (first != last) {
auto const cp = *first;
#if 0
// See note above.
if (supplemantary(cp))
++first;
#endif
auto const check = quick_check_(cp);
if (check == quick_check::no)
return quick_check::no;
if (check == quick_check::maybe)
retval = quick_check::maybe;
auto const ccc_ = ccc(cp);
if (ccc_ && ccc_ < prev_ccc)
return quick_check::no;
prev_ccc = ccc_;
++first;
}
return retval;
}
template<
typename Iter,
typename Sentinel,
typename DecomposeFunc,
typename QuickCheckFunc>
bool normalized_decomposed(
Iter first,
Sentinel last,
DecomposeFunc && decompose,
QuickCheckFunc && quick_check_) noexcept
{
auto const check =
normalized_quick_check(first, last, quick_check_);
if (check == quick_check::maybe) {
container::static_vector<uint32_t, 64> buffer;
using buffer_iterator =
container::static_vector<uint32_t, 64>::iterator;
return normalize_to_decomposed_impl(
first,
last,
buffer,
decompose,
[&first, last](
buffer_iterator buffer_first,
buffer_iterator buffer_last) {
while (first != last && buffer_first != buffer_last) {
if (*first++ != *buffer_first++)
return false;
}
return true;
});
}
return check == quick_check::yes;
}
template<
typename Iter,
typename Sentinel,
typename DecomposeFunc,
typename QuickCheckFunc>
bool normalized_composed(
Iter first,
Sentinel last,
DecomposeFunc && decompose,
QuickCheckFunc && quick_check_) noexcept
{
auto const check =
normalized_quick_check(first, last, quick_check_);
if (check == quick_check::maybe) {
container::static_vector<uint32_t, 64> buffer;
using buffer_iterator =
container::static_vector<uint32_t, 64>::iterator;
return normalize_to_composed_impl<false>(
first,
last,
buffer,
decompose,
quick_check_,
[&first, last](
buffer_iterator buffer_first,
buffer_iterator buffer_last) {
while (first != last && buffer_first != buffer_last) {
if (*first++ != *buffer_first++)
return false;
}
return true;
});
}
return check == quick_check::yes;
}
}
/** Writes sequence <code>[first, last)</code> in Unicode normalization
form NFD to <code>out</code>.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel, typename OutIter>
inline auto normalize_to_nfd(CPIter first, Sentinel last, OutIter out)
-> detail::cp_iter_ret_t<OutIter, CPIter>
{
return detail::normalize_to_decomposed(
first, last, out, [](uint32_t cp) {
return detail::canonical_decompose(cp);
});
}
/** Writes sequence <code>r</code> in Unicode normalization form NFD to
<code>out</code>. */
template<typename CPRange, typename OutIter>
inline OutIter normalize_to_nfd(CPRange const & r, OutIter out)
{
return normalize_to_nfd(std::begin(r), std::end(r), out);
}
/** Writes sequence <code>[first, last)</code> in Unicode normalization
form NFKD to <code>out</code>.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel, typename OutIter>
inline auto normalize_to_nfkd(CPIter first, Sentinel last, OutIter out)
-> detail::cp_iter_ret_t<OutIter, CPIter>
{
return detail::normalize_to_decomposed(
first, last, out, [](uint32_t cp) {
return detail::compatible_decompose(cp);
});
}
/** Writes sequence <code>r</code> in Unicode normalization form NFKD to
* <code>out</code>. */
template<typename CPRange, typename OutIter>
inline OutIter normalize_to_nfkd(CPRange const & r, OutIter out)
{
return normalize_to_nfkd(std::begin(r), std::end(r), out);
}
/** Writes sequence <code>[first, last)</code> in Unicode normalization
form NFC to <code>out</code>.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel, typename OutIter>
inline auto normalize_to_nfc(CPIter first, Sentinel last, OutIter out)
-> detail::cp_iter_ret_t<OutIter, CPIter>
{
return detail::normalize_to_composed<false>(
first,
last,
out,
[](uint32_t cp) { return detail::canonical_decompose(cp); },
[](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); });
}
/** Writes sequence <code>r</code> in Unicode normalization form NFC to
* <code>out</code>. */
template<typename CPRange, typename OutIter>
inline OutIter normalize_to_nfc(CPRange const & r, OutIter out)
{
return normalize_to_nfc(std::begin(r), std::end(r), out);
}
/** Writes sequence <code>[first, last)</code> in Unicode normalization
form NFKC to <code>out</code>.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel, typename OutIter>
inline auto normalize_to_nfkc(CPIter first, Sentinel last, OutIter out)
-> detail::cp_iter_ret_t<OutIter, CPIter>
{
return detail::normalize_to_composed<false>(
first,
last,
out,
[](uint32_t cp) { return detail::compatible_decompose(cp); },
[](uint32_t cp) {
return detail::quick_check_nfkc_code_point(cp);
});
}
/** Writes sequence <code>r</code> in Unicode normalization form NFKC to
* <code>out</code>. */
template<typename CPRange, typename OutIter>
inline OutIter normalize_to_nfkc(CPRange const & r, OutIter out)
{
return normalize_to_nfkc(std::begin(r), std::end(r), out);
}
/** Returns true iff the given sequence of code points is normalized
NFD.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel>
auto normalized_nfd(CPIter first, Sentinel last) noexcept
-> detail::cp_iter_ret_t<bool, CPIter>
{
return detail::normalized_decomposed(
first,
last,
[](uint32_t cp) { return detail::canonical_decompose(cp); },
[](uint32_t cp) { return detail::quick_check_nfd_code_point(cp); });
}
/** Returns true iff the given range of code points is normalized
NFD. */
template<typename CPRange>
bool normalized_nfd(CPRange const & r) noexcept
{
return normalized_nfd(std::begin(r), std::end(r));
}
/** Returns true iff the given sequence of code points is normalized
NFKD.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel>
auto normalized_nfkd(CPIter first, Sentinel last) noexcept
-> detail::cp_iter_ret_t<bool, CPIter>
{
return detail::normalized_decomposed(
first,
last,
[](uint32_t cp) { return detail::compatible_decompose(cp); },
[](uint32_t cp) {
return detail::quick_check_nfkd_code_point(cp);
});
}
/** Returns true iff the given range of code points is normalized
NFKD. */
template<typename CPRange>
bool normalized_nfkd(CPRange const & r) noexcept
{
return normalized_nfkd(std::begin(r), std::end(r));
}
/** Returns true iff the given sequence of code points is normalized
NFC.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel>
auto normalized_nfc(CPIter first, Sentinel last) noexcept
-> detail::cp_iter_ret_t<bool, CPIter>
{
return detail::normalized_composed(
first,
last,
[](uint32_t cp) { return detail::canonical_decompose(cp); },
[](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); });
}
/** Returns true iff the given range of code points is normalized
NFC. */
template<typename CPRange>
bool normalized_nfc(CPRange const & r) noexcept
{
return normalized_nfc(std::begin(r), std::end(r));
}
/** Returns true iff the given sequence of code points is normalized
NFKC.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel>
auto normalized_nfkc(CPIter first, Sentinel last) noexcept
-> detail::cp_iter_ret_t<bool, CPIter>
{
return detail::normalized_composed(
first,
last,
[](uint32_t cp) { return detail::compatible_decompose(cp); },
[](uint32_t cp) {
return detail::quick_check_nfkc_code_point(cp);
});
}
/** Returns true iff the given range of code points is normalized
NFKC. */
template<typename CPRange>
bool normalized_nfkc(CPRange const & r) noexcept
{
return normalized_nfkc(std::begin(r), std::end(r));
}
/** Returns true iff the given sequence of code points is in an FCD
form.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept. */
template<typename CPIter, typename Sentinel>
auto fcd_form(CPIter first, Sentinel last) noexcept
-> detail::cp_iter_ret_t<bool, CPIter>
{
// http://www.unicode.org/notes/tn5/#FCD_Test
int prev_ccc = 0;
while (first != last) {
auto const cp = *first;
auto const decomp = detail::canonical_decompose(cp);
auto const ccc = detail::ccc(*decomp.begin());
if (ccc && ccc < prev_ccc)
return false;
prev_ccc =
decomp.size_ == 1 ? ccc : detail::ccc(*(decomp.end() - 1));
++first;
}
return true;
}
/** Returns true iff the given range of code points is in an FCD form. */
template<typename CPRange>
bool fcd_form(CPRange const & r) noexcept
{
return fcd_form(std::begin(r), std::end(r));
}
/** Writes sequence <code>[first, last)</code> in normalization
form FCC to <code>out</code>.
This function only participates in overload resolution if
<code>CPIter</code> models the CPIter concept.
\see https://unicode.org/notes/tn5
*/
template<typename CPIter, typename Sentinel, typename OutIter>
inline auto normalize_to_fcc(CPIter first, Sentinel last, OutIter out)
-> detail::cp_iter_ret_t<OutIter, CPIter>
{
return detail::normalize_to_composed<true>(
first,
last,
out,
[](uint32_t cp) { return detail::canonical_decompose(cp); },
[](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); });
}
/** Writes sequence <code>r</code> in normalization form FCC to
<code>out</code>.
\see https://unicode.org/notes/tn5
*/
template<typename CPRange, typename OutIter>
inline OutIter normalize_to_fcc(CPRange const & r, OutIter out)
{
return normalize_to_fcc(std::begin(r), std::end(r), out);
}
}}
#endif
| 36.330849
| 89
| 0.533145
|
jan-moeller
|
a286214987b0d5bc0e6b30aaf759eac0a030398a
| 118
|
cpp
|
C++
|
stack/tempCodeRunnerFile.cpp
|
yusufkhan004/DSA-practice-problems
|
04e0ea2b311a63a38fbf9d28e974b266da1a60a1
|
[
"MIT"
] | null | null | null |
stack/tempCodeRunnerFile.cpp
|
yusufkhan004/DSA-practice-problems
|
04e0ea2b311a63a38fbf9d28e974b266da1a60a1
|
[
"MIT"
] | null | null | null |
stack/tempCodeRunnerFile.cpp
|
yusufkhan004/DSA-practice-problems
|
04e0ea2b311a63a38fbf9d28e974b266da1a60a1
|
[
"MIT"
] | null | null | null |
// st.pop();
// cout << st.Top() << endl;
// st.pop();
// st.pop();
// st.pop();
// cout << st.em
| 19.666667
| 32
| 0.347458
|
yusufkhan004
|
a287bde9e3020f15b712a9521be0a95bb82b6aea
| 277
|
cpp
|
C++
|
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
|
AhmedRamadan6/Codeforces
|
efd61d610243160381491f44702b5634b004e5fb
|
[
"MIT"
] | 1
|
2020-04-13T00:45:25.000Z
|
2020-04-13T00:45:25.000Z
|
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
|
AhmedRamadan6/Codeforces
|
efd61d610243160381491f44702b5634b004e5fb
|
[
"MIT"
] | null | null | null |
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
|
AhmedRamadan6/Codeforces
|
efd61d610243160381491f44702b5634b004e5fb
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int c[n-1];
for (int i=0;i<n;i++)
cin >> c[i];
sort(c,c+n);
for (int i=0;i<n;i++)
cout << c[i] << " " ;
return 0;
}
| 17.3125
| 30
| 0.418773
|
AhmedRamadan6
|
a2922759fb4b76a506c8637d71d5c458986bcbe6
| 341
|
cpp
|
C++
|
ZZZ_OtherDemo/00-dyld-832.7.3/testing/kernel-cache-tests/auxkc-vtable-metaclass-patching/foo.cpp
|
1079278593/TreasureChest
|
8b1ebe04ed7c2ed399c4ecf3b75b3fee0a1aced8
|
[
"MIT"
] | null | null | null |
ZZZ_OtherDemo/00-dyld-832.7.3/testing/kernel-cache-tests/auxkc-vtable-metaclass-patching/foo.cpp
|
1079278593/TreasureChest
|
8b1ebe04ed7c2ed399c4ecf3b75b3fee0a1aced8
|
[
"MIT"
] | null | null | null |
ZZZ_OtherDemo/00-dyld-832.7.3/testing/kernel-cache-tests/auxkc-vtable-metaclass-patching/foo.cpp
|
1079278593/TreasureChest
|
8b1ebe04ed7c2ed399c4ecf3b75b3fee0a1aced8
|
[
"MIT"
] | null | null | null |
#include "foo.h"
#include <memory.h>
void* operator new(size_t size) { return (void*)1; }
void operator delete(void*) { }
OSDefineMetaClassAndStructors( Foo, OSObject )
OSMetaClassDefineReservedUnused( Foo, 0 )
OSMetaClassDefineReservedUnused( Foo, 1 )
OSMetaClassDefineReservedUnused( Foo, 2 )
OSMetaClassDefineReservedUnused( Foo, 3 )
| 24.357143
| 52
| 0.771261
|
1079278593
|
a2942b9f952745a967812b3fde5c4e6ddeac6068
| 12,519
|
cpp
|
C++
|
computation.cpp
|
hotzevzl/marxan
|
23ba3a0ada90e721c745b922363458bece3477dc
|
[
"MIT"
] | 5
|
2021-02-16T07:50:47.000Z
|
2021-09-14T00:17:13.000Z
|
computation.cpp
|
hotzevzl/marxan
|
23ba3a0ada90e721c745b922363458bece3477dc
|
[
"MIT"
] | 7
|
2021-02-17T00:03:09.000Z
|
2021-10-05T14:46:22.000Z
|
computation.cpp
|
hotzevzl/marxan
|
23ba3a0ada90e721c745b922363458bece3477dc
|
[
"MIT"
] | 2
|
2020-10-02T18:08:17.000Z
|
2021-06-18T09:03:01.000Z
|
// All functions here should be unit and should not have dependencies on the core marxan files.
#include <algorithm>
#include "computation.hpp"
#include "marxan.hpp"
#include "utils.hpp"
namespace marxan {
// Sums all connectivity edges for a pu.
double connectionCost1(const sconnections& connections, double cm, int asymmetricconnectivity)
{
double fcost;
fcost = connections.fixedcost;
for (const auto& p : connections.first)
{
if (asymmetricconnectivity)
{
if (p.connectionorigon)
fcost += p.cost;
}
else
{
fcost += p.cost;
}
}
return (fcost * cm);
}
/*** Counts the number of species missing from the reserve ****/
// compute the number of species whose representation fraction is less that the MISSLEVEL parameter
int computeRepresentationMISSLEVEL(int spno, const vector<sspecies>& spec, double misslevel, double& shortfall, double& rMinimumProportionMet)
{
int i, isp = 0;
double rProportionMet;
shortfall = 0;
rMinimumProportionMet = 1;
for (i = 0; i < spno; i++)
{
checkAndUpdateTargetProportion(spec[i].target, spec[i].amount, shortfall, rMinimumProportionMet); // check regular target
checkAndUpdateTargetProportion(spec[i].targetocc, spec[i].occurrence, shortfall, rMinimumProportionMet); // check occurence target
if (spec[i].target)
{
if (spec[i].amount / spec[i].target < misslevel)
{
isp++;
continue;
}
}
if (spec[i].targetocc)
{
if ((double)spec[i].occurrence / (double)spec[i].targetocc < misslevel)
{
isp++;
continue;
}
}
if (spec[i].sepdistance && spec[i].separation < 3)
{
isp++; /* count species if not met separation and not already counted */
}
}
return(isp);
}
// compute connectivity total, in, edge, out for summary report
void computeConnectivityIndices(double& rConnectivityTotal, double& rConnectivityIn,
double& rConnectivityEdge, double& rConnectivityOut,
int puno, const vector<int>& R, const vector<sconnections>& connections)
// We record 4 categories for connectivity;
// - total, all connections in the region
// - in, all connections entirely within the reserve network (ie. both pu's in)
// - edge, all connections on the edge of the reserve network (ie. one pu in & one pu out)
// - out, all connections not captured in the reserve network (ie. both pu's out)
//
// Of these, we previously only recorded "edge", referring to it as boundary length.
// The proportion of connections captured is given by;
// in / total
//
// total = in + edge + out
{
int i;
double rFixed;
for (i = 0; i < puno; i++)
{
rFixed = connections[i].fixedcost;
rConnectivityTotal += rFixed;
if (R[i] == 1 || R[i] == 2)
{ // add to 'in' or 'edge'
rConnectivityEdge += rFixed;
for (sneighbour p : connections[i].first)
{
if (p.nbr > i)
{
if (R[p.nbr] == 1 || R[p.nbr] == 2) // add to 'in'
rConnectivityIn += p.cost;
else // add to 'edge'
rConnectivityEdge += p.cost;
// add to 'total'
rConnectivityTotal += p.cost;
}
}
}
else
{ // add to 'out' or 'edge'
rConnectivityOut += rFixed;
for (sneighbour p : connections[i].first)
{
if (p.nbr > i)
{
if (R[p.nbr] == 1 || R[p.nbr] == 2) // add to 'edge'
rConnectivityEdge += p.cost;
else // add to 'out'
rConnectivityOut += p.cost;
// add to 'total'
rConnectivityTotal += p.cost;
}
}
}
}
}
// Merging repeated area computation code. Recomputes TO, TA etc. from scratch.
void computeOccurrencesAndAreas(int& puno, const vector<spustuff>& pu, const vector<spu>& SM,
vector<int>& TotalOccurrences, vector<int>& TO_2, vector<int>& TO_3,
vector<double>& TotalAreas, vector<double>& TA_2, vector<double>& TA_3) {
int ism, isp;
for (int ipu = 0; ipu < puno; ipu++)
{
if (pu[ipu].richness)
{
for (int i = 0; i < pu[ipu].richness; i++)
{
ism = pu[ipu].offset + i;
isp = SM[ism].spindex;
TotalOccurrences[isp]++;
TotalAreas[isp] += SM[ism].amount;
if (pu[ipu].status == 2)
{
TO_2[isp]++;
TA_2[isp] += SM[ism].amount;
}
if (pu[ipu].status == 3)
{
TO_3[isp]++;
TA_3[isp] += SM[ism].amount;
}
}
}
}
}
// Used in ReturnProbabilityAmounts1D and ReturnProbabilityAmounts2D
void computeExpectedAndVariance(int ipu, const vector<spustuff>& pu, const vector<spu>& SM, vector<double>& variance, vector<double>& expected) {
int i, ism, isp;
if (pu[ipu].richness)
{
for (i = 0; i < pu[ipu].richness; i++)
{
ism = pu[ipu].offset + i;
isp = SM[ism].spindex;
if (SM[ism].amount)
{
expected[isp] += SM[ism].amount * (1 - pu[ipu].prob);
variance[isp] += SM[ism].amount * SM[ism].amount * pu[ipu].prob * (1 - pu[ipu].prob);
}
}
}
}
// Returns both index and species amount for a planning unit
pair<int, double> returnAmountSpecAtPu(const spustuff& pu, const vector<spu>& SM, int iSpecIndex)
{
if (pu.richness > 0)
{
auto start_it = SM.begin() + pu.offset;
auto end_it = start_it + pu.richness;
auto spindex_cmp = [](const spu& lhs, int rhs) -> bool { return lhs.spindex < rhs; };
auto elem_it = std::lower_bound(start_it, end_it, iSpecIndex, spindex_cmp);
if (elem_it != end_it && elem_it->spindex == iSpecIndex)
{
size_t index = elem_it - SM.begin();
return pair<int, double>(index, elem_it->amount);
}
}
return pair<int, double>(-1, 0);
}
// Sums the total spec amount across all pu
double computeTotalSpecAmtAllPu(const vector<spustuff>& PU, const vector<spu>& SM, int speciesInd)
{
double totalAmount = 0.0;
for (int ipu = 0; ipu < PU.size(); ipu++)
totalAmount += returnAmountSpecAtPu(PU[ipu], SM, speciesInd).second;
return totalAmount;
}
// compute proportional target for species when prop target is specified
// use the prop value from the conservation feature file to set a proportion target for species
void computeSpecProp(int spno, vector<sspecies>& spec, int puno, const vector<spustuff>& pu, const vector<spu>& SM)
{
// compute and set target for species with a prop value
for (int isp = 0; isp < spno; isp++)
{
if (spec[isp].prop > 0)
{
spec[isp].target = computeTotalSpecAmtAllPu(pu, SM, isp) * spec[isp].prop;
}
}
}
// Computes penalty for a species given a reserve, based on only fixed pu
void computeFixedPenaltyForSpec(const vector<int>& R, const vector<spustuff>& pu, const vector<spu>& SM, const vector<sconnections>& connections, int spIndex,
double& ftarget, int& itargetocc, double& penalty, double cm, int asymmetricconnectivity)
{
ftarget = 0, itargetocc = 0, penalty = 0;
for (int j = 0; j < pu.size(); j++)
{
if (R[j] == 2)
{
ftarget += returnAmountSpecAtPu(pu[j], SM, spIndex).second;
itargetocc++;
penalty += computePlanningUnitValue(pu[j], connections[j], cm, asymmetricconnectivity);
}
}
}
// ********* Connection Cost Type 2 **************
// ** Requires R[]. imode2 = 0 there is no negative cost for removing connection, we are calling from ReserveCost
// or 1 there is a negative cost for removing connection, we are calling from Annealing
// imode = -1 we are removing the planning unit from a reserve, calling from Annealing
// or 1 we are adding the planning unit to a reserve, or it is already in reserve
// It seems that the behaviour of this function is undefined/unsupported if imode2=0 and imode=-1
double ConnectionCost2(const sconnections& connection, const vector<int>& R, int imode, int imode2, double cm,
int asymmetricconnectivity, int fOptimiseConnectivityIn)
{
double fcost = connection.fixedcost * imode;
int R_pu1;
if (asymmetricconnectivity)
{
for (const sneighbour& p : connection.first)
{
if (imode2) // calling from Annealing
{
// determines if ipu is currently switched on or not
// if imode==1 then we assume currently switched off, and will switch on.
if (imode == 1)
R_pu1 = 0;
else
R_pu1 = 1;
if (p.connectionorigon)
{
if (R[p.nbr] == 0)
{
if (R_pu1 == 1)
{
fcost -= p.cost;
}
else
{
fcost += p.cost;
}
}
}
else
{
if (R[p.nbr] == 1 || R[p.nbr] == 2)
{
if (R_pu1 == 1)
{
fcost += p.cost;
}
else
{
fcost -= p.cost;
}
}
}
}
else // calling from ReserveCost
{
if (R[p.nbr] == 0)
if (p.connectionorigon)
{
fcost += p.cost;
}
}
}
}
else
{
for (const sneighbour& p : connection.first) // treatment for symmetric connectivity
{
if (fOptimiseConnectivityIn == 1)
{ // optimise for "Connectivity In"
if (R[p.nbr] == 1 || R[p.nbr] == 2)
{
fcost += imode * p.cost;
}
else
{
fcost += imode * imode2 * p.cost * -1;
}
}
else
{ // optimise for "Connectivity Edge"
if (R[p.nbr] == 1 || R[p.nbr] == 2)
{
fcost += imode * imode2 * p.cost * -1;
}
else
{
fcost += imode * p.cost;
}
}
}
}
return (fcost * cm);
}
} // namespace marxan
| 35.974138
| 162
| 0.455627
|
hotzevzl
|
a2948dac22b52450e64e88418bbf4ea6981b03ad
| 442
|
cc
|
C++
|
src/interpreter/command/mc-cmd-list.cc
|
babynewton/mycurl
|
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
|
[
"MIT"
] | null | null | null |
src/interpreter/command/mc-cmd-list.cc
|
babynewton/mycurl
|
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
|
[
"MIT"
] | null | null | null |
src/interpreter/command/mc-cmd-list.cc
|
babynewton/mycurl
|
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
|
[
"MIT"
] | null | null | null |
#include "command/mc-cmd-list.h"
#include <cstdio>
void mcCmdList::help(void){
fprintf(stdout, "Usage: list\n");
fprintf(stdout, " lists opend urls or alias\n");
}
mcLanguageState mcCmdList::parse(mcScanner& scanner, mcIPerformer* performer){
mcToken token = scanner.tokenize();
if(token.id != MC_TOKEN_EOL) {
fprintf(stderr, "invalid argument %s\n", token.buffer.c_str());
return MC_LANG_CONTINUE;
}
return performer->list();
}
| 26
| 78
| 0.717195
|
babynewton
|
a2948e60903235901f2f0b6f06b045b1eb45a3e8
| 19,455
|
cpp
|
C++
|
Source/BWEB/Station.cpp
|
Cmccrave/CMProtoBot
|
220cddaf41724004daf5aace5b48a07e28931279
|
[
"MIT"
] | 32
|
2017-03-04T19:38:13.000Z
|
2022-03-16T02:03:01.000Z
|
libs/BWEB/Source/Station.cpp
|
krogenth/AdditionalPylons
|
60a2ba5503857de9c6aafa5261e911f39ad0ccf1
|
[
"MIT"
] | 39
|
2022-01-10T22:23:20.000Z
|
2022-03-31T03:56:21.000Z
|
libs/BWEB/Source/Station.cpp
|
krogenth/AdditionalPylons
|
60a2ba5503857de9c6aafa5261e911f39ad0ccf1
|
[
"MIT"
] | 8
|
2017-12-26T23:47:18.000Z
|
2021-09-15T04:25:28.000Z
|
#include "BWEB.h"
using namespace std;
using namespace BWAPI;
namespace BWEB {
namespace {
vector<Station> stations;
vector<const BWEM::Base *> mainBases;
vector<const BWEM::Base *> natBases;
}
void Station::addResourceReserves()
{
const auto addReserve = [&](Unit resource) {
TilePosition start(resource->getPosition());
vector<TilePosition> directions{ {1,0}, {-1,0}, {0, 1}, {0,-1} };
auto end = (base->Center() * 5 / 6) + (resourceCentroid / 6);
// Get the starting tile
auto distClosest = DBL_MAX;
for (int x = resource->getTilePosition().x; x < resource->getTilePosition().x + resource->getType().tileWidth(); x++) {
for (int y = resource->getTilePosition().y; y < resource->getTilePosition().y + resource->getType().tileHeight(); y++) {
auto tile = TilePosition(x, y);
auto center = Position(tile) + Position(16, 16);
auto dist = center.getDistance(resourceCentroid);
if (dist < distClosest) {
start = tile;
distClosest = dist;
}
}
}
TilePosition next = start;
while (next != TilePosition(end)) {
auto distBest = DBL_MAX;
start = next;
for (auto &t : directions) {
auto tile = start + t;
auto pos = Position(tile) + Position(16, 16);
if (!tile.isValid())
continue;
auto dist = pos.getDistance(end);
if (dist <= distBest) {
next = tile;
distBest = dist;
}
}
if (next.isValid()) {
Map::addReserve(next, 1, 1);
// Remove any defenses in the way of a geyser
if (!resource->getType().isMineralField()) {
for (auto &def : defenses) {
if (next.x >= def.x && next.x < def.x + 2 && next.y >= def.y && next.y < def.y + 2) {
defenses.erase(def);
break;
}
}
}
}
}
};
// Add reserved tiles
for (auto &m : base->Minerals()) {
Map::addReserve(m->TopLeft(), 2, 1);
addReserve(m->Unit());
}
for (auto &g : base->Geysers()) {
Map::addReserve(g->TopLeft(), 4, 2);
addReserve(g->Unit());
}
}
void Station::initialize()
{
auto cnt = 0;
// Resource and defense centroids
for (auto &mineral : base->Minerals()) {
resourceCentroid += mineral->Pos();
cnt++;
}
if (cnt > 0)
defenseCentroid = resourceCentroid / cnt;
for (auto &gas : base->Geysers()) {
defenseCentroid = (defenseCentroid + gas->Pos()) / 2;
resourceCentroid += gas->Pos();
cnt++;
}
if (cnt > 0)
resourceCentroid = resourceCentroid / cnt;
Map::addUsed(base->Location(), Broodwar->self()->getRace().getResourceDepot());
}
void Station::findChoke()
{
// Only find a Chokepoint for mains or naturals
if (!main && !natural)
return;
// Get closest partner base
auto distBest = DBL_MAX;
for (auto &potentialPartner : (main ? natBases : mainBases)) {
auto dist = potentialPartner->Center().getDistance(base->Center());
if (dist < distBest) {
partnerBase = potentialPartner;
distBest = dist;
}
}
if (!partnerBase)
return;
if (main && !Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).empty()) {
choke = Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).front();
// Partner only has one chokepoint means we have a shared choke with this path
if (partnerBase->GetArea()->ChokePoints().size() == 1)
choke = Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).back();
}
else {
// Only one chokepoint in this area
if (base->GetArea()->ChokePoints().size() == 1) {
choke = base->GetArea()->ChokePoints().front();
return;
}
set<BWEM::ChokePoint const *> nonChokes;
for (auto &choke : Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()))
nonChokes.insert(choke);
auto distBest = DBL_MAX;
const BWEM::Area* second = nullptr;
// Iterate each neighboring area to get closest to this natural area
for (auto &area : base->GetArea()->AccessibleNeighbours()) {
auto center = area->Top();
const auto dist = Position(center).getDistance(Map::mapBWEM.Center());
bool wrongArea = false;
for (auto &choke : area->ChokePoints()) {
if ((!choke->Blocked() && choke->Pos(choke->end1).getDistance(choke->Pos(choke->end2)) <= 2) || nonChokes.find(choke) != nonChokes.end()) {
wrongArea = true;
}
}
if (wrongArea)
continue;
if (center.isValid() && dist < distBest) {
second = area;
distBest = dist;
}
}
distBest = DBL_MAX;
for (auto &c : base->GetArea()->ChokePoints()) {
if (c->Center() == BWEB::Map::getMainChoke()->Center()
|| c->Blocked()
|| c->Geometry().size() <= 3
|| (c->GetAreas().first != second && c->GetAreas().second != second))
continue;
const auto dist = Position(c->Center()).getDistance(Position(partnerBase->Center()));
if (dist < distBest) {
choke = c;
distBest = dist;
}
}
}
if (choke && !main)
defenseCentroid = Position(choke->Center());
}
void Station::findSecondaryLocations()
{
if (Broodwar->self()->getRace() != Races::Zerg)
return;
auto cnt = 0;
if (main)
cnt = 1;
if (!main && !natural)
cnt = 2;
for (int i = 0; i < cnt; i++) {
auto distBest = DBL_MAX;
auto tileBest = TilePositions::Invalid;
for (auto x = base->Location().x - 4; x <= base->Location().x + 4; x++) {
for (auto y = base->Location().y - 3; y <= base->Location().y + 3; y++) {
auto tile = TilePosition(x, y);
auto center = Position(tile) + Position(64, 48);
auto dist = center.getDistance(resourceCentroid);
if (dist < distBest && Map::isPlaceable(Broodwar->self()->getRace().getResourceDepot(), tile)) {
distBest = dist;
tileBest = tile;
}
}
}
if (tileBest.isValid()) {
secondaryLocations.insert(tileBest);
Map::addUsed(tileBest, Broodwar->self()->getRace().getResourceDepot());
}
}
}
void Station::findDefenses()
{
vector<TilePosition> basePlacements;
vector<TilePosition> geyserPlacements ={ {-2, -2}, {-2, 0}, {-2, 2}, {0, -2}, {0, 2}, {2, -2}, {2, 2}, {4, -2}, {4, 0}, {4, 2} };
auto here = base->Location();
auto defenseType = UnitTypes::None;
if (Broodwar->self()->getRace() == Races::Protoss)
defenseType = UnitTypes::Protoss_Photon_Cannon;
if (Broodwar->self()->getRace() == Races::Terran)
defenseType = UnitTypes::Terran_Missile_Turret;
if (Broodwar->self()->getRace() == Races::Zerg)
defenseType = UnitTypes::Zerg_Creep_Colony;
// Get angle of chokepoint
if (choke && base && (main || natural)) {
auto dist = min(480.0, getBase()->Center().getDistance(Position(choke->Center())));
baseAngle = fmod(Map::getAngle(make_pair(getBase()->Center(), Position(choke->Center()) + Position(4, 4))), 3.14);
chokeAngle = fmod(Map::getAngle(make_pair(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2)))), 3.14);
auto diff = baseAngle - chokeAngle;
diff > 0.7 ? baseAngle -= 1.57 : baseAngle += 1.57;
defenseAngle = max(0.0, (baseAngle * (dist / 480.0)) + (chokeAngle * (480.0 - dist) / 480.0));
if (base->GetArea()->ChokePoints().size() >= 3) {
const BWEM::ChokePoint * validSecondChoke = nullptr;
for (auto &otherChoke : base->GetArea()->ChokePoints()) {
if (choke == otherChoke)
continue;
if ((choke->GetAreas().first == otherChoke->GetAreas().first && choke->GetAreas().second == otherChoke->GetAreas().second)
|| (choke->GetAreas().first == otherChoke->GetAreas().second && choke->GetAreas().second == otherChoke->GetAreas().first))
validSecondChoke = otherChoke;
}
if (validSecondChoke)
defenseAngle = (Map::getAngle(make_pair(Position(choke->Center()), Position(validSecondChoke->Center()))) + Map::getAngle(make_pair(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2))))) / 2.0;
}
}
else {
defenseCentroid = BWEB::Map::mapBWEM.Center();
defenseAngle = fmod(Map::getAngle(make_pair(Position(getBase()->Center()), defenseCentroid)), 3.14) + 1.57;
}
// Round to nearest pi/8 rads
auto nearestEight = int(round(defenseAngle / 0.3926991));
auto angle = nearestEight % 8;
// Generate defenses
if (main)
basePlacements ={ {-2, -2}, {-2, 1}, {1, -2} };
else {
if (angle == 0)
basePlacements ={ {-2, 2}, {-2, 0}, {-2, -2}, {0, 3}, {0, -2}, {2, -2}, {4, -2}, {4, 0}, {4, 2} }; // 0/8
if (angle == 1 || angle == 7)
basePlacements ={ {-2, 3}, {-2, 1}, {-2, -1}, {0, -2}, {1, 3}, {2, -2}, {4, -1}, {4, 1}, }; // pi/8
if (angle == 2 || angle == 6)
basePlacements ={ {-2, 2}, {-2, 0}, {0, 3}, {0, -2}, {2, -2}, {4, -2}, {4, 0} }; // pi/4
if (angle == 3 || angle == 5)
basePlacements ={ {-2, 2}, {-2, 0}, {-1, -2}, {0, 3}, {1, -2}, {2, 3}, {3, -2}, {4, 0} }; // 3pi/8
if (angle == 4)
basePlacements ={ {-2, 2}, {-2, 0}, {-2, -2}, {0, 3}, {0, -2}, {2, 3}, {2, -2}, {4, 3}, {4, -2} }; // pi/2
}
// Flip them vertically / horizontally as needed
if (base->Center().y < defenseCentroid.y) {
for (auto &placement : basePlacements)
placement.y = -(placement.y - 1);
}
if (base->Center().x < defenseCentroid.x) {
for (auto &placement : basePlacements)
placement.x = -(placement.x - 2);
}
// Add scanner addon for Terran
if (Broodwar->self()->getRace() == Races::Terran) {
auto scannerTile = here + TilePosition(4, 1);
defenses.insert(scannerTile);
Map::addUsed(scannerTile, defenseType);
}
// Add a defense near each base placement if possible
for (auto &placement : basePlacements) {
auto tile = base->Location() + placement;
if (Map::isPlaceable(defenseType, tile)) {
defenses.insert(tile);
Map::addUsed(tile, defenseType);
}
}
// Add geyser defenses
if (main) {
for (auto &geyser : base->Geysers()) {
for (auto &placement : geyserPlacements) {
auto tile = geyser->TopLeft() + placement;
auto center = Position(tile) + Position(16, 16);
if (center.getDistance(base->Center()) > geyser->Pos().getDistance(base->Center()) && Map::isPlaceable(defenseType, tile)) {
defenses.insert(tile);
Map::addUsed(tile, defenseType);
}
}
}
}
}
void Station::draw()
{
int color = Broodwar->self()->getColor();
int textColor = color == 185 ? textColor = Text::DarkGreen : Broodwar->self()->getTextColor();
// Draw boxes around each feature
for (auto &tile : defenses) {
Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(65, 65), color);
Broodwar->drawTextMap(Position(tile) + Position(4, 52), "%cS", textColor);
}
// Draw corresponding choke
if (choke && base && (main || natural)) {
if (base->GetArea()->ChokePoints().size() >= 3) {
const BWEM::ChokePoint * validSecondChoke = nullptr;
for (auto &otherChoke : base->GetArea()->ChokePoints()) {
if (choke == otherChoke)
continue;
if ((choke->GetAreas().first == otherChoke->GetAreas().first && choke->GetAreas().second == otherChoke->GetAreas().second)
|| (choke->GetAreas().first == otherChoke->GetAreas().second && choke->GetAreas().second == otherChoke->GetAreas().first))
validSecondChoke = choke;
}
if (validSecondChoke) {
Broodwar->drawLineMap(Position(validSecondChoke->Pos(validSecondChoke->end1)), Position(validSecondChoke->Pos(validSecondChoke->end2)), Colors::Grey);
Broodwar->drawLineMap(base->Center(), Position(validSecondChoke->Center()), Colors::Grey);
Broodwar->drawLineMap(Position(choke->Center()), Position(validSecondChoke->Center()), Colors::Grey);
}
}
Broodwar->drawLineMap(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2)), Colors::Grey);
Broodwar->drawLineMap(base->Center(), Position(choke->Center()), Colors::Grey);
}
// Label angle
Broodwar->drawTextMap(base->Center() - Position(0, 16), "%c%.2f", Text::White, baseAngle);
Broodwar->drawTextMap(base->Center(), "%c%.2f", Text::White, chokeAngle);
Broodwar->drawTextMap(base->Center() + Position(0, 16), "%c%.2f", Text::White, defenseAngle);
Broodwar->drawBoxMap(Position(base->Location()), Position(base->Location()) + Position(129, 97), color);
Broodwar->drawTextMap(Position(base->Location()) + Position(4, 84), "%cS", textColor);
for (auto &location : secondaryLocations) {
Broodwar->drawBoxMap(Position(location), Position(location) + Position(129, 97), color);
Broodwar->drawTextMap(Position(location) + Position(4, 84), "%cS", textColor);
}
}
void Station::cleanup()
{
// Remove used on defenses
for (auto &tile : defenses) {
Map::removeUsed(tile, 2, 2);
Map::addReserve(tile, 2, 2);
}
// Remove used on secondary locations
for (auto &tile : secondaryLocations) {
Map::removeUsed(tile, 4, 3);
Map::addReserve(tile, 4, 3);
}
// Remove used on main location
Map::removeUsed(getBase()->Location(), 4, 3);
Map::addReserve(getBase()->Location(), 4, 3);
}
}
namespace BWEB::Stations {
void findStations()
{
// Find all main bases
for (auto &area : Map::mapBWEM.Areas()) {
for (auto &base : area.Bases()) {
if (base.Starting())
mainBases.push_back(&base);
}
}
// Find all natural bases
for (auto &main : mainBases) {
const BWEM::Base * baseBest = nullptr;
auto distBest = DBL_MAX;
for (auto &area : Map::mapBWEM.Areas()) {
for (auto &base : area.Bases()) {
// Must have gas, be accesible and at least 5 mineral patches
if (base.Starting()
|| base.Geysers().empty()
|| base.GetArea()->AccessibleNeighbours().empty()
|| base.Minerals().size() < 5)
continue;
const auto dist = Map::getGroundDistance(base.Center(), main->Center());
if (dist < distBest) {
distBest = dist;
baseBest = &base;
}
}
}
// Store any natural we found
if (baseBest)
natBases.push_back(baseBest);
}
// Create Stations
for (auto &area : Map::mapBWEM.Areas()) {
for (auto &base : area.Bases()) {
auto isMain = find(mainBases.begin(), mainBases.end(), &base) != mainBases.end();
auto isNatural = find(natBases.begin(), natBases.end(), &base) != natBases.end();
// Add to our station lists
Station newStation(&base, isMain, isNatural);
stations.push_back(newStation);
}
}
}
void draw()
{
for (auto &station : Stations::getStations())
station.draw();
}
Station * getClosestStation(TilePosition here)
{
auto distBest = DBL_MAX;
Station* bestStation = nullptr;
for (auto &station : stations) {
const auto dist = here.getDistance(station.getBase()->Location());
if (dist < distBest) {
distBest = dist;
bestStation = &station;
}
}
return bestStation;
}
Station * getClosestMainStation(TilePosition here)
{
auto distBest = DBL_MAX;
Station * bestStation = nullptr;
for (auto &station : stations) {
if (!station.isMain())
continue;
const auto dist = here.getDistance(station.getBase()->Location());
if (dist < distBest) {
distBest = dist;
bestStation = &station;
}
}
return bestStation;
}
Station * getClosestNaturalStation(TilePosition here)
{
auto distBest = DBL_MAX;
Station* bestStation = nullptr;
for (auto &station : stations) {
if (!station.isNatural())
continue;
const auto dist = here.getDistance(station.getBase()->Location());
if (dist < distBest) {
distBest = dist;
bestStation = &station;
}
}
return bestStation;
}
vector<Station>& getStations() {
return stations;
}
}
| 38.448617
| 230
| 0.486199
|
Cmccrave
|
a29558a201889d425c1ff0f0cea1b6f5d0a907fa
| 125
|
cpp
|
C++
|
chapter-12/12.1.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
chapter-12/12.1.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
chapter-12/12.1.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
// b1 has 4 elements;
// b2's code block has ended, os b2 is destroyed, there is no point in saying how many elements in b2.
| 41.666667
| 102
| 0.72
|
zero4drift
|
a29908b3004fb0fad0016b7a77e184713333d6a2
| 477
|
cpp
|
C++
|
replacinginteger.cpp
|
tanner00/ICPC-Season-2
|
0be745706e6551005f45343dfda6a0e658dfbbfb
|
[
"MIT"
] | null | null | null |
replacinginteger.cpp
|
tanner00/ICPC-Season-2
|
0be745706e6551005f45343dfda6a0e658dfbbfb
|
[
"MIT"
] | null | null | null |
replacinginteger.cpp
|
tanner00/ICPC-Season-2
|
0be745706e6551005f45343dfda6a0e658dfbbfb
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int64_t n, k;
cin >> n >> k;
// we take the smaller of these two values:
// n % k is what we'd be left over with if we stopped before negatives
// k - (n % k) is what we'd be left over with (positive) if we did one more
cout << min(n % k, k - (n % k));
// also could be (makes more sense to me with above):
// min(n % k, abs((n % k) - k))
return 0;
}
| 22.714286
| 76
| 0.610063
|
tanner00
|
a299120c0bfba1ae5fd788d09a6a17dd01e38fb5
| 1,175
|
cpp
|
C++
|
vsedit/src/script_editor/script_completer.cpp
|
jkotra/vapoursynth-editor
|
ee028830d5d390bd3fbde5577577444c011f4987
|
[
"MIT"
] | null | null | null |
vsedit/src/script_editor/script_completer.cpp
|
jkotra/vapoursynth-editor
|
ee028830d5d390bd3fbde5577577444c011f4987
|
[
"MIT"
] | null | null | null |
vsedit/src/script_editor/script_completer.cpp
|
jkotra/vapoursynth-editor
|
ee028830d5d390bd3fbde5577577444c011f4987
|
[
"MIT"
] | null | null | null |
#include "script_completer.h"
//==============================================================================
ScriptCompleter::ScriptCompleter(QAbstractItemModel *a_pModel,
QObject *a_pParent) : QCompleter(a_pModel, a_pParent)
{
}
//==============================================================================
ScriptCompleter::~ScriptCompleter()
{
}
//==============================================================================
QString ScriptCompleter::pathFromIndex(const QModelIndex &a_index) const
{
if (!a_index.isValid()) {
return QString();
}
QString path = model()->data(a_index, Qt::EditRole).toString();
QModelIndex index = a_index;
while (index.parent().isValid()) {
index = index.parent();
path.prepend('.');
path.prepend(model()->data(index, Qt::EditRole).toString());
}
return path;
}
//==============================================================================
QStringList ScriptCompleter::splitPath(const QString &a_path) const
{
return a_path.split('.');
}
//==============================================================================
| 25.543478
| 86
| 0.417872
|
jkotra
|
a29f8b5a1efa699a8f6745882ba77ee3b1446821
| 566
|
cpp
|
C++
|
test/doc/algo/any_of.cpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
test/doc/algo/any_of.cpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
test/doc/algo/any_of.cpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
#include <eve/module/core.hpp>
#include <eve/algo.hpp>
#include <iostream>
#include <vector>
#include "print.hpp"
int main()
{
std::vector<int> v = {2,6,-10,32,-8,2,-6,8,-2,4};
std::cout << " -> v = ";
doc_utils::print(v);
std::cout << " -> eve::algo::any_of(v, i >= 4) = "
<< std::boolalpha << eve::algo::any_of(v, [](auto i){ return i >= 4; })<< "\n";
std::cout << " -> eve::algo::any_of(v, eve::is_odd) = "
<< std::boolalpha << eve::algo::any_of(v, eve::is_odd)<< "\n";
return 0;
}
| 26.952381
| 91
| 0.484099
|
clayne
|
9474be3b14b2bc74de0da5b8ec349fc737cf28e2
| 3,219
|
cc
|
C++
|
basic/exact.cc
|
ririripley/recipes
|
04267c68a7424326b4aa8dd14b1a879b59ab887c
|
[
"BSD-3-Clause"
] | 1,418
|
2015-01-07T09:40:09.000Z
|
2022-03-29T08:37:02.000Z
|
basic/exact.cc
|
algoideas/recipes
|
77bc5cb180e49edb31983938386ef23f752e2d2f
|
[
"BSD-3-Clause"
] | 22
|
2015-02-17T17:31:18.000Z
|
2022-02-08T07:00:29.000Z
|
basic/exact.cc
|
algoideas/recipes
|
77bc5cb180e49edb31983938386ef23f752e2d2f
|
[
"BSD-3-Clause"
] | 854
|
2015-01-03T11:56:10.000Z
|
2022-03-31T08:50:28.000Z
|
#include "uint.h"
#include <float.h>
#include <stdio.h>
#include <iostream>
#include <ios>
// convert a floating point number to exact decimal number
class Float
{
public:
Float(int exponent, uint64_t mantissa)
: E(exponent), M(mantissa)
{
}
std::string decimal() const
{
std::string dec = integer();
std::pair<std::string, int> frac = fraction();
dec += '.';
dec.append(frac.second, '0');
dec.append(frac.first);
return dec;
}
static Float fromDouble(double x)
{
union
{
double f;
uint64_t u;
};
f = x;
// CAUTION: only works on 64-bit platforms?
return fromDouble((u & 0x7ff0000000000000) >> 52, u & 0xFFFFFFFFFFFFF);
}
static Float fromDouble(int exponent, uint64_t fraction)
{
// FIXME: subnormal
return Float(exponent-1023-52, fraction | 0x10000000000000);
}
private:
std::string integer() const
{
int e = E;
uint64_t m = M;
while (e < 0)
{
m >>= 1;
++e;
}
uint32_t lo = m & 0xFFFFFFFF;
uint32_t hi = m >> 32;
UnsignedInt u(lo);
if (hi)
{
UnsignedInt x(hi);
x.multiply(0x10000);
x.multiply(0x10000);
u.add(x);
}
if (e)
{
UnsignedInt y(2);
y.power(e);
u.multiply(y);
}
return u.toDec();
}
// 0.1111111111
// ||||||||||
// 0.5|||||||||
// 0.25||||||||
// 0.125|||||||
// 0.0625||||||
// 0.03125|||||
// 0.015625||||
// 0.0078125|||
// 0.00390625||
// 0.001953125|
// 0.0009765625
std::pair<std::string, int> fraction() const
{
int e = E;
uint64_t m = M;
UnsignedInt f(0);
UnsignedInt d(5);
while (e < 0 && (m & 1) == 0)
{
m >>= 1;
++e;
}
const int digits = (e < 0) ? -e : 0;
while (e < 0)
{
f.multiply(5);
if (m & 1)
{
f.add(d);
}
m >>= 1;
++e;
d.multiply(10);
}
std::string x = f.toDec();
int zeros = x.size() < digits ? digits - x.size() : 0;
return std::make_pair(x, zeros);
}
private:
const int E;
const uint64_t M;
};
using namespace std;
int main(int argc, char* argv[])
{
if (argc > 1)
{
for (int i = 1; i < argc; ++i)
{
double x = strtod(argv[i], NULL);
printf("%s = %a\n", argv[i], x);
cout << Float::fromDouble(x).decimal() << endl;
if (i != argc - 1)
printf("\n");
}
}
else
{
Float f1 = Float::fromDouble(1);
cout << f1.decimal() << endl;
Float pi = Float::fromDouble(0x400, 0x921fb54442d18);
cout << pi.decimal() << endl;
Float f3 = Float::fromDouble(0x3fd, 0x5555555555555);
cout << f3.decimal() << endl;
Float f01 = Float::fromDouble(0.1);
cout << f01.decimal() << endl;
Float fy(1023, 2); // 2 ** 1024
cout << fy.decimal() << endl;
assert(strtod("0x1.FffffFFFFffffP1023", NULL) == DBL_MAX);
Float fx = Float::fromDouble(DBL_MAX);
cout << fx.decimal() << endl;
Float fm = Float::fromDouble(DBL_MIN);
cout << fm.decimal() << endl;
Float fe = Float::fromDouble(DBL_EPSILON);
cout << fe.decimal() << endl;
printf("%a\n", DBL_MAX);
printf("%a\n", DBL_MIN);
printf("%a\n", DBL_EPSILON);
}
}
| 19.993789
| 75
| 0.522833
|
ririripley
|
9475d8991e797c396727f113c84eaf86110dfe5c
| 1,000
|
hpp
|
C++
|
packages/raspiSync/include/raspiSync.hpp
|
Falcons-Robocup/code
|
2281a8569e7f11cbd3238b7cc7341c09e2e16249
|
[
"Apache-2.0"
] | 2
|
2021-01-15T13:27:19.000Z
|
2021-08-04T08:40:52.000Z
|
packages/raspiSync/include/raspiSync.hpp
|
Falcons-Robocup/code
|
2281a8569e7f11cbd3238b7cc7341c09e2e16249
|
[
"Apache-2.0"
] | null | null | null |
packages/raspiSync/include/raspiSync.hpp
|
Falcons-Robocup/code
|
2281a8569e7f11cbd3238b7cc7341c09e2e16249
|
[
"Apache-2.0"
] | 5
|
2018-05-01T10:39:31.000Z
|
2022-03-25T03:02:35.000Z
|
// Copyright 2019 Andre Pool (Falcons)
// SPDX-License-Identifier: Apache-2.0
// Copyright 2019 Andre Pool
// SPDX-License-Identifier: Apache-2.0
#ifndef RASPI_SYNC_HPP
#define RASPI_SYNC_HPP
#include "camGrabReceive.hpp"
#include "raspiControl.hpp"
#include <cstdint>
#include <iostream>
#include <thread>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
class raspiSync {
private:
raspiControl *raspiCtrl; // used to send pixel offset to the camera's
camGrabReceive *camGrabRecv;
struct timespec nextWakeTime; // to align "exactly" on the 500ms of the clock
std::thread camGrabRecvThread;
cv::Mat timeFrame;
cv::Scalar cam0Color;
cv::Scalar cam1Color;
cv::Scalar cam2Color;
cv::Scalar cam3Color;
cv::Scalar referenceColor;
cv::Scalar markerColor[4];
int pixelsOffset[4];
int pixelsOffsetPrev[4];
int pixelsOffsetIntegrator[4];
public:
raspiSync();
~raspiSync();
bool update();
};
#endif
| 20
| 81
| 0.71
|
Falcons-Robocup
|
9478ba14e0f0a379ffba877339acfe10100a8e16
| 522
|
cpp
|
C++
|
gongen/src/version.cpp
|
Bitrium-Games/gongen
|
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
|
[
"MIT"
] | 3
|
2021-07-01T13:59:45.000Z
|
2021-07-07T13:53:09.000Z
|
gongen/src/version.cpp
|
Bitrium-Games/gongen
|
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
|
[
"MIT"
] | null | null | null |
gongen/src/version.cpp
|
Bitrium-Games/gongen
|
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
|
[
"MIT"
] | 2
|
2021-06-21T17:45:20.000Z
|
2021-06-21T19:22:19.000Z
|
#include <gen/version.hpp>
#undef ERROR
gen::gongen_version::gongen_version(uint16 milestone, uint16 major, uint16 minor, uint16 patch) : milestone(milestone), major(major), minor(minor), patch(patch) {
}
gen::string gen::gongen_version::toString() const {
gen::string result;
result.append(std::to_string(milestone));
result.append(".");
result.append(std::to_string(major));
result.append(".");
result.append(std::to_string(minor));
result.append(".");
result.append(std::to_string(patch));
return result;
}
| 27.473684
| 162
| 0.726054
|
Bitrium-Games
|
9478bf286211f52fd3d102c698c510a47899f840
| 3,938
|
cpp
|
C++
|
source/block.cpp
|
theKlanc/Z3
|
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
|
[
"MIT"
] | 4
|
2020-08-09T20:34:28.000Z
|
2021-07-22T23:30:40.000Z
|
source/block.cpp
|
theKlanc/Z3
|
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
|
[
"MIT"
] | 5
|
2020-02-18T23:19:14.000Z
|
2020-02-18T23:26:24.000Z
|
source/block.cpp
|
theKlanc/Z3
|
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "services.hpp"
#include "block.hpp"
#include "json.hpp"
using nlohmann::json;
blockRotation operator++(blockRotation& a, int)
{
return a = (blockRotation)((static_cast<int>(a) + 1) % 4);
}
blockRotation operator--(blockRotation& a, int)
{
return a = (blockRotation)(( static_cast<int>(a) + 3) % 4);
}
bool baseBlock::operator==(const baseBlock& right)
{
return ID == right.ID;
}
void baseBlock::loadTerrainTable()
{
terrainTable.clear();
std::ifstream terrainTableFile(HI2::getDataPath().append("blockTable.json"));
json j;
terrainTableFile >> j;
j.get_to(baseBlock::terrainTable);
metaBlock::nullBlock.base = &baseBlock::terrainTable[0];
}
reactphysics3d::Quaternion metaBlock::getRotationQuat() const
{
//return rp3d::Quaternion::identity();
double r = M_PI*0.5*(float) rotation;
if(flip)
r+=M_PI;
double cz = cos(r*0.5);
double sz = sin(r*0.5);
rp3d::Quaternion q;
q.w = cz;
q.x = 0;
q.y = 0;
q.z = sz;
return q;
}
bool metaBlock::operator==(const metaBlock& right) const
{
if(base->ID == 0 && right.base->ID == 0)
return true;
if (saveMeta == false && saveMeta == false)
return base == right.base;
return base == right.base && rotation == right.rotation && flip == right.flip;
}
std::ostream& operator<<(std::ostream& os, const metaBlock& m)
{
if (m.saveMeta)
{
return os << m.base->ID << ' ' << m.saveMeta << ' ' << static_cast<int>(m.rotation) << ' ' << m.flip;
}
else {
return os << m.base->ID << ' ' << m.saveMeta;
}
}
std::ostream& operator<<(std::ostream& os, const std::vector<metaBlock>& m)
{
metaBlock lastBlock = m[0];
unsigned accumulatedLength = 0;
for (const metaBlock& b : m)
{
if (b != lastBlock)
{
os << lastBlock << ' ' << accumulatedLength << std::endl;
lastBlock = b;
accumulatedLength = 1;
}
else
{
accumulatedLength++;
}
}
return os << lastBlock << ' ' << accumulatedLength << std::endl;
}
std::istream& operator>>(std::istream& is, std::vector<metaBlock>& m)
{
m.clear();
m.resize(0);
unsigned blockID;
blockRotation rotation;
bool flip;
bool savedMeta;
unsigned length;
std::string input;
while (is >> input)
{
blockID = std::stoi(input);
is >> input;
savedMeta = std::stoi(input);
if (savedMeta) {
is >> input;
rotation = (blockRotation)std::stoi(input);
is >> flip;
}
is >> input;
length = std::stoi(input);
for (int i = 0; i < length; ++i)
{
m.push_back({ &baseBlock::terrainTable[blockID],(savedMeta ? rotation : (blockRotation)(rand() % 4)), (savedMeta ? flip : false),savedMeta });
}
}
return is;
}
void to_json(nlohmann::json& j, const baseBlock& b)
{
j = json{ {"name",b.name},{"ID",b.ID},{"visible",b.visible},{"solid",b.solid},{"opaque",b.opaque},{"mass",b.mass} };
if (b.spr != nullptr) {
j.push_back({ "frames",b.spr->getAllFrames() });
}
}
void from_json(const nlohmann::json& j, baseBlock& b)
{
j.at("name").get_to(b.name);
j.at("ID").get_to(b.ID);
j.at("visible").get_to(b.visible);
j.at("solid").get_to(b.solid);
j.at("opaque").get_to(b.opaque);
j.at("mass").get_to(b.mass);
std::vector<frame> frames;
if (j.contains("sprite")) {
for (const nlohmann::json& element : j.at("sprite").at("frames")) {
frames.push_back(element.get<frame>());
}
b.spr = Services::graphics.loadSprite(b.name, "spritesheet", frames);
}
if(j.contains("collider")){
b.collider = j.at("collider").get<colliderType>();
}
}
std::vector<baseBlock> baseBlock::terrainTable;
metaBlock metaBlock::nullBlock;
void to_json(nlohmann::json &j, const metaBlock &b)
{
j = nlohmann::json{{"baseID",b.base->ID},{"flip",b.flip},{"rotation",b.rotation},{"save",b.saveMeta}};
}
void from_json(const nlohmann::json &j, metaBlock &b)
{
b.base = &baseBlock::terrainTable[j.at("baseID").get<unsigned>()];
b.flip = j.at("flip").get<bool>();
b.rotation = j.at("rotation").get<blockRotation>();
b.saveMeta = j.at("save").get<bool>();
}
| 23.722892
| 145
| 0.636872
|
theKlanc
|
947a23c26e6596b74361c63d2aa235d8f1d1bf0f
| 361
|
cpp
|
C++
|
nodelibpd.cpp
|
teropa/node-libpd
|
3a07bb10fe7080473a4579ba851746cd9d0d72a2
|
[
"BSD-3-Clause"
] | 1
|
2021-05-04T16:34:59.000Z
|
2021-05-04T16:34:59.000Z
|
nodelibpd.cpp
|
teropa/node-libpd
|
3a07bb10fe7080473a4579ba851746cd9d0d72a2
|
[
"BSD-3-Clause"
] | null | null | null |
nodelibpd.cpp
|
teropa/node-libpd
|
3a07bb10fe7080473a4579ba851746cd9d0d72a2
|
[
"BSD-3-Clause"
] | null | null | null |
#include "src/NodePd.hpp"
using v8::FunctionTemplate;
namespace nodePd {
// NativeExtension.cc represents the top level of the module.
// C++ constructs that are exposed to javascript are exported here
NAN_MODULE_INIT(InitAll) {
// Passing target down to the next NAN_MODULE_INIT
NodePd::Init(target);
}
NODE_MODULE(nodelibpd, InitAll)
}; // namespace
| 21.235294
| 66
| 0.756233
|
teropa
|
947a85f61825eec5c0801f30004ef88198c36edb
| 7,756
|
cpp
|
C++
|
tests/test_local_ham.cpp
|
chaeyeunpark/ExactDiagonalization
|
c93754e724486cc68453399c5dda6a2dadf45cb8
|
[
"MIT"
] | 1
|
2021-04-24T08:47:05.000Z
|
2021-04-24T08:47:05.000Z
|
tests/test_local_ham.cpp
|
chaeyeunpark/ExactDiagonalization
|
c93754e724486cc68453399c5dda6a2dadf45cb8
|
[
"MIT"
] | 1
|
2021-09-28T19:02:14.000Z
|
2021-09-28T19:02:14.000Z
|
tests/test_local_ham.cpp
|
chaeyeunpark/ExactDiagonalization
|
c93754e724486cc68453399c5dda6a2dadf45cb8
|
[
"MIT"
] | 1
|
2020-03-22T18:59:11.000Z
|
2020-03-22T18:59:11.000Z
|
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <unsupported/Eigen/KroneckerProduct>
#include <Spectra/MatOp/SparseSymMatProd.h>
#include <Spectra/SymEigsSolver.h>
#include <iostream>
#include <cassert>
#include <random>
#include <algorithm>
#include "edlib/EDP/LocalHamiltonian.hpp"
#include "edlib/EDP/ConstructSparseMat.hpp"
Eigen::SparseMatrix<double> getSX()
{
Eigen::SparseMatrix<double> res(2,2);
res.insert(0,1) = 1.0;
res.insert(1,0) = 1.0;
res.makeCompressed();
return res;
}
Eigen::SparseMatrix<std::complex<double> > getSY()
{
Eigen::SparseMatrix<std::complex<double> > res(2,2);
constexpr std::complex<double> I(0., 1.);
res.insert(0,1) = -I;
res.insert(1,0) = I;
res.makeCompressed();
return res;
}
Eigen::SparseMatrix<double> getSZ()
{
Eigen::SparseMatrix<double> res(2,2);
res.insert(0,0) = 1.0;
res.insert(1,1) = -1.0;
res.makeCompressed();
return res;
}
template<typename T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
twoQubitOp(int N, int pos1, int pos2,
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1,
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2)
{
using namespace Eigen;
const uint32_t dim = (1<<N);
assert(pos1 < pos2);
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1,1);
res(0,0) = 1.0;
for(int i = 0; i < pos1; i++)
{
res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();
}
res = Eigen::kroneckerProduct(v1, res).eval();
for(int i = pos1+1; i < pos2; i++)
{
res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();
}
res = Eigen::kroneckerProduct(v2, res).eval();
for(int i = pos2+1; i < N; i++)
{
res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();
}
return res;
}
template<typename T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
singleQubitOp(int N, int pos,
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v)
{
using namespace Eigen;
const uint32_t dim = (1<<N);
using MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> ;
MatrixT res(1,1);
res(0,0) = 1.0;
for(int i = 0; i < pos; i++)
{
res = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();
}
res = Eigen::kroneckerProduct(v, res).eval();
for(int i = pos+1; i < N; i++)
{
res = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();
}
return res;
}
Eigen::SparseMatrix<double> getSXXYY()
{
Eigen::SparseMatrix<double> res(4,4);
res.insert(1,2) = 2.0;
res.insert(2,1) = 2.0;
res.makeCompressed();
return res;
}
Eigen::SparseMatrix<double> getSXX()
{
Eigen::SparseMatrix<double> res(4,4);
res.insert(0,3) = 1.0;
res.insert(1,2) = 1.0;
res.insert(2,1) = 1.0;
res.insert(3,0) = 1.0;
res.makeCompressed();
return res;
}
Eigen::SparseMatrix<double> getSYY()
{
Eigen::SparseMatrix<double> res(4,4);
res.insert(0,3) = -1.0;
res.insert(1,2) = 1.0;
res.insert(2,1) = 1.0;
res.insert(3,0) = -1.0;
res.makeCompressed();
return res;
}
Eigen::SparseMatrix<double> getSZZ()
{
Eigen::SparseMatrix<double> res(4,4);
res.insert(0,0) = 1.0;
res.insert(1,1) = -1.0;
res.insert(2,2) = -1.0;
res.insert(3,3) = 1.0;
res.makeCompressed();
return res;
}
class GraphGenerator
{
private:
int numVertices_;
std::vector<std::pair<int,int> > allEdges_;
std::vector<int> allVertices_;
public:
GraphGenerator(int numVertices)
: numVertices_{numVertices}
{
for(int i = 0; i < numVertices-1; ++i)
{
for(int j = i+1; j < numVertices; ++j)
{
allEdges_.emplace_back(i,j);
}
}
for(int i = 0; i < numVertices_; ++i)
{
allVertices_.emplace_back(i);
}
}
std::vector<std::pair<int,int> > createRandomGraph(int numEdges)
{
std::vector<std::pair<int,int> > edges = allEdges_;
std::random_shuffle(edges.begin(), edges.end());
edges.resize(numEdges);
return edges;
}
std::vector<int> createRandomVertexSet(int n)
{
std::vector<int> v = allVertices_;
std::random_shuffle(v.begin(), v.end());
v.resize(n);
return v;
}
};
constexpr int N = 10;
TEST_CASE("Test single qubit operators", "[LocalHamSingle]") {
std::random_device rd;
std::default_random_engine re{rd()};
std::uniform_int_distribution<> uid(0, N-1);
std::uniform_real_distribution<> urd;
using cx_double = std::complex<double>;
SECTION("Test contructing pauli X") {
edp::LocalHamiltonian<double> lh(N,2);
for(int n = 0; n < 100; ++n)
{
lh.clearTerms();
int idx = uid(re);
double val = urd(re);
lh.addOneSiteTerm(idx, val*getSX());
auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));
auto mat2 = singleQubitOp<double>(N, idx, val*getSX()) ;
REQUIRE((mat1-mat2).squaredNorm() < 1e-8);
}
}
SECTION("Test contructing pauli Z") {
edp::LocalHamiltonian<double> lh(N,2);
for(int n = 0; n < 100; ++n)
{
lh.clearTerms();
int idx = uid(re);
double val = urd(re);
lh.addOneSiteTerm(idx, val*getSZ());
auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));
auto mat2 = singleQubitOp<double>(N, idx, val*getSZ()) ;
REQUIRE((mat1-mat2).squaredNorm() < 1e-8);
}
}
SECTION("Test contructing pauli Y") {
edp::LocalHamiltonian<cx_double> lh(N,2);
for(int n = 0; n < 100; ++n)
{
lh.clearTerms();
int idx = uid(re);
double val = urd(re);
lh.addOneSiteTerm(idx, val*getSY());
auto mat1 = Eigen::MatrixXcd(edp::constructSparseMat<cx_double>(1<<N, lh));
auto mat2 = singleQubitOp<cx_double>(N, idx, val*getSY()) ;
REQUIRE((mat1-mat2).squaredNorm() < 1e-8);
}
}
}
TEST_CASE("Test 2-local Hamiltonians", "[LocalHam2loc]") {
std::random_device rd;
std::default_random_engine re{rd()};
std::uniform_int_distribution<> uid(0, N-1);
std::uniform_int_distribution<> numEdgesRd(1, N*(N-1)/2);
std::uniform_real_distribution<> urd;
using cx_double = std::complex<double>;
GraphGenerator ggen{N};
SECTION("Random XYZ Hamiltonian") {
edp::LocalHamiltonian<double> lh(N,2);
for(int n = 0; n < 10; ++n)
{
lh.clearTerms();
int numEdges = numEdgesRd(re);
auto edges = ggen.createRandomGraph(numEdges);
auto matEx = Eigen::MatrixXd(1<<N, 1<<N);
matEx.setZero();
for(const auto& edge: edges)
{
double v1 = urd(re);
double v2 = urd(re);
double v3 = urd(re);
lh.addTwoSiteTerm(edge, v1*getSXX());
lh.addTwoSiteTerm(edge, v2*getSYY());
lh.addTwoSiteTerm(edge, v3*getSZZ());
matEx += v1*twoQubitOp<double>(N, edge.first, edge.second, getSX(), getSX());
auto matYY = twoQubitOp<cx_double>(N, edge.first, edge.second, getSY(), getSY());
matEx += v2*matYY.real();
matEx += v3*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());
}
auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));
REQUIRE((mat-matEx).squaredNorm() < 1e-8);
}
}
SECTION("Random Field Ising Hamiltonian") {
edp::LocalHamiltonian<double> lh(N,2);
for(int n = 0; n < 20; ++n)
{
lh.clearTerms();
int numEdges = numEdgesRd(re);
auto edges = ggen.createRandomGraph(numEdges);
auto matEx = Eigen::MatrixXd(1<<N, 1<<N);
matEx.setZero();
for(const auto& edge: edges)
{
double v = urd(re);
lh.addTwoSiteTerm(edge, v*getSZZ());
matEx += v*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());
}
auto numFields = uid(re);
auto vs = ggen.createRandomVertexSet(numFields);
for(auto v: vs)
{
double h1 = urd(re);
double h3 = urd(re);
lh.addOneSiteTerm(v, h1*getSX());
lh.addOneSiteTerm(v, h3*getSZ());
matEx += h1*singleQubitOp<double>(N, v, getSX());
matEx += h3*singleQubitOp<double>(N, v, getSZ());
}
auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));
REQUIRE((mat-matEx).squaredNorm() < 1e-8);
}
}
}
| 24.31348
| 85
| 0.647886
|
chaeyeunpark
|
947d1390256ada9bca1292f25b4b71686952c03e
| 10,408
|
cpp
|
C++
|
pxr/usdImaging/lib/usdImaging/materialAdapter.cpp
|
navefx/YuksUSD
|
56c2e1def36ee07121f4ecb349c1626472b3c338
|
[
"AML"
] | 6
|
2018-08-26T13:27:22.000Z
|
2021-08-14T23:57:38.000Z
|
pxr/usdImaging/lib/usdImaging/materialAdapter.cpp
|
navefx/YuksUSD
|
56c2e1def36ee07121f4ecb349c1626472b3c338
|
[
"AML"
] | 1
|
2021-08-14T23:57:51.000Z
|
2021-08-14T23:57:51.000Z
|
pxr/usdImaging/lib/usdImaging/materialAdapter.cpp
|
navefx/YuksUSD
|
56c2e1def36ee07121f4ecb349c1626472b3c338
|
[
"AML"
] | 4
|
2018-06-14T18:14:59.000Z
|
2021-09-13T22:20:50.000Z
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usdImaging/usdImaging/materialAdapter.h"
#include "pxr/usdImaging/usdImaging/delegate.h"
#include "pxr/usdImaging/usdImaging/indexProxy.h"
#include "pxr/usdImaging/usdImaging/tokens.h"
#include "pxr/imaging/hd/material.h"
#include "pxr/usd/usdShade/connectableAPI.h"
#include "pxr/usd/usdRi/materialAPI.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfType)
{
typedef UsdImagingMaterialAdapter Adapter;
TfType t = TfType::Define<Adapter, TfType::Bases<Adapter::BaseAdapter> >();
t.SetFactory< UsdImagingPrimAdapterFactory<Adapter> >();
}
UsdImagingMaterialAdapter::~UsdImagingMaterialAdapter()
{
}
bool
UsdImagingMaterialAdapter::IsSupported(UsdImagingIndexProxy const* index) const
{
return index->IsSprimTypeSupported(HdPrimTypeTokens->material);
}
bool
UsdImagingMaterialAdapter::IsPopulatedIndirectly()
{
// Materials are populated as a consequence of populating a prim
// which uses the material.
return true;
}
SdfPath
UsdImagingMaterialAdapter::Populate(UsdPrim const& prim,
UsdImagingIndexProxy* index,
UsdImagingInstancerContext const* instancerContext)
{
// Since material are populated by reference, they need to take care not to
// be populated multiple times.
SdfPath cachePath = prim.GetPath();
if (index->IsPopulated(cachePath)) {
return cachePath;
}
index->InsertSprim(HdPrimTypeTokens->material,
cachePath,
prim, shared_from_this());
HD_PERF_COUNTER_INCR(UsdImagingTokens->usdPopulatedPrimCount);
return prim.GetPath();
}
/* virtual */
void
UsdImagingMaterialAdapter::TrackVariability(UsdPrim const& prim,
SdfPath const& cachePath,
HdDirtyBits* timeVaryingBits,
UsdImagingInstancerContext const*
instancerContext) const
{
// XXX: Time-varying parameters are not yet implemented
}
/* virtual */
void
UsdImagingMaterialAdapter::UpdateForTime(UsdPrim const& prim,
SdfPath const& cachePath,
UsdTimeCode time,
HdDirtyBits requestedBits,
UsdImagingInstancerContext const*
instancerContext) const
{
UsdImagingValueCache* valueCache = _GetValueCache();
if (requestedBits & HdMaterial::DirtyResource) {
// Walk the material network and generate a HdMaterialNetworkMap
// structure to store it in the value cache.
HdMaterialNetworkMap materialNetworkMap;
_GetMaterialNetworkMap(prim, &materialNetworkMap);
valueCache->GetMaterialResource(cachePath) = materialNetworkMap;
// Compute union of primvars from all networks
std::vector<TfToken> primvars;
for (const auto& entry: materialNetworkMap.map) {
primvars.insert(primvars.end(),
entry.second.primvars.begin(),
entry.second.primvars.end());
}
std::sort(primvars.begin(), primvars.end());
primvars.erase(std::unique(primvars.begin(), primvars.end()),
primvars.end());
valueCache->GetMaterialPrimvars(cachePath) = primvars;
}
}
/* virtual */
HdDirtyBits
UsdImagingMaterialAdapter::ProcessPropertyChange(UsdPrim const& prim,
SdfPath const& cachePath,
TfToken const& propertyName)
{
// XXX: This doesn't get notifications for dependent nodes.
return HdChangeTracker::AllDirty;
}
/* virtual */
void
UsdImagingMaterialAdapter::MarkDirty(UsdPrim const& prim,
SdfPath const& cachePath,
HdDirtyBits dirty,
UsdImagingIndexProxy* index)
{
index->MarkSprimDirty(cachePath, dirty);
}
/* virtual */
void
UsdImagingMaterialAdapter::_RemovePrim(SdfPath const& cachePath,
UsdImagingIndexProxy* index)
{
index->RemoveSprim(HdPrimTypeTokens->material, cachePath);
}
static
void extractPrimvarsFromNode(UsdShadeShader const & shadeNode,
HdMaterialNode const & node,
HdMaterialNetwork *materialNetwork)
{
// Check if it is a node that reads primvars.
// XXX : We could be looking at more stuff here like manifolds..
if (node.type == TfToken("Primvar_3")) {
// Extract the primvar name from the usd shade node
// and store it in the list of primvars in the network
UsdShadeInput nameAttrib = shadeNode.GetInput(TfToken("varname"));
if (nameAttrib) {
VtValue value;
nameAttrib.Get(&value);
if (value.IsHolding<std::string>()) {
materialNetwork->primvars.push_back(
TfToken(value.Get<std::string>()));
}
}
}
}
// Walk the shader graph and emit nodes in topological order
// to avoid forward-references.
static
void walkGraph(UsdShadeShader const & shadeNode,
HdMaterialNetwork *materialNetwork)
{
// Store the path of the node
HdMaterialNode node;
node.path = shadeNode.GetPath();
if (!TF_VERIFY(node.path != SdfPath::EmptyPath())) {
return;
}
// If this node has already been found via another path, we do
// not need to add it again.
for (HdMaterialNode const& existingNode: materialNetwork->nodes) {
if (existingNode.path == node.path) {
return;
}
}
// Visit the inputs of this node to ensure they are emitted first.
const std::vector<UsdShadeInput> shadeNodeInputs = shadeNode.GetInputs();
for (UsdShadeInput const& input: shadeNodeInputs) {
// Check if this input is a connection and if so follow the path
UsdShadeConnectableAPI source;
TfToken outputName;
UsdShadeAttributeType sourceType;
if (UsdShadeConnectableAPI::GetConnectedSource(input,
&source, &outputName, &sourceType)) {
// When we find a connection, we try to walk it.
UsdShadeShader connectedNode(source);
walkGraph(connectedNode, materialNetwork);
}
}
// Extract the type of the node
VtValue value;
shadeNode.GetIdAttr().Get(&value);
if (value.IsHolding<TfToken>()){
node.type = value.UncheckedGet<TfToken>();
// If a node is recognizable, we will try to extract the primvar
// names that is using since this can help render delegates
// optimize what what is needed from a prim when making data
// accessible for renderers.
extractPrimvarsFromNode(shadeNode, node, materialNetwork);
} else {
TF_WARN("UsdShade Shader without an id: %s.", node.path.GetText());
node.type = TfToken("PbsNetworkMaterialStandIn_2");
}
// Add the parameters and the relationships of this node
for (UsdShadeInput const& input: shadeNodeInputs) {
// Check if this input is a connection and if so follow the path
UsdShadeConnectableAPI source;
TfToken outputName;
UsdShadeAttributeType sourceType;
if (UsdShadeConnectableAPI::GetConnectedSource(input,
&source, &outputName, &sourceType)) {
// Store the relationship
HdMaterialRelationship relationship;
relationship.sourceId = shadeNode.GetPath();
relationship.sourceTerminal = input.GetBaseName();
relationship.remoteId = source.GetPath();
relationship.remoteTerminal = outputName;
materialNetwork->relationships.push_back(relationship);
} else {
// Parameters detected, let's store it
if (input.Get(&value)) {
node.parameters[input.GetBaseName()] = value;
}
}
}
materialNetwork->nodes.push_back(node);
}
void
UsdImagingMaterialAdapter::_GetMaterialNetworkMap(UsdPrim const &usdPrim,
HdMaterialNetworkMap *materialNetworkMap) const
{
// This function expects a usdPrim of type Material. However, it will
// only be able to fill the HdMaterialNetwork structures if the Material
// contains a material network with a riLook relationship. Otherwise, it
// will return the HdMaterialNetwork structures without any change.
UsdRiMaterialAPI m(usdPrim);
// For each network type:
// Resolve the binding to the first node which
// is usually the standin node in the case of a UsdRi.
// If it fails to provide a relationship then we are not in a
// usdPrim that contains a correct terminal to a UsdShade Shader node.
if (UsdShadeShader surfaceShader = m.GetSurface()) {
walkGraph(surfaceShader,
&materialNetworkMap->map[UsdImagingTokens->bxdf]);
}
if (UsdShadeShader dispShader = m.GetDisplacement()) {
walkGraph(dispShader,
&materialNetworkMap->map[UsdImagingTokens->displacement]);
}
}
PXR_NAMESPACE_CLOSE_SCOPE
| 37.039146
| 79
| 0.64412
|
navefx
|
947ffd82a8f2ee330e0277e49c4d1f0ddb1f328c
| 752
|
cc
|
C++
|
ext/snow-ext/hash.cc
|
nilium/snow
|
296466e49fd5ebd8d4d40dbf96b14903daa705a8
|
[
"Zlib",
"BSD-2-Clause"
] | 4
|
2015-10-01T20:10:20.000Z
|
2021-08-28T23:43:33.000Z
|
ext/snow-ext/hash.cc
|
nilium/snow
|
296466e49fd5ebd8d4d40dbf96b14903daa705a8
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
ext/snow-ext/hash.cc
|
nilium/snow
|
296466e49fd5ebd8d4d40dbf96b14903daa705a8
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
#include "hash.hh"
#include "murmur3.h"
namespace murmur3 {
uint32_t hash32(const string &str, uint32_t seed)
{
return hash32(str.c_str(), str.size(), seed);
}
uint64_t hash64(const string &str, uint32_t seed)
{
return hash64(str.c_str(), str.size(), seed);
}
uint64_t hash64(const char *str, const size_t length, uint32_t seed)
{
union {
struct {
uint64_t lower;
uint64_t upper;
} block;
char raw[16];
} buf;
MurmurHash3_x86_128(str, static_cast<int>(length), seed, buf.raw);
return buf.block.upper;
}
uint32_t hash32(const char *str, const size_t length, uint32_t seed)
{
uint32_t result = 0;
MurmurHash3_x86_32(str, static_cast<int>(length), seed, static_cast<void *>(&result));
return result;
}
}
| 18.8
| 88
| 0.683511
|
nilium
|
9480e7c1a18f1682a67c7f2ee6baec0dfc9b7093
| 16,998
|
ipp
|
C++
|
include/native/async/ActionCallbackFinally.ipp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 16
|
2016-03-16T22:16:18.000Z
|
2021-04-05T04:46:38.000Z
|
include/native/async/ActionCallbackFinally.ipp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 11
|
2016-03-16T22:02:26.000Z
|
2021-04-04T02:20:51.000Z
|
include/native/async/ActionCallbackFinally.ipp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 5
|
2016-03-22T14:03:34.000Z
|
2021-01-06T18:08:46.000Z
|
#ifndef __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__
#define __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__
/*-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* Propose :
* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/
#include "./ActionCallbackFinally.hpp"
#include "./Future.hpp"
namespace native {
template <typename R, typename... Args>
std::shared_ptr<ActionCallbackFinally<R, Args...>>
ActionCallbackFinally<R, Args...>::Create(std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinally<R, Args...>>(
new ActionCallbackFinally<R, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename R, typename... Args>
std::shared_ptr<ActionCallbackFinally<Future<R>, Args...>> ActionCallbackFinally<Future<R>, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinally<Future<R>, Args...>>(
new ActionCallbackFinally<Future<R>, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename... Args>
std::shared_ptr<ActionCallbackFinally<Future<void>, Args...>> ActionCallbackFinally<Future<void>, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<Future<void>(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinally<Future<void>, Args...>>(
new ActionCallbackFinally<Future<void>, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename... Args>
std::shared_ptr<ActionCallbackFinally<void, Args...>> ActionCallbackFinally<void, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinally<void, Args...>>(
new ActionCallbackFinally<void, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename R, typename P, typename... Args>
std::shared_ptr<ActionCallbackFinallyP1<R, P, Args...>> ActionCallbackFinallyP1<R, P, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinallyP1<R, P, Args...>>(
new ActionCallbackFinallyP1<R, P, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename R, typename P, typename... Args>
std::shared_ptr<ActionCallbackFinallyP1<Future<R>, P, Args...>> ActionCallbackFinallyP1<Future<R>, P, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinallyP1<Future<R>, P, Args...>>(
new ActionCallbackFinallyP1<Future<R>, P, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename P, typename... Args>
std::shared_ptr<ActionCallbackFinallyP1<Future<void>, P, Args...>>
ActionCallbackFinallyP1<Future<void>, P, Args...>::Create(std::shared_ptr<Loop> iLoop,
std::function<Future<void>(Args...)> f,
Args &&... args) {
return std::shared_ptr<ActionCallbackFinallyP1<Future<void>, P, Args...>>(
new ActionCallbackFinallyP1<Future<void>, P, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename P, typename... Args>
std::shared_ptr<ActionCallbackFinallyP1<void, P, Args...>> ActionCallbackFinallyP1<void, P, Args...>::Create(
std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) {
return std::shared_ptr<ActionCallbackFinallyP1<void, P, Args...>>(
new ActionCallbackFinallyP1<void, P, Args...>(iLoop, f, std::forward<Args>(args)...));
}
template <typename R, typename... Args>
ActionCallbackFinally<R, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop,
std::function<R(Args...)> f,
Args &&... args)
: ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<R>::Create(iLoop)) {}
template <typename R, typename... Args>
ActionCallbackFinally<Future<R>, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop,
std::function<Future<R>(Args...)> f,
Args &&... args)
: ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<R>::Create(iLoop)) {}
template <typename... Args>
ActionCallbackFinally<Future<void>, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop,
std::function<Future<void>(Args...)> f,
Args &&... args)
: ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<void>::Create(iLoop)) {}
template <typename... Args>
ActionCallbackFinally<void, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop,
std::function<void(Args...)> f,
Args &&... args)
: ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<void>::Create(iLoop)) {}
template <typename R, typename P, typename... Args>
ActionCallbackFinallyP1<R, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop,
std::function<R(Args...)> f,
Args &&... args)
: ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) {
}
template <typename R, typename P, typename... Args>
ActionCallbackFinallyP1<Future<R>, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop,
std::function<Future<R>(Args...)> f,
Args &&... args)
: ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) {
}
template <typename P, typename... Args>
ActionCallbackFinallyP1<Future<void>, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop,
std::function<Future<void>(Args...)> f,
Args &&... args)
: ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<void>::Create(iLoop)) {}
template <typename P, typename... Args>
ActionCallbackFinallyP1<void, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop,
std::function<void(Args...)> f,
Args &&... args)
: ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...),
_future(FutureShared<void>::Create(iLoop)) {}
template <typename R, typename... Args>
std::shared_ptr<FutureShared<R>> ActionCallbackFinally<R, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename R, typename... Args>
std::shared_ptr<FutureShared<R>> ActionCallbackFinally<Future<R>, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename... Args>
std::shared_ptr<FutureShared<void>> ActionCallbackFinally<Future<void>, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename... Args> std::shared_ptr<FutureShared<void>> ActionCallbackFinally<void, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename R, typename P, typename... Args>
std::shared_ptr<FutureShared<R>> ActionCallbackFinallyP1<R, P, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename R, typename P, typename... Args>
std::shared_ptr<FutureShared<R>> ActionCallbackFinallyP1<Future<R>, P, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename P, typename... Args>
std::shared_ptr<FutureShared<void>> ActionCallbackFinallyP1<Future<void>, P, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename P, typename... Args>
std::shared_ptr<FutureShared<void>> ActionCallbackFinallyP1<void, P, Args...>::getFuture() {
NNATIVE_ASSERT(this->_future);
return this->_future;
}
template <typename R, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinally<R, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
try {
this->getFuture()->resolve(this->_f(std::get<Is>(this->_args)...));
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename R, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinally<Future<R>, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
std::shared_ptr<ActionCallbackBase<void>> iInstance = this->getInstance();
try {
this->_f(std::get<Is>(this->_args)...)
.template then<std::function<void(R)>>([iInstance](R &&r) {
ActionCallbackFinally<Future<R>, Args...> *currPtr =
static_cast<ActionCallbackFinally<Future<R>, Args...> *>(iInstance.get());
currPtr->getFuture()->resolve(std::forward<R>(r));
})
.template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) {
ActionCallbackFinally<Future<R>, Args...> *currPtr =
static_cast<ActionCallbackFinally<Future<R>, Args...> *>(iInstance.get());
currPtr->getFuture()->reject(iError);
});
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename... Args>
template <std::size_t... Is>
void ActionCallbackFinally<Future<void>, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
std::shared_ptr<ActionCallbackBase<void>> iInstance = this->getInstance();
try {
this->_f(std::get<Is>(this->_args)...)
.template then<std::function<void()>>([iInstance]() {
ActionCallbackFinally<Future<void>, Args...> *currPtr =
static_cast<ActionCallbackFinally<Future<void>, Args...> *>(iInstance.get());
currPtr->getFuture()->resolve();
})
.template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) {
ActionCallbackFinally<Future<void>, Args...> *currPtr =
static_cast<ActionCallbackFinally<Future<void>, Args...> *>(iInstance.get());
currPtr->getFuture()->reject(iError);
});
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename... Args>
template <std::size_t... Is>
void ActionCallbackFinally<void, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
try {
this->_f(std::get<Is>(this->_args)...);
this->getFuture()->resolve();
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename R, typename P, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinallyP1<R, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
try {
this->getFuture()->resolve(this->_f(std::get<Is>(this->_args)...));
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename R, typename P, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinallyP1<Future<R>, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
std::shared_ptr<ActionCallbackBase<P>> iInstance = this->getInstance();
try {
this->_f(std::get<Is>(this->_args)...)
.template then<std::function<void(R)>>([iInstance](R &&r) {
ActionCallbackFinallyP1<Future<R>, P, Args...> *currPtr =
static_cast<ActionCallbackFinallyP1<Future<R>, P, Args...> *>(iInstance.get());
currPtr->getFuture()->resolve(std::forward<R>(r));
})
.template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) {
ActionCallbackFinallyP1<Future<R>, P, Args...> *currPtr =
static_cast<ActionCallbackFinallyP1<Future<R>, P, Args...> *>(iInstance.get());
currPtr->getFuture()->reject(iError);
});
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename P, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinallyP1<Future<void>, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
std::shared_ptr<ActionCallbackBase<P>> iInstance = this->getInstance();
try {
this->_f(std::get<Is>(this->_args)...)
.template then<std::function<void()>>([iInstance]() {
ActionCallbackFinallyP1<Future<void>, P, Args...> *currPtr =
static_cast<ActionCallbackFinallyP1<Future<void>, P, Args...> *>(iInstance.get());
currPtr->getFuture()->resolve();
})
.template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) {
ActionCallbackFinallyP1<Future<void>, P, Args...> *currPtr =
static_cast<ActionCallbackFinallyP1<Future<void>, P, Args...> *>(iInstance.get());
currPtr->getFuture()->reject(iError);
});
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename P, typename... Args>
template <std::size_t... Is>
void ActionCallbackFinallyP1<void, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) {
try {
this->_f(std::get<Is>(this->_args)...);
this->getFuture()->resolve();
} catch (const FutureError &e) {
this->getFuture()->reject(e);
}
}
template <typename R, typename... Args> void ActionCallbackFinally<R, Args...>::resolveCb() {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename... Args> void ActionCallbackFinally<Future<R>, Args...>::resolveCb() {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename... Args> void ActionCallbackFinally<Future<void>, Args...>::resolveCb() {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename... Args> void ActionCallbackFinally<void, Args...>::resolveCb() {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename P, typename... Args> void ActionCallbackFinallyP1<R, P, Args...>::resolveCb(P p) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename P, typename... Args>
void ActionCallbackFinallyP1<Future<R>, P, Args...>::resolveCb(P p) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename P, typename... Args> void ActionCallbackFinallyP1<Future<void>, P, Args...>::resolveCb(P p) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename P, typename... Args> void ActionCallbackFinallyP1<void, P, Args...>::resolveCb(P p) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename... Args> void ActionCallbackFinally<R, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename... Args>
void ActionCallbackFinally<Future<R>, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename... Args> void ActionCallbackFinally<Future<void>, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename... Args> void ActionCallbackFinally<void, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename P, typename... Args>
void ActionCallbackFinallyP1<R, P, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename R, typename P, typename... Args>
void ActionCallbackFinallyP1<Future<R>, P, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename P, typename... Args>
void ActionCallbackFinallyP1<Future<void>, P, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
template <typename P, typename... Args>
void ActionCallbackFinallyP1<void, P, Args...>::rejectCb(const FutureError &iError) {
this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>());
}
} /* namespace native */
#endif /* __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__ */
| 45.571046
| 120
| 0.628486
|
nodenative
|
9483c83e1d7cb618fe4f641897f083fd06d51411
| 18,291
|
cpp
|
C++
|
skinManagerGui-gtk/src/main.cpp
|
robotology-legacy/icub-gtk-modules
|
10b1d645b4a9818b0cb002b0d2d015e13ad32168
|
[
"BSD-3-Clause"
] | null | null | null |
skinManagerGui-gtk/src/main.cpp
|
robotology-legacy/icub-gtk-modules
|
10b1d645b4a9818b0cb002b0d2d015e13ad32168
|
[
"BSD-3-Clause"
] | null | null | null |
skinManagerGui-gtk/src/main.cpp
|
robotology-legacy/icub-gtk-modules
|
10b1d645b4a9818b0cb002b0d2d015e13ad32168
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370
* Authors: Andrea Del Prete
* email: andrea.delprete@iit.it
* website: www.robotcub.org
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* http://www.robotcub.org/icub/license/gpl.txt
*
* 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
*/
/**
*
* @ingroup icub_tools
* @ingroup icub_guis
* \defgroup icub_skinManagerGui skinManagerGui
*
* A simple graphical interface for controlling and monitoring an instance of the \ref icub_skinManager module.
* This GUI needs at least the version 2.14 of GtkPlus.
*
* \image html driftCompensationGui_filters.png "Screenshots: skinManagerGui running on Windows"
*
* \section intro_sec Description
*
* This GUI can be used for the following purposes:
*
* - calibrate the skin
* - see the touch threshold of each skin taxels
* - turn on/off the binarization filter
* - turn on/off the smooth filter
* - tune the smooth factor of the smooth filter
* - tune the compensation algorithm parameters (i.e. safety threshold, compensation gain, contact compensation gain)
* - monitor the skin data frequency
* - monitor the drift of each skin taxel
* - get warning and error messages related to the skin
* - see all the ports read by the interested \ref icub_skinManager module
*
* \section parameters_sec Parameters
*
* \code
* --name: name of the gui (used to form port names)
* --from: configuration file
* --context: directory where to search the configuration file (specified from $ICUB_ROOT/app)
* --xpos: position of the gui on the screen on the x axis expressed in pixel
* --ypos: position of the gui on the screen on the y axis expressed in pixel
* \endcode
* Example:
* \code
* skinManagerGui --name skinManGuiLeft --from skinManGuiLeft.ini --context skinGui
* \endcode
*
* \section portsa_sec Ports Accessed
* None
*
* \section portsc_sec Ports Created
* Three ports are created for communicating with the \ref icub_skinManager module.
* The port names are:
* - "/" + guiName + "/rpc:o"
* - "/" + guiName + "/monitor:i"
* - "/" + guiName + "/info:i"
* \n These ports should be externally connected to the corresponding \ref icub_skinManager ports.
*
* \section conf_file_sec Configuration Files
*
* None.
*
* \section tested_os_sec Tested OS
* Linux and Windows.
*
* \author Andrea Del Prete (andrea.delprete@iit.it)
*
*Copyright (C) 2010 RobotCub Consortium
*
*CopyPolicy: Released under the terms of the GNU GPL v2.0.
*
*This file can be edited at main/src/tools/skinManagerGui/src/main.cpp.
**/
#include <string>
#include "iCub/skinManagerGui/guiCallback.h"
bool initGuiStatus() {
Bottle reply = sendRpcCommand(true, get_binarization);
if(string(reply.toString().c_str()).compare("on") == 0){
gtk_toggle_button_set_active(btnBinarization, true);
gtk_button_set_label(GTK_BUTTON(btnBinarization), "ON");
}
reply = sendRpcCommand(true, get_smooth_filter);
if(string(reply.toString().c_str()).compare("on") == 0){
gtk_toggle_button_set_active(btnSmooth, true);
gtk_button_set_label(GTK_BUTTON(btnSmooth), "ON");
gtk_widget_set_sensitive(GTK_WIDGET(scaleSmooth), true);
}else{
gtk_widget_set_sensitive(GTK_WIDGET(scaleSmooth), false);
}
reply = sendRpcCommand(true, get_smooth_factor);
currentSmoothFactor = reply.get(0).asDouble();
gtk_adjustment_set_value(scaleSmooth->range.adjustment, currentSmoothFactor);
reply = sendRpcCommand(true, get_threshold);
if(reply.isNull() || reply.size()==0 || !reply.get(0).isInt()){
printLog("Error while getting the safety threshold");
return false;
}else{
currentThreshold = reply.get(0).asInt();
gtk_adjustment_set_value(spinThreshold->adjustment, currentThreshold);
}
reply = sendRpcCommand(true, get_gain);
if(reply.isNull() || reply.size()==0 || (!reply.get(0).isDouble() && !reply.get(0).isInt())){
printLog("Error while getting the compensation gain");
return false;
}else{
currentCompGain = reply.get(0).asDouble();
gtk_adjustment_set_value(spinGain->adjustment, currentCompGain);
}
reply = sendRpcCommand(true,get_cont_gain);
if(reply.isNull() || reply.size()==0 || (!reply.get(0).isDouble() && !reply.get(0).isInt())){
printLog("Error while getting the contact compensation gain");
return false;
}else{
currentContCompGain = reply.get(0).asDouble();
gtk_adjustment_set_value(spinContGain->adjustment, currentContCompGain);
}
reply = sendRpcCommand(true,get_max_neigh_dist);
if(reply.isNull() || reply.size()==0 || (!reply.get(0).isDouble() && !reply.get(0).isInt())){
printLog("Error while getting the max neighbor distance");
return false;
}else{
currentMaxNeighDist = reply.get(0).asDouble();
gtk_adjustment_set_value(spinMaxNeighDist->adjustment, 1e2*currentMaxNeighDist);
}
// get module information
reply = sendRpcCommand(true, get_info);
if(reply.isNull() || reply.size()!=3){
printLog("Error while reading the module information");
gtk_label_set_text(lblInfo, reply.toString().c_str());
return false;
}
stringstream ss;
ss<< reply.get(0).toString().c_str()<< endl;
ss<< reply.get(1).toString().c_str()<< "\nInput ports:";
Bottle* portList = reply.get(2).asList();
portNames.resize(portList->size()/2);
portDim.resize(portList->size()/2);
//int numTaxels = 0;
for(unsigned int i=0;i<portDim.size();i++){
portNames[i] = portList->get(i*2).toString().c_str();
portDim[i] = portList->get(i*2+1).asInt();
//numTaxels += portDim[i];
ss<< "\n - "<< portNames[i]<< " ("<< portDim[i]<< " taxels)";
}
gtk_label_set_text(lblInfo, ss.str().c_str());
// plot
unsigned int numTriangles = portDim[0]/12;
GtkTreeIter iter;
//gtk_label_set_text(lblMaxX, ss.str().c_str());
for(unsigned int i=0;i<portDim.size();i++){
gtk_list_store_append (listPort, &iter);
gtk_list_store_set (listPort, &iter, 0, i, 1, portNames[i].c_str(), -1);
}
for(unsigned int i=0;i<numTriangles;i++){
gtk_list_store_append (listTriangle, &iter);
gtk_list_store_set (listTriangle, &iter, 0, i, -1);
}
for(unsigned int i=0;i<12;i++){
gtk_list_store_append (listTaxel, &iter);
gtk_list_store_set (listTaxel, &iter, 0, i, -1);
}
gtk_combo_box_set_active(comboPort, 0);
gtk_combo_box_set_active(comboTriangle, 0);
gtk_combo_box_set_active(comboTaxel, 0);
stringstream maxXS; maxXS<< currentSampleNum/currentSampleFreq;
gtk_label_set_text(lblMaxX, maxXS.str().c_str());
gtk_curve_set_range(curveComp, 0, (gfloat)currentSampleNum, 0, 255);
// check whether the skin calibration is in process
reply = sendRpcCommand(true, is_calibrating);
if(string(reply.toString().c_str()).compare("yes")==0){
gtk_widget_show(GTK_WIDGET(progBarCalib));
g_timeout_add(100, progressbar_calibration, NULL);
gtk_widget_set_sensitive(GTK_WIDGET(btnCalibration), false);
}
return true;
}
bool initNetwork(Network& yarp, ResourceFinder &rf, int argc, char *argv[], string &guiName, unsigned int& gXpos, unsigned int& gYpos){
rf.setDefaultConfigFile("skinManGui.ini"); //overridden by --from parameter
rf.setDefaultContext("skinGui"); //overridden by --context parameter
rf.configure(argc, argv);
gXpos=10;
gYpos=10;
if (rf.check("xpos")) gXpos=rf.find("xpos").asInt();
if (rf.check("ypos")) gYpos=rf.find("ypos").asInt();
string driftCompRpcPortName = rf.check("skinManRpcPort", Value("/skinManager/rpc")).asString().c_str();
string driftCompMonitorPortName = rf.check("skinManMonitorPort", Value("/skinManager/monitor:o")).asString().c_str();
string skinDiagnosticsErrorPortName = rf.check("skinDiagnosticsErrorsPort", Value("/diagnostics/skin/errors:o")).asString().c_str();
guiName = rf.check("name", Value("skinManGui")).asString().c_str();
string guiRpcPortName = "/" + guiName + "/rpc:o";
string guiMonitorPortName = "/" + guiName + "/monitor:i";
string guiInfoPortName = "/" + guiName + "/info:i";
string guiDiagnosticsErrorPortName = "/" + guiName + "/diagnostics/skin/errors:i";
//string wholeBodyRpcPortName = "/" + guiName + "/wholeBody/rpc";
if (!guiRpcPort.open(guiRpcPortName.c_str())) {
string msg = string("Unable to open port ") + guiRpcPortName.c_str();
openDialog(msg.c_str(), GTK_MESSAGE_ERROR);
return false;
}
if (!driftCompMonitorPort.open(guiMonitorPortName.c_str())){
string msg = string("Unable to open port ") + guiMonitorPortName.c_str();
openDialog(msg.c_str(), GTK_MESSAGE_ERROR);
return false;
}
if (!driftCompInfoPort.open(guiInfoPortName.c_str())){
string msg = string("Unable to open port ") + guiInfoPortName.c_str();
openDialog(msg.c_str(), GTK_MESSAGE_ERROR);
return false;
}
// Open skin diagnostics port
if (!portSkinDiagnosticsErrorsIn.open(guiDiagnosticsErrorPortName.c_str())) {
string msg = string("Unable to open port ") + guiDiagnosticsErrorPortName.c_str();
openDialog(msg.c_str(), GTK_MESSAGE_ERROR);
return false;
}
// if (!wholeBodyRpcPort.open(wholeBodyRpcPortName.c_str())){
// string msg = string("Unable to open port ") + wholeBodyRpcPortName.c_str();
// openDialog(msg.c_str(), GTK_MESSAGE_ERROR);
// return false;
//}
driftCompInfoPort.setStrict();
// automatic connections removed because they gave problems when running the gui
// just after the skinDriftCompensation module (using manager.py)
/*if(!yarp.connect(guiRpcPortName.c_str(), driftCompRpcPortName.c_str())){
string msg = string("Unable to connect to skinDriftCompensation rpc port: ")
+ driftCompRpcPortName.c_str() + ". Connect later.";
openDialog(msg.c_str(), GTK_MESSAGE_WARNING);
}
if(!yarp.connect(driftCompMonitorPortName.c_str(), guiMonitorPortName.c_str())){
string msg = string("Unable to connect to skinDriftCompensation monitor port: ")
+ driftCompMonitorPortName.c_str() + ". Connect later.";
openDialog(msg.c_str(), GTK_MESSAGE_WARNING);
}
if(!yarp.connect(driftCompInfoPortName.c_str(), guiInfoPortName.c_str())){
string msg = string("Unable to connect to skinDriftCompensation info port: ")
+ driftCompInfoPortName.c_str() + ". Connect later.";
openDialog(msg.c_str(), GTK_MESSAGE_WARNING);
}*/
/*if(!yarp.connect(wholeBodyRpcPort.getName().c_str(), "/wholeBodyDynamics/rpc:i"))
openDialog("Unable to connect to wholeBodyDynamics rpc port. Connect later.", GTK_MESSAGE_WARNING);*/
return true;
}
int main (int argc, char *argv[])
{
GtkBuilder *builder;
GtkButton *btnTouchThr;
GtkButton *btnClearLog;
GtkSpinButton *spinSampleFreq;
GtkSpinButton *spinSampleNum;
GError *error = NULL;
Network yarp;
ResourceFinder rf;
string guiName;
unsigned int gXpos, gYpos;
#if !GLIB_CHECK_VERSION(2, 32, 0)
// since Glib 2.32 g_thread_init is deprecated
g_thread_init (NULL);
#endif
gdk_threads_init ();
gdk_threads_enter ();
gtk_init (&argc, &argv); // initialize gtk
builder = gtk_builder_new ();
if(!initNetwork(yarp, rf, argc, argv, guiName, gXpos, gYpos))
return 0;
rf.setDefault("gladeFile", "skinManGui.glade");
string gladeFile = rf.findFile("gladeFile");
if( !gtk_builder_add_from_file (builder, gladeFile.c_str(), &error)){
g_warning( "%s", error->message );
clean_exit();
return 0;
}
// get pointers to the widgets we are interested in
window = GTK_WINDOW (gtk_builder_get_object (builder, "window"));
btnSmooth = GTK_TOGGLE_BUTTON (gtk_builder_get_object (builder, "btnSmooth"));
btnBinarization = GTK_TOGGLE_BUTTON (gtk_builder_get_object (builder, "btnBinarization"));
btnClearLog = GTK_BUTTON (gtk_builder_get_object (builder, "btnClearLog"));
scaleSmooth = GTK_SCALE (gtk_builder_get_object (builder, "scaleSmooth"));
btnCalibration = GTK_BUTTON (gtk_builder_get_object (builder, "btnCalibration"));
progBarCalib = GTK_PROGRESS_BAR (gtk_builder_get_object (builder, "progressbarCalib"));
btnTouchThr = GTK_BUTTON (gtk_builder_get_object (builder, "btnThreshold"));
spinThreshold = GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonThreshold"));
spinGain = GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonGain"));
spinContGain = GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonContGain"));
spinMaxNeighDist= GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonMaxNeighDist"));
tbLog = GTK_TEXT_BUFFER (gtk_builder_get_object (builder, "textbufferLog"));
tvLog = GTK_TEXT_VIEW (gtk_builder_get_object (builder, "textviewLog"));
lblInfo = GTK_LABEL (gtk_builder_get_object (builder, "labelInfo"));
treeBaselines = GTK_TREE_VIEW (gtk_builder_get_object (builder, "treeview"));
treeStoreComp = GTK_TREE_STORE (gtk_builder_get_object (builder, "treestore"));
curveComp = GTK_CURVE (gtk_builder_get_object (builder, "curve"));
lblMaxY = GTK_LABEL (gtk_builder_get_object (builder, "lblMaxY"));
lblMinY = GTK_LABEL (gtk_builder_get_object (builder, "lblMinY"));
lblMaxX = GTK_LABEL (gtk_builder_get_object (builder, "lblMaxX"));
lblMinX = GTK_LABEL (gtk_builder_get_object (builder, "lblMinX"));
comboPort = GTK_COMBO_BOX (gtk_builder_get_object (builder, "comboboxPort"));
comboTriangle = GTK_COMBO_BOX (gtk_builder_get_object (builder, "comboboxTriangle"));
comboTaxel = GTK_COMBO_BOX (gtk_builder_get_object (builder, "comboboxTaxel"));
listPort = GTK_LIST_STORE(gtk_builder_get_object (builder, "liststorePort"));
listTriangle = GTK_LIST_STORE(gtk_builder_get_object (builder, "liststoreTriangle"));
listTaxel = GTK_LIST_STORE(gtk_builder_get_object (builder, "liststoreTaxel"));
spinSampleFreq = GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonSampleFreq"));
spinSampleNum = GTK_SPIN_BUTTON (gtk_builder_get_object (builder, "spinbuttonSampleNum"));
statusBar = GTK_STATUSBAR (gtk_builder_get_object (builder, "statusBar"));
statusBarFreq = GTK_STATUSBAR (gtk_builder_get_object (builder, "statusbarFreq"));
// if the rpc port is connected, then initialize the gui status
initDone = false;
if(guiRpcPort.getOutputCount()>0)
initDone = initGuiStatus();
if(initDone)
printLog("GUI connected!");
else
printLog("GUI not connected. Connect it to the module to make it work.");
// otherwise the gui will try to initialize every timeout (i.e. 1 sec)
currentSampleFreq = 5;
currentSampleNum = 100;
dataPlot.resize(currentSampleNum);
gtk_adjustment_set_value(spinSampleFreq->adjustment, currentSampleFreq);
gtk_adjustment_set_value(spinSampleNum->adjustment, currentSampleNum);
// connect all the callback functions (after the initialization, so as not to activate the callbacks)
g_signal_connect(window, "destroy", G_CALLBACK(on_window_destroy_event), NULL);
g_signal_connect(btnSmooth, "button-press-event", G_CALLBACK(toggle_button_smooth), scaleSmooth);
g_signal_connect(btnBinarization, "button-press-event", G_CALLBACK(toggle_button_binarization), NULL);
g_signal_connect(btnCalibration, "button-press-event", G_CALLBACK(button_calibration), NULL);
g_signal_connect(btnTouchThr, "button-press-event", G_CALLBACK(button_threshold), NULL);
g_signal_connect(btnClearLog, "button-press-event", G_CALLBACK(button_clear_log), NULL);
g_signal_connect(scaleSmooth, "change-value", G_CALLBACK(scale_smooth_value_changed), NULL);
g_signal_connect(spinThreshold, "value-changed", G_CALLBACK(spin_threshold_value_changed), NULL);
g_signal_connect(spinGain, "value-changed", G_CALLBACK(spin_gain_value_changed), NULL);
g_signal_connect(spinContGain, "value-changed", G_CALLBACK(spin_cont_gain_value_changed), NULL);
g_signal_connect(spinMaxNeighDist, "value-changed", G_CALLBACK(spin_max_neigh_dist_value_changed), NULL);
g_signal_connect(comboPort , "changed", G_CALLBACK(comboPort_changed), NULL);
g_signal_connect(comboTriangle , "changed", G_CALLBACK(comboTriangle_changed), NULL);
g_signal_connect(comboTaxel , "changed", G_CALLBACK(comboTaxel_changed), NULL);
g_signal_connect(spinSampleFreq, "value-changed", G_CALLBACK(spinSampleFreq_value_changed), NULL);
g_signal_connect(spinSampleNum, "value-changed", G_CALLBACK(spinSampleNum_value_changed), NULL);
timeoutId = gdk_threads_add_timeout(1000/currentSampleFreq, (periodic_timeout), NULL); // thread safe version of "g_timeout_add()
// free the memory used by the glade xml file
g_object_unref (G_OBJECT (builder));
gtk_widget_show(GTK_WIDGET(window));
gtk_window_set_title(window, guiName.c_str());
gtk_window_set_resizable(window, true);
gtk_window_set_default_size(GTK_WINDOW(window),600,200);
gtk_window_resize(GTK_WINDOW(window),600,200);
gtk_window_move(GTK_WINDOW(window),gXpos,gYpos);
//printf("Main thread: %p\n", g_thread_self());
gtk_main ();
gdk_threads_leave();
return 0;
}
| 45.7275
| 139
| 0.691542
|
robotology-legacy
|
9483cd23602c72ffc8cd854fe54102cea2e0eb0a
| 1,846
|
cc
|
C++
|
test/test_file_writer.cc
|
wobbals/barc
|
ce7a417b37941a696105904e67058adbf0a35c59
|
[
"Apache-2.0"
] | 8
|
2017-02-21T21:07:44.000Z
|
2021-05-16T10:22:06.000Z
|
test/test_file_writer.cc
|
wobbals/barc
|
ce7a417b37941a696105904e67058adbf0a35c59
|
[
"Apache-2.0"
] | 11
|
2017-03-06T22:09:34.000Z
|
2020-05-12T07:06:09.000Z
|
test/test_file_writer.cc
|
wobbals/barc
|
ce7a417b37941a696105904e67058adbf0a35c59
|
[
"Apache-2.0"
] | 6
|
2017-02-21T21:35:48.000Z
|
2019-12-03T06:42:27.000Z
|
//
// test_file_writer.c
// barc
//
// Created by Charley Robinson on 3/16/17.
//
extern "C" {
#include <unistd.h>
#include "file_writer.h"
}
#include "gtest/gtest.h"
TEST(FileWriter, AllocFileWriter) {
struct file_writer_t* file_writer = NULL;
file_writer_alloc(&file_writer);
EXPECT_TRUE(file_writer != NULL);
file_writer_free(file_writer);
}
AVFrame* empty_audio_frame() {
AVFrame* frame = av_frame_alloc();
// TODO: Dig the format out of the file writer context for better flexibility
frame->pts = 0;
frame->format = AV_SAMPLE_FMT_FLTP;
frame->nb_samples = 1024;
frame->channel_layout = AV_CH_LAYOUT_MONO;
frame->sample_rate = 48000;
frame->channels = 1;
frame->data[0] = NULL;
EXPECT_TRUE(NULL == frame->data[0]);
int ret = av_frame_get_buffer(frame, 0);
EXPECT_TRUE(NULL != frame->data[0]);
return frame;
}
/* This isn't working. I think it might be waiting for a video frame.
* TODO: add a video frame.
TEST(FileWriter, WriteFrame) {
av_register_all();
avfilter_register_all();
int ret;
const char* outfile = "/tmp/output.mp4";
struct file_writer_t* file_writer = NULL;
file_writer_alloc(&file_writer);
EXPECT_TRUE(NULL != file_writer);
ret = file_writer_open(file_writer, outfile, 320, 240);
EXPECT_TRUE(0 == ret);
for (int i = 0; i < 1000; i++) {
AVFrame* frame = empty_audio_frame();
frame->pts = (i * 48000) / 20;
// probably the filtergraph resetting the frame. is this safe?
ret = file_writer_push_audio_frame(file_writer, frame);
// write frames until the filter graph is happy
if (0 == ret) {
break;
}
}
if (ret) printf("%s\n", av_err2str(ret));
EXPECT_TRUE(0 == ret);
ret = file_writer_close(file_writer);
EXPECT_TRUE(0 == ret);
EXPECT_TRUE(file_writer != NULL);
file_writer_free(file_writer);
unlink(outfile);
}
*/
| 26.371429
| 79
| 0.684724
|
wobbals
|
9486169b2ea75e97af60597fe4737dea2993fe73
| 1,088
|
cpp
|
C++
|
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | 3
|
2022-01-25T07:33:43.000Z
|
2022-03-30T10:25:09.000Z
|
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | null | null | null |
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | 2
|
2022-01-17T13:39:12.000Z
|
2022-03-30T10:25:12.000Z
|
#include <iostream>
#include <type_traits>
int a(int i){return i;} // function
int(*b)(int)=a; // pointer to function
struct C { int operator()(int i){return i;} } c; // function-like class
int main( int argc, char **argv )
{
{
# define REF(x) << #x " ?: " << x << '\n'
std::cout << std::boolalpha
REF( std::is_function<decltype(a)>::value )
REF( std::is_function<decltype(b)>::value )
REF( std::is_function<decltype(c)>::value )
REF( std::is_function<C>::value )
REF( std::is_function<int(int)>::value )
REF( std::is_function<int(*)(int)>::value );
# undef REF
}
{
# define REF(x) << #x " ?: " << x << '\n'
std::cout << std::boolalpha
REF( std::is_function_v<decltype(a)> )
REF( std::is_function_v<decltype(b)> )
REF( std::is_function_v<decltype(c)> )
REF( std::is_function_v<C> )
REF( std::is_function_v<int(int)> )
REF( std::is_function_v<int(*)(int)> );
# undef REF
}
return 0;
}
| 31.085714
| 72
| 0.517463
|
eric2003
|
94898f7becfe84ce195e0163ca94a9fdce0d90aa
| 2,735
|
cpp
|
C++
|
test/net/ReceiverTest.cpp
|
RoboTeamTwente/roboteam_mimir
|
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
|
[
"MIT"
] | 1
|
2019-11-16T17:44:13.000Z
|
2019-11-16T17:44:13.000Z
|
test/net/ReceiverTest.cpp
|
RoboTeamTwente/roboteam_mimir
|
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
|
[
"MIT"
] | 51
|
2019-09-29T09:16:22.000Z
|
2020-10-24T10:04:59.000Z
|
test/net/ReceiverTest.cpp
|
RoboTeamTwente/roboteam_mimir
|
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
|
[
"MIT"
] | null | null | null |
//
// Created by rolf on 19-09-19.
//
#include "net/Receiver.h"
#include "gtest/gtest.h"
TEST(ReceiverTest,receiveTest){
//We are going to manually send commands to test the receiver
QUdpSocket sendSocket;
QHostAddress address("127.0.0.1");
unsigned int port = 10006;
net::Receiver receiver(address,port);
// at this point the receiver should already be listening
sendSocket.bind(address,port);
mimir_robotcommand command;
// values we use to test
int id=7;
bool teamIsYellow=false;
float dribblespeed=0.5;
float velx= 0.3;
float vely= 0.4;
float angle = 1.0;
command.set_id(id);
command.set_teamisyellow(false);
command.set_dribblerspeed(0.5);
globalVelocity vel;
vel.set_angle(angle);
vel.set_velx(velx);
vel.set_vely(vely);
command.mutable_globalvel()->CopyFrom(vel);
bool chip=true;
int geneva=4;
float kickpower=0.8;
Kicker kicker;
kicker.set_chip(chip);
kicker.set_genevaangle(geneva);
kicker.set_kickchippower(kickpower);
command.mutable_kicker()->CopyFrom(kicker);
// now actually send the command twice!
QByteArray datagram;
datagram.resize(command.ByteSize());
ASSERT_TRUE(command.SerializeToArray(datagram.data(),datagram.size()));
ASSERT_EQ(sendSocket.writeDatagram(datagram,address,port),command.ByteSize());
ASSERT_EQ(sendSocket.writeDatagram(datagram,address,port),command.ByteSize());
auto messages=receiver.readMessages();
ASSERT_EQ(messages.size(),2);
auto msg=messages[0];
EXPECT_EQ(msg.id(),id);
EXPECT_EQ(msg.teamisyellow(),teamIsYellow);
EXPECT_FLOAT_EQ(msg.dribblerspeed(),dribblespeed);
EXPECT_TRUE(msg.has_globalvel());
EXPECT_FALSE(msg.has_robotvel());
EXPECT_FALSE(msg.has_wheels());
EXPECT_FLOAT_EQ(msg.globalvel().vely(),vely);
EXPECT_FLOAT_EQ(msg.globalvel().velx(),velx);
EXPECT_EQ(msg.globalvel().angleControl_case(),msg.globalvel().kAngleFieldNumber);
EXPECT_EQ(msg.globalvel().angle(),angle);
EXPECT_TRUE(msg.has_kicker());
EXPECT_EQ(msg.kicker().chip(),chip);
EXPECT_EQ(msg.kicker().genevaangle(),geneva);
EXPECT_FLOAT_EQ(msg.kicker().kickchippower(),kickpower);
}
TEST(ReceiverTest,setterGetters){
QHostAddress address("127.0.0.1");
unsigned int port = 10006;
net::Receiver receiver(address,port);
EXPECT_EQ(receiver.getPort(),port);
EXPECT_EQ(receiver.getIP(),"127.0.0.1");
int newPort=10005;
receiver.setIP(QHostAddress("127.0.0.2"));
receiver.setPort(newPort);
EXPECT_NE(receiver.getPort(),port);
EXPECT_NE(receiver.getIP(),"127.0.0.1");
EXPECT_EQ(receiver.getPort(),newPort);
EXPECT_EQ(receiver.getIP(),"127.0.0.2");
}
| 31.079545
| 85
| 0.696527
|
RoboTeamTwente
|
948b863e1c8374f2af65293d88e38b9c4aacbf52
| 11,235
|
cpp
|
C++
|
src/caffe/layers/search_n_layer.cpp
|
suyuan32/atlas_200dk_caffe
|
119c7696ea787363e2f58c2a7fb6e7395098b0d1
|
[
"MIT"
] | 1
|
2021-09-17T14:24:01.000Z
|
2021-09-17T14:24:01.000Z
|
src/caffe/layers/search_n_layer.cpp
|
suyuan32/atlas_200dk_caffe
|
119c7696ea787363e2f58c2a7fb6e7395098b0d1
|
[
"MIT"
] | null | null | null |
src/caffe/layers/search_n_layer.cpp
|
suyuan32/atlas_200dk_caffe
|
119c7696ea787363e2f58c2a7fb6e7395098b0d1
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Apache License Version 2.0.You may not use this file except in compliance with the License.
*
* 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
* Apache License for more details at
* http://www.apache.org/licenses/LICENSE-2.0
*
* @brief search shift bit layer cpp source
*
* @version 1.0
*/
#include <vector>
#include <cmath>
#include <fstream>
#include <iostream>
#include <map>
#include "caffe/layers/search_n_layer.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/amct_util.hpp"
namespace caffe {
const int LSTM_CHANNEL_NUM = 4;
const int LSTM_XH_CHANNEL_AXIS = 2;
const int LSTM_S_CHANNEL_AXIS = 1;
const int CONV_HEIGHT_AXIS = 2;
const int CONV_WIDTH_AXIS = 3;
template <typename Dtype>
void SearchNLayer<Dtype>::Reshape(const vector<Blob<Dtype>* >& bottom,
const vector<Blob<Dtype>* >& top)
{
if (top.size() == 1) {
top[0]->ReshapeLike(*bottom[0]);
}
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::ReadRecord(ScaleOffsetRecord* records)
{
if (!ReadProtoFromTextFile(recordFileName.c_str(), records)) {
LOG(ERROR) << "Read records from " << recordFileName << " failed.";
}
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::GetBottomChannels()
{
ScaleOffsetRecord records;
ReadRecord(&records);
for (auto layerName : quantLayerNames) {
bool found = false;
for (int i = 0; i < records.record_size(); i++) {
const ScaleOffsetRecord_MapFiledEntry& record = records.record(i);
if (record.has_key() && record.key() == layerName) {
found = true;
const SingleLayerRecord& layerQuantInfo = record.value();
int channel = layerQuantInfo.scale_w_size();
CHECK_GE(channel, 1);
bottomChannels.push_back(channel);
}
}
CHECK(found) << "Layer " << layerName << " not found in " << recordFileName;
}
for (int i = 1; i < bottomChannels.size(); i++) {
CHECK_EQ(bottomChannels[i], bottomChannels[0]) << "Channel number of layer " <<
quantLayerNames.Get(i) << "(" << bottomChannels[i] << ")" <<
" is different from layer " << quantLayerNames.Get(0) << "(" << bottomChannels[0] << ").";
}
for (int i = 0; i < bottomChannels.size(); i++) {
if (quantLayerTypes.Get(i) == string("InnerProduct")) {
CHECK_EQ(bottomChannels[i], 1) << "The channel number of InnerProduct layer(" << quantLayerNames.Get(i) <<
") should be 1, but actually is " << bottomChannels[i];
}
}
}
template <typename Dtype>
void SearchNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>* >& bottom,
const vector<Blob<Dtype>* >& top)
{
targetBatchNum = this->layer_param_.search_n_param().batch_num();
quantLayerNames = this->layer_param_.search_n_param().layer_name();
CHECK_GE(quantLayerNames.size(), 1);
showQuantLayerNames = "[";
for (auto layerName : quantLayerNames) {
showQuantLayerNames += layerName;
showQuantLayerNames += " ";
}
showQuantLayerNames[showQuantLayerNames.size() - 1] = ']';
quantLayerTypes = this->layer_param_.search_n_param().layer_type();
CHECK_EQ(quantLayerNames.size(), quantLayerTypes.size()) << "layer_name size(" << quantLayerNames.size() <<
") must be equal to layer_type size(" << quantLayerTypes.size() << ").";
recordFileName = this->layer_param_.search_n_param().record_file_path();
GetBottomChannels();
channelNum = bottomChannels[0];
for (int index = 0; index < quantLayerTypes.size(); ++index) {
if (quantLayerTypes.Get(index) == "Convolution" && channelNum > 1) {
if (bottom[index]->shape(CONV_HEIGHT_AXIS) == 1 && bottom[index]->shape(CONV_WIDTH_AXIS) == 1) {
globalConvFlag_ = true;
channelNum = 1;
LOG(INFO) << "Find layer \"" << quantLayerNames.Get(index) << "\" is global conv";
}
}
}
storedData.resize(channelNum);
}
template <typename Dtype>
void SearchNLayer<Dtype>::AccumulateData(const vector<Blob<Dtype>* >& bottom)
{
for (int i = 0; i < bottom.size(); i++) {
CHECK_GE(bottom[i]->shape().size(), MIN_SHAPE_SIZE);
if (quantLayerTypes.Get(0) != "LSTM_X" &&
quantLayerTypes.Get(0) != "LSTM_H" &&
quantLayerTypes.Get(0) != "LSTM_S") {
if (channelNum != 1) {
CHECK_EQ(bottom[i]->shape()[1], channelNum) << "Channel wise but scale size: " \
<< channelNum << " != channel in: " << bottom[i]->shape()[1];
}
} else {
CHECK_EQ(channelNum, LSTM_CHANNEL_NUM);
}
}
for (int i = 0; i < bottom.size(); i++) {
Blob<Dtype>* curBottom = bottom[i];
int count = curBottom->count();
const Dtype* bottomData = curBottom->cpu_data();
unsigned int channelID = 0;
unsigned int CHW = curBottom->count(C_INDEX);
unsigned int HW = curBottom->count(H_INDEX);
if (quantLayerTypes.Get(0) == "LSTM_X" || quantLayerTypes.Get(0) == "LSTM_H") {
CHW = curBottom->count(LSTM_XH_CHANNEL_AXIS);
HW = curBottom->shape(LSTM_XH_CHANNEL_AXIS) / LSTM_CHANNEL_NUM;
} else if (quantLayerTypes.Get(0) == "LSTM_S") {
CHW = curBottom->count(LSTM_S_CHANNEL_AXIS);
HW = curBottom->shape(LSTM_S_CHANNEL_AXIS) / LSTM_CHANNEL_NUM;
}
if (channelNum > 1) {
for (int offset = 0; offset < count; offset++) {
channelID = (offset % CHW) / HW;
storedData[channelID].push_back(bottomData[offset]);
}
} else {
for (int offset = 0; offset < count; offset++) {
storedData[channelID].push_back(bottomData[offset]);
}
}
}
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::GetDeqScale()
{
ScaleOffsetRecord records;
ReadRecord(&records);
Dtype scaleD = 0;
vector<vector<Dtype>> allDeqScales(quantLayerNames.size());
for (int i = 0; i < quantLayerNames.size(); i++) {
string layerName(quantLayerNames.Get(i));
for (int j = 0; j < records.record_size(); j++) {
const ScaleOffsetRecord_MapFiledEntry& record = records.record(j);
if (record.has_key() && record.key() == layerName) {
const SingleLayerRecord& layerQuantInfo = record.value();
int scaleWSize = layerQuantInfo.scale_w_size();
CHECK_EQ(layerQuantInfo.has_scale_d(), true);
scaleD = layerQuantInfo.scale_d();
for (int k = 0; k < scaleWSize; k++) {
allDeqScales[i].push_back(layerQuantInfo.scale_d() * layerQuantInfo.scale_w(k));
}
}
}
}
for (int i = 1; i < allDeqScales.size(); i++) {
CHECK_EQ(allDeqScales[i].size(), allDeqScales[0].size());
for (int j = 0; j < allDeqScales[i].size(); j++) {
CHECK_EQ(allDeqScales[i][j], allDeqScales[0][j]);
}
}
for (int i = 0; i < allDeqScales[0].size(); i++) {
deqScale.push_back(allDeqScales[0][i]);
}
if (globalConvFlag_) {
Dtype maxDeqScale = 0;
for (auto singleDeqScale : deqScale) {
if (singleDeqScale > maxDeqScale) {
maxDeqScale = singleDeqScale;
}
}
for (int i = 0; i < deqScale.size(); i++) {
deqScale[i] = maxDeqScale;
}
UpdateScaleW(deqScale, scaleD);
}
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::RecordN(vector<int>& bestN)
{
ScaleOffsetRecord records;
ReadRecord(&records);
if (globalConvFlag_) {
CHECK_EQ(bestN.size(), 1) << "Do global conv search_n, searched n should 1, actual " << bestN.size();
for (int i = 1; i < bottomChannels[0]; ++i) {
bestN.push_back(bestN[0]);
}
}
for (int i = 0; i < quantLayerNames.size(); i++) {
string layerName(quantLayerNames.Get(i));
for (int j = 0; j < records.record_size(); j++) {
ScaleOffsetRecord_MapFiledEntry* record = records.mutable_record(j);
if (record->has_key() && record->key() == layerName) {
SingleLayerRecord* layerQuantInfo = record->mutable_value();
for (int k = 0; k < bestN.size(); k++) {
layerQuantInfo->add_shift_bit(bestN[k]);
}
}
}
}
WriteProtoToTextFile(records, recordFileName.c_str());
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::UpdateScaleW(vector<Dtype>& deqScale, Dtype scaleD)
{
ScaleOffsetRecord records;
ReadRecord(&records);
for (int i = 0; i < quantLayerNames.size(); i++) {
string layerName(quantLayerNames.Get(i));
for (int j = 0; j < records.record_size(); j++) {
ScaleOffsetRecord_MapFiledEntry* record = records.mutable_record(j);
if (record->has_key() && record->key() == layerName) {
SingleLayerRecord* layerQuantInfo = record->mutable_value();
for (int k = 0; k < deqScale.size(); k++) {
layerQuantInfo->set_scale_w(k, deqScale[k] / scaleD);
}
}
}
}
WriteProtoToTextFile(records, recordFileName.c_str());
return;
}
template <typename Dtype>
void SearchNLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>* >& bottom,
const vector<Blob<Dtype>* >& top)
{
if (curBatchNum < targetBatchNum) {
AccumulateData(bottom);
curBatchNum++;
LOG(INFO) << "Doing layer: " << showQuantLayerNames << " search shift bits calibration, already store "
<< curBatchNum << "/" << targetBatchNum << " data.";
}
if (curBatchNum == targetBatchNum) {
GetDeqScale();
vector<int> bestN;
SearchShitBit(storedData, deqScale, bestN);
RecordN(bestN);
LOG(INFO) << "Do layer: " << showQuantLayerNames << " search shift bits calibration success!";
storedData.clear();
storedData.shrink_to_fit();
curBatchNum++;
}
if (top.size() == 1) {
const int count = bottom[0]->count();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
caffe_copy(count, bottom_data, top_data);
}
}
template <typename Dtype>
void SearchNLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>* >& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>* >& bottom)
{
return;
}
#ifdef CPU_ONLY
STUB_GPU(SearchNLayer);
#endif
INSTANTIATE_CLASS(SearchNLayer);
REGISTER_LAYER_CLASS(SearchN);
} // namespace caffe
| 35.330189
| 120
| 0.594482
|
suyuan32
|
948c95b8a409ced5d4964cb99c3bd1dd77ce1fe6
| 7,467
|
cpp
|
C++
|
src/tools/cppgen/code/ast_decl.cpp
|
brezillon/opensplice
|
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
|
[
"Apache-2.0"
] | 133
|
2017-11-09T02:10:00.000Z
|
2022-03-29T09:45:10.000Z
|
src/tools/cppgen/code/ast_decl.cpp
|
brezillon/opensplice
|
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
|
[
"Apache-2.0"
] | 131
|
2017-11-07T14:48:43.000Z
|
2022-03-13T15:30:47.000Z
|
src/tools/cppgen/code/ast_decl.cpp
|
brezillon/opensplice
|
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
|
[
"Apache-2.0"
] | 94
|
2017-11-09T02:26:19.000Z
|
2022-02-24T06:38:25.000Z
|
/*
COPYRIGHT
Copyright 1992, 1993, 1994 Sun Microsystems, Inc. Printed in the United
States of America. All Rights Reserved.
This product is protected by copyright and distributed under the following
license restricting its use.
The Interface Definition Language Compiler Front End (CFE) is made
available for your use provided that you include this license and copyright
notice on all media and documentation and the software program in which
this product is incorporated in whole or part. You may copy and extend
functionality (but may not remove functionality) of the Interface
Definition Language CFE without charge, but you are not authorized to
license or distribute it to anyone else except as part of a product or
program developed by you or with the express written consent of Sun
Microsystems, Inc. ("Sun").
The names of Sun Microsystems, Inc. and any of its subsidiaries or
affiliates may not be used in advertising or publicity pertaining to
distribution of Interface Definition Language CFE as permitted herein.
This license is effective until terminated by Sun for failure to comply
with this license. Upon termination, you shall destroy or return all code
and documentation for the Interface Definition Language CFE.
INTERFACE DEFINITION LANGUAGE CFE IS PROVIDED AS IS WITH NO WARRANTIES OF
ANY KIND INCLUDING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS
FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR ARISING FROM A COURSE OF
DEALING, USAGE OR TRADE PRACTICE.
INTERFACE DEFINITION LANGUAGE CFE IS PROVIDED WITH NO SUPPORT AND WITHOUT
ANY OBLIGATION ON THE PART OF Sun OR ANY OF ITS SUBSIDIARIES OR AFFILIATES
TO ASSIST IN ITS USE, CORRECTION, MODIFICATION OR ENHANCEMENT.
SUN OR ANY OF ITS SUBSIDIARIES OR AFFILIATES SHALL HAVE NO LIABILITY WITH
RESPECT TO THE INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY
INTERFACE DEFINITION LANGUAGE CFE OR ANY PART THEREOF.
IN NO EVENT WILL SUN OR ANY OF ITS SUBSIDIARIES OR AFFILIATES BE LIABLE FOR
ANY LOST REVENUE OR PROFITS OR OTHER SPECIAL, INDIRECT AND CONSEQUENTIAL
DAMAGES, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Use, duplication, or disclosure by the government is subject to
restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in
Technical Data and Computer Software clause at DFARS 252.227-7013 and FAR
52.227-19.
Sun, Sun Microsystems and the Sun logo are trademarks or registered
trademarks of Sun Microsystems, Inc.
SunSoft, Inc.
2550 Garcia Avenue
Mountain View, California 94043
NOTE:
SunOS, SunSoft, Sun, Solaris, Sun Microsystems or the Sun logo are
trademarks or registered trademarks of Sun Microsystems, Inc.
*/
/*
* ast_decl.cc - Implementation of class AST_Decl
*
* AST_Decl is the base class for all AST nodes except AST_Expression.
* AST_Decls have a node type (a value from the enum AST_Decl::NodeType)
* a name (a UTL_ScopedName) and pragma info.
* Additionally AST_Decl nodes record the scope of definition, the
* file name in which they were defined, the line on which they were
* defined in that file, and a boolean denoting whether this is the
* main file or an #include'd file.
*/
#include <idl.h>
#include <idl_extern.h>
/*
* Constructor(s) and destructor
*/
AST_Decl::AST_Decl ()
:
pd_imported (false),
pd_in_main_file (false),
pd_defined_in (NULL),
pd_node_type (NT_module),
pd_line (-1),
pd_file_name (NULL),
pd_name (NULL),
pd_local_name (NULL),
pd_added (false),
pd_gen_any (false)
{}
AST_Decl::AST_Decl (NodeType nt, UTL_ScopedName *n)
:
pd_imported (idl_global->imported()),
pd_in_main_file (idl_global->in_main_file()),
pd_defined_in
(
idl_global->scopes()->depth() > 0
? idl_global->scopes()->top()
: NULL
),
pd_node_type (nt),
pd_line (idl_global->lineno()),
pd_file_name (idl_global->filename()),
pd_local_name (n == NULL ? NULL : n->last_component()),
pd_added (false),
pd_gen_any (false)
{
compute_full_name (n);
}
AST_Decl::AST_Decl (NodeType nt, UTL_ScopedName *n, const UTL_Pragmas &p)
:
pd_imported (idl_global->imported()),
pd_in_main_file (idl_global->in_main_file()),
pd_defined_in
(
idl_global->scopes()->depth() > 0
? idl_global->scopes()->top()
: NULL
),
pd_node_type (nt),
pd_line (idl_global->lineno()),
pd_file_name (idl_global->filename()),
pd_local_name (n == NULL ? NULL : n->last_component()),
pd_added (false),
pd_gen_any (false),
pd_pragmas (p)
{
compute_full_name (n);
pd_pragmas.set_name (pd_name);
}
/*
* Private operations
*/
/*
* Compute the full scoped name of an AST node
*/
void
AST_Decl::compute_full_name(UTL_ScopedName *n)
{
UTL_ScopedName *cn = NULL;
AST_Decl *d = NULL;
/*
* Initialize this name to NULL
*/
pd_name = NULL;
/*
* Global scope?
*/
if (defined_in() == NULL)
{
pd_name = n;
return ;
}
/*
* OK, not global. So copy name of containing scope, then
* smash last cdr of copy with new component
*/
d = ScopeAsDecl(defined_in());
if (d != NULL)
cn = d->name();
if (cn != NULL)
pd_name = (UTL_ScopedName *) cn->copy();
if (pd_name == NULL)
pd_name = new UTL_ScopedName(local_name(), NULL);
else
pd_name->nconc(new UTL_ScopedName(local_name(), NULL));
}
/*
* Public operations
*/
/*
* Return TRUE if one of my ancestor scopes is "s"
* and FALSE otherwise
*/
bool AST_Decl::has_ancestor(AST_Decl *s)
{
if (this == s)
return true;
if (pd_defined_in == NULL)
return false;
return ScopeAsDecl(pd_defined_in)->has_ancestor(s);
}
void AST_Decl::dump (ostream &o)
{
pd_local_name->dump(o);
}
bool AST_Decl::imported ()
{
return pd_imported;
}
void AST_Decl::set_imported (bool is_it)
{
pd_imported = is_it;
}
bool AST_Decl::in_main_file ()
{
return pd_in_main_file;
}
void AST_Decl::set_in_main_file (bool is_it)
{
pd_in_main_file = is_it;
}
bool AST_Decl::added()
{
return pd_added;
}
void AST_Decl::set_added (bool is_it)
{
pd_added = is_it;
}
UTL_Scope * AST_Decl::defined_in ()
{
return pd_defined_in;
}
void AST_Decl::set_defined_in (UTL_Scope *s)
{
pd_defined_in = s;
}
AST_Decl::NodeType AST_Decl::node_type ()
{
return pd_node_type;
}
long AST_Decl::line ()
{
return pd_line;
}
void AST_Decl::set_line (long l)
{
pd_line = l;
}
UTL_String * AST_Decl::file_name ()
{
return pd_file_name;
}
void AST_Decl::set_file_name (UTL_String *s)
{
pd_file_name = s;
}
UTL_ScopedName * AST_Decl::name ()
{
return pd_name;
}
void AST_Decl::set_name (UTL_ScopedName *n)
{
pd_name = n;
if (n != NULL)
pd_local_name = n->last_component();
}
Identifier * AST_Decl::local_name ()
{
return pd_local_name;
}
bool AST_Decl::get_gen_any (void)
{
// printf ("AST_Decl::get_gen_any: %d\n", pd_gen_any || all_gen_any);
return pd_gen_any || all_gen_any;
}
void AST_Decl::virt_set_gen_any (void)
{
// Reimplemented by types that need to propagate any generation flag
}
// Whether any generation flag used for anything
bool AST_Decl::some_gen_any = false;
// Whether any generation flag used for everything
bool AST_Decl::all_gen_any = false;
void AST_Decl::set_gen_any (void)
{
pd_gen_any = true;
some_gen_any = true;
virt_set_gen_any ();
}
IMPL_NARROW_METHODS0 (AST_Decl)
IMPL_NARROW_FROM_DECL (AST_Decl)
IMPL_NARROW_METHODS0 (COMMON_Base)
| 23.189441
| 75
| 0.714745
|
brezillon
|
948d4b4be64c30871044e059a320c622fa676986
| 1,919
|
cpp
|
C++
|
src/GreenFractals.cpp
|
ecssiah/Buddhabrot-Variations
|
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
|
[
"MIT"
] | null | null | null |
src/GreenFractals.cpp
|
ecssiah/Buddhabrot-Variations
|
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
|
[
"MIT"
] | null | null | null |
src/GreenFractals.cpp
|
ecssiah/Buddhabrot-Variations
|
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <complex>
#include <vector>
#include <iostream>
#include <Eigen/Geometry>
#include <Magick++.h>
#include "Constants.h"
#include "ImageGenerator.h"
#include "FractalInstance.h"
using namespace std;
using namespace Eigen;
using namespace Magick;
vector<FractalInstance> fractals;
// user literal for millions (i.e. 1_m = 10000000)
constexpr unsigned long long operator "" _m(unsigned long long l) {
return l * 1000 * 1000;
}
int main(int argc, char** argv)
{
InitializeMagick(*argv);
auto theta(0.0);
auto delta(2 * M_PI / NUM_FRAMES);
auto offset1(0.0);
auto offset2(0.0);
auto offset3(0.0);
Vector3f axis1(1, 0, 0);
Vector3f axis2(0, 1, 0);
Vector3f axis3(0, 0, 1);
axis1.normalize();
axis2.normalize();
axis3.normalize();
Vector3f vec(-1/6.0, 1/120.0, -1/5040.0);
auto vec1(vec);
auto vec2(vec);
auto vec3(vec);
FractalInstance::num_points = 10_m;
FractalInstance::complex_range = 6.0;
FractalInstance::default_iterations = 1e2;
/* FractalInstance fi( */
/* {1, vec1.x(), vec1.y(), vec1.z()}, */
/* {1, 2, 4, 6}, */
/* {0, 0, 3.0, 3.0} */
/* ); */
/* ImageGenerator::generate(fi); */
for (auto frame(1); frame <= NUM_FRAMES; ++frame)
{
FractalInstance rfi(
{1, vec1.x(), vec1.y(), vec1.z()},
{1, 2, 4, 6},
{0, 0, 4.0, 4.0}
);
FractalInstance gfi(
{1, vec2.x(), vec2.y(), vec2.z()},
{1, 2, 4, 6},
{0, 0, 4.0, 4.0}
);
FractalInstance bfi(
{1, vec3.x(), vec3.y(), vec3.z()},
{1, 2, 4, 6},
{0, 0, 4.0, 4.0}
);
ImageGenerator::generate({rfi, gfi, bfi}, frame);
theta += delta;
auto t1(AngleAxis<float>(theta + offset1, axis1));
vec1 = t1 * vec;
auto t2(AngleAxis<float>(theta + offset2, axis2));
vec2 = t2 * vec;
auto t3(AngleAxis<float>(theta + offset3, axis3));
vec3 = t3 * vec;
}
return 0;
}
| 20.634409
| 67
| 0.583116
|
ecssiah
|
948dff59d71da8ab5af5b4c07aaf0576684d3bcc
| 1,171
|
cpp
|
C++
|
Camp_2-2563/07_MST/39_CableCar.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_2-2563/07_MST/39_CableCar.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_2-2563/07_MST/39_CableCar.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
/*
* AUTHOR : Hydrolyzed~
* SCHOOL : RYW
* CENTER : BUU
* TASK : Cable Car TOI12
* ALGO : Minimum Spanning Tree
* DATE : 9 May 2021
* */
#include<bits/stdc++.h>
using namespace std;
#define dec(x,y) fixed << setprecision(y) << x
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define int long long
using LL = long long;
int n, m;
struct Node{
int v, w;
bool operator < (const Node&o) const{
return w < o.w;
}
};
priority_queue<Node>pq;
vector<Node> g[2555];
int dist[2555];
void solve(){
cin >> n >> m;
for(int i=0; i<m; ++i){
int u, v, w;
cin >> u >> v >> w;
g[u].push_back({v, w});
g[v].push_back({u, w});
}
int u, v, w;
cin >> u >> v >> w;
dist[u] = INT_MAX;
pq.push({u, INT_MAX});
while(!pq.empty()){
Node now = pq.top();
pq.pop();
if(now.v == v){
cout << (int)ceil((double)w / (now.w-1));
break;
}
for(auto x: g[now.v]){
if(dist[x.v] >= min(now.w, x.w)){
continue;
}
dist[x.v] = min(now.w, x.w);
pq.push({x.v, dist[x.v]});
}
}
return ;
}
int32_t main(){
cin.tie(nullptr)->ios::sync_with_stdio(false);
int t=1;
// cin >> t;
while(t--){
solve();
cout << endl;
}
return 0;
}
| 16.492958
| 49
| 0.541418
|
MasterIceZ
|
9497622dfd397a60d8fcf26e94920c41c83170e6
| 430
|
hpp
|
C++
|
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
|
phoenix-engine/phoenix
|
c3285482ee507b566a1c38da071439dab507a877
|
[
"MIT"
] | 2
|
2019-05-04T19:33:26.000Z
|
2019-06-29T13:19:33.000Z
|
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
|
phoenix-engine/phoenix
|
c3285482ee507b566a1c38da071439dab507a877
|
[
"MIT"
] | 13
|
2019-05-05T12:40:54.000Z
|
2020-02-29T20:32:11.000Z
|
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
|
phoenix-engine/phoenix
|
c3285482ee507b566a1c38da071439dab507a877
|
[
"MIT"
] | 4
|
2018-09-15T21:59:08.000Z
|
2019-05-04T20:19:07.000Z
|
//
// PHXViewDelegate.hpp
// CocoaPhoenix
//
// Created by Bodie Solomon on 3/12/19.
//
#ifndef PHXViewDelegate_hpp
#define PHXViewDelegate_hpp
/// PHXViewDelegate responds to UI draw events by making the appropriate calls
/// into the Phoenix engine object.
@interface PHXViewDelegate : NSObject<MTKViewDelegate>
+ (instancetype _Nullable) makeWithPhoenix:(MetalPhoenix* _Nonnull)p;
@end
#endif /* PHXViewDelegate_hpp */
| 21.5
| 78
| 0.765116
|
phoenix-engine
|
949ca9f22fa28763a77c01cce817538524129fc5
| 3,809
|
cpp
|
C++
|
Projects/RealityEngine/source/Engine.cpp
|
Volta948/RealityEngine
|
1a9e4b7db00617176d06004af934d6602dd5920a
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/RealityEngine/source/Engine.cpp
|
Volta948/RealityEngine
|
1a9e4b7db00617176d06004af934d6602dd5920a
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/RealityEngine/source/Engine.cpp
|
Volta948/RealityEngine
|
1a9e4b7db00617176d06004af934d6602dd5920a
|
[
"BSD-3-Clause"
] | 1
|
2021-11-05T02:55:27.000Z
|
2021-11-05T02:55:27.000Z
|
// Copyright Reality Engine. All Rights Reserved.
#include "Engine.h"
#define GLFW_INCLUDE_NONE
#include <glfw/glfw3.h>
Reality::GameEngine::GameEngine() {
g_SceneManager = new SceneManager;
g_Logger = new Logger;
g_AudioEngine = new AudioEngine;
g_Randomizer = new Randomizer;
g_PlayerPref = new PlayerPref;
g_Io = new IO;
g_Io->Window = std::make_unique<GlfwWindow>();
g_Io->Input = std::make_unique<GlfwInput>();
g_Io->Time = std::make_unique<GlfwTime>();
GLContext::Init(reinterpret_cast<GLContext::ProcAddr>(glfwGetProcAddress));
g_ShaderHelper = new GLShaderHelper;
g_DebugDrawing = new GLDebugDrawing;
g_MeshHelper = new GLMeshHelper;
g_MeshHelper->Quad.Material = g_MeshHelper->Circle.Material = g_MeshHelper->Cube.Material =
g_MeshHelper->Sphere.Material = &g_MeshHelper->Default;
g_ResourceManager = new ResourceManager;
g_Io->Window->SetTitle("Reality Engine");
g_Io->Window->SetPos({ 250.f, 150.f });
auto& scene{ g_SceneManager->CreateScene("Scene0") };
SceneSerializer::Load("Resources/Scenes.json", scene);
}
Reality::GameEngine::~GameEngine() {
SceneSerializer::Save("Resources/Scenes.json", *g_SceneManager->ActiveScene);
delete g_ResourceManager;
delete g_SceneManager;
delete g_Logger;
delete g_AudioEngine;
delete g_ShaderHelper;
delete g_MeshHelper;
delete g_DebugDrawing;
delete g_Randomizer;
delete g_PlayerPref;
delete g_Io;
}
void Reality::GameEngine::Update() {
g_ResourceManager->Update();
}
RE_CORE Reality::PlayerPref* Reality::g_PlayerPref{};
RE_CORE Reality::Randomizer* Reality::g_Randomizer{};
RE_CORE Reality::Logger* Reality::g_Logger{};
RE_CORE Reality::SceneManager* Reality::g_SceneManager{};
RE_CORE Reality::AudioEngine* Reality::g_AudioEngine{};
RE_CORE Reality::GLShaderHelper* Reality::g_ShaderHelper{};
RE_CORE Reality::GLDebugDrawing* Reality::g_DebugDrawing{};
RE_CORE Reality::GLMeshHelper* Reality::g_MeshHelper{};
RE_CORE Reality::IO* Reality::g_Io{};
RE_CORE Reality::ResourceManager* Reality::g_ResourceManager{};
const Reality::Quaternion Reality::Quaternion::Identity{ 0.f, 0.f, 0.f, 1.f };
const Reality::Matrix4 Reality::Matrix4::Zero{};
const Reality::Matrix4 Reality::Matrix4::Identity{
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f
};
const Reality::Vector4 Reality::Vector4::Back{ 0.f, 0.f, -1.f, 1.f };
const Reality::Vector4 Reality::Vector4::Down{ 0.f, -1.f, 0.f, 1.f };
const Reality::Vector4 Reality::Vector4::Forward{ 0.f, 0.f, 1.f, 1.f };
const Reality::Vector4 Reality::Vector4::Left{ -1.f, 0.f, 0.f, 1.f };
const Reality::Vector4 Reality::Vector4::One{ 1.f, 1.f, 1.f, 1.f };
const Reality::Vector4 Reality::Vector4::Right{ 1.f, 0.f, 0.f, 1.f };
const Reality::Vector4 Reality::Vector4::Up{ 0.f, 1.f, 0.f, 1.f };
const Reality::Vector4 Reality::Vector4::Zero{ 0.f, 0.f, 0.f, 0.f };
const Reality::Vector3 Reality::Vector3::Back{ 0.f, 0.f, -1.f };
const Reality::Vector3 Reality::Vector3::Down{ 0.f, -1.f, 0.f };
const Reality::Vector3 Reality::Vector3::Forward{ 0.f, 0.f, 1.f };
const Reality::Vector3 Reality::Vector3::Left{ -1.f, 0.f, 0.f };
const Reality::Vector3 Reality::Vector3::One{ 1.f, 1.f, 1.f };
const Reality::Vector3 Reality::Vector3::Right{ 1.f, 0.f, 0.f };
const Reality::Vector3 Reality::Vector3::Up{ 0.f, 1.f, 0.f };
const Reality::Vector3 Reality::Vector3::Zero{ 0.f, 0.f, 0.f };
const Reality::Vector2 Reality::Vector2::Down{ 0.f, -1.f };
const Reality::Vector2 Reality::Vector2::Left{ -1.f, 0.f };
const Reality::Vector2 Reality::Vector2::One{ 1.f, 1.f };
const Reality::Vector2 Reality::Vector2::Right{ 1.f, 0.f };
const Reality::Vector2 Reality::Vector2::Up{ 0.f, 1.f };
const Reality::Vector2 Reality::Vector2::Zero{ 0.f, 0.f };
| 38.474747
| 93
| 0.699396
|
Volta948
|
949d5267be41656bf2b98284eeddb72ab25c34c6
| 3,754
|
cpp
|
C++
|
src/csaltTester/src/TestOptCtrl/src/pointpath/RayleighControlStateConstraintPointObject.cpp
|
IncompleteWorlds/GMAT_2020
|
624de54d00f43831a4d46b46703e069d5c8c92ff
|
[
"Apache-2.0"
] | null | null | null |
src/csaltTester/src/TestOptCtrl/src/pointpath/RayleighControlStateConstraintPointObject.cpp
|
IncompleteWorlds/GMAT_2020
|
624de54d00f43831a4d46b46703e069d5c8c92ff
|
[
"Apache-2.0"
] | null | null | null |
src/csaltTester/src/TestOptCtrl/src/pointpath/RayleighControlStateConstraintPointObject.cpp
|
IncompleteWorlds/GMAT_2020
|
624de54d00f43831a4d46b46703e069d5c8c92ff
|
[
"Apache-2.0"
] | null | null | null |
//$Id$
//------------------------------------------------------------------------------
// RayleighControlStateConstraintPointObject
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Author: Claire Conway
// Created: 2017.01.30
//
/**
* Developed based on RayleighControlStateConstraintPointObject.m
*/
//------------------------------------------------------------------------------
#include "RayleighControlStateConstraintPointObject.hpp"
#include "MessageInterface.hpp"
//#define DEBUG_RayleighControlStateConstraint_POINT
//------------------------------------------------------------------------------
// static data
//------------------------------------------------------------------------------
// none
//------------------------------------------------------------------------------
// public methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// default constructor
//------------------------------------------------------------------------------
RayleighControlStateConstraintPointObject::RayleighControlStateConstraintPointObject() :
UserPointFunction()
{
}
//------------------------------------------------------------------------------
// copy constructor
//------------------------------------------------------------------------------
RayleighControlStateConstraintPointObject::RayleighControlStateConstraintPointObject(const RayleighControlStateConstraintPointObject ©) :
UserPointFunction(copy)
{
}
//------------------------------------------------------------------------------
// operator=
//------------------------------------------------------------------------------
RayleighControlStateConstraintPointObject& RayleighControlStateConstraintPointObject::operator=(const RayleighControlStateConstraintPointObject ©)
{
if (© == this)
return *this;
UserPointFunction::operator=(copy);
return *this;
}
//------------------------------------------------------------------------------
// destructor
//------------------------------------------------------------------------------
RayleighControlStateConstraintPointObject::~RayleighControlStateConstraintPointObject()
{
}
//------------------------------------------------------------------------------
// void EvaluateFunctions()
//-----------------------------------------------------------------------------
void RayleighControlStateConstraintPointObject::EvaluateFunctions()
{
Rvector stateInit = GetInitialStateVector(0);
Real tInit = GetInitialTime(0);
Real tFinal = GetFinalTime(0);
Rvector boundVector(4,tInit, tFinal, stateInit(0), stateInit(1));
Rvector boundVecLower(4,0.0, 4.5, -5.0, -5.0);
Rvector boundVecUpper(4,0.0, 4.5, -5.0, -5.0);
SetFunctions(ALGEBRAIC, boundVector);
SetFunctionBounds(ALGEBRAIC, LOWER, boundVecLower);
SetFunctionBounds(ALGEBRAIC, UPPER, boundVecUpper);
}
//------------------------------------------------------------------------------
// void EvaluateJacobians()
//-----------------------------------------------------------------------------
void RayleighControlStateConstraintPointObject::EvaluateJacobians()
{
// Currently does nothing
}
//------------------------------------------------------------------------------
// protected methods
//------------------------------------------------------------------------------
// none
| 37.168317
| 150
| 0.415024
|
IncompleteWorlds
|
94a56834a38a173a81c91e308bac6853c89f697e
| 1,299
|
cpp
|
C++
|
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
|
chromatic-universe/cci-llvm-clang-cpp
|
e2fcc54067237c5d68d629d00952cb0e525a1012
|
[
"MIT"
] | null | null | null |
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
|
chromatic-universe/cci-llvm-clang-cpp
|
e2fcc54067237c5d68d629d00952cb0e525a1012
|
[
"MIT"
] | null | null | null |
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
|
chromatic-universe/cci-llvm-clang-cpp
|
e2fcc54067237c5d68d629d00952cb0e525a1012
|
[
"MIT"
] | null | null | null |
//clang_mini_rpc_client.cpp william k. johnson
#include <iostream>
#include <memory>
#include <string>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include "gen-cpp/cci_mini_clang_rpc.h"
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace shared;
using cci_rpc = cci_mini_clang_rpcClient;
int main( int argc , char* argv[] )
{
boost::shared_ptr<TTransport> socket( new TSocket( "localhost" , 9090 ) );
boost::shared_ptr<TTransport> transport( new TBufferedTransport( socket) );
boost::shared_ptr<TProtocol> protocol( new TBinaryProtocol(transport ) );
std::unique_ptr<cci_rpc> clang_rpc_client( new cci_rpc( protocol ) );
try
{
transport->open();
std::string str;
std::string str_idx( "foo" );
try
{
clang_rpc_client->perform_diag( str , str_idx );
std::cout << str << "\n";
}
catch( invalid_clang_op& err )
{
std::cerr << err << "\n";
}
transport->close();
}
catch ( TException& tx )
{
std::cerr << "error: " << tx.what() << std::endl;
}
return 0;
}
| 24.055556
| 79
| 0.627406
|
chromatic-universe
|
94a5afc4e5dc980877c947b6ac3ec47d6ab1db74
| 26,883
|
cpp
|
C++
|
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | 15
|
2017-05-15T15:52:24.000Z
|
2022-03-23T06:48:48.000Z
|
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | null | null | null |
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | 4
|
2017-09-07T10:55:36.000Z
|
2021-01-29T08:51:01.000Z
|
/*
copyright (c) 1996 - 2008 Ivan Varzar. lusores@gmail.com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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 "stdafx.h"
#include "Helpers.h"
#include "Resource.h"
#include "DragDrop.h"
#include "WalkingDead.h"
#include "Extension.Viewer.ABR.h"
namespace BigBrotherAndy {
#define DEF_HELP L"navigate between brushes\tleft, right arrows, mouse wheel\r\nzoom in/out\t\t\tup, down arrows, mouse wheel with ctrl\r\ninverse color\t\t\tspace\r\nsend to photoshop\t\tenter (return)\r\nclose window\t\t\tright mouse click, escape\r\nnext file:\t\t\tpgdn \r\nprev file:\t\t\tpgup"
CABRViewer::CABRViewer() : Window<CABRViewer>(0,0) {
m_uItsShowTimeBaby = ShowBrokenHeart;
m_dwMagicNumber = 0;
m_pBrushes = 0;
m_hDragCursor = m_hArrowCursor = 0;
m_hDetailsFont = m_hSmileFont = m_hFont = m_hSmallFont = 0;
m_hFrameBrush = m_hBackgroundBrush = 0;
m_fZoomFactor = 1.0;
m_clrBackground = 0x000000;
m_clrHalfColor = 0x0F0F0F;
m_clrQuaterColor = 0x9F9F9F;
for ( unsigned int i = 0; i < 256; i++ ) {
m_BlackPallette[i].rgbBlue =
m_BlackPallette[i].rgbRed =
m_BlackPallette[i].rgbGreen = 0xFF - i;
m_BlackPallette[i].rgbReserved = 0;
m_WhitePallette[i].rgbBlue =
m_WhitePallette[i].rgbRed =
m_WhitePallette[i].rgbGreen = i;
m_WhitePallette[i].rgbReserved = 0;
};
m_bIsDecodingIsActive = FALSE;
m_bTerminateApplication = FALSE;
m_pDropTarget = 0;
}
CABRViewer::~CABRViewer() {
if ( m_pBrushes ) {
m_pBrushes->Release();
};
if ( m_hDragCursor ) {
DeleteObject ( m_hDragCursor );
};
if ( m_hArrowCursor ) {
DeleteObject ( m_hArrowCursor );
};
if ( m_hSmallFont ) {
DeleteObject ( m_hSmallFont );
};
if ( m_hFont ) {
DeleteObject ( m_hFont );
};
if ( m_hSmileFont ) {
DeleteObject ( m_hSmileFont );
};
if ( m_hDetailsFont ) {
DeleteObject ( m_hDetailsFont );
};
if ( m_hFrameBrush ) {
DeleteObject(m_hFrameBrush);
};
if ( m_hBackgroundBrush ) {
DeleteObject ( m_hBackgroundBrush );
};
}
BOOL CABRViewer::Create(HINSTANCE hInstance) {
// Take it
m_hInstance = hInstance;
//If the window class has not been registered, then do so.
WNDCLASS wc;
if ( !GetClassInfo ( m_hInstance, WINDOW_CLASS_NAME, &wc ) ) {
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)this->WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hInstance;
wc.hIcon = 0;
wc.hCursor = LoadCursor ( 0, IDC_ARROW );
wc.hbrBackground = 0;
wc.lpszMenuName = 0;
wc.lpszClassName = WINDOW_CLASS_NAME;
if ( !RegisterClass ( &wc ) ) {
return FALSE;
};
};
// Create the window. The WndProc will set m_hWnd
if ( ! ( m_hWnd = CreateWindowEx ( WS_EX_ACCEPTFILES, WINDOW_CLASS_NAME, NULL, WS_OVERLAPPED | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 500, 500, 0, 0, m_hInstance, (LPVOID)this )) ) {
return FALSE;
};
// Create arrow cursor
m_hArrowCursor = LoadCursor ( NULL,IDC_ARROW );
m_hDragCursor = LoadCursor(NULL,IDC_CROSS);
// Create font
// Create font (lovely Tahoma family)
m_hFont = CreateFont ( -112, 0, 0, 0, FW_DEMIBOLD, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" );
m_hSmileFont = CreateFont ( -248, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Wingdings" );
m_hSmallFont = CreateFont ( -14, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" );
m_hDetailsFont = CreateFont ( -11, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" );
//
Recolor();
// Show window
ShowWindow ( m_hWnd, SW_SHOW );
// Update window
UpdateWindow ( m_hWnd );
return TRUE;
}
void CABRViewer::Recolor() {
m_clrBackground = ( ~m_clrBackground ) & 0x00FFFFFF;
if ( m_clrBackground ) {
m_clrHalfColor = 0x9F9F9F;
m_clrQuaterColor = 0x0F0F0F;
} else {
m_clrHalfColor = 0x0F0F0F;
m_clrQuaterColor = 0x9F9F9F;
}
// Clean-up
if ( m_hFrameBrush ) {
DeleteObject(m_hFrameBrush);
};
if ( m_hBackgroundBrush ) {
DeleteObject ( m_hBackgroundBrush );
};
// Yeah, baby!
m_hFrameBrush = CreateSolidBrush ( m_clrHalfColor );
m_hBackgroundBrush = CreateSolidBrush ( m_clrBackground );
if ( m_pBrushes ) {
for ( DWORD i = 0; i < m_pBrushes->Count(); i++ ) {
if ( IAdobeBrush* pBrush = m_pBrushes->Get(i) ) {
if ( pBrush->Type() == AdobeBrushTypeSampled ) {
memcpy ( ((AdobeBrushDibData*)pBrush->Data())->oHeader->bmiColors + 1, m_clrBackground ? m_BlackPallette : m_WhitePallette, 256 * sizeof(RGBQUAD) );
};
pBrush->Release();
};
};
};
}
LRESULT CABRViewer::OnDrop ( STGMEDIUM* pstgmed, FORMATETC* pFormatEtc ) {
//
if ( !pFormatEtc && !pstgmed ) {
return 0;
};
//
if ( pFormatEtc->cfFormat == CF_HDROP && pFormatEtc->tymed == TYMED_HGLOBAL ) {
// we asked for the data as a HGLOBAL, so access it appropriately
HDROP hDrop = (HDROP)GlobalLock(pstgmed->hGlobal);
OnDropFiles ( hDrop );
GlobalUnlock ( pstgmed->hGlobal );
};
return 0x00;
};
LRESULT CABRViewer::OnDropFiles ( HDROP hDrop ) {
if ( !hDrop ) {
return 0;
};
WCHAR wsFileName[MAX_PATH];
if ( DragQueryFile ( hDrop, 0, wsFileName, MAX_PATH ) ) {
YetAnotherBeginUnpack ( wsFileName );
m_WalkingDead.reset();
};
DragFinish(hDrop);
return 0;
}
void CABRViewer::YetAnotherBeginUnpack ( WCHAR* wcsFileName ) {
if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) {
m_uItsShowTimeBaby = ShowLoadingBrushes;
m_dwMagicNumber = 0;
if ( HDC hDC = GetDC ( m_hWnd ) ) {
RECT rc;
GetClientRect ( m_hWnd, &rc );
BufferedDrawWindow ( CBufferDC ( m_hWnd, hDC ), &rc );
ReleaseDC ( m_hWnd, hDC );
};
if ( m_pBrushes ) {
m_pBrushes->Release();
m_pBrushes = 0;
};
BeginUnpackAdobeBrushesPresetFile ( wcsFileName );
SetWindowText ( m_hWnd, wcsFileName );
};
}
void CABRViewer::BufferedDrawWindow ( HDC hDC, RECT* prc ) {
DrawWindow ( CBufferDC ( m_hWnd, hDC ), prc );
}
void CABRViewer::DrawWindow ( HDC hDC, RECT* prc ) {
// Hey, bro!
FillRect ( hDC, prc, m_hBackgroundBrush );
// What do you wand to do today?
switch ( m_uItsShowTimeBaby ) {
case ShowBrokenHeart:
{
HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hSmileFont );
SetBkMode ( hDC, TRANSPARENT );
SetTextColor ( hDC, m_clrHalfColor );
DrawText ( hDC, L"J", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SetTextColor ( hDC, m_clrQuaterColor );
hOldFont = (HFONT)SelectObject ( hDC, m_hSmallFont );
DrawText ( hDC, L"Drop point ;)", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SelectObject ( hDC, m_hDetailsFont );
prc->left += 10;
prc->top += 10;
DrawText ( hDC, DEF_HELP, -1, prc, DT_WORDBREAK | DT_EXPANDTABS );
SelectObject ( hDC, hOldFont );
};
break;
case ShowLoadingBrushes:
{
HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hFont );
WCHAR wsProgress[10];
wsprintf ( wsProgress, L"%d", m_dwMagicNumber );
SetBkMode ( hDC, TRANSPARENT );
SetTextColor ( hDC, m_clrHalfColor );
DrawText ( hDC, wsProgress, -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SetTextColor ( hDC, m_clrQuaterColor );
hOldFont = (HFONT)SelectObject ( hDC, m_hSmallFont );
DrawText ( hDC, L"One moment please...", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SelectObject ( hDC, m_hDetailsFont );
prc->left += 10;
prc->top += 10;
DrawText ( hDC, DEF_HELP, -1, prc, DT_WORDBREAK | DT_EXPANDTABS );
SelectObject ( hDC, hOldFont );
};
break;
case ShowSingleBrush:
if ( m_pBrushes ) {
if ( IAdobeBrush* pBrush = m_pBrushes->Get ( m_dwCurrentBrush ) ) {
RECT rc;
memcpy ( &rc, prc, sizeof(RECT) );
OffsetRect ( &rc, -rc.left + 10, -rc.top + 10);
double width = rc.right - rc.left - 20;
double height = rc.bottom - rc.top - 20;
double w = pBrush->Width();
double h = pBrush->Height();
double raten = min(1, min ((width/w), (height/h)));
h *= ( raten * m_fZoomFactor );
w *= ( raten * m_fZoomFactor );
double pointx = ( width - w ) / 2 + 10 + m_ptOffset.x;
double pointy = ( height - h ) / 2 + 10 + m_ptOffset.y;
if ( pBrush->Type() == 1 ) {
w = rc.right - rc.left;
h = rc.bottom - rc.top;
pointx = rc.left;
pointy = rc.top;
};
SetBkColor ( hDC,m_clrHalfColor );
SetBkMode ( hDC, TRANSPARENT );
if ( w < pBrush->Width() || h < pBrush->Height() ) {
SetStretchBltMode(hDC, HALFTONE );
} else {
SetStretchBltMode(hDC, BLACKONWHITE );
};
//////////////////////////////////////////////////////////////////////////
if ( pBrush->Type() == AdobeBrushTypeSampled ) {
// Draw pixels to window
StretchDIBits ( hDC, (int)pointx, (int)pointy, (int)w, (int)h, 0, 0, pBrush->Width(), pBrush->Height(), ((AdobeBrushDibData*)pBrush->Data())->pBits, ((AdobeBrushDibData*)pBrush->Data())->oHeader, DIB_RGB_COLORS, SRCCOPY );
} else {
HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hSmileFont );
SetTextColor ( hDC, m_clrHalfColor );
DrawText ( hDC, L"A", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SetTextColor ( hDC, m_clrQuaterColor );
SelectObject ( hDC, m_hSmallFont );
DrawText ( hDC, L"Sampled brush", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
SelectObject ( hDC, hOldFont );
}
RECT rcText;
rcText.top = prc->bottom - 80;
rcText.bottom = rcText.top + 50;
rcText.left = 0;
rcText.right = 180;
FillRect ( hDC, &rcText, m_hFrameBrush );
SetTextColor ( hDC,0xFFFFFF );
rcText.left += 10;
rcText.top += 10;
HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hDetailsFont );
if ( IAdobeProperty* pProperty = pBrush->GetProperty ( L"Nm ", 4, PropertyTypeText ) ) {
WCHAR* Name = wcsstr ( pProperty->Value().wValue, L"=" );
DrawText ( hDC, Name ? Name + 1 : pProperty->Value().wValue, -1, &rcText, DT_LEFT | DT_TOP );
pProperty->Release();
} else {
DrawText ( hDC, L"Unnamed brush", -1, &rcText, DT_LEFT | DT_TOP );
}
rcText.top += 12;
WCHAR wsSize[60];
wsprintf ( wsSize, L"%d of %d. Sample size: %dpx", m_dwCurrentBrush + 1, m_pBrushes->Count(), max(pBrush->Width(), pBrush->Height()) );
DrawText ( hDC, wsSize, -1, &rcText, DT_LEFT | DT_TOP );
SelectObject ( hDC, hOldFont );
//////////////////////////////////////////////////////////////////////////
HRGN hrgn = CreateRectRgn(min(m_rcClip.left,(long)pointx), min(m_rcClip.top,(long)pointy), max(m_rcClip.right,(long)(pointx+w)), max(m_rcClip.bottom,(long)(pointy+h)) );
SelectClipRgn ( hDC, hrgn );
m_rcClip.left = (long)pointx;
m_rcClip.top = (long)pointy;
m_rcClip.right = m_rcClip.left + (long)w;
m_rcClip.bottom = m_rcClip.top + (long)h;
pBrush->Release();
};
};
break;
case ShowMultipleBrushes:
// Always halftone stretch mode
SetStretchBltMode(hDC, HALFTONE );
if ( m_pBrushes ) {
RECT rc;
memcpy ( &rc, prc, sizeof(RECT) );
OffsetRect ( &rc, -rc.left + 10, -rc.top + 10 );
rc.bottom -= 20;
rc.right -= 20;
int count = (int)(1 / m_fZoomFactor );
int offset = 10;
int width = ( offset + rc.right - rc.left ) / (long)(1 / m_fZoomFactor) - offset;
int height = ( offset + rc.bottom - rc.top ) / (long)(1 / m_fZoomFactor) - offset;
for ( int y = 0; y < count ; y++ ) {
for ( int x = 0; x < count; x++ ) {
if ( IAdobeBrush* pBrush = m_pBrushes->Get ( m_dwCurrentBrush + y * count + x ) ) {
RECT rcBrush;
rcBrush.left = rc.left + ( width + offset ) * x;
rcBrush.right = rcBrush.left + width;
rcBrush.top = rc.top + ( height + offset ) * y;
rcBrush.bottom = rcBrush.top + height;
FrameRect ( hDC, &rcBrush, m_hFrameBrush );
double raten = min(1, min (((width-4.0)/pBrush->Width()), ((height-4.0)/pBrush->Height())));
int w = (int)(raten * pBrush->Width());
int h = (int)(raten * pBrush->Height());
if ( pBrush->Type() == AdobeBrushTypeSampled ) {
// Draw pixels to window
StretchDIBits ( hDC, rcBrush.left + ( width - w ) / 2, rcBrush.top + ( height - h ) / 2, (int)w, (int)h, 0, 0, pBrush->Width(), pBrush->Height(), ((AdobeBrushDibData*)pBrush->Data())->pBits, ((AdobeBrushDibData*)pBrush->Data())->oHeader, DIB_RGB_COLORS, SRCCOPY );
};
pBrush->Release();
};
};
};
};
break;
};
}
LRESULT CABRViewer::OnPaint() {
// Small and simple
PAINTSTRUCT ps;
HDC hDC = BeginPaint ( m_hWnd, &ps );
RECT rc;
GetClientRect ( m_hWnd, &rc );
BufferedDrawWindow( hDC, &rc );
EndPaint ( m_hWnd, &ps );
return 0;
}
LRESULT CABRViewer::OnEraseBkgnd(HDC hDC) {
return 0x0;
};
LRESULT CABRViewer::OnDestroy() {
if ( m_bIsDecodingIsActive ) {
m_bTerminateApplication = TRUE;
ShowWindow ( m_hWnd, SW_HIDE );
} else {
if ( m_pDropTarget ) {
CDropTarget::UnregisterDropWindow ( m_hWnd, m_pDropTarget );
};
PostQuitMessage(0);
};
return 0;
}
LRESULT CABRViewer::OnMouseMove(UINT uVirtualKey, int x, int y) {
if ((uVirtualKey && MK_LBUTTON) && m_fBrushDrag ) {
m_ptOffset.x += ( x - m_ptDragPoint.x );
m_ptOffset.y += ( y - m_ptDragPoint.y );
InvalidateRect ( m_hWnd, 0, FALSE );
// Save the coordinates of the mouse cursor.
m_ptDragPoint.x = x;
m_ptDragPoint.y = y;
}
return 0;
}
LRESULT CABRViewer::OnLButtonDown(UINT uVirtualKey, int x, int y) {
RECT rc;
GetWindowRect ( m_hWnd, &rc );
// Restrict the mouse cursor to the client area. This
// ensures that the window receives a matching
// WM_LBUTTONUP message.
ClipCursor(&rc);
// Save the coordinates of the mouse cursor.
m_ptDragPoint.x = x;
m_ptDragPoint.y = y;
SetCursor ( m_hDragCursor );
SetClassLong ( m_hWnd, GCL_HCURSOR, (__int3264)(LONG_PTR)m_hDragCursor );
m_fBrushDrag = TRUE;
return 0;
}
LRESULT CABRViewer::OnLButtonUp(UINT uVirtualKey, int x, int y) {
// Check
if ( m_fBrushDrag ) {
m_fBrushDrag = FALSE;
SetCursor ( m_hArrowCursor );
SetClassLong ( m_hWnd, GCL_HCURSOR, (__int3264)(LONG_PTR)m_hArrowCursor);
// Release the mouse cursor.
ClipCursor(0);
};
return 0;
}
LRESULT CABRViewer::OnRButtonUp(UINT uVirtualKey, int x, int y) {
return OnDestroy();
}
LRESULT CABRViewer::OnLButtonDblClk ( UINT vkCode, int x, int y ) {
if ( m_bIsDecodingIsActive || !m_wBrushesFile ) {
return 0;
};
// Lookup for photoshop executable
if ( !m_wPhotoshopExecutable.get() ) {
IEnumAssocHandlers* pEnumAssocHandlers = 0;
if ( SUCCEEDED ( SHAssocEnumHandlers ( L".abr", ASSOC_FILTER_RECOMMENDED, &pEnumAssocHandlers ) ) && pEnumAssocHandlers ) {
ULONG ulFetched = 0;
IAssocHandler* pAssocHandler = 0;
while ( SUCCEEDED ( pEnumAssocHandlers->Next(1, &pAssocHandler, &ulFetched ) ) && pAssocHandler ) {
LPWSTR lpwExecutableName = 0;
if ( SUCCEEDED ( pAssocHandler->GetName(&lpwExecutableName) ) && lpwExecutableName ) {
if ( wcsstr ( lpwExecutableName, L"otoshop.exe" ) ) {
size_t dwLenght;
StringCchLength ( lpwExecutableName, MAX_PATH, &dwLenght );
m_wPhotoshopExecutable.reset ( new WCHAR[dwLenght+1] );
StringCchCopy ( m_wPhotoshopExecutable, dwLenght + 1, lpwExecutableName );
pAssocHandler->Release();
break;
};
};
pAssocHandler->Release();
};
pEnumAssocHandlers->Release();
};
};
if ( m_wPhotoshopExecutable.get() ) {
ShellExecute ( m_hWnd, 0, m_wPhotoshopExecutable, m_wBrushesFile, 0, SW_SHOW );
};
return 0;
};
LRESULT CABRViewer::OnNcHitTest(WPARAM wParam, LPARAM lParam) {
if ( ( GetKeyState (VK_CONTROL) & 0x8000 ) || ( GetKeyState ( GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON ) & 0x8000 ) ) {
return HTCLIENT;
} else {
return HTCAPTION;
}
}
void CABRViewer::Zoom ( BOOL bOut, WORD xPos, WORD yPos ) {
if ( bOut ) {
if ( m_fZoomFactor == 1 ) {
m_fZoomFactor = 0.5;
m_uItsShowTimeBaby = ShowMultipleBrushes;
InvalidateRect ( m_hWnd, 0, FALSE );
} else if ( m_fZoomFactor < 1 ) {
if ( m_fZoomFactor != 0.125 ) {
m_fZoomFactor /= 2;
};
InvalidateRect ( m_hWnd, 0, FALSE );
} else {
if ( m_fZoomFactor != 1 ) {
m_fZoomFactor--;
if ( m_fZoomFactor < 1 ) {
m_fZoomFactor = 1;
};
m_ptOffset.x /= 2;
m_ptOffset.y /= 2;
InvalidateRect ( m_hWnd, 0, FALSE );
};
}
} else {
if ( m_fZoomFactor < 1 ) {
int count = (int)(1 / m_fZoomFactor );
RECT rcRect;
GetWindowRect(m_hWnd, &rcRect);
int x = ( xPos - rcRect.left ) / (( rcRect.right - rcRect.left ) / count );
int y = ( yPos - rcRect.top ) / (( rcRect.bottom - rcRect.top ) / count );
m_dwCurrentBrush += ( count * y + x );
if ( m_dwCurrentBrush >= m_pBrushes->Count() ) {
m_dwCurrentBrush = m_pBrushes->Count() - 1;
}
m_fZoomFactor *= 2;
if ( m_fZoomFactor == 1 ) {
m_uItsShowTimeBaby = ShowSingleBrush;
};
InvalidateRect ( m_hWnd, 0, FALSE );
} else if ( m_fZoomFactor != 10 ) {
m_fZoomFactor++;
if ( m_fZoomFactor > 10 ) {
m_fZoomFactor = 10;
};
InvalidateRect( m_hWnd, 0, FALSE );
};
};
}
void CABRViewer::Move ( BOOL bForward ) {
if ( m_pBrushes ) {
switch ( m_uItsShowTimeBaby ) {
case ShowSingleBrush:
if ( bForward ) {
if ( m_dwCurrentBrush != ( m_pBrushes->Count() - 1 ) ) {
m_dwCurrentBrush++;
m_fZoomFactor = 1;
ZeroMemory ( &m_ptOffset, sizeof(POINT) );
InvalidateRect ( m_hWnd, 0, FALSE);
};
} else {
if ( m_dwCurrentBrush != 0 ) {
m_dwCurrentBrush--;
m_fZoomFactor = 1;
ZeroMemory ( &m_ptOffset, sizeof(POINT) );
InvalidateRect ( m_hWnd, 0, FALSE);
};
};
break;
case ShowMultipleBrushes:
{
unsigned int count = (int)(1 / m_fZoomFactor );
count *= count;
if ( bForward ) {
if ( ( m_dwCurrentBrush + count ) < m_pBrushes->Count() ) {
m_dwCurrentBrush += count;
InvalidateRect ( m_hWnd, 0, FALSE);
};
} else {
if ( m_dwCurrentBrush && ( m_dwCurrentBrush < count ) ) {
m_dwCurrentBrush = 0;
InvalidateRect ( m_hWnd, 0, FALSE);
} if ( m_dwCurrentBrush >= count ) {
m_dwCurrentBrush -= count;
InvalidateRect ( m_hWnd, 0, FALSE);
};
};
}
break;
}
};
}
LRESULT CABRViewer::OnMouseWheel ( WORD wKeys, short zDelta, WORD xPos, WORD yPos ) {
wKeys & MK_CONTROL ? Zoom ( ((short)zDelta) < 0, xPos, yPos ) : Move ( ((short)zDelta) < 0 );
return 0L;
}
LRESULT CABRViewer::OnKeyUp ( UINT vkKeyCode, UINT vkParams ) {
BOOL bUpdate = FALSE;
switch ( vkKeyCode ) {
case VK_SPACE:
Recolor();
bUpdate = TRUE;
break;
case VK_LEFT:
Move ( FALSE );
bUpdate = TRUE;
break;
case VK_RIGHT:
Move ( TRUE );
bUpdate = TRUE;
break;
case VK_UP:
Zoom ( FALSE, 0, 0 );
bUpdate = TRUE;
break;
case VK_DOWN:
Zoom ( TRUE, 0, 0 );
bUpdate = TRUE;
break;
case VK_ESCAPE:
OnRButtonUp(0,0,0);
break;
case VK_RETURN:
OnLButtonDblClk (0,0,0);
break;
case VK_NEXT:
if ( !m_WalkingDead ) {
m_WalkingDead.reset ( new _WalkingDead() );
m_WalkingDead->Enum ( m_wBrushesFile );
};
if ( m_WalkingDead->IsValid() ) {
if ( WCHAR* wcsNewFile = m_WalkingDead->Next() ) {
if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) {
YetAnotherBeginUnpack(wcsNewFile);
};
};
}
break;
case VK_PRIOR:
if ( !m_WalkingDead ) {
m_WalkingDead.reset ( new _WalkingDead() );
m_WalkingDead->Enum ( m_wBrushesFile );
};
if ( m_WalkingDead->IsValid() ) {
if ( WCHAR* wcsNewFile = m_WalkingDead->Prev() ) {
if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) {
YetAnotherBeginUnpack(wcsNewFile);
};
};
};
break;
};
if ( bUpdate ) {
if ( HDC hDC = GetDC ( m_hWnd ) ) {
RECT rc;
GetClientRect ( m_hWnd, &rc );
BufferedDrawWindow ( CBufferDC ( m_hWnd, hDC ), &rc );
ReleaseDC ( m_hWnd, hDC );
};
};
return 0xFF01;
};
LRESULT CABRViewer::OnABRJobInProgress ( DWORD dwTotalBrushes, DWORD dwCurrentBrush ) {
m_uItsShowTimeBaby = ShowLoadingBrushes;
m_dwMagicNumber = dwCurrentBrush;
if ( HDC hOriginalDC = GetDC ( m_hWnd ) ) {
RECT rc;
GetClientRect ( m_hWnd, &rc );
BufferedDrawWindow ( CBufferDC ( m_hWnd, hOriginalDC ), &rc );
ReleaseDC ( m_hWnd, hOriginalDC );
};
return 0L;
}
LRESULT CABRViewer::OnABRJobComplete ( DWORD dwTotalBrushes, IAdobeBrushes* pBrushes ) {
m_uItsShowTimeBaby = ( dwTotalBrushes && pBrushes ) ? ShowSingleBrush : ShowBrokenHeart;
m_dwCurrentBrush = 0;
m_fZoomFactor = 1.0;
if ( m_pBrushes ) {
m_pBrushes->Release();
};
//
// m_clrBackground = 0x000000;
// Recolor();
m_pBrushes = pBrushes;
m_dwMagicNumber = dwTotalBrushes;
m_uItsShowTimeBaby = ShowMultipleBrushes;
m_fZoomFactor = 0.5;
if ( HDC hOriginalDC = GetDC ( m_hWnd ) ) {
RECT rc;
GetClientRect ( m_hWnd, &rc );
BufferedDrawWindow ( CBufferDC ( m_hWnd, hOriginalDC ), &rc );
ReleaseDC ( m_hWnd, hOriginalDC );
};
m_bIsDecodingIsActive = FALSE;
if ( m_bTerminateApplication ) {
if ( m_pDropTarget ) {
CDropTarget::UnregisterDropWindow ( m_hWnd, m_pDropTarget );
};
PostQuitMessage(0);
};
return 0L;
}
BOOL CABRViewer::BeginUnpackAdobeBrushesPresetFile(WCHAR* wcsFileName) {
//
// m_clrBackground = 0xFFFFFF;
// Recolor();
m_bIsDecodingIsActive = TRUE;
size_t dwLenght;
StringCchLength ( wcsFileName, MAX_PATH, &dwLenght );
m_wBrushesFile.reset ( new WCHAR[dwLenght+1] );
StringCchCopy ( m_wBrushesFile, dwLenght+1, wcsFileName );
ReadAdobePhotoshopBrushFile ( wcsFileName, AdobeBrushDataTypeFile, AdobeBrushDataTypeDIB, UnpackingJobCallback, this );
return TRUE;
}
BOOL CABRViewer::UnpackingJobCallback ( ABRPARSER_JOB* pJobStatus ) {
if ( pJobStatus ) {
if ( pJobStatus->bJobFinished ) {
SendMessage ( ((CABRViewer*)(pJobStatus->pParam))->m_hWnd, WM_ABRJOBCOMPLETE, (WPARAM)pJobStatus->dwBrushesTotal, (LPARAM)pJobStatus->pBrushes );
} else {
SendMessage ( ((CABRViewer*)(pJobStatus->pParam))->m_hWnd, WM_ABRJOBINPROGRESS, (WPARAM)pJobStatus->dwBrushesTotal, (LPARAM)pJobStatus->dwCurrentBrush );
}
};
return TRUE;
}
}
CABRViewer g_AdobeBrushViewerApp;
typedef BOOL (__stdcall *CHANGEWINDOWMESSAGEFILTER)( UINT message, DWORD dwFlag);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) {
//
MSG msg;
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_EXTENSIONVIEWERABR));
WCHAR** szArgList;
int argCount;
g_AdobeBrushViewerApp.m_uItsShowTimeBaby = ShowLoadingBrushes;
// Create application instance
g_AdobeBrushViewerApp.Create ( hInstance );
// Parse command line
szArgList = CommandLineToArgvW ( GetCommandLine(), &argCount );
if ( szArgList && argCount >= 2 ) {
g_AdobeBrushViewerApp.BeginUnpackAdobeBrushesPresetFile ( szArgList[1] );
SetWindowText ( g_AdobeBrushViewerApp.m_hWnd, szArgList[1] );
} else {
g_AdobeBrushViewerApp.m_uItsShowTimeBaby = ShowBrokenHeart;
SetWindowText ( g_AdobeBrushViewerApp.m_hWnd, L"Lightweight .ABR Viewer" );
InvalidateRect ( g_AdobeBrushViewerApp.m_hWnd, 0, FALSE );
};
if ( OleInitialize(0) != S_OK || !CDropTarget::RegisterDropWindow ( g_AdobeBrushViewerApp.m_hWnd, &g_AdobeBrushViewerApp.m_pDropTarget ) ) {
if ( HMODULE hUser32 = LoadLibrary(L"user32.dll" ) ) {
if ( CHANGEWINDOWMESSAGEFILTER fnChangeWindowMessageFilter = (CHANGEWINDOWMESSAGEFILTER)GetProcAddress ( hUser32, "ChangeWindowMessageFilter") ) {
fnChangeWindowMessageFilter ( 73 , MSGFLT_ADD );
fnChangeWindowMessageFilter ( WM_DROPFILES, MSGFLT_ADD);
}
FreeLibrary(hUser32);
};
DragAcceptFiles ( g_AdobeBrushViewerApp.m_hWnd, TRUE );
}
// Enter main message loop
while (GetMessage(&msg, NULL, 0, 0)) {
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
};
};
// anyway we're going out of there
// so one and only one failed call is not a bug
// ...
// i think
OleUninitialize();
return (int) msg.wParam;
}
| 29.803769
| 301
| 0.621582
|
lusores
|
94a7e264c212454507fb4d9832d699e9d812651f
| 2,727
|
cpp
|
C++
|
unit_tests/test_supportvectormachine.cpp
|
BrentP-tmx/Pamplemousse
|
6cd69d3369bf557c344d9a3a82b9c15f2381c366
|
[
"Apache-2.0"
] | 6
|
2020-09-23T15:38:28.000Z
|
2021-11-16T20:39:21.000Z
|
unit_tests/test_supportvectormachine.cpp
|
BrentP-tmx/Pamplemousse
|
6cd69d3369bf557c344d9a3a82b9c15f2381c366
|
[
"Apache-2.0"
] | null | null | null |
unit_tests/test_supportvectormachine.cpp
|
BrentP-tmx/Pamplemousse
|
6cd69d3369bf557c344d9a3a82b9c15f2381c366
|
[
"Apache-2.0"
] | 2
|
2021-10-04T22:16:48.000Z
|
2022-02-25T00:32:40.000Z
|
// Copyright 2018-2020 Lexis Nexis Risk Solutions
//
// 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.
//
// Created by Caleb Moore on 24/11/18.
//
#include <stdio.h>
#include "Cuti.h"
#include "document.hpp"
#include "testutils.hpp"
using namespace TestUtils;
TEST_CLASS (TestSupportVectorMachine)
{
public:
void testSVM()
{
tinyxml2::XMLDocument document;
CPPUNIT_ASSERT_EQUAL(tinyxml2::XML_SUCCESS, document.LoadFile(getPathToFile("SupportVectorXor.pmml").c_str()));
lua_State * L;
std::string prediction;
L = makeState(document);
CPPUNIT_ASSERT(L != nullptr);
// This model is just an xor function... treat it like that
for (int testCase = 0; testCase < 4; ++testCase)
{
int x = testCase % 2;
int y = testCase / 2;
CPPUNIT_ASSERT(executeModel(L, "x1", x , "x2", y));
CPPUNIT_ASSERT_EQUAL(true, getValue(L, "class", prediction));
CPPUNIT_ASSERT_EQUAL(std::string(x != y ? "yes" : "no"), prediction);
}
}
void testBinaryClass()
{
tinyxml2::XMLDocument document;
CPPUNIT_ASSERT_EQUAL(tinyxml2::XML_SUCCESS, document.LoadFile(getPathToFile("SupportVectorBinary.pmml").c_str()));
lua_State * L;
std::string prediction;
L = makeState(document);
CPPUNIT_ASSERT(L != nullptr);
CPPUNIT_ASSERT(executeModel(L, "Age", 14 , "Employment", "Consultant"));
CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction));
CPPUNIT_ASSERT_EQUAL(std::string("1"), prediction);
CPPUNIT_ASSERT(executeModel(L, "Age", 14 , "Employment", "SelfEmp"));
CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction));
CPPUNIT_ASSERT_EQUAL(std::string("0"), prediction);
CPPUNIT_ASSERT(executeModel(L, "Age", 34 , "Employment", "SelfEmp"));
CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction));
CPPUNIT_ASSERT_EQUAL(std::string("1"), prediction);
}
CPPUNIT_TEST_SUITE(TestSupportVectorMachine);
CPPUNIT_TEST(testSVM);
CPPUNIT_TEST(testBinaryClass);
CPPUNIT_TEST_SUITE_END();
};
| 34.518987
| 122
| 0.650532
|
BrentP-tmx
|
94ad15b7992a92d00844ca3b0402a9c6b2cd0ec0
| 311
|
cpp
|
C++
|
Get_Started_contest/8.find_me.cpp
|
MadanParth786/Codeshef_DSA_learning_Series
|
0582c5a1598c2233c9ab433ce71feb9816166bc7
|
[
"MIT"
] | 2
|
2021-07-03T09:00:06.000Z
|
2021-07-03T09:46:27.000Z
|
Get_Started_contest/8.find_me.cpp
|
MadanParth786/Codeshef_DSA_learning_Series
|
0582c5a1598c2233c9ab433ce71feb9816166bc7
|
[
"MIT"
] | null | null | null |
Get_Started_contest/8.find_me.cpp
|
MadanParth786/Codeshef_DSA_learning_Series
|
0582c5a1598c2233c9ab433ce71feb9816166bc7
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main(void)
{
int n,k;
bool found=false;
int a[n];
cin>>n>>k;
for(int i=0;i<n;i++)
{
cin>>a[i];
if(a[i]==k){
found=true;
break;
}
}
if(found){
cout<<"1"<<"\n";
}
else{
cout<<"-1"<<"\n";
}
}
| 11.518519
| 24
| 0.418006
|
MadanParth786
|
94ad617e30613b47e2fa342e23ce2bcec974c57a
| 3,489
|
cpp
|
C++
|
Overworld/Forest.cpp
|
NoahKittleson/RPG-Engine
|
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
|
[
"MIT",
"Unlicense"
] | 4
|
2016-06-30T19:55:40.000Z
|
2020-01-10T21:03:00.000Z
|
Overworld/Forest.cpp
|
NoahKittleson/RPG-Engine
|
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
|
[
"MIT",
"Unlicense"
] | null | null | null |
Overworld/Forest.cpp
|
NoahKittleson/RPG-Engine
|
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// Forest.cpp
// Overworld
//
// Created by Noah Kittleson on 7/7/18.
// Copyright © 2018 Noah. All rights reserved.
//
#include "Forest.hpp"
Forest::Forest(const ResourceHolder& resources, const std::vector<Condition>& activeConds)
: MapSection(MapID::Forest, NoMusic, sf::Vector2f(550 * scale, 350 * scale)) {
background.setTexture(resources.getTexture(Textures::Forest));
background.setScale(scale, scale);
//A Dead Tree (or is it?)
MapObject deadTree (make_unique<GraphicsComponent>(resources.getTexture(Textures::DeadTree), sf::Vector2f (200,200)));
deadTree.setScale(scale);
//deadTree.addCollisionBox(-18 * scale, 20 * scale, 42 * scale, 11 * scale);
deadTree.addCollisionBox(-3 * scale, 19 * scale, 14 * scale, 7 * scale);
deadTree.offsetBase(-13 * scale + 1); //added plus one to avoid weird draw order interactions with player
addObject(deadTree);
MapObject Tree1 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree1), sf::Vector2f (80,80)));
Tree1.setScale(scale);
Tree1.addCollisionBox(-10 * scale, 40 * scale, 12 * scale, 7 * scale);
Tree1.offsetBase(-8 * scale + 1);
addObject(Tree1);
MapObject Tree2 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree2), sf::Vector2f (600,400)));
Tree2.setScale(scale);
Tree2.addCollisionBox(-9 * scale, 24 * scale, 14 * scale, 7 * scale);
Tree2.offsetBase(-8 * scale + 1);
addObject(Tree2);
MapObject Tree3 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree3), sf::Vector2f (700,220)));
Tree3.setScale(scale);
Tree3.addCollisionBox(-9 * scale, 23 * scale, 14 * scale, 7 * scale);
Tree3.offsetBase(-9 * scale + 1);
addObject(Tree3);
MapObject Tree4 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree4), sf::Vector2f (400,120)));
Tree4.setScale(scale);
Tree4.addCollisionBox(-6 * scale, 26 * scale, 10 * scale, 7 * scale);
Tree4.offsetBase(-6 * scale + 1);
addObject(Tree4);
MapObject Tree5 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree5), sf::Vector2f (400,450)));
Tree5.setScale(scale);
Tree5.addCollisionBox(-5 * scale, 25 * scale, 10 * scale, 5 * scale);
Tree5.offsetBase(-7 * scale + 1);
addObject(Tree5);
MapObject Tree6 (make_unique<GraphicsComponent>(resources.getTexture(Textures::Tree6), sf::Vector2f (200,500)));
Tree6.setScale(scale);
Tree6.addCollisionBox(-6 * scale, 25 * scale, 10 * scale, 6 * scale);
Tree6.offsetBase(-7 * scale + 1);
addObject(Tree6);
//Set up Zone Exits
sf::Vector2u totalArea = background.getTexture()->getSize();
totalArea = sf::Vector2u(totalArea.x * scale, totalArea.y * scale);
exits.emplace_back(sf::FloatRect(0, -100, totalArea.x, 100),
sf::Vector2f(0, -mapClearance), MapID::MountainSouth); //entire top
exits.emplace_back(sf::FloatRect(-100, 0, 100, 150 * scale),
sf::Vector2f(-mapClearance, 0), MapID::Start); //top left
exits.emplace_back(sf::FloatRect(-100, 150 * scale, 100, 125 * scale),
sf::Vector2f(-mapClearance, 0), MapID::SouthOfStart); //bottom left
exits.emplace_back(sf::FloatRect(totalArea.x, 0, 100, 45 * scale),
sf::Vector2f(mapClearance, 0), MapID::TownEast); //top right
exits.emplace_back(sf::FloatRect(totalArea.x, 45 * scale, 100, 230 * scale),
sf::Vector2f(mapClearance, 0), MapID::Swamp); //bottom right
exits.emplace_back(sf::FloatRect(0, totalArea.y, totalArea.x, 100),
sf::Vector2f(0, mapClearance), MapID::TownSouth); //entire bottom
}
| 43.6125
| 119
| 0.70364
|
NoahKittleson
|
94aec82990bbfe9f1179dec54262e4b9f55a02d6
| 413
|
cpp
|
C++
|
swexpert/3308.cpp
|
juseongkr/BOJ
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 7
|
2020-02-03T10:00:19.000Z
|
2021-11-16T11:03:57.000Z
|
swexpert/3308.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2021-01-03T06:58:24.000Z
|
2021-01-03T06:58:24.000Z
|
swexpert/3308.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2020-01-22T14:34:03.000Z
|
2020-01-22T14:34:03.000Z
|
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 100001
int num[MAX];
int main()
{
int T, n, x;
cin >> T;
for (int t=1; t<=T; ++t) {
cin >> n;
int len = 0;
fill(num, num+MAX, 0);
for (int i=0; i<n; ++i) {
cin >> x;
int it = lower_bound(num, num+len, x) - num;
if (it == len)
len++;
num[it] = x;
}
cout << "#" << t << " " << len << '\n';
}
return 0;
}
| 14.241379
| 47
| 0.486683
|
juseongkr
|
94b0fee0885891546ad81efcc2e98b090642d5d4
| 782
|
cpp
|
C++
|
Section 8/Video 3/locks.cpp
|
irshadqemu/C-Standard-Template-Library-in-Practice
|
05a52a03c2fc50031f065da41d89cfbf651499f9
|
[
"MIT"
] | 17
|
2019-10-10T21:09:51.000Z
|
2022-01-13T15:54:24.000Z
|
Section 8/Video 3/locks.cpp
|
irshadqemu/C-Standard-Template-Library-in-Practice
|
05a52a03c2fc50031f065da41d89cfbf651499f9
|
[
"MIT"
] | null | null | null |
Section 8/Video 3/locks.cpp
|
irshadqemu/C-Standard-Template-Library-in-Practice
|
05a52a03c2fc50031f065da41d89cfbf651499f9
|
[
"MIT"
] | 16
|
2019-10-10T21:09:55.000Z
|
2022-02-13T11:42:52.000Z
|
#include <thread>
#include <iostream>
#include <mutex>
#define TRANSACTIONS 100000
using namespace std;
void deposit(int& account, mutex& m) {
for (int i = 0; i < TRANSACTIONS; i++) {
{
lock_guard<mutex> lock(m);
++account;
}
}
}
void withdraw(int& account, mutex& m) {
for (int i = 0; i < TRANSACTIONS; i++) {
{
lock_guard<mutex> lock(m);
--account;
}
}
}
int main() {
unsigned int threads = thread::hardware_concurrency();
cout << threads << " Threads supported\n";
int account = 0;
mutex m;
thread t1 (deposit, std::ref(account), std::ref(m));
thread t2 (withdraw, std::ref(account), std::ref(m));
t1.join();
t2.join();
cout << "After the threads, account value is: " << account << "\n";
return 0;
}
| 17.377778
| 69
| 0.589514
|
irshadqemu
|
94b6a75b96c61ac067d3fa7995e4942a579bbe9a
| 3,092
|
cpp
|
C++
|
codeforces/F - Music in Car/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/F - Music in Car/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/F - Music in Car/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Jun/09/2020 16:14
* solution_verdict: Accepted language: GNU C++14
* run_time: 608 ms memory_used: 85600 KB
* problem: https://codeforces.com/contest/746/problem/F
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=2e5;
struct persistent
{
int l,r,sm,cn,od;
}seg[N*20+2];
int rot[N+2],nw;
void upd(int node,int pnode,int lo,int hi,int id,int vl)
{
if(lo==hi)
{
seg[node].sm=seg[pnode].sm+vl;seg[node].cn=seg[pnode].cn+1;
seg[node].od=seg[pnode].od+vl%2;return ;
}
int md=(lo+hi)/2;
if(id<=md)
{
if(!seg[node].l)seg[node].l=++nw;upd(seg[node].l,seg[pnode].l,lo,md,id,vl);
seg[node].r=seg[pnode].r;
}
else
{
if(!seg[node].r)seg[node].r=++nw;upd(seg[node].r,seg[pnode].r,md+1,hi,id,vl);
seg[node].l=seg[pnode].l;
}
seg[node].sm=seg[seg[node].l].sm+seg[seg[node].r].sm;
seg[node].cn=seg[seg[node].l].cn+seg[seg[node].r].cn;
seg[node].od=seg[seg[node].l].od+seg[seg[node].r].od;
}
pair<int,int>get(int node,int pnode,int lo,int hi,int k)
{
if(lo==hi)
{
assert(k==1);return {seg[node].sm-seg[pnode].sm,seg[node].od-seg[pnode].od};
}
int md=(lo+hi)/2;
int rm=seg[seg[node].l].cn-seg[seg[pnode].l].cn;
if(rm>=k)return get(seg[node].l,seg[pnode].l,lo,md,k);
else
{
pair<int,int>p=get(seg[node].r,seg[pnode].r,md+1,hi,k-rm);
return {p.first+seg[seg[node].l].sm-seg[seg[pnode].l].sm,p.second+seg[seg[node].l].od-seg[seg[pnode].l].od};
}
}
int a[N+2],t[N+2],id[N+2];
int qm[N+2],od[N+2],w,k,n;
pair<int,int>p[N+2];
bool ok(int i,int j)
{
long tt=0;int s=qm[j-1]-qm[i-1],o=od[j-1]-od[i-1];
if(j-i<=w)return (s+o)/2<=k;
int rm=(j-i)-w;
pair<int,int>p=get(rot[i],rot[j],1,n,rm);
s-=p.first,o-=p.second;
return p.first+(s+o)/2<=k;
}
int aa[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n>>w>>k;
for(int i=1;i<=n;i++)cin>>a[i],aa[i]=aa[i-1]+a[i];
for(int i=1;i<=n;i++)cin>>t[i],p[i]={t[i],i};
for(int i=1;i<=n;i++)
{
qm[i]=qm[i-1]+t[i];
od[i]=od[i-1]+t[i]%2;
}
sort(p+1,p+n+1);
for(int i=1;i<=n;i++)id[p[i].second]=i;
int ans=0;
for(int i=n;i>=1;i--)
{
rot[i]=++nw;upd(rot[i],rot[i+1],1,n,id[i],t[i]);
if((t[i]+1)/2>k)continue;
int lo=i,hi=n,md;
while(hi-lo>2)
{
md=(lo+hi)/2;
if(ok(i,md+1))lo=md;
else hi=md;
}
for(md=hi;md>=lo;md--)if(ok(i,md+1))break;
ans=max(ans,aa[md]-aa[i-1]);
}
cout<<ans<<endl;
return 0;
}
| 27.855856
| 112
| 0.518758
|
kzvd4729
|
94b71997dcf168861cb127f7c6f17f6248a1201b
| 7,968
|
hpp
|
C++
|
src/arch/pico/video/ssd1351.hpp
|
yocto-8/yocto-8
|
4911a82f399776731d3030234c731c15593f1910
|
[
"MIT"
] | 22
|
2021-06-20T21:23:29.000Z
|
2022-03-26T01:46:10.000Z
|
src/arch/pico/video/ssd1351.hpp
|
yocto-8/yocto-8
|
4911a82f399776731d3030234c731c15593f1910
|
[
"MIT"
] | 2
|
2021-09-06T12:08:32.000Z
|
2021-09-06T12:23:55.000Z
|
src/arch/pico/video/ssd1351.hpp
|
yocto-8/yocto-8
|
4911a82f399776731d3030234c731c15593f1910
|
[
"MIT"
] | 1
|
2021-11-26T08:34:59.000Z
|
2021-11-26T08:34:59.000Z
|
#pragma once
#include <hardware/gpio.h>
#include <hardware/spi.h>
#include <hardware/dma.h>
#include <array>
#include <cstdint>
#include <cmath>
#include <span>
#include <emu/emulator.hpp>
#include <devices/image.hpp>
#include <devices/screenpalette.hpp>
#include <video/palette.hpp>
namespace arch::pico::video
{
static constexpr std::array<std::uint16_t, 32> rgb_palette_to_ssd1351_format(std::span<const std::uint32_t, 32> palette)
{
std::array<std::uint16_t, 32> ret{};
for (std::size_t i = 0; i < 32; ++i)
{
const std::uint32_t rgb8 = palette[i];
std::uint8_t
r5 = ((rgb8 >> 16) & 0xFF) >> (8 - 5),
g6 = ((rgb8 >> 8) & 0xFF) >> (8 - 6),
b5 = ((rgb8 >> 0) & 0xFF) >> (8 - 5);
ret[i] = (r5 << (5 + 6)) | (g6 << 5) | b5;
// Swap LSB/MSB
ret[i] = ((ret[i] & 0xFF) << 8) | (ret[i] >> 8);
}
return ret;
}
class SSD1351
{
public:
enum class Command : std::uint8_t
{
SET_COLUMN = 0x15,
SET_ROW = 0x75,
RAM_WRITE = 0x5C,
RAM_READ = 0x5D,
SET_REMAP = 0xA0,
SET_START_LINE = 0xA1,
SET_DISPLAY_OFFSET = 0xA2,
DISPLAY_ALL_OFF = 0xA4,
DISPLAY_ALL_ON = 0xA5,
NORMAL_DISPLAY = 0xA6,
INVERT_DISPLAY = 0xA7,
SET_FUNCTION = 0xAB,
DISPLAY_OFF = 0xAE,
DISPLAY_ON = 0xAF,
SET_PRECHARGE_PERIOD = 0xB1,
MAGIC_ENHANCE_DISPLAY = 0xB2, //< no idea what this does, the datasheet is not any more clear
SET_CLOCK_DIVIDER = 0xB3,
SET_VSL = 0xB4,
SET_GPIO = 0xB5,
SET_PRECHARGE2_PERIOD = 0xB6,
SET_GRAYSCALE_LUT = 0xB8,
SET_DEFAULT_LUT = 0xB9,
SET_PRECHARGE_VOLTAGE = 0xBB,
SET_COM_DESELECT_VOLTAGE = 0xBE,
SET_CHANNEL_CONTRAST = 0xC1,
SET_GLOBAL_CONTRAST = 0xC7,
SET_MUX_RATIO = 0xCA,
SET_COMMAND_LOCK = 0xFD,
SET_HORIZONTAL_SCROLL = 0x96,
STOP_HORIZONTAL_SCROLL = 0x9E,
START_HORIZONTAL_SCROLL = 0x9F
};
struct Pinout
{
std::uint32_t sclk, tx, rst, cs, dc;
};
struct Config
{
spi_inst_t* spi;
Pinout pinout;
};
void init(Config config)
{
_spi = config.spi;
_pinout = config.pinout;
gpio_set_function(_pinout.sclk, GPIO_FUNC_SPI);
gpio_set_function(_pinout.tx, GPIO_FUNC_SPI);
gpio_init(_pinout.rst);
gpio_set_dir(_pinout.rst, GPIO_OUT);
gpio_put(_pinout.rst, 1);
gpio_init(_pinout.cs);
gpio_set_dir(_pinout.cs, GPIO_OUT);
gpio_put(_pinout.cs, 1);
gpio_init(_pinout.dc);
gpio_set_dir(_pinout.dc, GPIO_OUT);
gpio_put(_pinout.dc, 0);
reset_blocking();
submit_init_sequence();
/*_dma_channel = dma_claim_unused_channel(true);
dma_channel_config dma_cfg = dma_channel_get_default_config(_dma_channel);
channel_config_set_transfer_data_size(&dma_cfg, DMA_SIZE_32);
channel_config_set_dreq(&dma_cfg, spi_get_index(spi_default) ? DREQ_SPI1_TX : DREQ_SPI0_TX);*/
}
void load_rgb_palette(std::span<const std::uint32_t, 32> new_rgb_palette)
{
palette = rgb_palette_to_ssd1351_format(new_rgb_palette);
}
void reset_blocking()
{
gpio_put(_pinout.rst, 1);
sleep_ms(1);
gpio_put(_pinout.rst, 0);
sleep_ms(1);
gpio_put(_pinout.rst, 1);
sleep_ms(1);
}
template<std::size_t N>
using DataBuffer = std::array<std::uint8_t, N>;
// scale 0x0..0xF
void set_brightness(std::uint8_t scale)
{
write(Command::SET_GLOBAL_CONTRAST, DataBuffer<1>{scale});
}
void submit_init_sequence()
{
// Enable MCU interface (else some commands will be dropped)
write(Command::SET_COMMAND_LOCK, DataBuffer<1>{0x12});
write(Command::SET_COMMAND_LOCK, DataBuffer<1>{0xB1});
// Shut off the display while we set it up
write(Command::DISPLAY_OFF);
// Set clock division stuff and cover the entire screen
write(Command::SET_CLOCK_DIVIDER, DataBuffer<1>{0xF0});
write(Command::SET_MUX_RATIO, DataBuffer<1>{127});
// 64K 16-bit format, enable split, CBA, correct rotation
write(Command::SET_REMAP, DataBuffer<1>{0b01110100});
// Set display offsets
write(Command::SET_START_LINE, DataBuffer<1>{0});
write(Command::SET_DISPLAY_OFFSET, DataBuffer<1>{0});
// Disable both GPIO pins
write(Command::SET_GPIO, DataBuffer<1>{0x00});
// Set SPI interface, disable sleep mode
write(Command::SET_FUNCTION, DataBuffer<1>{0b00'1});
// Timing tweaks
write(Command::SET_PRECHARGE_PERIOD, DataBuffer<1>{0b0010'0010});
write(Command::SET_PRECHARGE2_PERIOD, DataBuffer<1>{0b0001});
// Voltage tweaks
write(Command::SET_PRECHARGE_VOLTAGE, DataBuffer<1>{0b11111});
write(Command::SET_COM_DESELECT_VOLTAGE, DataBuffer<1>{0b111});
// Seems to be useless?
//write(Command::MAGIC_ENHANCE_DISPLAY, DataBuffer<3>{0xA4, 0x00, 0x00});
// Display regular pixel data
write(Command::NORMAL_DISPLAY);
// Contrast settings
write(Command::SET_CHANNEL_CONTRAST, DataBuffer<3>{0xFF, 0xFF, 0xFF});
//set_brightness(0xA); const float gamma = 1.25;
//set_brightness(0xA); const float gamma = 1.0;
set_brightness(0x5); const float gamma = 0.75;
//set_brightness(0x3); const float gamma = 0.7;
//set_brightness(0x2); const float gamma = 0.6;
// Set cryptic command from the datasheet that does fuck knows
write(Command::SET_VSL, DataBuffer<3>{0xA0, 0xB5, 0x55});
DataBuffer<63> gamma_lut;
for (std::size_t i = 0; i < gamma_lut.size(); ++i)
{
gamma_lut[i] = round(180.0f * pow(i/63.0f, gamma));
}
write(Command::SET_GRAYSCALE_LUT, gamma_lut);
// Start display
write(Command::DISPLAY_ON);
}
void write(Command command, std::span<const std::uint8_t> data = {})
{
gpio_put(_pinout.dc, 0);
gpio_put(_pinout.cs, 0);
spi_write_blocking(_spi, reinterpret_cast<std::uint8_t*>(&command), 1);
if (!data.empty())
{
gpio_put(_pinout.dc, 1);
spi_write_blocking(_spi, data.data(), data.size());
}
gpio_put(_pinout.cs, 1);
}
void update_frame(devices::Framebuffer view, devices::ScreenPalette screen_palette)
{
//const auto time_start = get_absolute_time();
// SRAM writes should cover all the framebuffer (0..127)
write(Command::SET_COLUMN, DataBuffer<2>{0, 127});
write(Command::SET_ROW, DataBuffer<2>{0, 127});
// Start write
write(Command::RAM_WRITE);
gpio_put(_pinout.dc, 1);
gpio_put(_pinout.cs, 0);
/*dma_channel_configure(
_dma_channel,
&dma_cfg,
&spi_get_hw(_spi)->dr,
emu::emulator.frame_buffer().data.data(),
8192 / 4,
false);*/
for (std::size_t i = 0; i < view.frame_bytes; ++i)
{
const auto pixel_pair = std::array{
palette[screen_palette.get_color(view.data[i] & 0x0F)],
palette[screen_palette.get_color(view.data[i] >> 4)]
};
spi_write_blocking(
_spi,
reinterpret_cast<const std::uint8_t*>(pixel_pair.data()),
2 * pixel_pair.size()
);
}
gpio_put(_pinout.cs, 1);
//const auto time_end = get_absolute_time();
//printf("%fms\n", absolute_time_diff_us(time_start, time_end) / 1000.0f);
}
std::array<std::uint16_t, 32> palette;
private:
//unsigned _dma_channel;
spi_inst_t* _spi;
Pinout _pinout;
};
}
| 28.457143
| 120
| 0.593499
|
yocto-8
|
94bc4de85927f68c910556ea6200887766e422e4
| 16,007
|
cpp
|
C++
|
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
|
AlejandroC1983/cvrtgi
|
9894fc79d4036a0490dbc194b9d04654574f16d4
|
[
"Apache-2.0"
] | 2
|
2022-03-25T00:37:25.000Z
|
2022-03-26T00:13:53.000Z
|
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
|
AlejandroC1983/cvrtgi
|
9894fc79d4036a0490dbc194b9d04654574f16d4
|
[
"Apache-2.0"
] | null | null | null |
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
|
AlejandroC1983/cvrtgi
|
9894fc79d4036a0490dbc194b9d04654574f16d4
|
[
"Apache-2.0"
] | 1
|
2022-03-02T21:11:29.000Z
|
2022-03-02T21:11:29.000Z
|
/*
Copyright 2022 Alejandro Cosin & Gustavo Patow
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.
*/
// GLOBAL INCLUDES
// PROJECT INCLUDES
#include "../../include/rastertechnique/clustervisibleprefixsumtechnique.h"
#include "../../include/buffer/buffer.h"
#include "../../include/buffer/buffermanager.h"
#include "../../include/rastertechnique/clustervisibilitytechnique.h"
#include "../../include/core/gpupipeline.h"
#include "../../include/core/coremanager.h"
#include "../../include/material/materialprefixsum.h"
#include "../../include/util/bufferverificationhelper.h"
#include "../../include/rastertechnique/bufferprefixsumtechnique.h"
// NAMESPACE
// DEFINES
// STATIC MEMBER INITIALIZATION
/////////////////////////////////////////////////////////////////////////////////////////////
ClusterVisiblePrefixSumTechnique::ClusterVisiblePrefixSumTechnique(string&& name, string&& className) : RasterTechnique(move(name), move(className))
, m_clusterVisibilityBuffer(nullptr)
, m_clusterVisibilityCompactedBuffer(nullptr)
, m_clusterVisibilityFirstIndexBuffer(nullptr)
, m_prefixSumBuffer(nullptr)
, m_clusterVisibilityTechnique(nullptr)
, m_prefixSumPlanarBufferSize(0)
, m_numberStepsReduce(0)
, m_firstSetIsSingleElement(false)
, m_numberStepsDownSweep(0)
, m_currentStep(0)
, m_currentPhase(0)
, m_compactionStepDone(false)
, m_firstIndexOccupiedElement(0)
, m_currentStepEnum(PrefixSumStep_::PS_REDUCTION)
, m_numElementAnalyzedPerThread(0)
{
m_active = false;
m_needsToRecord = false;
m_rasterTechniqueType = RasterTechniqueType::RTT_COMPUTE;
m_computeHostSynchronize = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ClusterVisiblePrefixSumTechnique::init()
{
// Shader storage buffer used to store the whole prefix sum steps (reduction and sweepdown)
// The buffer will be resized once slotClusterVisibility is called
m_prefixSumBuffer = bufferM->buildBuffer(
move(string("prefixSumBuffer")),
nullptr,
256,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
// TODO: Rename to more generic, prefix sum values
// TODO: Delete prefixSumBuffer once the prefix sum part is done
m_clusterVisibilityBuffer = bufferM->getElement(move(string("clusterVisibilityBuffer")));
m_clusterVisibilityCompactedBuffer = bufferM->getElement(move(string("clusterVisibilityCompactedBuffer")));
m_clusterVisibilityFirstIndexBuffer = bufferM->getElement(move(string("clusterVisibilityFirstIndexBuffer")));
m_vectorMaterialName.resize(1);
m_vectorMaterial.resize(1);
m_vectorMaterialName[0] = string("MaterialPrefixSum");
m_vectorMaterial[0] = materialM->buildMaterial(move(string("MaterialPrefixSum")), move(string("MaterialPrefixSum")), nullptr);
m_clusterVisibilityTechnique = static_cast<ClusterVisibilityTechnique*>(gpuPipelineM->getRasterTechniqueByName(move(string("ClusterVisibilityTechnique"))));
m_clusterVisibilityTechnique->refSignalClusterVisibilityCompletion().connect<ClusterVisiblePrefixSumTechnique, &ClusterVisiblePrefixSumTechnique::slotClusterVisibility>(this);
m_numElementAnalyzedPerThread = m_clusterVisibilityTechnique->getNumThreadPerLocalWorkgroup();
}
/////////////////////////////////////////////////////////////////////////////////////////////
VkCommandBuffer* ClusterVisiblePrefixSumTechnique::record(int currentImage, uint& commandBufferID, CommandBufferType& commandBufferType)
{
MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]);
commandBufferType = CommandBufferType::CBT_COMPUTE_QUEUE;
VkCommandBuffer* commandBuffer;
commandBuffer = addRecordedCommandBuffer(commandBufferID);
addCommandBufferQueueType(commandBufferID, commandBufferType);
coreM->allocCommandBuffer(&coreM->getLogicalDevice(), coreM->getComputeCommandPool(), commandBuffer);
coreM->beginCommandBuffer(*commandBuffer);
#ifdef USE_TIMESTAMP
vkCmdWriteTimestamp(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, coreM->getComputeQueueQueryPool(), m_queryIndex0);
#endif
// Dispatch the compute shader to build the prefix sum, the buffer m_prefixSumPlanarBuffer
// has all the required prefix sum level number of elements
// Several dispatchs can be needed to complete the algorithm (depending on the number of elements
// in the buffer), the method postQueueSubmit is used to coordinate the dispatchs
vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, material->getPipeline()->getPipeline());
uint dynamicAllignment = materialM->getMaterialUBDynamicAllignment();
uint32_t offsetData = static_cast<uint32_t>(material->getMaterialUniformBufferIndex() * dynamicAllignment);
vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, material->getPipelineLayout(), 0, 1, &material->refDescriptorSet(), 1, &offsetData);
uint finalWorkgroupSize;
// 0 means reduction step, 1 sweep down, 2 write final compacted buffer
if (m_currentPhase == 0)
{
finalWorkgroupSize = m_vectorPrefixSumNumElement[m_currentStep];
}
else if (m_currentPhase == 1)
{
finalWorkgroupSize = uint(ceilf(float(m_vectorPrefixSumNumElement[m_currentStep]) / float(m_numElementAnalyzedPerThread)));
}
else if (m_currentPhase == 2)
{
finalWorkgroupSize = m_vectorPrefixSumNumElement[0];
}
vkCmdDispatch(*commandBuffer, finalWorkgroupSize, 1, 1); // Compute shader global workgroup https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html
#ifdef USE_TIMESTAMP
vkCmdWriteTimestamp(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, coreM->getComputeQueueQueryPool(), m_queryIndex1);
#endif
coreM->endCommandBuffer(*commandBuffer);
// NOTE: Clear command buffer if re-recorded
m_vectorCommand.push_back(commandBuffer);
return commandBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ClusterVisiblePrefixSumTechnique::postCommandSubmit()
{
switch (m_currentStepEnum)
{
case PrefixSumStep_::PS_REDUCTION:
{
MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]);
if ((m_currentStep + 1) < m_numberStepsReduce)
{
m_currentStep++;
material->setCurrentStep(m_currentStep);
}
else
{
//BufferVerificationHelper::verifyPrefixSumData();
m_currentPhase++;
material->setCurrentPhase(m_currentPhase);
if (m_firstSetIsSingleElement)
{
m_currentStep--;
material->setCurrentStep(m_currentStep);
}
m_firstIndexOccupiedElement = retrieveAccumulatedNumValues();
// Since the indices to the clusters are encoded using 16 bits, half of the amount of indices is needed
uint bufferSize = uint(round(float(m_firstIndexOccupiedElement) / 2.0f));
//bufferM->resize(m_clusterVisibilityCompactedBuffer, nullptr, m_firstIndexOccupiedElement * sizeof(uint));
bufferM->resize(m_clusterVisibilityCompactedBuffer, nullptr, bufferSize * sizeof(uint));
m_currentStepEnum = PrefixSumStep_::PS_SWEEPDOWN;
cout << "Total number of visible cluster from all voxel faces is " << m_firstIndexOccupiedElement << endl;
cout << "Size m_clusterVisibilityCompactedBuffer=" << ((m_clusterVisibilityCompactedBuffer->getDataSize()) / 1024.0f) / 1024.0f << "MB" << endl;
}
break;
}
case PrefixSumStep_::PS_SWEEPDOWN:
{
MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]);
if (m_currentStep > 0)
{
m_currentStep--;
material->setCurrentStep(m_currentStep);
}
else
{
m_currentPhase++;
m_currentStepEnum = PrefixSumStep_::PS_LAST_STEP;
material->setCurrentPhase(m_currentPhase);
}
break;
}
case PrefixSumStep_::PS_LAST_STEP:
{
// Copy the data in prefixSumBuffer that contains, for each element in voxelHashedPositionCompactedBuffer
// the indices where to get in clusterVisibilityCompactedBuffer the clusters visible for that voxel,
// for each one of the six voxel faces. This is stored at the beginning of prefixSumBuffer
// after the algorithm ends
Buffer* prefixSumBuffer = bufferM->getElement(move(string("prefixSumBuffer")));
BufferPrefixSumTechnique* techniquePrefixSum = static_cast<BufferPrefixSumTechnique*>(gpuPipelineM->getRasterTechniqueByName(move(string("BufferPrefixSumTechnique"))));
uint numOccupiedVoxel = techniquePrefixSum->getFirstIndexOccupiedElement();
uint numElementToCopy = numOccupiedVoxel * 6;
// Resize the cluster visibility first index buffer, which is used in combination with clusterVisibilityNumberBuffer
// and clusterVisibilityCompactedBuffer to know, for each voxel face of each generated voxel, where in
// clusterVisibilityCompactedBuffer start the amount of visible clusters from that voxel
bufferM->resize(m_clusterVisibilityFirstIndexBuffer, nullptr, numElementToCopy * sizeof(uint));
cout << "The size of the clusterVisibilityFirstIndexBuffer buffer is" << numElementToCopy * sizeof(uint) << endl;
// Copy the content to clusterVisibilityFirstIndexBuffer, which is generated at the end of the prefix sum process
// and is present in the prefixSumBuffer buffer
bufferM->copyBuffer(prefixSumBuffer, m_clusterVisibilityFirstIndexBuffer, 0, 0, int(m_clusterVisibilityFirstIndexBuffer->getDataSize()));
//BufferVerificationHelper::verifyClusterVisibilityFirstIndexBuffer();
//BufferVerificationHelper::verifyClusterVisibilityCompactedData();
m_compactionStepDone = true;
m_active = false;
m_executeCommand = false;
m_needsToRecord = false;
m_currentStepEnum = PrefixSumStep_::PS_FINISHED;
m_signalClusterVisiblePrefixSumTechnique.emit(); // notify the prefix sum step has been completed
/**/
//m_prefixSumBuffer
vectorUint8 m_prefixSumBufferNumberBuffer;
Buffer* clusterVisibilityNumberBuffer = bufferM->getElement(move(string("clusterVisibilityCompactedBuffer")));
clusterVisibilityNumberBuffer->getContentCopy(m_prefixSumBufferNumberBuffer);
uint numClusterVisibilityNumberBuffer = uint(clusterVisibilityNumberBuffer->getDataSize()) / sizeof(uint);
uint* pClusterVisibilityNumberBuffer = (uint*)(m_prefixSumBufferNumberBuffer.data());
// Now do a verification of clusterVisibilityFirstIndexBuffer
//for (uint i = 0; i < numClusterVisibilityNumberBuffer; ++i)
for (uint i = 0; i < 100; ++i)
{
uint temp = 0;
uint decoded0 = pClusterVisibilityNumberBuffer[i];
decoded0 &= (0x0000FFFF << (temp * 16));
decoded0 >>= (temp * 16);
temp = 1;
uint decoded1 = pClusterVisibilityNumberBuffer[i];
decoded1 &= (0x0000FFFF << (temp * 16));
decoded1 >>= (temp * 16);
cout << "i = " << i << ", decoded0=" << decoded0 << ", decoded1=" << decoded1 << endl;
}
/**/
break;
}
default:
{
cout << "ERROR: no enum value in ClusterVisiblePrefixSumTechnique::postCommandSubmit" << endl;
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ClusterVisiblePrefixSumTechnique::slotClusterVisibility()
{
m_needsToRecord = true;
m_active = true;
// TODO: Put the code below in a utility method and refactor with BufferPrefixSumTechnique
m_vectorPrefixSumNumElement.resize(5); // Up to four levels needed to the prefix parallel sum
memset(m_vectorPrefixSumNumElement.data(), 0, m_vectorPrefixSumNumElement.size() * size_t(sizeof(uint)));
// The amount of elements to process is the value of ClusterVisibilityTechnique::m_bufferNumElement
// which is the amount of occupied voxels multiplied by the number of faces of each voxel (6)
m_vectorPrefixSumNumElement[0] = m_clusterVisibilityTechnique->getBufferNumElement() / m_numElementAnalyzedPerThread;
MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]);
material->setNumElementBase(m_vectorPrefixSumNumElement[0]);
material->setCurrentStep(m_currentStep);
// The maximum number of elements in bufferHistogramBuffer is 536862720,
// given that each thread processes 128 elements of bufferHistogramBuffer in the initial pass, up to
// four levels are needed to complete the algorithm.
float numElementPerThread = float(m_numElementAnalyzedPerThread);
m_prefixSumPlanarBufferSize += uint(m_vectorPrefixSumNumElement[0]);
float prefixSumNumElemenCurrentStep = float(m_vectorPrefixSumNumElement[0]);
bool stop = ((prefixSumNumElemenCurrentStep / numElementPerThread) <= 1.0f);
m_numberStepsReduce++;
while (!stop)
{
prefixSumNumElemenCurrentStep = ceilf(prefixSumNumElemenCurrentStep / numElementPerThread);
m_prefixSumPlanarBufferSize += uint(prefixSumNumElemenCurrentStep);
m_vectorPrefixSumNumElement[m_numberStepsReduce] = uint(prefixSumNumElemenCurrentStep);
stop = (prefixSumNumElemenCurrentStep <= 1.0f);
m_numberStepsReduce++;
}
m_currentPhase = 0;
m_compactionStepDone = false;
m_firstIndexOccupiedElement = 0;
material->setNumElementLevel0(m_vectorPrefixSumNumElement[1]);
material->setNumElementLevel1(m_vectorPrefixSumNumElement[2]);
material->setNumElementLevel2(m_vectorPrefixSumNumElement[3]);
material->setNumElementLevel3(m_vectorPrefixSumNumElement[4]);
material->setNumberStepsReduce(m_numberStepsReduce);
material->setCurrentPhase(m_currentPhase);
m_numberStepsDownSweep = m_numberStepsReduce;
uint numElement = uint(m_vectorPrefixSumNumElement.size());
forI(numElement)
{
if (m_vectorPrefixSumNumElement[numElement - 1 - i] > 1)
{
if ((i > 0) && (m_vectorPrefixSumNumElement[numElement - i] == 1))
{
m_firstSetIsSingleElement = true;
m_numberStepsDownSweep--;
}
break;
}
}
m_usedCommandBufferNumber = m_numberStepsReduce + m_numberStepsDownSweep + 2;
material->setNumberStepsDownSweep(m_numberStepsDownSweep);
bufferM->resize(m_prefixSumBuffer, nullptr, m_prefixSumPlanarBufferSize * sizeof(uint));
}
/////////////////////////////////////////////////////////////////////////////////////////////
uint ClusterVisiblePrefixSumTechnique::retrieveAccumulatedNumValues()
{
// TODO: Set as utility function and reuse it in BufferPrefixSumTechnique, right now duplicated
uint offsetIndex;
uint numElementLastStep;
uint maxIndex = uint(m_vectorPrefixSumNumElement.size());
forI(maxIndex)
{
if (m_vectorPrefixSumNumElement[maxIndex - i - 1] > 0)
{
numElementLastStep = m_vectorPrefixSumNumElement[maxIndex - i - 1];
offsetIndex = maxIndex - i - 1;
break;
}
}
uint offset = 0;
forI(offsetIndex)
{
offset += m_vectorPrefixSumNumElement[i];
}
vector<uint8_t> vectorReductionLastStep;
vectorReductionLastStep.resize(numElementLastStep * sizeof(uint));
void* mappedMemory;
VkResult result = vkMapMemory(coreM->getLogicalDevice(), m_prefixSumBuffer->getMemory(), offset * sizeof(uint), numElementLastStep * sizeof(uint), 0, &mappedMemory);
assert(result == VK_SUCCESS);
memcpy((void*)vectorReductionLastStep.data(), mappedMemory, numElementLastStep * sizeof(uint));
vkUnmapMemory(coreM->getLogicalDevice(), m_prefixSumBuffer->getMemory());
uint accumulated = 0;
uint* pData = (uint*)(vectorReductionLastStep.data());
forI(numElementLastStep)
{
accumulated += pData[i];
}
return accumulated;
}
/////////////////////////////////////////////////////////////////////////////////////////////
| 41.1491
| 176
| 0.736928
|
AlejandroC1983
|
94bccdd9ce6a0352d4348011bfd28601edcec459
| 15,876
|
hpp
|
C++
|
ThirdParty-mod/java2cpp/java/util/concurrent/SynchronousQueue.hpp
|
kakashidinho/HQEngine
|
8125b290afa7c62db6cc6eac14e964d8138c7fd0
|
[
"MIT"
] | 1
|
2019-04-03T01:53:28.000Z
|
2019-04-03T01:53:28.000Z
|
ThirdParty-mod/java2cpp/java/util/concurrent/SynchronousQueue.hpp
|
kakashidinho/HQEngine
|
8125b290afa7c62db6cc6eac14e964d8138c7fd0
|
[
"MIT"
] | null | null | null |
ThirdParty-mod/java2cpp/java/util/concurrent/SynchronousQueue.hpp
|
kakashidinho/HQEngine
|
8125b290afa7c62db6cc6eac14e964d8138c7fd0
|
[
"MIT"
] | null | null | null |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.util.concurrent.SynchronousQueue
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_DECL
#define J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_DECL
namespace j2cpp { namespace java { namespace io { class Serializable; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace util { class AbstractQueue; } } }
namespace j2cpp { namespace java { namespace util { class Iterator; } } }
namespace j2cpp { namespace java { namespace util { namespace concurrent { class BlockingQueue; } } } }
namespace j2cpp { namespace java { namespace util { namespace concurrent { class TimeUnit; } } } }
namespace j2cpp { namespace java { namespace util { class Collection; } } }
#include <java/io/Serializable.hpp>
#include <java/lang/Object.hpp>
#include <java/util/AbstractQueue.hpp>
#include <java/util/Collection.hpp>
#include <java/util/Iterator.hpp>
#include <java/util/concurrent/BlockingQueue.hpp>
#include <java/util/concurrent/TimeUnit.hpp>
namespace j2cpp {
namespace java { namespace util { namespace concurrent {
class SynchronousQueue;
class SynchronousQueue
: public object<SynchronousQueue>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
J2CPP_DECLARE_METHOD(12)
J2CPP_DECLARE_METHOD(13)
J2CPP_DECLARE_METHOD(14)
J2CPP_DECLARE_METHOD(15)
J2CPP_DECLARE_METHOD(16)
J2CPP_DECLARE_METHOD(17)
J2CPP_DECLARE_METHOD(18)
J2CPP_DECLARE_METHOD(19)
J2CPP_DECLARE_METHOD(20)
J2CPP_DECLARE_METHOD(21)
J2CPP_DECLARE_METHOD(22)
explicit SynchronousQueue(jobject jobj)
: object<SynchronousQueue>(jobj)
{
}
operator local_ref<java::util::AbstractQueue>() const;
operator local_ref<java::util::concurrent::BlockingQueue>() const;
operator local_ref<java::io::Serializable>() const;
SynchronousQueue();
SynchronousQueue(jboolean);
void put(local_ref< java::lang::Object > const&);
jboolean offer(local_ref< java::lang::Object > const&, jlong, local_ref< java::util::concurrent::TimeUnit > const&);
jboolean offer(local_ref< java::lang::Object > const&);
local_ref< java::lang::Object > take();
local_ref< java::lang::Object > poll(jlong, local_ref< java::util::concurrent::TimeUnit > const&);
local_ref< java::lang::Object > poll();
jboolean isEmpty();
jint size();
jint remainingCapacity();
void clear();
jboolean contains(local_ref< java::lang::Object > const&);
jboolean remove(local_ref< java::lang::Object > const&);
jboolean containsAll(local_ref< java::util::Collection > const&);
jboolean removeAll(local_ref< java::util::Collection > const&);
jboolean retainAll(local_ref< java::util::Collection > const&);
local_ref< java::lang::Object > peek();
local_ref< java::util::Iterator > iterator();
local_ref< array< local_ref< java::lang::Object >, 1> > toArray();
local_ref< array< local_ref< java::lang::Object >, 1> > toArray(local_ref< array< local_ref< java::lang::Object >, 1> > const&);
jint drainTo(local_ref< java::util::Collection > const&);
jint drainTo(local_ref< java::util::Collection > const&, jint);
}; //class SynchronousQueue
} //namespace concurrent
} //namespace util
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_IMPL
#define J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_IMPL
namespace j2cpp {
java::util::concurrent::SynchronousQueue::operator local_ref<java::util::AbstractQueue>() const
{
return local_ref<java::util::AbstractQueue>(get_jobject());
}
java::util::concurrent::SynchronousQueue::operator local_ref<java::util::concurrent::BlockingQueue>() const
{
return local_ref<java::util::concurrent::BlockingQueue>(get_jobject());
}
java::util::concurrent::SynchronousQueue::operator local_ref<java::io::Serializable>() const
{
return local_ref<java::io::Serializable>(get_jobject());
}
java::util::concurrent::SynchronousQueue::SynchronousQueue()
: object<java::util::concurrent::SynchronousQueue>(
call_new_object<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(0),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
java::util::concurrent::SynchronousQueue::SynchronousQueue(jboolean a0)
: object<java::util::concurrent::SynchronousQueue>(
call_new_object<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(1),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
{
}
void java::util::concurrent::SynchronousQueue::put(local_ref< java::lang::Object > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(2),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(2),
void
>(get_jobject(), a0);
}
jboolean java::util::concurrent::SynchronousQueue::offer(local_ref< java::lang::Object > const &a0, jlong a1, local_ref< java::util::concurrent::TimeUnit > const &a2)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(3),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(3),
jboolean
>(get_jobject(), a0, a1, a2);
}
jboolean java::util::concurrent::SynchronousQueue::offer(local_ref< java::lang::Object > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(4),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(4),
jboolean
>(get_jobject(), a0);
}
local_ref< java::lang::Object > java::util::concurrent::SynchronousQueue::take()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(5),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(5),
local_ref< java::lang::Object >
>(get_jobject());
}
local_ref< java::lang::Object > java::util::concurrent::SynchronousQueue::poll(jlong a0, local_ref< java::util::concurrent::TimeUnit > const &a1)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(6),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(6),
local_ref< java::lang::Object >
>(get_jobject(), a0, a1);
}
local_ref< java::lang::Object > java::util::concurrent::SynchronousQueue::poll()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(7),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(7),
local_ref< java::lang::Object >
>(get_jobject());
}
jboolean java::util::concurrent::SynchronousQueue::isEmpty()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(8),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(8),
jboolean
>(get_jobject());
}
jint java::util::concurrent::SynchronousQueue::size()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(9),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(9),
jint
>(get_jobject());
}
jint java::util::concurrent::SynchronousQueue::remainingCapacity()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(10),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(10),
jint
>(get_jobject());
}
void java::util::concurrent::SynchronousQueue::clear()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(11),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(11),
void
>(get_jobject());
}
jboolean java::util::concurrent::SynchronousQueue::contains(local_ref< java::lang::Object > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(12),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(12),
jboolean
>(get_jobject(), a0);
}
jboolean java::util::concurrent::SynchronousQueue::remove(local_ref< java::lang::Object > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(13),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(13),
jboolean
>(get_jobject(), a0);
}
jboolean java::util::concurrent::SynchronousQueue::containsAll(local_ref< java::util::Collection > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(14),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(14),
jboolean
>(get_jobject(), a0);
}
jboolean java::util::concurrent::SynchronousQueue::removeAll(local_ref< java::util::Collection > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(15),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(15),
jboolean
>(get_jobject(), a0);
}
jboolean java::util::concurrent::SynchronousQueue::retainAll(local_ref< java::util::Collection > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(16),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(16),
jboolean
>(get_jobject(), a0);
}
local_ref< java::lang::Object > java::util::concurrent::SynchronousQueue::peek()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(17),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(17),
local_ref< java::lang::Object >
>(get_jobject());
}
local_ref< java::util::Iterator > java::util::concurrent::SynchronousQueue::iterator()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(18),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(18),
local_ref< java::util::Iterator >
>(get_jobject());
}
local_ref< array< local_ref< java::lang::Object >, 1> > java::util::concurrent::SynchronousQueue::toArray()
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(19),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(19),
local_ref< array< local_ref< java::lang::Object >, 1> >
>(get_jobject());
}
local_ref< array< local_ref< java::lang::Object >, 1> > java::util::concurrent::SynchronousQueue::toArray(local_ref< array< local_ref< java::lang::Object >, 1> > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(20),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(20),
local_ref< array< local_ref< java::lang::Object >, 1> >
>(get_jobject(), a0);
}
jint java::util::concurrent::SynchronousQueue::drainTo(local_ref< java::util::Collection > const &a0)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(21),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(21),
jint
>(get_jobject(), a0);
}
jint java::util::concurrent::SynchronousQueue::drainTo(local_ref< java::util::Collection > const &a0, jint a1)
{
return call_method<
java::util::concurrent::SynchronousQueue::J2CPP_CLASS_NAME,
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_NAME(22),
java::util::concurrent::SynchronousQueue::J2CPP_METHOD_SIGNATURE(22),
jint
>(get_jobject(), a0, a1);
}
J2CPP_DEFINE_CLASS(java::util::concurrent::SynchronousQueue,"java/util/concurrent/SynchronousQueue")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,1,"<init>","(Z)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,2,"put","(Ljava/lang/Object;)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,3,"offer","(Ljava/lang/Object;JLjava/util/concurrent/TimeUnit;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,4,"offer","(Ljava/lang/Object;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,5,"take","()Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,6,"poll","(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,7,"poll","()Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,8,"isEmpty","()Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,9,"size","()I")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,10,"remainingCapacity","()I")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,11,"clear","()V")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,12,"contains","(Ljava/lang/Object;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,13,"remove","(Ljava/lang/Object;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,14,"containsAll","(Ljava/util/Collection;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,15,"removeAll","(Ljava/util/Collection;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,16,"retainAll","(Ljava/util/Collection;)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,17,"peek","()Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,18,"iterator","()Ljava/util/Iterator;")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,19,"toArray","()[java.lang.Object")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,20,"toArray","([java.lang.Object)[java.lang.Object")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,21,"drainTo","(Ljava/util/Collection;)I")
J2CPP_DEFINE_METHOD(java::util::concurrent::SynchronousQueue,22,"drainTo","(Ljava/util/Collection;I)I")
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_CONCURRENT_SYNCHRONOUSQUEUE_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 39.492537
| 173
| 0.736017
|
kakashidinho
|
94bd48507b8a1b6eaef772d2ef1544ff3a92f888
| 7,841
|
cpp
|
C++
|
RobWork/src/sandbox/optimization/example_optimization.cpp
|
ZLW07/RobWork
|
e713881f809d866b9a0749eeb15f6763e64044b3
|
[
"Apache-2.0"
] | 1
|
2021-12-29T14:16:27.000Z
|
2021-12-29T14:16:27.000Z
|
RobWork/src/sandbox/optimization/example_optimization.cpp
|
ZLW07/RobWork
|
e713881f809d866b9a0749eeb15f6763e64044b3
|
[
"Apache-2.0"
] | null | null | null |
RobWork/src/sandbox/optimization/example_optimization.cpp
|
ZLW07/RobWork
|
e713881f809d866b9a0749eeb15f6763e64044b3
|
[
"Apache-2.0"
] | null | null | null |
/*
* example_gradientdescent.cpp
*
* Created on: Feb 7, 2015
* Author: dagothar
*
* This example shows how to use optimizers.
*/
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <rw/math/Math.hpp>
#include <rw/math/Q.hpp>
#include <rw/math/FunctionFactory.hpp>
#include <rw/rw.hpp>
#include <rw/math/FunctionWithNumericalDerivative.hpp>
#include <rw/math/FirstDifferences.hpp>
#include <rwlibs/optimization/GoldenSectionLineSearch.hpp>
#include <rwlibs/optimization/GradientDescentOptimizer.hpp>
#include <rwlibs/optimization/TaxiCabOptimizer.hpp>
#include <rwlibs/optimization/PowellOptimizer.hpp>
#include <rwlibs/optimization/DownhillOptimizer.hpp>
#include <rwlibs/optimization/SimulatedAnnealingOptimizer.hpp>
#include <rwlibs/optimization/BFGSOptimizer.hpp>
using namespace std;
USE_ROBWORK_NAMESPACE
using namespace robwork;
using namespace rwlibs::optimization;
// NASTY global function call count
unsigned gCallCount = 0;
/*
* Simple function:
* f(x, y) = x^2 + y^2
*/
class Simple: public FunctionType {
public:
// this is our evaluation method
double f(Q q) {
RW_ASSERT(q.size() == 2);
++gCallCount;
double x = q(0);
double y = q(1);
return x * x + y * y;
}
};
/*
* Simple function in 3D:
* f(x, y) = x^2 + y^2
*/
class Simple3D: public FunctionType {
public:
// this is our evaluation method
double f(Q q) {
RW_ASSERT(q.size() == 3);
++gCallCount;
double x = q(0);
double y = q(1);
double z = q(2);
return x * x + y * y + fabs(z);
}
};
/*
* Simple function in 10D:
*/
class Simple10D: public FunctionType {
public:
// this is our evaluation method
double f(Q q) {
RW_ASSERT(q.size() == 10);
++gCallCount;
double s = 0.0;
for (unsigned i = 0; i < 10; ++i) {
s += q[i] * q[i];
}
return s;
}
};
/*
* Rosenbrock function:
*/
class Rosenbrock: public FunctionType {
public:
// this is our evaluation method
double f(Q q) {
RW_ASSERT(q.size() == 2);
++gCallCount;
double x = q(0);
double y = q(1);
return (1.0 - x) * (1.0 - x) + 100.0 * (y - x * x) * (y - x * x);
}
};
// a function that prints optimizer's log
void printLog(Optimizer::Ptr optimizer) {
for (unsigned i = 0; i < optimizer->getLog().size(); ++i) {
Optimizer::State state = optimizer->getLog()[i];
cout << "#" << state.step << " MIN= " << state.guess << " VAL= "
<< state.value << " ERR= " << state.error << endl;
}
}
// saves optimizer log to a csv file
void saveLogCSV(const string& filename, Optimizer::Ptr optimizer) {
ofstream file(filename);
for (unsigned i = 0; i < optimizer->getLog().size(); ++i) {
Optimizer::State state = optimizer->getLog()[i];
RW_ASSERT(state.guess.size() >= 2);
file << state.guess(0) << ", " << state.guess(1) << endl;
}
file.close();
}
/*
* MAIN
*/
int main(int argc, char* argv[]) {
Math::seed();
/*
* Read the starting point from the command line.
*/
typename FunctionType::Ptr tfunction;
Q initialGuess(2, 0.0);
/*if (argc >= 2) {
if (string(argv[1]) == "rosenbrock") {
tfunction = new Rosenbrock();
} else if (string(argv[1]) == "simple") {
tfunction = new Simple();
}
} else {
tfunction = new Rosenbrock();
}
if (argc == 4) {
initialGuess(0) = boost::lexical_cast<double>(argv[2]);
initialGuess(1) = boost::lexical_cast<double>(argv[3]);
}*/
tfunction = new Simple10D();
initialGuess = Q(10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
cout << "Using initial guess= " << initialGuess << endl;
//initialGuess = Q(3, 1, 1, 1);
/*
* First step: wrap function in numerical derivative
*/
FunctionType::Ptr function = new FunctionWithNumericalDerivative<double, Q,
Q>(tfunction, new FirstDifferences<double, Q, Q>(0.01));
/*
* Define stop condition
*/
StopCondition stopCondition(1000, 0.01);
/*
* Test line search
*/
cout << "LINE SEARCH OPTIMIZER (ALONG X)" << endl;
Optimizer::Ptr optimizer = new GoldenSectionLineSearch(function, Q(2, 1, 0),
-1.0, 1.0);
optimizer->setLogging(true);
Q minimum = optimizer->optimize(initialGuess, stopCondition);
double value = optimizer->getCurrentValue();
double error = optimizer->getCurrentError();
saveLogCSV("linesearch.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* Test TaxiCab optimizer
*/
cout << "TAXI CAB OPTIMIZER" << endl;
optimizer = new TaxiCabOptimizer(function, 1.0,
new StopCondition(1000, 0.01));
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
saveLogCSV("taxicab.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* Powell optimizer
*/
cout << "POWELL OPTIMIZER" << endl;
optimizer = new PowellOptimizer(function, 1.0,
new StopCondition(1000, 0.01));
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
saveLogCSV("powell.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* Downhill optimizer
*/
cout << "DOWNHILL OPTIMIZER" << endl;
optimizer = new DownhillOptimizer(function, 0.01);
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
//printLog(downhillOptimizer);
saveLogCSV("downhill.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* Gradient descent optimizer
*/
cout << "GRADIENT DESCENT OPTIMIZER" << endl;
optimizer = new GradientDescentOptimizer(function, 0.001, 0.1);
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
saveLogCSV("descent.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* Simulated annealing optimizer
*/
cout << "SIMULATED ANNEALING OPTIMIZER" << endl;
optimizer = new SimulatedAnnealingOptimizer(function, 1.0, 1.0, 0.001);
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
//printLog(descentOptimizer);
saveLogCSV("annealing.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
/*
* BFGS optimizer
*/
cout << "BFGS OPTIMIZER" << endl;
optimizer = new BFGSOptimizer(function, 1.0);
optimizer->setLogging(true);
minimum = optimizer->optimize(initialGuess, stopCondition);
value = optimizer->getCurrentValue();
error = optimizer->getCurrentError();
saveLogCSV("bfgs.csv", optimizer);
cout << "#" << optimizer->getStepCount() << " MIN= " << minimum << " VAL= "
<< value << " ERR= " << error << endl;
cout << "Function evaluations: " << gCallCount << endl;
gCallCount = 0;
cout << endl;
return 0;
}
| 25.792763
| 77
| 0.647877
|
ZLW07
|
94bebc0bc1fa72ff75ac4ce8285ea09d86c34f6d
| 1,245
|
hpp
|
C++
|
src/adapt/sierra_element/MeshObjTopology.hpp
|
jrood-nrel/percept
|
363cdd0050443760d54162f140b2fb54ed9decf0
|
[
"BSD-2-Clause"
] | 3
|
2017-08-08T21:06:02.000Z
|
2020-01-08T13:23:36.000Z
|
src/adapt/sierra_element/MeshObjTopology.hpp
|
jrood-nrel/percept
|
363cdd0050443760d54162f140b2fb54ed9decf0
|
[
"BSD-2-Clause"
] | 2
|
2016-12-17T00:18:56.000Z
|
2019-08-09T15:29:25.000Z
|
src/adapt/sierra_element/MeshObjTopology.hpp
|
jrood-nrel/percept
|
363cdd0050443760d54162f140b2fb54ed9decf0
|
[
"BSD-2-Clause"
] | 2
|
2017-11-30T07:02:41.000Z
|
2019-08-05T17:07:04.000Z
|
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef adapt_sierra_element_MeshObjTopology_hpp
#define adapt_sierra_element_MeshObjTopology_hpp
#include <adapt/sierra_element/CellTopology.hpp>
namespace percept {
namespace Elem {
class MeshObjTopology
{
public:
MeshObjTopology(
const CellTopologyData * cell_topology_data)
: m_cellTopology(cell_topology_data)
{}
public:
~MeshObjTopology()
{}
Elem::CellTopology getCellTopology() const {
return m_cellTopology;
}
protected:
Elem::CellTopology m_cellTopology;
private:
MeshObjTopology();
MeshObjTopology(const MeshObjTopology &);
MeshObjTopology & operator = (const MeshObjTopology &);
};
} // namespace Elem
} // namespace percept
#endif // adapt_sierra_element_MeshObjTopology_hpp
| 26.489362
| 73
| 0.652209
|
jrood-nrel
|
94bf0b992b8a6ac778e64cd8ecba77d2f76f9d48
| 2,781
|
cpp
|
C++
|
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/config/model/AggregateConformancePackCompliance.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ConfigService
{
namespace Model
{
AggregateConformancePackCompliance::AggregateConformancePackCompliance() :
m_complianceType(ConformancePackComplianceType::NOT_SET),
m_complianceTypeHasBeenSet(false),
m_compliantRuleCount(0),
m_compliantRuleCountHasBeenSet(false),
m_nonCompliantRuleCount(0),
m_nonCompliantRuleCountHasBeenSet(false),
m_totalRuleCount(0),
m_totalRuleCountHasBeenSet(false)
{
}
AggregateConformancePackCompliance::AggregateConformancePackCompliance(JsonView jsonValue) :
m_complianceType(ConformancePackComplianceType::NOT_SET),
m_complianceTypeHasBeenSet(false),
m_compliantRuleCount(0),
m_compliantRuleCountHasBeenSet(false),
m_nonCompliantRuleCount(0),
m_nonCompliantRuleCountHasBeenSet(false),
m_totalRuleCount(0),
m_totalRuleCountHasBeenSet(false)
{
*this = jsonValue;
}
AggregateConformancePackCompliance& AggregateConformancePackCompliance::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ComplianceType"))
{
m_complianceType = ConformancePackComplianceTypeMapper::GetConformancePackComplianceTypeForName(jsonValue.GetString("ComplianceType"));
m_complianceTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("CompliantRuleCount"))
{
m_compliantRuleCount = jsonValue.GetInteger("CompliantRuleCount");
m_compliantRuleCountHasBeenSet = true;
}
if(jsonValue.ValueExists("NonCompliantRuleCount"))
{
m_nonCompliantRuleCount = jsonValue.GetInteger("NonCompliantRuleCount");
m_nonCompliantRuleCountHasBeenSet = true;
}
if(jsonValue.ValueExists("TotalRuleCount"))
{
m_totalRuleCount = jsonValue.GetInteger("TotalRuleCount");
m_totalRuleCountHasBeenSet = true;
}
return *this;
}
JsonValue AggregateConformancePackCompliance::Jsonize() const
{
JsonValue payload;
if(m_complianceTypeHasBeenSet)
{
payload.WithString("ComplianceType", ConformancePackComplianceTypeMapper::GetNameForConformancePackComplianceType(m_complianceType));
}
if(m_compliantRuleCountHasBeenSet)
{
payload.WithInteger("CompliantRuleCount", m_compliantRuleCount);
}
if(m_nonCompliantRuleCountHasBeenSet)
{
payload.WithInteger("NonCompliantRuleCount", m_nonCompliantRuleCount);
}
if(m_totalRuleCountHasBeenSet)
{
payload.WithInteger("TotalRuleCount", m_totalRuleCount);
}
return payload;
}
} // namespace Model
} // namespace ConfigService
} // namespace Aws
| 24.830357
| 139
| 0.781014
|
perfectrecall
|
94bfdbab5f07f61ff7b9b16d9a59b462641acf97
| 20,188
|
cpp
|
C++
|
source/magma/vulkan/render-engine-impl.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 15
|
2018-02-26T08:20:03.000Z
|
2022-03-06T03:25:46.000Z
|
source/magma/vulkan/render-engine-impl.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 32
|
2018-02-26T08:26:38.000Z
|
2020-09-12T17:09:38.000Z
|
source/magma/vulkan/render-engine-impl.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | null | null | null |
#include "./render-engine-impl.hpp"
#include "../aft-vulkan/scene-aft.hpp"
#include "../shmag-reader.hpp"
#include "./helpers/queue.hpp"
#include "./holders/swapchain-holder.hpp"
#include "./render-image-impl.hpp"
#include "./render-targets/i-render-target-impl.hpp"
#include "./stages/present.hpp"
using namespace lava::magma;
using namespace lava::chamber;
RenderEngine::Impl::Impl(RenderEngine& engine)
: m_engine(engine)
, m_dummyImageHolder{*this, "magma.vulkan.render-engine.dummy-image"}
, m_dummyNormalImageHolder{*this, "magma.vulkan.render-engine.dummy-normal-image"}
, m_dummyInvisibleImageHolder{*this, "magma.vulkan.render-engine.dummy-invisible-image"}
, m_dummyCubeImageHolder{*this, "magma.vulkan.render-engine.dummy-cube-image"}
{
// @note This VR initialisation has to be done before initVulkan, because we need
// to get the extensions list to be enable.
initVr();
initVulkan();
}
RenderEngine::Impl::~Impl()
{
vr::VR_Shutdown();
device().waitIdle();
for (auto scene : m_scenes) {
m_engine.sceneAllocator().deallocate(scene);
}
}
void RenderEngine::Impl::update()
{
PROFILE_FUNCTION(PROFILER_COLOR_UPDATE);
updateVr();
updateShaders();
for (auto scene : m_scenes) {
scene->aft().update();
}
// @note The difference between RenderTarget::Impl::update and RenderTarget::Impl::prepare
// is that the latter should not update any UBOs.
// For instance, VrRenderTarget update is updating the VrCameraController for the eyes,
// and that should not be in prepare otherwise there might be concurrency issues with scene recording.
for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) {
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl();
renderTargetImpl.update();
}
}
void RenderEngine::Impl::draw()
{
// @note This function does both render and draw, so no color.
PROFILE_FUNCTION();
// We record all render scenes cameras once
for (auto scene : m_scenes) {
scene->aft().record();
}
// Prepare all render targets
for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) {
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl();
renderTargetBundle.prepareOk = renderTargetImpl.prepare();
}
// Wait for all scenes to be done with recording
for (auto sceneId = 0u; sceneId < m_scenes.size(); ++sceneId) {
auto scene = m_scenes[sceneId];
scene->aft().waitRecord();
// Tracking
if (m_logTracking) {
logger.info("magma.render-engine") << "Render scene " << sceneId << "." << std::endl;
logger.log().tab(1);
logger.log() << "draw-calls.flat-renderer: " << tracker.counter("draw-calls.flat-renderer") << std::endl;
logger.log() << "draw-calls.renderer: " << tracker.counter("draw-calls.renderer") << std::endl;
logger.log() << "draw-calls.shadows: " << tracker.counter("draw-calls.shadows") << std::endl;
logger.log().tab(-1);
m_logTracking = false;
}
}
// Submit all the command buffers and present to the render targets
for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) {
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
if (!renderTargetBundle.prepareOk) continue;
// Record command buffer each frame
auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl();
auto currentIndex = renderTargetImpl.currentBufferIndex();
const auto& commandBuffers = recordCommandBuffer(renderTargetId, currentIndex);
renderTargetImpl.draw(commandBuffers);
}
}
uint32_t RenderEngine::Impl::registerMaterialFromFile(const std::string& hrid, const fs::Path& shaderPath)
{
PROFILE_FUNCTION(PROFILER_COLOR_REGISTER);
if (m_materialInfos.find(hrid) != m_materialInfos.end()) {
logger.warning("magma.vulkan.render-engine").tab(1) << "Material " << hrid << " has already been registered." << std::endl;
return m_materialInfos[hrid].id;
}
auto materialId = m_materialInfos.size();
logger.info("magma.vulkan.render-engine").tab(1) << "Registering material " << hrid << " as " << materialId << "." << std::endl;
logger.log().tab(-1);
// @note ShaderManager cannot handle shmag directly, it uses @magma:impl thingy
// to be able to switch-case them or so in other renderer shaders.
ShmagReader shmagReader(shaderPath);
auto globalUniformDefinitions = shmagReader.globalUniformDefinitions();
auto uniformDefinitions = shmagReader.uniformDefinitions();
auto shaderImplementation = shmagReader.processedString();
if (shmagReader.errored()) {
logger.warning("magma.vulkan.render-engine")
<< "Cannot register material " << hrid << ", shmag reading failed." << std::endl;
return -1u;
}
// Start watching the file
const auto watchId = m_shadersWatcher.watch(shaderPath);
auto& materialInfo = m_materialInfos[hrid];
materialInfo.id = materialId;
materialInfo.globalUniformDefinitions = globalUniformDefinitions;
materialInfo.uniformDefinitions = uniformDefinitions;
materialInfo.sourcePath = shaderPath;
materialInfo.watchId = watchId;
m_shadersManager.registerImplGroup(hrid, shaderImplementation, materialId);
return materialId;
}
uint32_t RenderEngine::Impl::addView(RenderImage renderImage, IRenderTarget& renderTarget, const Viewport& viewport)
{
const auto& renderImageImpl = renderImage.impl();
if (renderImageImpl.uuid() == 0u) {
logger.warning("magma.vulkan.render-engine") << "Trying to add a RenderImage with no uuid." << std::endl;
return -1u;
}
if (!renderImageImpl.view()) {
logger.warning("magma.vulkan.render-engine") << "Trying to add an empty RenderImage as a view." << std::endl;
return -1u;
}
PROFILE_FUNCTION(PROFILER_COLOR_REGISTER);
// Find the render target bundle
uint32_t renderTargetId = renderTarget.interfaceImpl().id();
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
// Create the new render view
m_renderViews.emplace_back();
auto& renderView = m_renderViews.back();
renderView.renderImage = renderImage;
renderView.renderTargetId = renderTargetId;
// Add a new image to the present stage
// @fixme We should be able to forward the RenderImage directly
auto imageView = renderImageImpl.view();
auto imageLayout = renderImageImpl.layout();
auto channelCount = renderImageImpl.channelCount();
// @fixme Should be "compositorViewId"...
renderView.presentViewId =
renderTargetBundle.renderTarget->interfaceImpl().addView(imageView, imageLayout, m_dummySampler.get(), viewport, channelCount);
return m_renderViews.size() - 1u;
}
void RenderEngine::Impl::removeView(uint32_t viewId)
{
// @todo Handle views individually, generating a really unique id
// that has nothing to do with internal storage.
if (viewId != m_renderViews.size() - 1u) {
logger.warning("magma.vulkan.render-engine")
<< "Currently unable to remove a view that is not the last one added." << std::endl;
return;
}
PROFILE_FUNCTION(PROFILER_COLOR_REGISTER);
auto& renderView = m_renderViews[viewId];
auto& renderTargetBundle = m_renderTargetBundles[renderView.renderTargetId];
renderTargetBundle.renderTarget->interfaceImpl().removeView(renderView.presentViewId);
m_renderViews.erase(std::begin(m_renderViews) + viewId);
}
//----- Adders
void RenderEngine::Impl::add(Scene& scene)
{
const uint32_t sceneId = m_scenes.size();
logger.info("magma.vulkan.render-engine") << "Adding render scene " << sceneId << "." << std::endl;
logger.log().tab(1);
// If no device yet, the scene initialization will be postponed
// until it is created.
if (m_deviceHolder.device()) {
scene.aft().init();
}
m_scenes.emplace_back(&scene);
logger.log().tab(-1);
}
void RenderEngine::Impl::add(std::unique_ptr<IRenderTarget>&& renderTarget)
{
logger.info("magma.vulkan.render-engine") << "Adding render target " << m_renderTargetBundles.size() << "." << std::endl;
logger.log().tab(1);
auto& renderTargetImpl = renderTarget->interfaceImpl();
// @todo This is probably not the right thing to do.
// However - what can be the solution?
// Device creation requires a surface, which requires a handle.
// Thus, no window => unable to init the device.
// So we init what's left of the engine right here, when adding a renderTarget.
if (!m_deviceHolder.device()) {
// @fixme We never call it with a surface, so all that thingy thing might not be useful...
// But we *should* use it... Otherwise the selected queueFamily might not be adapted.
// To do so, we need a flag on RenderEngine creation (usage: Vr, Window, Offscreen).
// We would then init with surface only when a WindowRenderTarget is created,
// if the Window flag is on.
initVulkanDevice(nullptr);
// initVulkanDevice(&renderTargetImpl.surface());
}
uint32_t renderTargetId = m_renderTargetBundles.size();
renderTargetImpl.init(renderTargetId);
m_renderTargetBundles.emplace_back();
auto& renderTargetBundle = m_renderTargetBundles.back();
renderTargetBundle.renderTarget = std::move(renderTarget);
createCommandBuffers(renderTargetId);
logger.log().tab(-1);
}
void RenderEngine::Impl::updateRenderViews(RenderImage renderImage)
{
auto& renderImageImpl = renderImage.impl();
if (!renderImageImpl.image()) return;
if (renderImageImpl.uuid() == 0u) {
logger.warning("magma.vulkan.render-engine") << "Updating render views for an unset RenderImage uuid." << std::endl;
return;
}
// The renderImage has changed, we update all image views we were using from it
for (auto& renderView : m_renderViews) {
if (renderView.renderImage.impl().uuid() != renderImageImpl.uuid()) continue;
auto& renderTargetBundle = m_renderTargetBundles[renderView.renderTargetId];
auto imageView = renderImageImpl.view();
auto imageLayout = renderImageImpl.layout();
renderTargetBundle.renderTarget->interfaceImpl().updateView(renderView.presentViewId, imageView, imageLayout,
m_dummySampler.get());
}
}
const MaterialInfo& RenderEngine::Impl::materialInfo(const std::string& hrid) const
{
const auto iMaterialInfo = m_materialInfos.find(hrid);
if (iMaterialInfo == m_materialInfos.end()) {
logger.error("magma.vulkan.render-engine") << "Material '" << hrid << "' has not been registered." << std::endl;
}
return iMaterialInfo->second;
}
const MaterialInfo* RenderEngine::Impl::materialInfoIfExists(const std::string& hrid) const
{
const auto iMaterialInfo = m_materialInfos.find(hrid);
if (iMaterialInfo == m_materialInfos.end()) {
return nullptr;
}
return &iMaterialInfo->second;
}
void RenderEngine::Impl::createCommandPools(vk::SurfaceKHR* pSurface)
{
PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION);
logger.info("magma.vulkan.render-engine") << "Creating command pool." << std::endl;
auto queueFamilyIndices = vulkan::findQueueFamilies(physicalDevice(), pSurface);
vk::CommandPoolCreateInfo createInfo;
createInfo.queueFamilyIndex = queueFamilyIndices.graphics;
createInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
auto result = device().createCommandPoolUnique(createInfo);
m_commandPool = vulkan::checkMove(result, "render-engine", "Unable to create command pool.");
createInfo.queueFamilyIndex = queueFamilyIndices.transfer;
createInfo.flags = vk::CommandPoolCreateFlagBits(0x0);
result = device().createCommandPoolUnique(createInfo);
m_transferCommandPool = vulkan::checkMove(result, "render-engine", "Unable to create transfer command pool.");
}
void RenderEngine::Impl::createDummyTextures()
{
PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION);
logger.info("magma.vulkan.render-engine") << "Creating dummy textures." << std::endl;
// Plain white
std::vector<uint8_t> dummyData = {0xFF, 0xFF, 0xFF, 0xFF};
m_dummyImageHolder.setup(dummyData, 1, 1, 4);
// Flat blue
dummyData = {0x80, 0x80, 0xFF, 0xFF}; // 0.5, 0.5, 1.0
m_dummyNormalImageHolder.setup(dummyData, 1, 1, 4);
// Full zeros
dummyData = {0x00, 0x00, 0x00, 0x00};
m_dummyInvisibleImageHolder.setup(dummyData, 1, 1, 4);
// Plain transparent for cube maps
std::vector<uint8_t> dummyCubeData = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
m_dummyCubeImageHolder.setup(dummyCubeData, 1, 1, 4, 6);
// Sampler
vk::SamplerCreateInfo createInfo;
createInfo.magFilter = vk::Filter::eLinear;
createInfo.minFilter = vk::Filter::eLinear;
createInfo.addressModeU = vk::SamplerAddressMode::eRepeat;
createInfo.addressModeV = vk::SamplerAddressMode::eRepeat;
createInfo.addressModeW = vk::SamplerAddressMode::eRepeat;
createInfo.anisotropyEnable = true;
createInfo.maxAnisotropy = 16; // Over 16 is useless, but lower that for better performances
createInfo.unnormalizedCoordinates = false;
createInfo.compareEnable = false;
createInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
createInfo.maxLod = 10;
auto result = device().createSamplerUnique(createInfo);
m_dummySampler = vulkan::checkMove(result, "render-engine", "Unable to create dummy sampler.");
// Shadows sampler
createInfo.magFilter = vk::Filter::eLinear;
createInfo.minFilter = vk::Filter::eLinear;
createInfo.addressModeU = vk::SamplerAddressMode::eClampToBorder;
createInfo.addressModeV = vk::SamplerAddressMode::eClampToBorder;
createInfo.addressModeW = vk::SamplerAddressMode::eClampToBorder;
createInfo.anisotropyEnable = false;
createInfo.unnormalizedCoordinates = false;
createInfo.compareEnable = false;
createInfo.mipmapMode = vk::SamplerMipmapMode::eNearest;
result = device().createSamplerUnique(createInfo);
m_shadowsSampler = vulkan::checkMove(result, "render-engine", "Unable to create shadows sampler.");
}
std::vector<vk::CommandBuffer> RenderEngine::Impl::recordCommandBuffer(uint32_t renderTargetId, uint32_t bufferIndex)
{
PROFILE_FUNCTION(PROFILER_COLOR_RENDER);
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
if (bufferIndex >= renderTargetBundle.commandBuffers.size()) {
logger.error("magma.vulkan.render-engine")
<< "Invalid bufferIndex during command buffers recording (" << bufferIndex << ") that should have been between 0 and "
<< renderTargetBundle.commandBuffers.size() - 1u << "." << std::endl;
}
//----- Render all scenes
// @fixme Feels like we should be able to generate all render scenes images,
// and use these directly without having to re-render everything.
std::vector<vk::CommandBuffer> commandBuffers;
for (auto scene : m_scenes) {
const auto& sceneCommandBuffers = scene->aft().commandBuffers();
commandBuffers.insert(commandBuffers.end(), sceneCommandBuffers.begin(), sceneCommandBuffers.end());
}
//----- Render targets' specific rendering
auto commandBuffer = renderTargetBundle.commandBuffers[bufferIndex].get();
vk::CommandBufferBeginInfo beginInfo{vk::CommandBufferUsageFlagBits::eSimultaneousUse};
commandBuffer.begin(&beginInfo);
// @todo The names are unclear, what's the difference between render and draw?
// @fixme We probably don't need handle a render target command buffer by ourself
// because this line is the only thing we do with it.
renderTargetBundle.renderTarget->interfaceImpl().render(commandBuffer);
commandBuffer.end();
commandBuffers.emplace_back(commandBuffer);
return commandBuffers;
}
void RenderEngine::Impl::createCommandBuffers(uint32_t renderTargetId)
{
PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION);
logger.log() << "Creating command buffers for render target " << renderTargetId << "." << std::endl;
auto& renderTargetBundle = m_renderTargetBundles[renderTargetId];
auto& commandBuffers = renderTargetBundle.commandBuffers;
// (Re-)allocate them all
commandBuffers.resize(renderTargetBundle.renderTarget->interfaceImpl().buffersCount());
vk::CommandBufferAllocateInfo allocInfo;
allocInfo.commandPool = m_commandPool.get();
allocInfo.level = vk::CommandBufferLevel::ePrimary;
allocInfo.commandBufferCount = commandBuffers.size();
auto result = device().allocateCommandBuffersUnique(allocInfo);
commandBuffers = vulkan::checkMove(result, "render-engine", "Unable to create command buffers.");
}
void RenderEngine::Impl::initScenes()
{
if (m_scenes.size() == 0u) return;
PROFILE_FUNCTION(PROFILER_COLOR_INIT);
logger.info("magma.vulkan.render-engine") << "Initializing render scenes." << std::endl;
logger.log().tab(1);
for (const auto& scene : m_scenes) {
scene->aft().init();
}
logger.log().tab(-1);
}
void RenderEngine::Impl::initVr()
{
PROFILE_FUNCTION(PROFILER_COLOR_INIT);
logger.info("magma.vulkan.render-engine") << "Initializing VR." << std::endl;
logger.log().tab(1);
// @todo vr().init() / vr().update() should probably be called by RenderEngine itself (not Impl)
// as this is not vulkan dependent
m_engine.vr().init();
logger.log().tab(-1);
}
void RenderEngine::Impl::initVulkan()
{
PROFILE_FUNCTION(PROFILER_COLOR_INIT);
logger.info("magma.vulkan.render-engine") << "Initializing vulkan." << std::endl;
logger.log().tab(1);
m_instanceHolder.init(true, m_engine.vr());
logger.log().tab(-1);
}
void RenderEngine::Impl::initVulkanDevice(vk::SurfaceKHR* pSurface)
{
PROFILE_FUNCTION(PROFILER_COLOR_INIT);
logger.info("magma.vulkan.render-engine") << "Initializing vulkan device." << std::endl;
logger.log().tab(1);
m_deviceHolder.init(instance(), pSurface, m_instanceHolder.debugEnabled(), m_engine.vr());
createCommandPools(pSurface);
createDummyTextures();
initScenes();
logger.log().tab(-1);
}
void RenderEngine::Impl::updateVr()
{
if (m_engine.vr().enabled()) {
m_engine.vr().update();
}
}
void RenderEngine::Impl::updateShaders()
{
PROFILE_FUNCTION(PROFILER_COLOR_UPDATE);
while (auto event = m_shadersWatcher.pollEvent()) {
if (event->type == chamber::FileWatchEvent::Type::Modified) {
auto materialPath = event->path;
auto watchId = event->watchId;
logger.info("magma.vulkan.render-engine") << "Material source file " << event->path << " has changed." << std::endl;
logger.log().tab(1);
auto materialInfo =
std::find_if(m_materialInfos.begin(), m_materialInfos.end(),
[&watchId](const auto& materialInfo) { return materialInfo.second.watchId == watchId; });
ShmagReader shmagReader(materialPath);
auto shaderImplementation = shmagReader.processedString();
if (shmagReader.errored()) {
logger.warning("magma.vulkan.render-engine")
<< "Cannot update watched material " << materialInfo->first << ", shmag reading failed." << std::endl;
return;
}
m_shadersManager.updateImplGroup(materialInfo->first, shaderImplementation);
logger.log().tab(-1);
}
}
m_shadersManager.update();
}
| 37.594041
| 135
| 0.68932
|
Breush
|
94c0c556d4b31c5f87ff85882a08a0bbfa16e2c4
| 7,354
|
cc
|
C++
|
tests/test.cc
|
CS126SP20/final-project-ckesan2
|
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
|
[
"MIT"
] | null | null | null |
tests/test.cc
|
CS126SP20/final-project-ckesan2
|
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
|
[
"MIT"
] | null | null | null |
tests/test.cc
|
CS126SP20/final-project-ckesan2
|
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2020 CS126SP20. All rights reserved.
#define CATCH_CONFIG_MAIN
#include <mylibrary/gameengine.h>
#include <mylibrary/circle.h>
#include <catch2/catch.hpp>
TEST_CASE("Getting the correct score", "[game score]") {
//makes sure the score is 0 at the start of the game
mylibrary::GameEngine engine;
REQUIRE(engine.GetScore() == 0);
//makes sure score updated after increasing it
SECTION("Add to the score") {
engine.IncreaseScore();
REQUIRE(engine.GetScore() == 1);
}
//checks that score goes back to 0 after resetting the game
SECTION("Reset score") {
engine.IncreaseScore();
engine.IncreaseScore();
REQUIRE(engine.GetScore() == 2);
engine.ResetGame();
REQUIRE(engine.GetScore() == 0);
}
}
TEST_CASE("Accuracy of X Coordinates", "[coordinates]") {
//checks that x coordinate changes after every call of getX
mylibrary::Circle circle;
int x = circle.getX();
int x2 = circle.getX();
REQUIRE(x != x2);
}
TEST_CASE("Accuracy of Y Coordinates", "[coordinates]") {
//checks that y coordinate changes after every call of getY
mylibrary::Circle circle;
int y = circle.getY();
int y2 = circle.getY();
REQUIRE(y != y2);
}
TEST_CASE("X of Circle center is on screen", "[coordinates]") {
//checks that the x coordinate is not off screen
mylibrary::Circle circle;
int x = circle.getX();
REQUIRE(!circle.XIsInWindow(1000));
REQUIRE(!circle.XIsInWindow(-1));
REQUIRE(x >= 0);
REQUIRE(x <= 800);
REQUIRE(circle.XIsInWindow(x));
}
TEST_CASE("Y of Circle center is on screen", "[coordinates]") {
//checks that the y coordinate is not off screen
mylibrary::Circle circle;
int y = circle.getY();
REQUIRE(!circle.YIsInWindow(800));
REQUIRE(!circle.YIsInWindow(-1));
REQUIRE(y >= 0);
REQUIRE(y <= 680);
REQUIRE(circle.YIsInWindow(y));
}
TEST_CASE("Circle Not Clicked", "[location]") {
//checks that the circle is not clicked if click is outside the radius
mylibrary::GameEngine engine;
int radius = 20;
REQUIRE(!engine.ClickedCircle(20,20,200,200, radius));
SECTION("Off by 21 in x and y") {
REQUIRE(!engine.ClickedCircle(20,20,41,41, radius));
}
SECTION("Off by 21 in x") {
REQUIRE(!engine.ClickedCircle(20,20,41,40, radius));
}
SECTION("Off by 21 in y") {
REQUIRE(!engine.ClickedCircle(20,20,40,41, radius));
}
}
TEST_CASE("Circle Is Clicked", "[location]") {
//checks that the circle is clicked if click is inside the radius
mylibrary::GameEngine engine;
int radius = 20;
REQUIRE(engine.ClickedCircle(20,20,20,20, radius));
SECTION("Click In range") {
REQUIRE(engine.ClickedCircle(20,20,40,40, radius));
REQUIRE(engine.ClickedCircle(20,20,0,0, radius));
REQUIRE(engine.ClickedCircle(10,20,9,19, radius));
REQUIRE(engine.ClickedCircle(0,0,0,0, radius));
}
SECTION("Circle partially off screen") {
REQUIRE(engine.ClickedCircle(10,10,-1,-1, radius));
}
}
TEST_CASE("Picked Easy Game Mode", "[easy]") {
//checks that inputted coordinates means that user clicked the easy mode
mylibrary::GameEngine engine;
//assigned variables for numbers to just it have be more intuitive with the
//coordinates going into the function
int mouse_x = 400;
int mouse_y = 400;
int center_x = 400;
int center_y = 350;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "easy");
SECTION("Different x coordinates but in range of easy button") {
mouse_x = 360;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "easy");
}
}
TEST_CASE("Picked Medium Game Mode", "[medium]") {
//checks that inputted coordinates means that user clicked the medium mode
mylibrary::GameEngine engine;
int mouse_x = 200;
int mouse_y = 400;
int center_x = 200;
int center_y = 300;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "medium");
SECTION("Different x coordinate but in range of medium button") {
mouse_x = 145;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y,
center_x, center_y) == "medium");
}
}
TEST_CASE("Picked Hard Game Mode", "[hard]") {
//checks that inputted coordinates means that user clicked the hard mode
mylibrary::GameEngine engine;
int mouse_x = 400;
int mouse_y = 400;
int center_x = 400;
int center_y = 250;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "hard");
SECTION("Different x coordinates but in range of hard button") {
mouse_x = 448;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "hard");
}
}
TEST_CASE("No Game Mode Picked", "[no game mode]") {
//checks that these coordinates mean that the user has not clicked on a game
//mode's coordinates
mylibrary::GameEngine engine;
int mouse_x = 0;
int mouse_y = 0;
int center_x = 0;
int center_y = 0;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty());
SECTION("Different x coordinates and no game mode picked") {
mouse_x = 400;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty());
}
SECTION("Different y coordinates and no game mode picked") {
mouse_y = 200;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty());
}
SECTION("All same coordinates other than 0") {
mouse_x = 100;
mouse_y = 100;
center_x = 100;
center_y = 100;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty());
}
SECTION("All different coordinates") {
mouse_x = 100;
mouse_y = 200;
center_x = 300;
center_y = 400;
REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty());
}
}
TEST_CASE("Clicked on Item", "[picked item]") {
//makes sure it returns true when the click is on the center of the image
mylibrary::GameEngine engine;
int mouse_x = 400;
int mouse_y = 360;
int item_centerx = 400;
int item_centery = 360;
int width = 100;
int height = 100;
REQUIRE(engine.ClickedItem(mouse_x, mouse_y, item_centerx, item_centery,
width, height));
//make sure it returns true when the click is on the image but just not its
//center
SECTION("Not same coordinates") {
REQUIRE(engine.ClickedItem(401, 361, 400, 360, 100, 100));
}
//makes sure method returns true when the click is on the edge of the image
SECTION("Edge of the item") {
REQUIRE(engine.ClickedItem(200, 200, 250, 250, 100, 100));
REQUIRE(engine.ClickedItem(200, 200, 250, 200, 100, 100));
REQUIRE(engine.ClickedItem(200, 200, 300, 250, 200, 100));
REQUIRE(engine.ClickedItem(250, 350, 275, 375, 50, 50));
REQUIRE(engine.ClickedItem(0, 0, 0, 0, 0, 0));
}
}
TEST_CASE("Item Is Not Clicked", "[normal click]") {
//checks that the method return false when the mouse does not click in the
//image range
mylibrary::GameEngine engine;
int mouse_x = 400;
int mouse_y = 360;
int item_centerx = 1000;
int item_centery = 1000;
int width = 100;
int height = 100;
REQUIRE(!engine.ClickedItem(mouse_x, mouse_y, item_centerx,
item_centery, width, height));
//checks that the method returns false when the click x and y coordinates
//are both one off the edges of the image
SECTION("Off By One") {
REQUIRE(!engine.ClickedItem(100, 250, 201, 351, 200, 200));
REQUIRE(!engine.ClickedItem(400, 400, 299, 299, 200, 200));
}
}
| 28.393822
| 80
| 0.684389
|
CS126SP20
|
94c556dd34cd648160958e09cea3be093ebe2b20
| 825
|
cpp
|
C++
|
Game/Scene/EnemyGuide/RollBackGround.cpp
|
IndistinQuest/Game
|
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
|
[
"MIT"
] | 2
|
2016-12-09T02:21:23.000Z
|
2017-08-31T13:49:13.000Z
|
Game/Scene/EnemyGuide/RollBackGround.cpp
|
IndistinQuest/Game
|
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
|
[
"MIT"
] | null | null | null |
Game/Scene/EnemyGuide/RollBackGround.cpp
|
IndistinQuest/Game
|
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
|
[
"MIT"
] | null | null | null |
#include "RollBackGround.h"
const double RollBackGround::W = 1280;
const double RollBackGround::H = 720;
const int RollBackGround::ROLL_SPEED = 5;
RollBackGround::RollBackGround(String firstAssetName, String secondAssetName)
{
firstAssetName_m = firstAssetName;
secondAssetName_m = secondAssetName;
fPoint_m = Point(0.5*W, 0.5*H);
sPoint_m = Point(1.5*W, 0.5*H);
}
RollBackGround::~RollBackGround()
{
}
void RollBackGround::update()
{
fPoint_m.x -= ROLL_SPEED;
sPoint_m.x -= ROLL_SPEED;
if (fPoint_m.x <= static_cast<int>(-0.5*W))
{
fPoint_m.x = static_cast<int>(1.5*W);
}
if (sPoint_m.x <= static_cast<int>(-0.5*W))
{
sPoint_m.x = static_cast<int>(1.5*W);
}
}
void RollBackGround::draw() const
{
TextureAsset(firstAssetName_m).drawAt(fPoint_m);
TextureAsset(secondAssetName_m).drawAt(sPoint_m);
}
| 19.642857
| 77
| 0.718788
|
IndistinQuest
|
94cec4bf7f8985766a7a265da5c1f49a179e31f9
| 1,558
|
hxx
|
C++
|
inetsrv/query/filters/html/source/metatag.hxx
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
inetsrv/query/filters/html/source/metatag.hxx
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
inetsrv/query/filters/html/source/metatag.hxx
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//+-------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation, 1992 - 1996
//
// File: metatag.hxx
//
// Contents: Parsing algorithm for image tags
//
//--------------------------------------------------------------------------
#if !defined( __METATAG_HXX__ )
#define __METATAG_HXX__
#include <htmlelem.hxx>
enum MetaTagState
{
FilteringValue,
NoMoreValue,
};
//+-------------------------------------------------------------------------
//
// Class: CMetaTag
//
// Purpose: Parsing algorithm for meta tag in Html
//
//--------------------------------------------------------------------------
class CMetaTag : public CHtmlElement
{
public:
CMetaTag( CHtmlIFilter& htmlIFilter,
CSerialStream& serialStream );
virtual SCODE GetValue( VARIANT ** ppPropValue );
virtual BOOL InitStatChunk( STAT_CHUNK *pStat );
private:
MetaTagState _eState; // Current state of tag
WCHAR * _pwcValueBuf; // Buffer for value field
unsigned _cValueChars; // # chars in value buffer
// buffer scoped for PRSPEC_LPWSTRs to return with chunk FULLPROPSPECs
WCHAR _awszPropSpec[MAX_PROPSPEC_STRING_LENGTH+1];
//
// TRUE if surrounding quotes should be stripped before
// emitting the value.
//
BOOL m_fShouldStripSurroundingSingleQuotes;
};
#endif // __METATAG_HXX__
| 25.540984
| 77
| 0.485879
|
npocmaka
|
94d0714cb70d236d16149f4e358e5497b2949ded
| 2,541
|
hpp
|
C++
|
include/mmf/optimizationSO3_approx.hpp
|
jstraub/dpMM
|
538c432d5f98c040d5c1adb072e545e38f97fc69
|
[
"MIT-feh"
] | 11
|
2015-04-27T15:14:01.000Z
|
2021-11-18T00:19:18.000Z
|
include/mmf/optimizationSO3_approx.hpp
|
jstraub/dpMM
|
538c432d5f98c040d5c1adb072e545e38f97fc69
|
[
"MIT-feh"
] | null | null | null |
include/mmf/optimizationSO3_approx.hpp
|
jstraub/dpMM
|
538c432d5f98c040d5c1adb072e545e38f97fc69
|
[
"MIT-feh"
] | 6
|
2015-07-02T12:46:20.000Z
|
2022-03-30T04:39:30.000Z
|
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed
* under the MIT license. See the license file LICENSE.
*/
#pragma once
#include <stdint.h>
#include <iostream>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/QR>
// CUDA runtime
#include <cuda_runtime.h>
// Utilities and system includes
//#include <helper_functions.h>
#include <nvidia/helper_cuda.h>
//#include <mmf/defines.h>
using namespace Eigen;
using std::min;
using std::max;
using std::cout;
using std::endl;
template<typename T>
class OptSO3ApproxCpu
{
public:
OptSO3ApproxCpu(T t_max = 5.0, T dt = 0.05)
: t_max_(t_max), dt_(dt), t_(0)
{
R_ = Matrix<T,3,3>::Identity();
};
virtual ~OptSO3ApproxCpu()
{ };
// virtual T conjugateGradient(Matrix<T,3,3>& R, uint32_t maxIter=100);
virtual T conjugateGradient(Matrix<T,3,3>& R,
const Matrix<T,Dynamic,Dynamic>& qKarch,
const Matrix<T,Dynamic,1>& Ns,
uint32_t maxIter=100);
/* return a skew symmetric matrix from A */
Matrix<T,3,3> enforceSkewSymmetry(const Matrix<T,3,3> &A) const
{return 0.5*(A-A.transpose());};
const Matrix<T,3,3>& R() const {return R_;};
/* matrix of the 6 directions of the MF */
Matrix<T,Dynamic,Dynamic> M() const;
static Matrix<T,Dynamic,Dynamic> Rot2M(const Matrix<T,3,3>& R);
protected:
T t_max_, dt_;
uint32_t t_; // timestep
Matrix<T,3,3> R_; // previous rotation
Matrix<T,3,6> qKarch_; // karcher means for all axes
Matrix<T,1,6> Ns_; // number of normals for each axis
virtual void conjugateGradientPostparation_impl(Matrix<T,3,3>& R);
virtual T conjugateGradient_impl(Matrix<T,3,3>& R, T res0,
uint32_t maxIter=100);
/*
* evaluate cost function for a given assignment of npormals to axes
*/
virtual T evalCostFunction(Matrix<T,3,3>& R);
/* compute Jacobian */
virtual void computeJacobian(Matrix<T,3,3>&J, Matrix<T,3,3>& R);
/*
* updates G and H from rotation R and jacobian J
*/
virtual void updateGandH(Matrix<T,3,3>& G, Matrix<T,3,3>& G_prev,
Matrix<T,3,3>& H, const Matrix<T,3,3>& R, const Matrix<T,3,3>& J,
const Matrix<T,3,3>& M_t_min, bool resetH);
/*
* performs line search starting at R in direction of H returns min
* of cost function and updates R, and M_t_min
*/
virtual T linesearch(Matrix<T,3,3>& R, Matrix<T,3,3>& M_t_min, const
Matrix<T,3,3>& H, T t_max=1.0, T dt=0.1);
/* convert a Rotation matrix R to a MF representaiton of the axes */
void Rot2M(Matrix<T,3,3>& R, T *mu);
};
| 28.550562
| 72
| 0.668634
|
jstraub
|
94d2717921df8f08be83a2babe28c834bda1d911
| 3,176
|
hpp
|
C++
|
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | 34
|
2017-08-16T13:58:24.000Z
|
2022-03-31T11:50:25.000Z
|
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | null | null | null |
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
|
weiDDD/particleSystem
|
32652b09da35e025956999227f08be83b5d79cb1
|
[
"Apache-2.0"
] | 17
|
2017-08-18T07:42:44.000Z
|
2022-01-02T02:43:06.000Z
|
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.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.
****************************************************************************/
#ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H
#define COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H
#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif
#include "cocos2d.h"
#include "LuaScriptHandlerMgr.h"
NS_CC_BEGIN
class LuaEventListenerCustom
{
public:
static EventListenerCustom* create(const std::string& eventName);
};
class LuaEventListenerAcceleration
{
public:
static EventListenerAcceleration* create();
};
NS_CC_END
USING_NS_CC;
TOLUA_API int register_all_cocos2dx_manual(lua_State* tolua_S);
TOLUA_API int register_cocos2dx_event_releated(lua_State* tolua_S);
TOLUA_API int register_all_cocos2dx_module_manual(lua_State* tolua_S);
TOLUA_API int register_all_cocos2dx_math_manual(lua_State* tolua_S);
struct LuaEventAccelerationData
{
void* acc;
Event* event;
LuaEventAccelerationData(void* inAcc,Event* inEvent)
:acc(inAcc),event(inEvent)
{
}
};
struct LuaEventKeyboarData
{
int keyCode;
Event* event;
LuaEventKeyboarData(int inKeyCode,Event* inEvent)
:keyCode(inKeyCode),event(inEvent)
{
}
};
struct LuaEventTouchData
{
Touch* touch;
Event* event;
LuaEventTouchData(Touch* inTouch, Event* inEvent)
:touch(inTouch),
event(inEvent)
{
}
};
struct LuaEventTouchesData
{
std::vector<Touch*> touches;
Event* event;
LuaEventTouchesData(std::vector<Touch*> inTouches, Event* inEvent)
:touches(inTouches),
event(inEvent)
{
}
};
struct LuaEventMouseData
{
Event* event;
LuaEventMouseData(Event* inEvent)
:event(inEvent)
{
}
};
#endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H
| 26.689076
| 87
| 0.691751
|
weiDDD
|
94dab9a0cd96ec7ac344ae472ca764b0a84a3d26
| 192
|
cpp
|
C++
|
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
|
diegxsantiago/
|
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
|
[
"MIT"
] | 1
|
2021-02-08T18:22:50.000Z
|
2021-02-08T18:22:50.000Z
|
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
|
diegxsantiago/gii
|
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
|
[
"MIT"
] | null | null | null |
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
|
diegxsantiago/gii
|
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
|
[
"MIT"
] | null | null | null |
#include <stdlib.h>
#include <stdio.h>
#include "funciones.h"
/*
producto de dos numeros
*/
int division (int x, int y)
{
int tmp;
tmp = x / y;
return tmp;
}
| 10.666667
| 28
| 0.536458
|
diegxsantiago
|
94db874be36602fd7af0139f01c400625acb088a
| 925
|
cpp
|
C++
|
src/backend/generic/runtime/sycl/api.cpp
|
alexbatashev/athena
|
eafbb1e16ed0b273a63a20128ebd4882829aa2db
|
[
"MIT"
] | 2
|
2020-07-16T06:42:27.000Z
|
2020-07-16T06:42:28.000Z
|
src/backend/generic/runtime/sycl/api.cpp
|
PolarAI/polarai-framework
|
c5fd886732afe787a06ebf6fb05fc38069257457
|
[
"MIT"
] | null | null | null |
src/backend/generic/runtime/sycl/api.cpp
|
PolarAI/polarai-framework
|
c5fd886732afe787a06ebf6fb05fc38069257457
|
[
"MIT"
] | null | null | null |
//===----------------------------------------------------------------------===//
// Copyright (c) 2020 Athena. All rights reserved.
// https://getathena.ml
//
// Licensed under MIT license.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//===----------------------------------------------------------------------===//
#include "SYCLContext.h"
#include <athena/backend/llvm/runtime/api.h>
#include <athena/backend/llvm/runtime/runtime_export.h>
using namespace athena::backend::llvm;
extern "C" {
ATH_RT_LLVM_EXPORT Context* initContext() {
return new SYCLContext();
}
ATH_RT_LLVM_EXPORT void closeContext(Context* ctx) {
delete ctx;
}
}
| 28.90625
| 80
| 0.621622
|
alexbatashev
|
94e3575f63a486b5c93822233a7c3fa80e2e1de1
| 95,049
|
hh
|
C++
|
extern/glow/src/glow/detail/xxHash/xxh3.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | 11
|
2019-10-23T19:15:42.000Z
|
2021-12-07T07:37:39.000Z
|
extern/glow/src/glow/detail/xxHash/xxh3.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | 6
|
2019-10-29T04:11:17.000Z
|
2020-10-30T16:27:23.000Z
|
extern/glow/src/glow/detail/xxHash/xxh3.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | 2
|
2020-01-22T17:53:55.000Z
|
2020-10-01T09:18:00.000Z
|
/*
* xxHash - Extremely Fast Hash algorithm
* Development source file for `xxh3`
* Copyright (C) 2019-2020 Yann Collet
*
* BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* Note: This file is separated for development purposes.
* It will be integrated into `xxhash.h` when development stage is completed.
*
* Credit: most of the work on vectorial and asm variants comes from @easyaspi314
*/
#ifndef XXH3_H_1397135465
#define XXH3_H_1397135465
/* === Dependencies === */
#ifndef XXHASH_H_5627135585666179
/* special: when including `xxh3.h` directly, turn on XXH_INLINE_ALL */
#undef XXH_INLINE_ALL /* avoid redefinition */
#define XXH_INLINE_ALL
#endif
#include "xxhash.hh"
/* === Compiler specifics === */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* >= C99 */
#define XXH_RESTRICT restrict
#else
/* Note: it might be useful to define __restrict or __restrict__ for some C++ compilers */
#define XXH_RESTRICT /* disable */
#endif
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
#define XXH_likely(x) __builtin_expect(x, 1)
#define XXH_unlikely(x) __builtin_expect(x, 0)
#else
#define XXH_likely(x) (x)
#define XXH_unlikely(x) (x)
#endif
#if defined(__GNUC__)
#if defined(__AVX2__)
#include <immintrin.h>
#elif defined(__SSE2__)
#include <emmintrin.h>
#elif defined(__ARM_NEON__) || defined(__ARM_NEON)
#define inline __inline__ /* clang bug */
#include <arm_neon.h>
#undef inline
#endif
#elif defined(_MSC_VER)
#include <intrin.h>
#endif
/*
* One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while
* remaining a true 64-bit/128-bit hash function.
*
* This is done by prioritizing a subset of 64-bit operations that can be
* emulated without too many steps on the average 32-bit machine.
*
* For example, these two lines seem similar, and run equally fast on 64-bit:
*
* xxh_u64 x;
* x ^= (x >> 47); // good
* x ^= (x >> 13); // bad
*
* However, to a 32-bit machine, there is a major difference.
*
* x ^= (x >> 47) looks like this:
*
* x.lo ^= (x.hi >> (47 - 32));
*
* while x ^= (x >> 13) looks like this:
*
* // note: funnel shifts are not usually cheap.
* x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13));
* x.hi ^= (x.hi >> 13);
*
* The first one is significantly faster than the second, simply because the
* shift is larger than 32. This means:
* - All the bits we need are in the upper 32 bits, so we can ignore the lower
* 32 bits in the shift.
* - The shift result will always fit in the lower 32 bits, and therefore,
* we can ignore the upper 32 bits in the xor.
*
* Thanks to this optimization, XXH3 only requires these features to be efficient:
*
* - Usable unaligned access
* - A 32-bit or 64-bit ALU
* - If 32-bit, a decent ADC instruction
* - A 32 or 64-bit multiply with a 64-bit result
* - For the 128-bit variant, a decent byteswap helps short inputs.
*
* The first two are already required by XXH32, and almost all 32-bit and 64-bit
* platforms which can run XXH32 can run XXH3 efficiently.
*
* Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one
* notable exception.
*
* First of all, Thumb-1 lacks support for the UMULL instruction which
* performs the important long multiply. This means numerous __aeabi_lmul
* calls.
*
* Second of all, the 8 functional registers are just not enough.
* Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need
* Lo registers, and this shuffling results in thousands more MOVs than A32.
*
* A32 and T32 don't have this limitation. They can access all 14 registers,
* do a 32->64 multiply with UMULL, and the flexible operand allowing free
* shifts is helpful, too.
*
* Therefore, we do a quick sanity check.
*
* If compiling Thumb-1 for a target which supports ARM instructions, we will
* emit a warning, as it is not a "sane" platform to compile for.
*
* Usually, if this happens, it is because of an accident and you probably need
* to specify -march, as you likely meant to compile for a newer architecture.
*/
#if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM)
#warning "XXH3 is highly inefficient without ARM or Thumb-2."
#endif
/* ==========================================
* Vectorization detection
* ========================================== */
#define XXH_SCALAR 0 /* Portable scalar version */
#define XXH_SSE2 1 /* SSE2 for Pentium 4 and all x86_64 */
#define XXH_AVX2 2 /* AVX2 for Haswell and Bulldozer */
#define XXH_NEON 3 /* NEON for most ARMv7-A and all AArch64 */
#define XXH_VSX 4 /* VSX and ZVector for POWER8/z13 */
#define XXH_AVX512 5 /* AVX512 for Skylake and Icelake */
#ifndef XXH_VECTOR /* can be defined on command line */
#if defined(__AVX512F__)
#define XXH_VECTOR XXH_AVX512
#elif defined(__AVX2__)
#define XXH_VECTOR XXH_AVX2
#elif defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2))
#define XXH_VECTOR XXH_SSE2
#elif defined(__GNUC__) /* msvc support maybe later */ \
&& (defined(__ARM_NEON__) || defined(__ARM_NEON)) \
&& (defined(__LITTLE_ENDIAN__) /* We only support little endian NEON */ \
|| (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
#define XXH_VECTOR XXH_NEON
#elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) || (defined(__s390x__) && defined(__VEC__)) && defined(__GNUC__) /* TODO: IBM XL */
#define XXH_VECTOR XXH_VSX
#else
#define XXH_VECTOR XXH_SCALAR
#endif
#endif
/*
* Controls the alignment of the accumulator.
* This is for compatibility with aligned vector loads, which are usually faster.
*/
#ifndef XXH_ACC_ALIGN
#if XXH_VECTOR == XXH_SCALAR /* scalar */
#define XXH_ACC_ALIGN 8
#elif XXH_VECTOR == XXH_SSE2 /* sse2 */
#define XXH_ACC_ALIGN 16
#elif XXH_VECTOR == XXH_AVX2 /* avx2 */
#define XXH_ACC_ALIGN 32
#elif XXH_VECTOR == XXH_NEON /* neon */
#define XXH_ACC_ALIGN 16
#elif XXH_VECTOR == XXH_VSX /* vsx */
#define XXH_ACC_ALIGN 16
#elif XXH_VECTOR == XXH_AVX512 /* avx512 */
#define XXH_ACC_ALIGN 64
#endif
#endif
/*
* UGLY HACK:
* GCC usually generates the best code with -O3 for xxHash.
*
* However, when targeting AVX2, it is overzealous in its unrolling resulting
* in code roughly 3/4 the speed of Clang.
*
* There are other issues, such as GCC splitting _mm256_loadu_si256 into
* _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which
* only applies to Sandy and Ivy Bridge... which don't even support AVX2.
*
* That is why when compiling the AVX2 version, it is recommended to use either
* -O2 -mavx2 -march=haswell
* or
* -O2 -mavx2 -mno-avx256-split-unaligned-load
* for decent performance, or to use Clang instead.
*
* Fortunately, we can control the first one with a pragma that forces GCC into
* -O2, but the other one we can't control without "failed to inline always
* inline function due to target mismatch" warnings.
*/
#if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
&& defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
&& defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
#pragma GCC push_options
#pragma GCC optimize("-O2")
#endif
#if XXH_VECTOR == XXH_NEON
/*
* NEON's setup for vmlal_u32 is a little more complicated than it is on
* SSE2, AVX2, and VSX.
*
* While PMULUDQ and VMULEUW both perform a mask, VMLAL.U32 performs an upcast.
*
* To do the same operation, the 128-bit 'Q' register needs to be split into
* two 64-bit 'D' registers, performing this operation::
*
* [ a | b ]
* | '---------. .--------' |
* | x |
* | .---------' '--------. |
* [ a & 0xFFFFFFFF | b & 0xFFFFFFFF ],[ a >> 32 | b >> 32 ]
*
* Due to significant changes in aarch64, the fastest method for aarch64 is
* completely different than the fastest method for ARMv7-A.
*
* ARMv7-A treats D registers as unions overlaying Q registers, so modifying
* D11 will modify the high half of Q5. This is similar to how modifying AH
* will only affect bits 8-15 of AX on x86.
*
* VZIP takes two registers, and puts even lanes in one register and odd lanes
* in the other.
*
* On ARMv7-A, this strangely modifies both parameters in place instead of
* taking the usual 3-operand form.
*
* Therefore, if we want to do this, we can simply use a D-form VZIP.32 on the
* lower and upper halves of the Q register to end up with the high and low
* halves where we want - all in one instruction.
*
* vzip.32 d10, d11 @ d10 = { d10[0], d11[0] }; d11 = { d10[1], d11[1] }
*
* Unfortunately we need inline assembly for this: Instructions modifying two
* registers at once is not possible in GCC or Clang's IR, and they have to
* create a copy.
*
* aarch64 requires a different approach.
*
* In order to make it easier to write a decent compiler for aarch64, many
* quirks were removed, such as conditional execution.
*
* NEON was also affected by this.
*
* aarch64 cannot access the high bits of a Q-form register, and writes to a
* D-form register zero the high bits, similar to how writes to W-form scalar
* registers (or DWORD registers on x86_64) work.
*
* The formerly free vget_high intrinsics now require a vext (with a few
* exceptions)
*
* Additionally, VZIP was replaced by ZIP1 and ZIP2, which are the equivalent
* of PUNPCKL* and PUNPCKH* in SSE, respectively, in order to only modify one
* operand.
*
* The equivalent of the VZIP.32 on the lower and upper halves would be this
* mess:
*
* ext v2.4s, v0.4s, v0.4s, #2 // v2 = { v0[2], v0[3], v0[0], v0[1] }
* zip1 v1.2s, v0.2s, v2.2s // v1 = { v0[0], v2[0] }
* zip2 v0.2s, v0.2s, v1.2s // v0 = { v0[1], v2[1] }
*
* Instead, we use a literal downcast, vmovn_u64 (XTN), and vshrn_n_u64 (SHRN):
*
* shrn v1.2s, v0.2d, #32 // v1 = (uint32x2_t)(v0 >> 32);
* xtn v0.2s, v0.2d // v0 = (uint32x2_t)(v0 & 0xFFFFFFFF);
*
* This is available on ARMv7-A, but is less efficient than a single VZIP.32.
*/
/*
* Function-like macro:
* void XXH_SPLIT_IN_PLACE(uint64x2_t &in, uint32x2_t &outLo, uint32x2_t &outHi)
* {
* outLo = (uint32x2_t)(in & 0xFFFFFFFF);
* outHi = (uint32x2_t)(in >> 32);
* in = UNDEFINED;
* }
*/
#if !defined(XXH_NO_VZIP_HACK) /* define to disable */ \
&& defined(__GNUC__) && !defined(__aarch64__) && !defined(__arm64__)
#define XXH_SPLIT_IN_PLACE(in, outLo, outHi) \
do \
{ \
/* Undocumented GCC/Clang operand modifier: %e0 = lower D half, %f0 = upper D half */ \
/* https://github.com/gcc-mirror/gcc/blob/38cf91e5/gcc/config/arm/arm.c#L22486 */ \
/* https://github.com/llvm-mirror/llvm/blob/2c4ca683/lib/Target/ARM/ARMAsmPrinter.cpp#L399 */ \
__asm__("vzip.32 %e0, %f0" : "+w"(in)); \
(outLo) = vget_low_u32(vreinterpretq_u32_u64(in)); \
(outHi) = vget_high_u32(vreinterpretq_u32_u64(in)); \
} while (0)
#else
#define XXH_SPLIT_IN_PLACE(in, outLo, outHi) \
do \
{ \
(outLo) = vmovn_u64(in); \
(outHi) = vshrn_n_u64((in), 32); \
} while (0)
#endif
#endif /* XXH_VECTOR == XXH_NEON */
/*
* VSX and Z Vector helpers.
*
* This is very messy, and any pull requests to clean this up are welcome.
*
* There are a lot of problems with supporting VSX and s390x, due to
* inconsistent intrinsics, spotty coverage, and multiple endiannesses.
*/
#if XXH_VECTOR == XXH_VSX
#if defined(__s390x__)
#include <s390intrin.h>
#else
#include <altivec.h>
#endif
#undef vector /* Undo the pollution */
typedef __vector unsigned long long xxh_u64x2;
typedef __vector unsigned char xxh_u8x16;
typedef __vector unsigned xxh_u32x4;
#ifndef XXH_VSX_BE
#if defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define XXH_VSX_BE 1
#elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__
#warning "-maltivec=be is not recommended. Please use native endianness."
#define XXH_VSX_BE 1
#else
#define XXH_VSX_BE 0
#endif
#endif /* !defined(XXH_VSX_BE) */
#if XXH_VSX_BE
/* A wrapper for POWER9's vec_revb. */
#if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
#define XXH_vec_revb vec_revb
#else
XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val)
{
xxh_u8x16 const vByteSwap = {0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08};
return vec_perm(val, val, vByteSwap);
}
#endif
#endif /* XXH_VSX_BE */
/*
* Performs an unaligned load and byte swaps it on big endian.
*/
XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void* ptr)
{
xxh_u64x2 ret;
memcpy(&ret, ptr, sizeof(xxh_u64x2));
#if XXH_VSX_BE
ret = XXH_vec_revb(ret);
#endif
return ret;
}
/*
* vec_mulo and vec_mule are very problematic intrinsics on PowerPC
*
* These intrinsics weren't added until GCC 8, despite existing for a while,
* and they are endian dependent. Also, their meaning swap depending on version.
* */
#if defined(__s390x__)
/* s390x is always big endian, no issue on this platform */
#define XXH_vec_mulo vec_mulo
#define XXH_vec_mule vec_mule
#elif defined(__clang__) && __has_builtin(__builtin_altivec_vmuleuw)
/* Clang has a better way to control this, we can just use the builtin which doesn't swap. */
#define XXH_vec_mulo __builtin_altivec_vmulouw
#define XXH_vec_mule __builtin_altivec_vmuleuw
#else
/* gcc needs inline assembly */
/* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */
XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b)
{
xxh_u64x2 result;
__asm__("vmulouw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b));
return result;
}
XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
{
xxh_u64x2 result;
__asm__("vmuleuw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b));
return result;
}
#endif /* XXH_vec_mulo, XXH_vec_mule */
#endif /* XXH_VECTOR == XXH_VSX */
/* prefetch
* can be disabled, by declaring XXH_NO_PREFETCH build macro */
#if defined(XXH_NO_PREFETCH)
#define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */
#else
#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) /* _mm_prefetch() is not defined outside of x86/x64 */
#include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
#define XXH_PREFETCH(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
#elif defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#define XXH_PREFETCH(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
#else
#define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */
#endif
#endif /* XXH_NO_PREFETCH */
/* ==========================================
* XXH3 default settings
* ========================================== */
#define XXH_SECRET_DEFAULT_SIZE 192 /* minimum XXH3_SECRET_SIZE_MIN */
#if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN)
#error "default keyset is not large enough"
#endif
/* Pseudorandom secret taken directly from FARSH */
XXH_ALIGN(64)
static const xxh_u8 kSecret[XXH_SECRET_DEFAULT_SIZE] = {
0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, 0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90,
0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, 0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d,
0xcc, 0xff, 0x72, 0x21, 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, 0x3c, 0x28,
0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e,
0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b,
0x4f, 0x1d, 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64,
0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb, 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0,
0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, 0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1,
0x7a, 0xd0, 0x31, 0xce, 0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
};
/*
* Calculates a 32-bit to 64-bit long multiply.
*
* Wraps __emulu on MSVC x86 because it tends to call __allmul when it doesn't
* need to (but it shouldn't need to anyways, it is about 7 instructions to do
* a 64x64 multiply...). Since we know that this will _always_ emit MULL, we
* use that instead of the normal method.
*
* If you are compiling for platforms like Thumb-1 and don't have a better option,
* you may also want to write your own long multiply routine here.
*
* XXH_FORCE_INLINE xxh_u64 XXH_mult32to64(xxh_u64 x, xxh_u64 y)
* {
* return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF);
* }
*/
#if defined(_MSC_VER) && defined(_M_IX86)
#include <intrin.h>
#define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y))
#else
/*
* Downcast + upcast is usually better than masking on older compilers like
* GCC 4.2 (especially 32-bit ones), all without affecting newer compilers.
*
* The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands
* and perform a full 64x64 multiply -- entirely redundant on 32-bit.
*/
#define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y))
#endif
/*
* Calculates a 64->128-bit long multiply.
*
* Uses __uint128_t and _umul128 if available, otherwise uses a scalar version.
*/
static XXH128_hash_t XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs)
{
/*
* GCC/Clang __uint128_t method.
*
* On most 64-bit targets, GCC and Clang define a __uint128_t type.
* This is usually the best way as it usually uses a native long 64-bit
* multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64.
*
* Usually.
*
* Despite being a 32-bit platform, Clang (and emscripten) define this type
* despite not having the arithmetic for it. This results in a laggy
* compiler builtin call which calculates a full 128-bit multiply.
* In that case it is best to use the portable one.
* https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677
*/
#if defined(__GNUC__) && !defined(__wasm__) && defined(__SIZEOF_INT128__) || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128)
__uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs;
XXH128_hash_t r128;
r128.low64 = (xxh_u64)(product);
r128.high64 = (xxh_u64)(product >> 64);
return r128;
/*
* MSVC for x64's _umul128 method.
*
* xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct);
*
* This compiles to single operand MUL on x64.
*/
#elif defined(_M_X64) || defined(_M_IA64)
#ifndef _MSC_VER
#pragma intrinsic(_umul128)
#endif
xxh_u64 product_high;
xxh_u64 const product_low = _umul128(lhs, rhs, &product_high);
XXH128_hash_t r128;
r128.low64 = product_low;
r128.high64 = product_high;
return r128;
#else
/*
* Portable scalar method. Optimized for 32-bit and 64-bit ALUs.
*
* This is a fast and simple grade school multiply, which is shown below
* with base 10 arithmetic instead of base 0x100000000.
*
* 9 3 // D2 lhs = 93
* x 7 5 // D2 rhs = 75
* ----------
* 1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15
* 4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45
* 2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21
* + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63
* ---------
* 2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27
* + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67
* ---------
* 6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975
*
* The reasons for adding the products like this are:
* 1. It avoids manual carry tracking. Just like how
* (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX.
* This avoids a lot of complexity.
*
* 2. It hints for, and on Clang, compiles to, the powerful UMAAL
* instruction available in ARM's Digital Signal Processing extension
* in 32-bit ARMv6 and later, which is shown below:
*
* void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm)
* {
* xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm;
* *RdLo = (xxh_u32)(product & 0xFFFFFFFF);
* *RdHi = (xxh_u32)(product >> 32);
* }
*
* This instruction was designed for efficient long multiplication, and
* allows this to be calculated in only 4 instructions at speeds
* comparable to some 64-bit ALUs.
*
* 3. It isn't terrible on other platforms. Usually this will be a couple
* of 32-bit ADD/ADCs.
*/
/* First calculate all of the cross products. */
xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF);
xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32, rhs & 0xFFFFFFFF);
xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32);
xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32, rhs >> 32);
/* Now add the products together. These will never overflow. */
xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi;
xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32) + hi_hi;
xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF);
XXH128_hash_t r128;
r128.low64 = lower;
r128.high64 = upper;
return r128;
#endif
}
/*
* Does a 64-bit to 128-bit multiply, then XOR folds it.
*
* The reason for the separate function is to prevent passing too many structs
* around by value. This will hopefully inline the multiply, but we don't force it.
*/
static xxh_u64 XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs)
{
XXH128_hash_t product = XXH_mult64to128(lhs, rhs);
return product.low64 ^ product.high64;
}
/* Seems to produce slightly better code on GCC for some reason. */
XXH_FORCE_INLINE xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift)
{
XXH_ASSERT(0 <= shift && shift < 64);
return v64 ^ (v64 >> shift);
}
/*
* We don't need to (or want to) mix as much as XXH64.
*
* Short hashes are more evenly distributed, so it isn't necessary.
*/
static XXH64_hash_t XXH3_avalanche(xxh_u64 h64)
{
h64 = XXH_xorshift64(h64, 37);
h64 *= 0x165667919E3779F9ULL;
h64 = XXH_xorshift64(h64, 32);
return h64;
}
/* ==========================================
* Short keys
* ==========================================
* One of the shortcomings of XXH32 and XXH64 was that their performance was
* sub-optimal on short lengths. It used an iterative algorithm which strongly
* favored lengths that were a multiple of 4 or 8.
*
* Instead of iterating over individual inputs, we use a set of single shot
* functions which piece together a range of lengths and operate in constant time.
*
* Additionally, the number of multiplies has been significantly reduced. This
* reduces latency, especially when emulating 64-bit multiplies on 32-bit.
*
* Depending on the platform, this may or may not be faster than XXH32, but it
* is almost guaranteed to be faster than XXH64.
*/
/*
* At very short lengths, there isn't enough input to fully hide secrets, or use
* the entire secret.
*
* There is also only a limited amount of mixing we can do before significantly
* impacting performance.
*
* Therefore, we use different sections of the secret and always mix two secret
* samples with an XOR. This should have no effect on performance on the
* seedless or withSeed variants because everything _should_ be constant folded
* by modern compilers.
*
* The XOR mixing hides individual parts of the secret and increases entropy.
*
* This adds an extra layer of strength for custom secrets.
*/
XXH_FORCE_INLINE XXH64_hash_t XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(input != NULL);
XXH_ASSERT(1 <= len && len <= 3);
XXH_ASSERT(secret != NULL);
/*
* len = 1: combined = { input[0], 0x01, input[0], input[0] }
* len = 2: combined = { input[1], 0x02, input[0], input[1] }
* len = 3: combined = { input[2], 0x03, input[0], input[1] }
*/
{
xxh_u8 const c1 = input[0];
xxh_u8 const c2 = input[len >> 1];
xxh_u8 const c3 = input[len - 1];
xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8);
xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed;
xxh_u64 const keyed = (xxh_u64)combined ^ bitflip;
xxh_u64 const mixed = keyed * PRIME64_1;
return XXH3_avalanche(mixed);
}
}
XXH_FORCE_INLINE XXH64_hash_t XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(input != NULL);
XXH_ASSERT(secret != NULL);
XXH_ASSERT(4 <= len && len < 8);
seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
{
xxh_u32 const input1 = XXH_readLE32(input);
xxh_u32 const input2 = XXH_readLE32(input + len - 4);
xxh_u64 const bitflip = (XXH_readLE64(secret + 8) ^ XXH_readLE64(secret + 16)) - seed;
xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32);
xxh_u64 x = input64 ^ bitflip;
/* this mix is inspired by Pelle Evensen's rrmxmx */
x ^= XXH_rotl64(x, 49) ^ XXH_rotl64(x, 24);
x *= 0x9FB21C651E98DF25ULL;
x ^= (x >> 35) + len;
x *= 0x9FB21C651E98DF25ULL;
return XXH_xorshift64(x, 28);
}
}
XXH_FORCE_INLINE XXH64_hash_t XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(input != NULL);
XXH_ASSERT(secret != NULL);
XXH_ASSERT(8 <= len && len <= 16);
{
xxh_u64 const bitflip1 = (XXH_readLE64(secret + 24) ^ XXH_readLE64(secret + 32)) + seed;
xxh_u64 const bitflip2 = (XXH_readLE64(secret + 40) ^ XXH_readLE64(secret + 48)) - seed;
xxh_u64 const input_lo = XXH_readLE64(input) ^ bitflip1;
xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2;
xxh_u64 const acc = len + XXH_swap64(input_lo) + input_hi + XXH3_mul128_fold64(input_lo, input_hi);
return XXH3_avalanche(acc);
}
}
XXH_FORCE_INLINE XXH64_hash_t XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(len <= 16);
{
if (XXH_likely(len > 8))
return XXH3_len_9to16_64b(input, len, secret, seed);
if (XXH_likely(len >= 4))
return XXH3_len_4to8_64b(input, len, secret, seed);
if (len)
return XXH3_len_1to3_64b(input, len, secret, seed);
return XXH3_avalanche((PRIME64_1 + seed) ^ (XXH_readLE64(secret + 56) ^ XXH_readLE64(secret + 64)));
}
}
/*
* DISCLAIMER: There are known *seed-dependent* multicollisions here due to
* multiplication by zero, affecting hashes of lengths 17 to 240.
*
* However, they are very unlikely.
*
* Keep this in mind when using the unseeded XXH3_64bits() variant: As with all
* unseeded non-cryptographic hashes, it does not attempt to defend itself
* against specially crafted inputs, only random inputs.
*
* Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes
* cancelling out the secret is taken an arbitrary number of times (addressed
* in XXH3_accumulate_512), this collision is very unlikely with random inputs
* and/or proper seeding:
*
* This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a
* function that is only called up to 16 times per hash with up to 240 bytes of
* input.
*
* This is not too bad for a non-cryptographic hash function, especially with
* only 64 bit outputs.
*
* The 128-bit variant (which trades some speed for strength) is NOT affected
* by this, although it is always a good idea to use a proper seed if you care
* about strength.
*/
XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input, const xxh_u8* XXH_RESTRICT secret, xxh_u64 seed64)
{
#if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
&& defined(__i386__) && defined(__SSE2__) /* x86 + SSE2 */ \
&& !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable like XXH32 hack */
/*
* UGLY HACK:
* GCC for x86 tends to autovectorize the 128-bit multiply, resulting in
* slower code.
*
* By forcing seed64 into a register, we disrupt the cost model and
* cause it to scalarize. See `XXH32_round()`
*
* FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600,
* XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on
* GCC 9.2, despite both emitting scalar code.
*
* GCC generates much better scalar code than Clang for the rest of XXH3,
* which is why finding a more optimal codepath is an interest.
*/
__asm__("" : "+r"(seed64));
#endif
{
xxh_u64 const input_lo = XXH_readLE64(input);
xxh_u64 const input_hi = XXH_readLE64(input + 8);
return XXH3_mul128_fold64(input_lo ^ (XXH_readLE64(secret) + seed64), input_hi ^ (XXH_readLE64(secret + 8) - seed64));
}
}
/* For mid range keys, XXH3 uses a Mum-hash variant. */
XXH_FORCE_INLINE XXH64_hash_t XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
(void)secretSize;
XXH_ASSERT(16 < len && len <= 128);
{
xxh_u64 acc = len * PRIME64_1;
if (len > 32)
{
if (len > 64)
{
if (len > 96)
{
acc += XXH3_mix16B(input + 48, secret + 96, seed);
acc += XXH3_mix16B(input + len - 64, secret + 112, seed);
}
acc += XXH3_mix16B(input + 32, secret + 64, seed);
acc += XXH3_mix16B(input + len - 48, secret + 80, seed);
}
acc += XXH3_mix16B(input + 16, secret + 32, seed);
acc += XXH3_mix16B(input + len - 32, secret + 48, seed);
}
acc += XXH3_mix16B(input + 0, secret + 0, seed);
acc += XXH3_mix16B(input + len - 16, secret + 16, seed);
return XXH3_avalanche(acc);
}
}
#define XXH3_MIDSIZE_MAX 240
XXH_NO_INLINE XXH64_hash_t XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
(void)secretSize;
XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
#define XXH3_MIDSIZE_STARTOFFSET 3
#define XXH3_MIDSIZE_LASTOFFSET 17
{
xxh_u64 acc = len * PRIME64_1;
int const nbRounds = (int)len / 16;
int i;
for (i = 0; i < 8; i++)
{
acc += XXH3_mix16B(input + (16 * i), secret + (16 * i), seed);
}
acc = XXH3_avalanche(acc);
XXH_ASSERT(nbRounds >= 8);
#if defined(__clang__) /* Clang */ \
&& (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
&& !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */
/*
* UGLY HACK:
* Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86.
* In everywhere else, it uses scalar code.
*
* For 64->128-bit multiplies, even if the NEON was 100% optimal, it
* would still be slower than UMAAL (see XXH_mult64to128).
*
* Unfortunately, Clang doesn't handle the long multiplies properly and
* converts them to the nonexistent "vmulq_u64" intrinsic, which is then
* scalarized into an ugly mess of VMOV.32 instructions.
*
* This mess is difficult to avoid without turning autovectorization
* off completely, but they are usually relatively minor and/or not
* worth it to fix.
*
* This loop is the easiest to fix, as unlike XXH32, this pragma
* _actually works_ because it is a loop vectorization instead of an
* SLP vectorization.
*/
#pragma clang loop vectorize(disable)
#endif
for (i = 8; i < nbRounds; i++)
{
acc += XXH3_mix16B(input + (16 * i), secret + (16 * (i - 8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
}
/* last bytes */
acc += XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
return XXH3_avalanche(acc);
}
}
/* === Long Keys === */
#define STRIPE_LEN 64
#define XXH_SECRET_CONSUME_RATE 8 /* nb of secret bytes consumed at each accumulation */
#define ACC_NB (STRIPE_LEN / sizeof(xxh_u64))
typedef enum
{
XXH3_acc_64bits,
XXH3_acc_128bits
} XXH3_accWidth_e;
/*
* XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized.
*
* It is a hardened version of UMAC, based off of FARSH's implementation.
*
* This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD
* implementations, and it is ridiculously fast.
*
* We harden it by mixing the original input to the accumulators as well as the product.
*
* This means that in the (relatively likely) case of a multiply by zero, the
* original input is preserved.
*
* On 128-bit inputs, we swap 64-bit pairs when we add the input to improve
* cross-pollination, as otherwise the upper and lower halves would be
* essentially independent.
*
* This doesn't matter on 64-bit hashes since they all get merged together in
* the end, so we skip the extra step.
*
* Both XXH3_64bits and XXH3_128bits use this subroutine.
*/
XXH_FORCE_INLINE void XXH3_accumulate_512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT input, const void* XXH_RESTRICT secret, XXH3_accWidth_e accWidth)
{
#if (XXH_VECTOR == XXH_AVX512)
XXH_ASSERT((((size_t)acc) & 63) == 0);
XXH_STATIC_ASSERT(STRIPE_LEN == sizeof(__m512i));
{
XXH_ALIGN(64) __m512i* const xacc = (__m512i*)acc;
/* data_vec = input[0]; */
__m512i const data_vec = _mm512_loadu_si512(input);
/* key_vec = secret[0]; */
__m512i const key_vec = _mm512_loadu_si512(secret);
/* data_key = data_vec ^ key_vec; */
__m512i const data_key = _mm512_xor_si512(data_vec, key_vec);
/* data_key_lo = data_key >> 32; */
__m512i const data_key_lo = _mm512_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
/* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
__m512i const product = _mm512_mul_epu32(data_key, data_key_lo);
if (accWidth == XXH3_acc_128bits)
{
/* xacc[0] += swap(data_vec); */
__m512i const data_swap = _mm512_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
__m512i const sum = _mm512_add_epi64(*xacc, data_swap);
/* xacc[0] += product; */
*xacc = _mm512_add_epi64(product, sum);
}
else
{ /* XXH3_acc_64bits */
/* xacc[0] += data_vec; */
__m512i const sum = _mm512_add_epi64(*xacc, data_vec);
/* xacc[0] += product; */
*xacc = _mm512_add_epi64(product, sum);
}
}
#elif (XXH_VECTOR == XXH_AVX2)
XXH_ASSERT((((size_t)acc) & 31) == 0);
{
XXH_ALIGN(32) __m256i* const xacc = (__m256i*)acc;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
const __m256i* const xinput = (const __m256i*)input;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
const __m256i* const xsecret = (const __m256i*)secret;
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(__m256i); i++)
{
/* data_vec = xinput[i]; */
__m256i const data_vec = _mm256_loadu_si256(xinput + i);
/* key_vec = xsecret[i]; */
__m256i const key_vec = _mm256_loadu_si256(xsecret + i);
/* data_key = data_vec ^ key_vec; */
__m256i const data_key = _mm256_xor_si256(data_vec, key_vec);
/* data_key_lo = data_key >> 32; */
__m256i const data_key_lo = _mm256_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
/* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
__m256i const product = _mm256_mul_epu32(data_key, data_key_lo);
if (accWidth == XXH3_acc_128bits)
{
/* xacc[i] += swap(data_vec); */
__m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
__m256i const sum = _mm256_add_epi64(xacc[i], data_swap);
/* xacc[i] += product; */
xacc[i] = _mm256_add_epi64(product, sum);
}
else
{ /* XXH3_acc_64bits */
/* xacc[i] += data_vec; */
__m256i const sum = _mm256_add_epi64(xacc[i], data_vec);
/* xacc[i] += product; */
xacc[i] = _mm256_add_epi64(product, sum);
}
}
}
#elif (XXH_VECTOR == XXH_SSE2)
/* SSE2 is just a half-scale version of the AVX2 version. */
XXH_ASSERT((((size_t)acc) & 15) == 0);
{
XXH_ALIGN(16) __m128i* const xacc = (__m128i*)acc;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
const __m128i* const xinput = (const __m128i*)input;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
const __m128i* const xsecret = (const __m128i*)secret;
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(__m128i); i++)
{
/* data_vec = xinput[i]; */
__m128i const data_vec = _mm_loadu_si128(xinput + i);
/* key_vec = xsecret[i]; */
__m128i const key_vec = _mm_loadu_si128(xsecret + i);
/* data_key = data_vec ^ key_vec; */
__m128i const data_key = _mm_xor_si128(data_vec, key_vec);
/* data_key_lo = data_key >> 32; */
__m128i const data_key_lo = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
/* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
__m128i const product = _mm_mul_epu32(data_key, data_key_lo);
if (accWidth == XXH3_acc_128bits)
{
/* xacc[i] += swap(data_vec); */
__m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2));
__m128i const sum = _mm_add_epi64(xacc[i], data_swap);
/* xacc[i] += product; */
xacc[i] = _mm_add_epi64(product, sum);
}
else
{ /* XXH3_acc_64bits */
/* xacc[i] += data_vec; */
__m128i const sum = _mm_add_epi64(xacc[i], data_vec);
/* xacc[i] += product; */
xacc[i] = _mm_add_epi64(product, sum);
}
}
}
#elif (XXH_VECTOR == XXH_NEON)
XXH_ASSERT((((size_t)acc) & 15) == 0);
{
XXH_ALIGN(16) uint64x2_t* const xacc = (uint64x2_t*)acc;
/* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */
uint8_t const* const xinput = (const uint8_t*)input;
uint8_t const* const xsecret = (const uint8_t*)secret;
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(uint64x2_t); i++)
{
/* data_vec = xinput[i]; */
uint8x16_t data_vec = vld1q_u8(xinput + (i * 16));
/* key_vec = xsecret[i]; */
uint8x16_t key_vec = vld1q_u8(xsecret + (i * 16));
uint64x2_t data_key;
uint32x2_t data_key_lo, data_key_hi;
if (accWidth == XXH3_acc_64bits)
{
/* xacc[i] += data_vec; */
xacc[i] = vaddq_u64(xacc[i], vreinterpretq_u64_u8(data_vec));
}
else
{ /* XXH3_acc_128bits */
/* xacc[i] += swap(data_vec); */
uint64x2_t const data64 = vreinterpretq_u64_u8(data_vec);
uint64x2_t const swapped = vextq_u64(data64, data64, 1);
xacc[i] = vaddq_u64(xacc[i], swapped);
}
/* data_key = data_vec ^ key_vec; */
data_key = vreinterpretq_u64_u8(veorq_u8(data_vec, key_vec));
/* data_key_lo = (uint32x2_t) (data_key & 0xFFFFFFFF);
* data_key_hi = (uint32x2_t) (data_key >> 32);
* data_key = UNDEFINED; */
XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
/* xacc[i] += (uint64x2_t) data_key_lo * (uint64x2_t) data_key_hi; */
xacc[i] = vmlal_u32(xacc[i], data_key_lo, data_key_hi);
}
}
#elif (XXH_VECTOR == XXH_VSX)
xxh_u64x2* const xacc = (xxh_u64x2*)acc; /* presumed aligned */
xxh_u64x2 const* const xinput = (xxh_u64x2 const*)input; /* no alignment restriction */
xxh_u64x2 const* const xsecret = (xxh_u64x2 const*)secret; /* no alignment restriction */
xxh_u64x2 const v32 = {32, 32};
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(xxh_u64x2); i++)
{
/* data_vec = xinput[i]; */
xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + i);
/* key_vec = xsecret[i]; */
xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + i);
xxh_u64x2 const data_key = data_vec ^ key_vec;
/* shuffled = (data_key << 32) | (data_key >> 32); */
xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32);
/* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */
xxh_u64x2 const product = XXH_vec_mulo((xxh_u32x4)data_key, shuffled);
xacc[i] += product;
if (accWidth == XXH3_acc_64bits)
{
xacc[i] += data_vec;
}
else
{ /* XXH3_acc_128bits */
/* swap high and low halves */
#ifdef __s390x__
xxh_u64x2 const data_swapped = vec_permi(data_vec, data_vec, 2);
#else
xxh_u64x2 const data_swapped = vec_xxpermdi(data_vec, data_vec, 2);
#endif
xacc[i] += data_swapped;
}
}
#else /* scalar variant of Accumulator - universal */
XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64* const xacc = (xxh_u64*)acc; /* presumed aligned */
const xxh_u8* const xinput = (const xxh_u8*)input; /* no alignment restriction */
const xxh_u8* const xsecret = (const xxh_u8*)secret; /* no alignment restriction */
size_t i;
XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN - 1)) == 0);
for (i = 0; i < ACC_NB; i++)
{
xxh_u64 const data_val = XXH_readLE64(xinput + 8 * i);
xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + i * 8);
if (accWidth == XXH3_acc_64bits)
{
xacc[i] += data_val;
}
else
{
xacc[i ^ 1] += data_val; /* swap adjacent lanes */
}
xacc[i] += XXH_mult32to64(data_key & 0xFFFFFFFF, data_key >> 32);
}
#endif
}
/*
* XXH3_scrambleAcc: Scrambles the accumulators to improve mixing.
*
* Multiplication isn't perfect, as explained by Google in HighwayHash:
*
* // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to
* // varying degrees. In descending order of goodness, bytes
* // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32.
* // As expected, the upper and lower bytes are much worse.
*
* Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291
*
* Since our algorithm uses a pseudorandom secret to add some variance into the
* mix, we don't need to (or want to) mix as often or as much as HighwayHash does.
*
* This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid
* extraction.
*
* Both XXH3_64bits and XXH3_128bits use this subroutine.
*/
XXH_FORCE_INLINE void XXH3_scrambleAcc(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
{
#if (XXH_VECTOR == XXH_AVX512)
XXH_ASSERT((((size_t)acc) & 63) == 0);
XXH_STATIC_ASSERT(STRIPE_LEN == sizeof(__m512i));
{
XXH_ALIGN(64) __m512i* const xacc = (__m512i*)acc;
const __m512i prime32 = _mm512_set1_epi32((int)PRIME32_1);
/* xacc[0] ^= (xacc[0] >> 47) */
__m512i const acc_vec = *xacc;
__m512i const shifted = _mm512_srli_epi64(acc_vec, 47);
__m512i const data_vec = _mm512_xor_si512(acc_vec, shifted);
/* xacc[0] ^= secret; */
__m512i const key_vec = _mm512_loadu_si512(secret);
__m512i const data_key = _mm512_xor_si512(data_vec, key_vec);
/* xacc[0] *= PRIME32_1; */
__m512i const data_key_hi = _mm512_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
__m512i const prod_lo = _mm512_mul_epu32(data_key, prime32);
__m512i const prod_hi = _mm512_mul_epu32(data_key_hi, prime32);
*xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32));
}
#elif (XXH_VECTOR == XXH_AVX2)
XXH_ASSERT((((size_t)acc) & 31) == 0);
{
XXH_ALIGN(32) __m256i* const xacc = (__m256i*)acc;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */
const __m256i* const xsecret = (const __m256i*)secret;
const __m256i prime32 = _mm256_set1_epi32((int)PRIME32_1);
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(__m256i); i++)
{
/* xacc[i] ^= (xacc[i] >> 47) */
__m256i const acc_vec = xacc[i];
__m256i const shifted = _mm256_srli_epi64(acc_vec, 47);
__m256i const data_vec = _mm256_xor_si256(acc_vec, shifted);
/* xacc[i] ^= xsecret; */
__m256i const key_vec = _mm256_loadu_si256(xsecret + i);
__m256i const data_key = _mm256_xor_si256(data_vec, key_vec);
/* xacc[i] *= PRIME32_1; */
__m256i const data_key_hi = _mm256_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
__m256i const prod_lo = _mm256_mul_epu32(data_key, prime32);
__m256i const prod_hi = _mm256_mul_epu32(data_key_hi, prime32);
xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32));
}
}
#elif (XXH_VECTOR == XXH_SSE2)
XXH_ASSERT((((size_t)acc) & 15) == 0);
{
XXH_ALIGN(16) __m128i* const xacc = (__m128i*)acc;
/* Unaligned. This is mainly for pointer arithmetic, and because
* _mm_loadu_si128 requires a const __m128i * pointer for some reason. */
const __m128i* const xsecret = (const __m128i*)secret;
const __m128i prime32 = _mm_set1_epi32((int)PRIME32_1);
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(__m128i); i++)
{
/* xacc[i] ^= (xacc[i] >> 47) */
__m128i const acc_vec = xacc[i];
__m128i const shifted = _mm_srli_epi64(acc_vec, 47);
__m128i const data_vec = _mm_xor_si128(acc_vec, shifted);
/* xacc[i] ^= xsecret[i]; */
__m128i const key_vec = _mm_loadu_si128(xsecret + i);
__m128i const data_key = _mm_xor_si128(data_vec, key_vec);
/* xacc[i] *= PRIME32_1; */
__m128i const data_key_hi = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1));
__m128i const prod_lo = _mm_mul_epu32(data_key, prime32);
__m128i const prod_hi = _mm_mul_epu32(data_key_hi, prime32);
xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32));
}
}
#elif (XXH_VECTOR == XXH_NEON)
XXH_ASSERT((((size_t)acc) & 15) == 0);
{
uint64x2_t* xacc = (uint64x2_t*)acc;
uint8_t const* xsecret = (uint8_t const*)secret;
uint32x2_t prime = vdup_n_u32(PRIME32_1);
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(uint64x2_t); i++)
{
/* xacc[i] ^= (xacc[i] >> 47); */
uint64x2_t acc_vec = xacc[i];
uint64x2_t shifted = vshrq_n_u64(acc_vec, 47);
uint64x2_t data_vec = veorq_u64(acc_vec, shifted);
/* xacc[i] ^= xsecret[i]; */
uint8x16_t key_vec = vld1q_u8(xsecret + (i * 16));
uint64x2_t data_key = veorq_u64(data_vec, vreinterpretq_u64_u8(key_vec));
/* xacc[i] *= PRIME32_1 */
uint32x2_t data_key_lo, data_key_hi;
/* data_key_lo = (uint32x2_t) (xacc[i] & 0xFFFFFFFF);
* data_key_hi = (uint32x2_t) (xacc[i] >> 32);
* xacc[i] = UNDEFINED; */
XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
{ /*
* prod_hi = (data_key >> 32) * PRIME32_1;
*
* Avoid vmul_u32 + vshll_n_u32 since Clang 6 and 7 will
* incorrectly "optimize" this:
* tmp = vmul_u32(vmovn_u64(a), vmovn_u64(b));
* shifted = vshll_n_u32(tmp, 32);
* to this:
* tmp = "vmulq_u64"(a, b); // no such thing!
* shifted = vshlq_n_u64(tmp, 32);
*
* However, unlike SSE, Clang lacks a 64-bit multiply routine
* for NEON, and it scalarizes two 64-bit multiplies instead.
*
* vmull_u32 has the same timing as vmul_u32, and it avoids
* this bug completely.
* See https://bugs.llvm.org/show_bug.cgi?id=39967
*/
uint64x2_t prod_hi = vmull_u32(data_key_hi, prime);
/* xacc[i] = prod_hi << 32; */
xacc[i] = vshlq_n_u64(prod_hi, 32);
/* xacc[i] += (prod_hi & 0xFFFFFFFF) * PRIME32_1; */
xacc[i] = vmlal_u32(xacc[i], data_key_lo, prime);
}
}
}
#elif (XXH_VECTOR == XXH_VSX)
XXH_ASSERT((((size_t)acc) & 15) == 0);
{
xxh_u64x2* const xacc = (xxh_u64x2*)acc;
const xxh_u64x2* const xsecret = (const xxh_u64x2*)secret;
/* constants */
xxh_u64x2 const v32 = {32, 32};
xxh_u64x2 const v47 = {47, 47};
xxh_u32x4 const prime = {PRIME32_1, PRIME32_1, PRIME32_1, PRIME32_1};
size_t i;
for (i = 0; i < STRIPE_LEN / sizeof(xxh_u64x2); i++)
{
/* xacc[i] ^= (xacc[i] >> 47); */
xxh_u64x2 const acc_vec = xacc[i];
xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47);
/* xacc[i] ^= xsecret[i]; */
xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + i);
xxh_u64x2 const data_key = data_vec ^ key_vec;
/* xacc[i] *= PRIME32_1 */
/* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF); */
xxh_u64x2 const prod_even = XXH_vec_mule((xxh_u32x4)data_key, prime);
/* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32); */
xxh_u64x2 const prod_odd = XXH_vec_mulo((xxh_u32x4)data_key, prime);
xacc[i] = prod_odd + (prod_even << v32);
}
}
#else /* scalar variant of Scrambler - universal */
XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64* const xacc = (xxh_u64*)acc; /* presumed aligned */
const xxh_u8* const xsecret = (const xxh_u8*)secret; /* no alignment restriction */
size_t i;
XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN - 1)) == 0);
for (i = 0; i < ACC_NB; i++)
{
xxh_u64 const key64 = XXH_readLE64(xsecret + 8 * i);
xxh_u64 acc64 = xacc[i];
acc64 = XXH_xorshift64(acc64, 47);
acc64 ^= key64;
acc64 *= PRIME32_1;
xacc[i] = acc64;
}
#endif
}
#define XXH_PREFETCH_DIST 384
#ifdef __clang__ // for clang
#define XXH_PREFETCH_DIST_AVX512_64 320
#define XXH_PREFETCH_DIST_AVX512_128 320
#else // for gcc
#define XXH_PREFETCH_DIST_AVX512_64 640
#define XXH_PREFETCH_DIST_AVX512_128 512
#endif
/*
* XXH3_accumulate()
* Loops over XXH3_accumulate_512().
* Assumption: nbStripes will not overflow the secret size
*/
XXH_FORCE_INLINE void XXH3_accumulate(xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT input, const xxh_u8* XXH_RESTRICT secret, size_t nbStripes, XXH3_accWidth_e accWidth)
{
size_t n;
for (n = 0; n < nbStripes; n++)
{
const xxh_u8* const in = input + n * STRIPE_LEN;
#if (XXH_VECTOR == XXH_AVX512)
if (accWidth == XXH3_acc_64bits)
XXH_PREFETCH(in + XXH_PREFETCH_DIST_AVX512_64);
else
XXH_PREFETCH(in + XXH_PREFETCH_DIST_AVX512_128);
#else
XXH_PREFETCH(in + XXH_PREFETCH_DIST);
#endif
XXH3_accumulate_512(acc, in, secret + n * XXH_SECRET_CONSUME_RATE, accWidth);
}
}
XXH_FORCE_INLINE void XXH3_hashLong_internal_loop(
xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH3_accWidth_e accWidth)
{
size_t const nb_rounds = (secretSize - STRIPE_LEN) / XXH_SECRET_CONSUME_RATE;
size_t const block_len = STRIPE_LEN * nb_rounds;
size_t const nb_blocks = len / block_len;
size_t n;
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
for (n = 0; n < nb_blocks; n++)
{
XXH3_accumulate(acc, input + n * block_len, secret, nb_rounds, accWidth);
XXH3_scrambleAcc(acc, secret + secretSize - STRIPE_LEN);
}
/* last partial block */
XXH_ASSERT(len > STRIPE_LEN);
{
size_t const nbStripes = (len - (block_len * nb_blocks)) / STRIPE_LEN;
XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE));
XXH3_accumulate(acc, input + nb_blocks * block_len, secret, nbStripes, accWidth);
/* last stripe */
if (len & (STRIPE_LEN - 1))
{
const xxh_u8* const p = input + len - STRIPE_LEN;
/* Do not align on 8, so that the secret is different from the scrambler */
#define XXH_SECRET_LASTACC_START 7
XXH3_accumulate_512(acc, p, secret + secretSize - STRIPE_LEN - XXH_SECRET_LASTACC_START, accWidth);
}
}
}
XXH_FORCE_INLINE xxh_u64 XXH3_mix2Accs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret)
{
return XXH3_mul128_fold64(acc[0] ^ XXH_readLE64(secret), acc[1] ^ XXH_readLE64(secret + 8));
}
static XXH64_hash_t XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 start)
{
xxh_u64 result64 = start;
size_t i = 0;
for (i = 0; i < 4; i++)
{
result64 += XXH3_mix2Accs(acc + 2 * i, secret + 16 * i);
#if defined(__clang__) /* Clang */ \
&& (defined(__arm__) || defined(__thumb__)) /* ARMv7 */ \
&& (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
&& !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */
/*
* UGLY HACK:
* Prevent autovectorization on Clang ARMv7-a. Exact same problem as
* the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b.
* XXH3_64bits, len == 256, Snapdragon 835:
* without hack: 2063.7 MB/s
* with hack: 2560.7 MB/s
*/
__asm__("" : "+r"(result64));
#endif
}
return XXH3_avalanche(result64);
}
#define XXH3_INIT_ACC \
{ \
PRIME32_3, PRIME64_1, PRIME64_2, PRIME64_3, PRIME64_4, PRIME32_2, PRIME64_5, PRIME32_1 \
}
XXH_FORCE_INLINE XXH64_hash_t XXH3_hashLong_64b_internal(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize)
{
XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[ACC_NB] = XXH3_INIT_ACC;
XXH3_hashLong_internal_loop(acc, input, len, secret, secretSize, XXH3_acc_64bits);
/* converge into final hash */
XXH_STATIC_ASSERT(sizeof(acc) == 64);
/* do not align on 8, so that the secret is different from the accumulator */
#define XXH_SECRET_MERGEACCS_START 11
XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
return XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * PRIME64_1);
}
XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64)
{
if (!XXH_CPU_LITTLE_ENDIAN)
v64 = XXH_swap64(v64);
memcpy(dst, &v64, sizeof(v64));
}
/* XXH3_initCustomSecret() :
* destination `customSecret` is presumed allocated and same size as `kSecret`.
*/
XXH_FORCE_INLINE void XXH3_initCustomSecret(xxh_u8* XXH_RESTRICT customSecret, xxh_u64 seed64)
{
int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16;
int i;
/*
* We need a separate pointer for the hack below.
* Any decent compiler will optimize this out otherwise.
*/
const xxh_u8* kSecretPtr = kSecret;
XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
#if defined(__clang__) && defined(__aarch64__)
/*
* UGLY HACK:
* Clang generates a bunch of MOV/MOVK pairs for aarch64, and they are
* placed sequentially, in order, at the top of the unrolled loop.
*
* While MOVK is great for generating constants (2 cycles for a 64-bit
* constant compared to 4 cycles for LDR), long MOVK chains stall the
* integer pipelines:
* I L S
* MOVK
* MOVK
* MOVK
* MOVK
* ADD
* SUB STR
* STR
* By forcing loads from memory (as the asm line causes Clang to assume
* that kSecretPtr has been changed), the pipelines are used more efficiently:
* I L S
* LDR
* ADD LDR
* SUB STR
* STR
* XXH3_64bits_withSeed, len == 256, Snapdragon 835
* without hack: 2654.4 MB/s
* with hack: 3202.9 MB/s
*/
__asm__("" : "+r"(kSecretPtr));
#endif
/*
* Note: in debug mode, this overrides the asm optimization
* and Clang will emit MOVK chains again.
*/
XXH_ASSERT(kSecretPtr == kSecret);
for (i = 0; i < nbRounds; i++)
{
/*
* The asm hack causes Clang to assume that kSecretPtr aliases with
* customSecret, and on aarch64, this prevented LDP from merging two
* loads together for free. Putting the loads together before the stores
* properly generates LDP.
*/
xxh_u64 lo = XXH_readLE64(kSecretPtr + 16 * i) + seed64;
xxh_u64 hi = XXH_readLE64(kSecretPtr + 16 * i + 8) - seed64;
XXH_writeLE64(customSecret + 16 * i, lo);
XXH_writeLE64(customSecret + 16 * i + 8, hi);
}
}
/*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_defaultSecret(const xxh_u8* XXH_RESTRICT input, size_t len)
{
return XXH3_hashLong_64b_internal(input, len, kSecret, sizeof(kSecret));
}
/*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_withSecret(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize)
{
return XXH3_hashLong_64b_internal(input, len, secret, secretSize);
}
/*
* XXH3_hashLong_64b_withSeed():
* Generate a custom key based on alteration of default kSecret with the seed,
* and then use this key for long mode hashing.
*
* This operation is decently fast but nonetheless costs a little bit of time.
* Try to avoid it whenever possible (typically when seed==0).
*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_withSeed(const xxh_u8* input, size_t len, XXH64_hash_t seed)
{
XXH_ALIGN(8) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
if (seed == 0)
return XXH3_hashLong_64b_defaultSecret(input, len);
XXH3_initCustomSecret(secret, seed);
return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret));
}
/* === Public entry point === */
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* input, size_t len)
{
if (len <= 16)
return XXH3_len_0to16_64b((const xxh_u8*)input, len, kSecret, 0);
if (len <= 128)
return XXH3_len_17to128_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0);
return XXH3_hashLong_64b_defaultSecret((const xxh_u8*)input, len);
}
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
/*
* If an action is to be taken if `secret` conditions are not respected,
* it should be done here.
* For now, it's a contract pre-condition.
* Adding a check and a branch here would cost performance at every hash.
*/
if (len <= 16)
return XXH3_len_0to16_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, 0);
if (len <= 128)
return XXH3_len_17to128_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0);
return XXH3_hashLong_64b_withSecret((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize);
}
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
{
if (len <= 16)
return XXH3_len_0to16_64b((const xxh_u8*)input, len, kSecret, seed);
if (len <= 128)
return XXH3_len_17to128_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed);
return XXH3_hashLong_64b_withSeed((const xxh_u8*)input, len, seed);
}
/* === XXH3 streaming === */
/*
* Malloc's a pointer that is always aligned to align.
*
* This must be freed with `XXH_alignedFree()`.
*
* malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte
* alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2
* or on 32-bit, the 16 byte aligned loads in SSE2 and NEON.
*
* This underalignment previously caused a rather obvious crash which went
* completely unnoticed due to XXH3_createState() not actually being tested.
* Credit to RedSpah for noticing this bug.
*
* The alignment is done manually: Functions like posix_memalign or _mm_malloc
* are avoided: To maintain portability, we would have to write a fallback
* like this anyways, and besides, testing for the existence of library
* functions without relying on external build tools is impossible.
*
* The method is simple: Overallocate, manually align, and store the offset
* to the original behind the returned pointer.
*
* Align must be a power of 2 and 8 <= align <= 128.
*/
static void* XXH_alignedMalloc(size_t s, size_t align)
{
XXH_ASSERT(align <= 128 && align >= 8); /* range check */
XXH_ASSERT((align & (align - 1)) == 0); /* power of 2 */
XXH_ASSERT(s != 0 && s < (s + align)); /* empty/overflow */
{ /* Overallocate to make room for manual realignment and an offset byte */
xxh_u8* base = (xxh_u8*)XXH_malloc(s + align);
if (base != NULL)
{
/*
* Get the offset needed to align this pointer.
*
* Even if the returned pointer is aligned, there will always be
* at least one byte to store the offset to the original pointer.
*/
size_t offset = align - ((size_t)base & (align - 1)); /* base % align */
/* Add the offset for the now-aligned pointer */
xxh_u8* ptr = base + offset;
XXH_ASSERT((size_t)ptr % align == 0);
/* Store the offset immediately before the returned pointer. */
ptr[-1] = (xxh_u8)offset;
return ptr;
}
return NULL;
}
}
/*
* Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass
* normal malloc'd pointers, XXH_alignedMalloc has a specific data layout.
*/
static void XXH_alignedFree(void* p)
{
if (p != NULL)
{
xxh_u8* ptr = (xxh_u8*)p;
/* Get the offset byte we added in XXH_malloc. */
xxh_u8 offset = ptr[-1];
/* Free the original malloc'd pointer */
xxh_u8* base = ptr - offset;
XXH_free(base);
}
}
XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void) { return (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64); }
XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr)
{
XXH_alignedFree(statePtr);
return XXH_OK;
}
XXH_PUBLIC_API void XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state) { memcpy(dst_state, src_state, sizeof(*dst_state)); }
static void XXH3_64bits_reset_internal(XXH3_state_t* statePtr, XXH64_hash_t seed, const xxh_u8* secret, size_t secretSize)
{
XXH_ASSERT(statePtr != NULL);
memset(statePtr, 0, sizeof(*statePtr));
statePtr->acc[0] = PRIME32_3;
statePtr->acc[1] = PRIME64_1;
statePtr->acc[2] = PRIME64_2;
statePtr->acc[3] = PRIME64_3;
statePtr->acc[4] = PRIME64_4;
statePtr->acc[5] = PRIME32_2;
statePtr->acc[6] = PRIME64_5;
statePtr->acc[7] = PRIME32_1;
statePtr->seed = seed;
XXH_ASSERT(secret != NULL);
statePtr->secret = secret;
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
statePtr->secretLimit = (XXH32_hash_t)(secretSize - STRIPE_LEN);
statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE;
}
XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH3_state_t* statePtr)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_64bits_reset_internal(statePtr, 0, kSecret, XXH_SECRET_DEFAULT_SIZE);
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_64bits_reset_internal(statePtr, 0, (const xxh_u8*)secret, secretSize);
if (secret == NULL)
return XXH_ERROR;
if (secretSize < XXH3_SECRET_SIZE_MIN)
return XXH_ERROR;
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_64bits_reset_internal(statePtr, seed, kSecret, XXH_SECRET_DEFAULT_SIZE);
XXH3_initCustomSecret(statePtr->customSecret, seed);
statePtr->secret = statePtr->customSecret;
return XXH_OK;
}
XXH_FORCE_INLINE void XXH3_consumeStripes(xxh_u64* acc,
XXH32_hash_t* nbStripesSoFarPtr,
XXH32_hash_t nbStripesPerBlock,
const xxh_u8* input,
size_t totalStripes,
const xxh_u8* secret,
size_t secretLimit,
XXH3_accWidth_e accWidth)
{
XXH_ASSERT(*nbStripesSoFarPtr < nbStripesPerBlock);
if (nbStripesPerBlock - *nbStripesSoFarPtr <= totalStripes)
{
/* need a scrambling operation */
size_t const nbStripes = nbStripesPerBlock - *nbStripesSoFarPtr;
XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripes, accWidth);
XXH3_scrambleAcc(acc, secret + secretLimit);
XXH3_accumulate(acc, input + nbStripes * STRIPE_LEN, secret, totalStripes - nbStripes, accWidth);
*nbStripesSoFarPtr = (XXH32_hash_t)(totalStripes - nbStripes);
}
else
{
XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, totalStripes, accWidth);
*nbStripesSoFarPtr += (XXH32_hash_t)totalStripes;
}
}
/*
* Both XXH3_64bits_update and XXH3_128bits_update use this routine.
*/
XXH_FORCE_INLINE XXH_errorcode XXH3_update(XXH3_state_t* state, const xxh_u8* input, size_t len, XXH3_accWidth_e accWidth)
{
if (input == NULL)
#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER >= 1)
return XXH_OK;
#else
return XXH_ERROR;
#endif
{
const xxh_u8* const bEnd = input + len;
state->totalLen += len;
if (state->bufferedSize + len <= XXH3_INTERNALBUFFER_SIZE)
{ /* fill in tmp buffer */
XXH_memcpy(state->buffer + state->bufferedSize, input, len);
state->bufferedSize += (XXH32_hash_t)len;
return XXH_OK;
}
/* input is now > XXH3_INTERNALBUFFER_SIZE */
#define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / STRIPE_LEN)
XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % STRIPE_LEN == 0); /* clean multiple */
/*
* There is some input left inside the internal buffer.
* Fill it, then consume it.
*/
if (state->bufferedSize)
{
size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize;
XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize);
input += loadSize;
XXH3_consumeStripes(state->acc, &state->nbStripesSoFar, state->nbStripesPerBlock, state->buffer, XXH3_INTERNALBUFFER_STRIPES,
state->secret, state->secretLimit, accWidth);
state->bufferedSize = 0;
}
/* Consume input by full buffer quantities */
if (input + XXH3_INTERNALBUFFER_SIZE <= bEnd)
{
const xxh_u8* const limit = bEnd - XXH3_INTERNALBUFFER_SIZE;
do
{
XXH3_consumeStripes(state->acc, &state->nbStripesSoFar, state->nbStripesPerBlock, input, XXH3_INTERNALBUFFER_STRIPES, state->secret,
state->secretLimit, accWidth);
input += XXH3_INTERNALBUFFER_SIZE;
} while (input <= limit);
}
if (input < bEnd)
{ /* Some remaining input: buffer it */
XXH_memcpy(state->buffer, input, (size_t)(bEnd - input));
state->bufferedSize = (XXH32_hash_t)(bEnd - input);
}
}
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update(XXH3_state_t* state, const void* input, size_t len)
{
return XXH3_update(state, (const xxh_u8*)input, len, XXH3_acc_64bits);
}
XXH_FORCE_INLINE void XXH3_digest_long(XXH64_hash_t* acc, const XXH3_state_t* state, XXH3_accWidth_e accWidth)
{
/*
* Digest on a local copy. This way, the state remains unaltered, and it can
* continue ingesting more input afterwards.
*/
memcpy(acc, state->acc, sizeof(state->acc));
if (state->bufferedSize >= STRIPE_LEN)
{
size_t const totalNbStripes = state->bufferedSize / STRIPE_LEN;
XXH32_hash_t nbStripesSoFar = state->nbStripesSoFar;
XXH3_consumeStripes(acc, &nbStripesSoFar, state->nbStripesPerBlock, state->buffer, totalNbStripes, state->secret, state->secretLimit, accWidth);
if (state->bufferedSize % STRIPE_LEN)
{ /* one last partial stripe */
XXH3_accumulate_512(acc, state->buffer + state->bufferedSize - STRIPE_LEN, state->secret + state->secretLimit - XXH_SECRET_LASTACC_START, accWidth);
}
}
else
{ /* bufferedSize < STRIPE_LEN */
if (state->bufferedSize)
{ /* one last stripe */
xxh_u8 lastStripe[STRIPE_LEN];
size_t const catchupSize = STRIPE_LEN - state->bufferedSize;
memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize);
memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize);
XXH3_accumulate_512(acc, lastStripe, state->secret + state->secretLimit - XXH_SECRET_LASTACC_START, accWidth);
}
}
}
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest(const XXH3_state_t* state)
{
if (state->totalLen > XXH3_MIDSIZE_MAX)
{
XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[ACC_NB];
XXH3_digest_long(acc, state, XXH3_acc_64bits);
return XXH3_mergeAccs(acc, state->secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)state->totalLen * PRIME64_1);
}
/* len <= XXH3_MIDSIZE_MAX: short code */
if (state->seed)
return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen), state->secret, state->secretLimit + STRIPE_LEN);
}
/* ==========================================
* XXH3 128 bits (a.k.a XXH128)
* ==========================================
* XXH3's 128-bit variant has better mixing and strength than the 64-bit variant,
* even without counting the significantly larger output size.
*
* For example, extra steps are taken to avoid the seed-dependent collisions
* in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B).
*
* This strength naturally comes at the cost of some speed, especially on short
* lengths. Note that longer hashes are about as fast as the 64-bit version
* due to it using only a slight modification of the 64-bit loop.
*
* XXH128 is also more oriented towards 64-bit machines. It is still extremely
* fast for a _128-bit_ hash on 32-bit (it usually clears XXH64).
*/
XXH_FORCE_INLINE XXH128_hash_t XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
/* A doubled version of 1to3_64b with different constants. */
XXH_ASSERT(input != NULL);
XXH_ASSERT(1 <= len && len <= 3);
XXH_ASSERT(secret != NULL);
/*
* len = 1: combinedl = { input[0], 0x01, input[0], input[0] }
* len = 2: combinedl = { input[1], 0x02, input[0], input[1] }
* len = 3: combinedl = { input[2], 0x03, input[0], input[1] }
*/
{
xxh_u8 const c1 = input[0];
xxh_u8 const c2 = input[len >> 1];
xxh_u8 const c3 = input[len - 1];
xxh_u32 const combinedl = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8);
xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13);
xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed;
xxh_u64 const bitfliph = (XXH_readLE32(secret + 8) ^ XXH_readLE32(secret + 12)) - seed;
xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl;
xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph;
xxh_u64 const mixedl = keyed_lo * PRIME64_1;
xxh_u64 const mixedh = keyed_hi * PRIME64_5;
XXH128_hash_t h128;
h128.low64 = XXH3_avalanche(mixedl);
h128.high64 = XXH3_avalanche(mixedh);
return h128;
}
}
XXH_FORCE_INLINE XXH128_hash_t XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(input != NULL);
XXH_ASSERT(secret != NULL);
XXH_ASSERT(4 <= len && len <= 8);
seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32;
{
xxh_u32 const input_lo = XXH_readLE32(input);
xxh_u32 const input_hi = XXH_readLE32(input + len - 4);
xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32);
xxh_u64 const bitflip = (XXH_readLE64(secret + 16) ^ XXH_readLE64(secret + 24)) + seed;
xxh_u64 const keyed = input_64 ^ bitflip;
/* Shift len to the left to ensure it is even, this avoids even multiplies. */
XXH128_hash_t m128 = XXH_mult64to128(keyed, PRIME64_1 + (len << 2));
m128.high64 += (m128.low64 << 1);
m128.low64 ^= (m128.high64 >> 3);
m128.low64 = XXH_xorshift64(m128.low64, 35);
m128.low64 *= 0x9FB21C651E98DF25ULL;
m128.low64 = XXH_xorshift64(m128.low64, 28);
m128.high64 = XXH3_avalanche(m128.high64);
return m128;
}
}
XXH_FORCE_INLINE XXH128_hash_t XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(input != NULL);
XXH_ASSERT(secret != NULL);
XXH_ASSERT(9 <= len && len <= 16);
{
xxh_u64 const bitflipl = (XXH_readLE64(secret + 32) ^ XXH_readLE64(secret + 40)) - seed;
xxh_u64 const bitfliph = (XXH_readLE64(secret + 48) ^ XXH_readLE64(secret + 56)) + seed;
xxh_u64 const input_lo = XXH_readLE64(input);
xxh_u64 input_hi = XXH_readLE64(input + len - 8);
XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, PRIME64_1);
/*
* Put len in the middle of m128 to ensure that the length gets mixed to
* both the low and high bits in the 128x64 multiply below.
*/
m128.low64 += (xxh_u64)(len - 1) << 54;
input_hi ^= bitfliph;
/*
* Add the high 32 bits of input_hi to the high 32 bits of m128, then
* add the long product of the low 32 bits of input_hi and PRIME32_2 to
* the high 64 bits of m128.
*
* The best approach to this operation is different on 32-bit and 64-bit.
*/
if (sizeof(void*) < sizeof(xxh_u64))
{ /* 32-bit */
/*
* 32-bit optimized version, which is more readable.
*
* On 32-bit, it removes an ADC and delays a dependency between the two
* halves of m128.high64, but it generates an extra mask on 64-bit.
*/
m128.high64 += (input_hi & 0xFFFFFFFF00000000) + XXH_mult32to64((xxh_u32)input_hi, PRIME32_2);
}
else
{
/*
* 64-bit optimized (albeit more confusing) version.
*
* Uses some properties of addition and multiplication to remove the mask:
*
* Let:
* a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF)
* b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000)
* c = PRIME32_2
*
* a + (b * c)
* Inverse Property: x + y - x == y
* a + (b * (1 + c - 1))
* Distributive Property: x * (y + z) == (x * y) + (x * z)
* a + (b * 1) + (b * (c - 1))
* Identity Property: x * 1 == x
* a + b + (b * (c - 1))
*
* Substitute a, b, and c:
* input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (PRIME32_2 - 1))
*
* Since input_hi.hi + input_hi.lo == input_hi, we get this:
* input_hi + ((xxh_u64)input_hi.lo * (PRIME32_2 - 1))
*/
m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, PRIME32_2 - 1);
}
/* m128 ^= XXH_swap64(m128 >> 64); */
m128.low64 ^= XXH_swap64(m128.high64);
{ /* 128x64 multiply: h128 = m128 * PRIME64_2; */
XXH128_hash_t h128 = XXH_mult64to128(m128.low64, PRIME64_2);
h128.high64 += m128.high64 * PRIME64_2;
h128.low64 = XXH3_avalanche(h128.low64);
h128.high64 = XXH3_avalanche(h128.high64);
return h128;
}
}
}
/*
* Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN
*/
XXH_FORCE_INLINE XXH128_hash_t XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
{
XXH_ASSERT(len <= 16);
{
if (len > 8)
return XXH3_len_9to16_128b(input, len, secret, seed);
if (len >= 4)
return XXH3_len_4to8_128b(input, len, secret, seed);
if (len)
return XXH3_len_1to3_128b(input, len, secret, seed);
{
XXH128_hash_t h128;
xxh_u64 const bitflipl = XXH_readLE64(secret + 64) ^ XXH_readLE64(secret + 72);
xxh_u64 const bitfliph = XXH_readLE64(secret + 80) ^ XXH_readLE64(secret + 88);
h128.low64 = XXH3_avalanche((PRIME64_1 + seed) ^ bitflipl);
h128.high64 = XXH3_avalanche((PRIME64_2 - seed) ^ bitfliph);
return h128;
}
}
}
/*
* A bit slower than XXH3_mix16B, but handles multiply by zero better.
*/
XXH_FORCE_INLINE XXH128_hash_t XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2, const xxh_u8* secret, XXH64_hash_t seed)
{
acc.low64 += XXH3_mix16B(input_1, secret + 0, seed);
acc.low64 ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8);
acc.high64 += XXH3_mix16B(input_2, secret + 16, seed);
acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8);
return acc;
}
XXH_FORCE_INLINE XXH128_hash_t XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
(void)secretSize;
XXH_ASSERT(16 < len && len <= 128);
{
XXH128_hash_t acc;
acc.low64 = len * PRIME64_1;
acc.high64 = 0;
if (len > 32)
{
if (len > 64)
{
if (len > 96)
{
acc = XXH128_mix32B(acc, input + 48, input + len - 64, secret + 96, seed);
}
acc = XXH128_mix32B(acc, input + 32, input + len - 48, secret + 64, seed);
}
acc = XXH128_mix32B(acc, input + 16, input + len - 32, secret + 32, seed);
}
acc = XXH128_mix32B(acc, input, input + len - 16, secret, seed);
{
XXH128_hash_t h128;
h128.low64 = acc.low64 + acc.high64;
h128.high64 = (acc.low64 * PRIME64_1) + (acc.high64 * PRIME64_4) + ((len - seed) * PRIME64_2);
h128.low64 = XXH3_avalanche(h128.low64);
h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
return h128;
}
}
}
XXH_NO_INLINE XXH128_hash_t XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
(void)secretSize;
XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
{
XXH128_hash_t acc;
int const nbRounds = (int)len / 32;
int i;
acc.low64 = len * PRIME64_1;
acc.high64 = 0;
for (i = 0; i < 4; i++)
{
acc = XXH128_mix32B(acc, input + (32 * i), input + (32 * i) + 16, secret + (32 * i), seed);
}
acc.low64 = XXH3_avalanche(acc.low64);
acc.high64 = XXH3_avalanche(acc.high64);
XXH_ASSERT(nbRounds >= 4);
for (i = 4; i < nbRounds; i++)
{
acc = XXH128_mix32B(acc, input + (32 * i), input + (32 * i) + 16, secret + XXH3_MIDSIZE_STARTOFFSET + (32 * (i - 4)), seed);
}
/* last bytes */
acc = XXH128_mix32B(acc, input + len - 16, input + len - 32, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16, 0ULL - seed);
{
XXH128_hash_t h128;
h128.low64 = acc.low64 + acc.high64;
h128.high64 = (acc.low64 * PRIME64_1) + (acc.high64 * PRIME64_4) + ((len - seed) * PRIME64_2);
h128.low64 = XXH3_avalanche(h128.low64);
h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64);
return h128;
}
}
}
XXH_FORCE_INLINE XXH128_hash_t XXH3_hashLong_128b_internal(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize)
{
XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[ACC_NB] = XXH3_INIT_ACC;
XXH3_hashLong_internal_loop(acc, input, len, secret, secretSize, XXH3_acc_128bits);
/* converge into final hash */
XXH_STATIC_ASSERT(sizeof(acc) == 64);
XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
{
XXH128_hash_t h128;
h128.low64 = XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * PRIME64_1);
h128.high64 = XXH3_mergeAccs(acc, secret + secretSize - sizeof(acc) - XXH_SECRET_MERGEACCS_START, ~((xxh_u64)len * PRIME64_2));
return h128;
}
}
/*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_defaultSecret(const xxh_u8* input, size_t len)
{
return XXH3_hashLong_128b_internal(input, len, kSecret, sizeof(kSecret));
}
/*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_withSecret(const xxh_u8* input, size_t len, const xxh_u8* secret, size_t secretSize)
{
return XXH3_hashLong_128b_internal(input, len, secret, secretSize);
}
/*
* It's important for performance that XXH3_hashLong is not inlined. Not sure
* why (uop cache maybe?), but the difference is large and easily measurable.
*/
XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_withSeed(const xxh_u8* input, size_t len, XXH64_hash_t seed)
{
XXH_ALIGN(8) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
if (seed == 0)
return XXH3_hashLong_128b_defaultSecret(input, len);
XXH3_initCustomSecret(secret, seed);
return XXH3_hashLong_128b_internal(input, len, secret, sizeof(secret));
}
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* input, size_t len)
{
if (len <= 16)
return XXH3_len_0to16_128b((const xxh_u8*)input, len, kSecret, 0);
if (len <= 128)
return XXH3_len_17to128_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0);
return XXH3_hashLong_128b_defaultSecret((const xxh_u8*)input, len);
}
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
{
XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
/*
* If an action is to be taken if `secret` conditions are not respected,
* it should be done here.
* For now, it's a contract pre-condition.
* Adding a check and a branch here would cost performance at every hash.
*/
if (len <= 16)
return XXH3_len_0to16_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, 0);
if (len <= 128)
return XXH3_len_17to128_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0);
return XXH3_hashLong_128b_withSecret((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize);
}
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
{
if (len <= 16)
return XXH3_len_0to16_128b((const xxh_u8*)input, len, kSecret, seed);
if (len <= 128)
return XXH3_len_17to128_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed);
if (len <= XXH3_MIDSIZE_MAX)
return XXH3_len_129to240_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed);
return XXH3_hashLong_128b_withSeed((const xxh_u8*)input, len, seed);
}
XXH_PUBLIC_API XXH128_hash_t XXH128(const void* input, size_t len, XXH64_hash_t seed) { return XXH3_128bits_withSeed(input, len, seed); }
/* === XXH3 128-bit streaming === */
/*
* All the functions are actually the same as for 64-bit streaming variant.
* The only difference is the finalizatiom routine.
*/
static void XXH3_128bits_reset_internal(XXH3_state_t* statePtr, XXH64_hash_t seed, const xxh_u8* secret, size_t secretSize)
{
XXH3_64bits_reset_internal(statePtr, seed, secret, secretSize);
}
XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH3_state_t* statePtr)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_128bits_reset_internal(statePtr, 0, kSecret, XXH_SECRET_DEFAULT_SIZE);
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_128bits_reset_internal(statePtr, 0, (const xxh_u8*)secret, secretSize);
if (secret == NULL)
return XXH_ERROR;
if (secretSize < XXH3_SECRET_SIZE_MIN)
return XXH_ERROR;
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
{
if (statePtr == NULL)
return XXH_ERROR;
XXH3_128bits_reset_internal(statePtr, seed, kSecret, XXH_SECRET_DEFAULT_SIZE);
XXH3_initCustomSecret(statePtr->customSecret, seed);
statePtr->secret = statePtr->customSecret;
return XXH_OK;
}
XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update(XXH3_state_t* state, const void* input, size_t len)
{
return XXH3_update(state, (const xxh_u8*)input, len, XXH3_acc_128bits);
}
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest(const XXH3_state_t* state)
{
if (state->totalLen > XXH3_MIDSIZE_MAX)
{
XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[ACC_NB];
XXH3_digest_long(acc, state, XXH3_acc_128bits);
XXH_ASSERT(state->secretLimit + STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START);
{
XXH128_hash_t h128;
h128.low64 = XXH3_mergeAccs(acc, state->secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)state->totalLen * PRIME64_1);
h128.high64 = XXH3_mergeAccs(acc, state->secret + state->secretLimit + STRIPE_LEN - sizeof(acc) - XXH_SECRET_MERGEACCS_START,
~((xxh_u64)state->totalLen * PRIME64_2));
return h128;
}
}
/* len <= XXH3_MIDSIZE_MAX : short code */
if (state->seed)
return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed);
return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen), state->secret, state->secretLimit + STRIPE_LEN);
}
/* 128-bit utility functions */
#include <string.h> /* memcmp, memcpy */
/* return : 1 is equal, 0 if different */
XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2)
{
/* note : XXH128_hash_t is compact, it has no padding byte */
return !(memcmp(&h1, &h2, sizeof(h1)));
}
/* This prototype is compatible with stdlib's qsort().
* return : >0 if *h128_1 > *h128_2
* <0 if *h128_1 < *h128_2
* =0 if *h128_1 == *h128_2 */
XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2)
{
XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1;
XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2;
int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64);
/* note : bets that, in most cases, hash values are different */
if (hcmp)
return hcmp;
return (h1.low64 > h2.low64) - (h2.low64 > h1.low64);
}
/*====== Canonical representation ======*/
XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash)
{
XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t));
if (XXH_CPU_LITTLE_ENDIAN)
{
hash.high64 = XXH_swap64(hash.high64);
hash.low64 = XXH_swap64(hash.low64);
}
memcpy(dst, &hash.high64, sizeof(hash.high64));
memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64));
}
XXH_PUBLIC_API XXH128_hash_t XXH128_hashFromCanonical(const XXH128_canonical_t* src)
{
XXH128_hash_t h;
h.high64 = XXH_readBE64(src);
h.low64 = XXH_readBE64(src->digest + 8);
return h;
}
/* Pop our optimization override from above */
#if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
&& defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
&& defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
#pragma GCC pop_options
#endif
#endif /* XXH3_H_1397135465 */
| 40.071248
| 177
| 0.636367
|
rovedit
|
94e5183afe2e08634bf2985a20f996ef87d685d8
| 1,946
|
cpp
|
C++
|
cdm/cpp/patient/conditions/SEChronicVentricularSystolicDysfunction.cpp
|
isuhao/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | 2
|
2019-03-15T04:20:11.000Z
|
2019-05-02T18:39:45.000Z
|
cdm/cpp/patient/conditions/SEChronicVentricularSystolicDysfunction.cpp
|
sinmx/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | null | null | null |
cdm/cpp/patient/conditions/SEChronicVentricularSystolicDysfunction.cpp
|
sinmx/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | 1
|
2018-09-22T04:10:37.000Z
|
2018-09-22T04:10:37.000Z
|
/* Distributed under the Apache License, Version 2.0.
See accompanying NOTICE file for details.*/
#include "stdafx.h"
#include "patient/conditions/SEChronicVentricularSystolicDysfunction.h"
PROTO_PUSH
#include "bind/cdm/PatientConditions.pb.h"
PROTO_POP
SEChronicVentricularSystolicDysfunction::SEChronicVentricularSystolicDysfunction() : SEChronicHeartFailure()
{
}
SEChronicVentricularSystolicDysfunction::~SEChronicVentricularSystolicDysfunction()
{
Clear();
}
void SEChronicVentricularSystolicDysfunction::Clear()
{
SEChronicHeartFailure::Clear();
}
bool SEChronicVentricularSystolicDysfunction::IsValid() const
{
return SEChronicHeartFailure::IsValid();
}
void SEChronicVentricularSystolicDysfunction::Load(const cdm::ChronicVentricularSystolicDysfunctionData& src, SEChronicVentricularSystolicDysfunction& dst)
{
SEChronicVentricularSystolicDysfunction::Serialize(src, dst);
}
void SEChronicVentricularSystolicDysfunction::Serialize(const cdm::ChronicVentricularSystolicDysfunctionData& src, SEChronicVentricularSystolicDysfunction& dst)
{
SEPatientCondition::Serialize(src.patientcondition(), dst);
}
cdm::ChronicVentricularSystolicDysfunctionData* SEChronicVentricularSystolicDysfunction::Unload(const SEChronicVentricularSystolicDysfunction& src)
{
cdm::ChronicVentricularSystolicDysfunctionData* dst = new cdm::ChronicVentricularSystolicDysfunctionData();
SEChronicVentricularSystolicDysfunction::Serialize(src, *dst);
return dst;
}
void SEChronicVentricularSystolicDysfunction::Serialize(const SEChronicVentricularSystolicDysfunction& src, cdm::ChronicVentricularSystolicDysfunctionData& dst)
{
SEPatientCondition::Serialize(src, *dst.mutable_patientcondition());
}
void SEChronicVentricularSystolicDysfunction::ToString(std::ostream &str) const
{
str << "Patient Condition : Ventricular Systolic Dysfunction Heart Failure";
if(HasComment())
str<<"\n\tComment: "<<m_Comment;
str << std::flush;
}
| 35.381818
| 160
| 0.828366
|
isuhao
|
94efd0d68247f41cfe2aca7fc2265f8b590afac7
| 3,063
|
cpp
|
C++
|
GrowtopiaServer/resource/server/GamePacket.cpp
|
LinkProfitSG/GTPS
|
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
|
[
"Apache-2.0"
] | 2
|
2021-06-08T08:17:56.000Z
|
2021-12-02T20:41:28.000Z
|
GrowtopiaServer/resource/server/GamePacket.cpp
|
LinkProfitSG/GTPS
|
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
|
[
"Apache-2.0"
] | 1
|
2021-12-02T20:46:47.000Z
|
2021-12-02T20:52:40.000Z
|
GrowtopiaServer/resource/server/GamePacket.cpp
|
LinkProfitSG/GTPS
|
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
|
[
"Apache-2.0"
] | 3
|
2021-07-27T21:30:35.000Z
|
2021-10-07T07:52:27.000Z
|
#pragma warning (disable : 4244)
#include "../../Server.hpp"
using namespace std;
GamePacket::~GamePacket() { delete[] data_; }
GamePacket::GamePacket(int delay, int netId) {
len_ = 61;
int messageType = 0x4, packetType = 0x1, charState = 0x8;
memset(data_, 0, 61);
memcpy(data_, &messageType, 4);
memcpy(data_ + 4, &packetType, 4);
memcpy(data_ + 8, &netId, 4);
memcpy(data_ + 16, &charState, 4);
memcpy(data_ + 24, &delay, 4);
}
GamePacket& GamePacket::extend(string str) {
unsigned char* data = new unsigned char[len_ + 2 + str.length() + 4];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x2;
unsigned long long len = str.length();
memcpy(data + len_ + 2, &len, 4);
memcpy(data + len_ + 6, str.data(), len);
len_ += 2 + len + 4;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::extend(int i) {
unsigned char* data = new unsigned char[len_ + 2 + 4];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x9;
memcpy(data + len_ + 2, &i, 4);
len_ += 2 + 4;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::extend(unsigned u) {
unsigned char* data = new unsigned char[len_ + 2 + 4];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x5;
memcpy(data + len_ + 2, &u, 4);
len_ += 2 + 4;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::extend(float f) {
unsigned char* data = new unsigned char[len_ + 2 + 4];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x1;
memcpy(data + len_ + 2, &f, 4);
len_ += 2 + 4;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::extend(float f, float f2) {
unsigned char* data = new unsigned char[len_ + 2 + 8];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x3;
memcpy(data + len_ + 2, &f, 4);
memcpy(data + len_ + 6, &f2, 4);
len_ += 2 + 8;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::extend(float f, float f2, float f3) {
unsigned char* data = new unsigned char[len_ + 2 + 12];
memcpy(data, this->data_, len_);
delete[] this->data_;
this->data_ = data;
data[len_] = index_;
data[len_ + 1] = 0x4;
memcpy(data + len_ + 2, &f, 4);
memcpy(data + len_ + 6, &f2, 4);
memcpy(data + len_ + 10, &f3, 4);
len_ += 2 + 12;
index_++;
data_[60] = static_cast<unsigned char>(index_);
return *this;
}
GamePacket& GamePacket::sendData(ENetPeer* peer) {
ENetPacket* packet = enet_packet_create(data_, len_, 1);
enet_peer_send(peer, 0, packet);
return *this;
}
| 25.525
| 71
| 0.615736
|
LinkProfitSG
|
94efd14de0824c213675483ff1b8d37b46fb5b2e
| 6,774
|
cpp
|
C++
|
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_AssociatedPowerManagementService.cpp
|
rgl/lms
|
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
|
[
"Apache-2.0"
] | 18
|
2019-04-17T10:43:35.000Z
|
2022-03-22T22:30:39.000Z
|
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_AssociatedPowerManagementService.cpp
|
rgl/lms
|
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
|
[
"Apache-2.0"
] | 9
|
2019-10-03T15:29:51.000Z
|
2021-12-27T14:03:33.000Z
|
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_AssociatedPowerManagementService.cpp
|
isabella232/lms
|
50d16f81b49aba6007388c001e8137352c5eb42e
|
[
"Apache-2.0"
] | 8
|
2019-06-13T23:30:50.000Z
|
2021-06-25T15:51:59.000Z
|
//----------------------------------------------------------------------------
//
// Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved.
//
// File: CIM_AssociatedPowerManagementService.cpp
//
// Contents: The association between a Managed System Element and its power management service.
//
// This file was automatically generated from CIM_AssociatedPowerManagementService.mof, version: 2.24.1
//
//----------------------------------------------------------------------------
#include "CIM_AssociatedPowerManagementService.h"
namespace Intel
{
namespace Manageability
{
namespace Cim
{
namespace Typed
{
const CimFieldAttribute CIM_AssociatedPowerManagementService::_metadata[] = {
{"ServiceProvided", true, false, true },
{"PowerState", false, false, false },
{"OtherPowerState", false, false, false },
{"RequestedPowerState", false, false, false },
{"OtherRequestedPowerState", false, false, false },
{"PowerOnTime", false, false, false },
{"AvailableRequestedPowerStates", false, false, false },
{"TransitioningToPowerState", false, false, false },
};
// class fields
const unsigned short CIM_AssociatedPowerManagementService::PowerState() const
{
unsigned short ret = 0;
TypeConverter::StringToType(GetField("PowerState"), ret);
return ret;
}
void CIM_AssociatedPowerManagementService::PowerState(const unsigned short value)
{
SetOrAddField("PowerState", TypeConverter::TypeToString(value));
}
bool CIM_AssociatedPowerManagementService::PowerStateExists() const
{
return ContainsField("PowerState");
}
void CIM_AssociatedPowerManagementService::RemovePowerState()
{
RemoveField("PowerState");
}
const string CIM_AssociatedPowerManagementService::OtherPowerState() const
{
return GetField("OtherPowerState")[0];
}
void CIM_AssociatedPowerManagementService::OtherPowerState(const string &value)
{
SetOrAddField("OtherPowerState", value);
}
bool CIM_AssociatedPowerManagementService::OtherPowerStateExists() const
{
return ContainsField("OtherPowerState");
}
void CIM_AssociatedPowerManagementService::RemoveOtherPowerState()
{
RemoveField("OtherPowerState");
}
const unsigned short CIM_AssociatedPowerManagementService::RequestedPowerState() const
{
unsigned short ret = 0;
TypeConverter::StringToType(GetField("RequestedPowerState"), ret);
return ret;
}
void CIM_AssociatedPowerManagementService::RequestedPowerState(const unsigned short value)
{
SetOrAddField("RequestedPowerState", TypeConverter::TypeToString(value));
}
bool CIM_AssociatedPowerManagementService::RequestedPowerStateExists() const
{
return ContainsField("RequestedPowerState");
}
void CIM_AssociatedPowerManagementService::RemoveRequestedPowerState()
{
RemoveField("RequestedPowerState");
}
const string CIM_AssociatedPowerManagementService::OtherRequestedPowerState() const
{
return GetField("OtherRequestedPowerState")[0];
}
void CIM_AssociatedPowerManagementService::OtherRequestedPowerState(const string &value)
{
SetOrAddField("OtherRequestedPowerState", value);
}
bool CIM_AssociatedPowerManagementService::OtherRequestedPowerStateExists() const
{
return ContainsField("OtherRequestedPowerState");
}
void CIM_AssociatedPowerManagementService::RemoveOtherRequestedPowerState()
{
RemoveField("OtherRequestedPowerState");
}
const CimDateTime CIM_AssociatedPowerManagementService::PowerOnTime() const
{
CimDateTime ret;
TypeConverter::StringToType(GetField("PowerOnTime"), ret);
return ret;
}
void CIM_AssociatedPowerManagementService::PowerOnTime(const CimDateTime &value)
{
SetOrAddField("PowerOnTime", TypeConverter::TypeToString(value));
}
bool CIM_AssociatedPowerManagementService::PowerOnTimeExists() const
{
return ContainsField("PowerOnTime");
}
void CIM_AssociatedPowerManagementService::RemovePowerOnTime()
{
RemoveField("PowerOnTime");
}
const vector<unsigned short> CIM_AssociatedPowerManagementService::AvailableRequestedPowerStates() const
{
vector<unsigned short> ret;
TypeConverter::StringToType(GetField("AvailableRequestedPowerStates"), ret);
return ret;
}
void CIM_AssociatedPowerManagementService::AvailableRequestedPowerStates(const vector<unsigned short> &value)
{
SetOrAddField("AvailableRequestedPowerStates", TypeConverter::TypeToString(value));
}
bool CIM_AssociatedPowerManagementService::AvailableRequestedPowerStatesExists() const
{
return ContainsField("AvailableRequestedPowerStates");
}
void CIM_AssociatedPowerManagementService::RemoveAvailableRequestedPowerStates()
{
RemoveField("AvailableRequestedPowerStates");
}
const unsigned short CIM_AssociatedPowerManagementService::TransitioningToPowerState() const
{
unsigned short ret = 0;
TypeConverter::StringToType(GetField("TransitioningToPowerState"), ret);
return ret;
}
void CIM_AssociatedPowerManagementService::TransitioningToPowerState(const unsigned short value)
{
SetOrAddField("TransitioningToPowerState", TypeConverter::TypeToString(value));
}
bool CIM_AssociatedPowerManagementService::TransitioningToPowerStateExists() const
{
return ContainsField("TransitioningToPowerState");
}
void CIM_AssociatedPowerManagementService::RemoveTransitioningToPowerState()
{
RemoveField("TransitioningToPowerState");
}
CimBase *CIM_AssociatedPowerManagementService::CreateFromCimObject(const CimObject &object)
{
CIM_AssociatedPowerManagementService *ret = NULL;
if(object.ObjectType() != CLASS_NAME)
{
ret = new CimExtended<CIM_AssociatedPowerManagementService>(object);
}
else
{
ret = new CIM_AssociatedPowerManagementService(object);
}
return ret;
}
vector<shared_ptr<CIM_AssociatedPowerManagementService> > CIM_AssociatedPowerManagementService::Enumerate(ICimWsmanClient *client, const CimKeys &keys)
{
return CimBase::Enumerate<CIM_AssociatedPowerManagementService>(client, keys);
}
void CIM_AssociatedPowerManagementService::Delete(ICimWsmanClient *client, const CimKeys &keys)
{
CimBase::Delete(client, CLASS_URI, keys);
}
const vector<CimFieldAttribute> &CIM_AssociatedPowerManagementService::GetMetaData() const
{
return _classMetaData;
}
const string CIM_AssociatedPowerManagementService::CLASS_NAME = "CIM_AssociatedPowerManagementService";
const string CIM_AssociatedPowerManagementService::CLASS_URI = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_AssociatedPowerManagementService";
const string CIM_AssociatedPowerManagementService::CLASS_NS = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_AssociatedPowerManagementService";
const string CIM_AssociatedPowerManagementService::CLASS_NS_PREFIX = "AAs349";
CIMFRAMEWORK_API vector <CimFieldAttribute> CIM_AssociatedPowerManagementService::_classMetaData;
}
}
}
}
| 34.212121
| 153
| 0.780632
|
rgl
|
94f541c491108f4eaf9f02fa2ed97656cd9c91a5
| 4,997
|
hpp
|
C++
|
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#ifndef MultiPaneSpecular_H
#define MultiPaneSpecular_H
#include <memory>
#include <vector>
#include "WCECommon.hpp"
namespace FenestrationCommon
{
enum class Side;
enum class Property;
class CSeries;
} // namespace FenestrationCommon
namespace SingleLayerOptics
{
class CSpecularCell;
class SpecularLayer;
} // namespace SingleLayerOptics
namespace MultiLayerOptics
{
class CEquivalentLayerSingleComponentMW;
class CAbsorptancesMultiPane;
class CEquivalentLayerSingleComponentMWAngle
{
public:
CEquivalentLayerSingleComponentMWAngle(
const std::shared_ptr<CEquivalentLayerSingleComponentMW> & t_Layer,
const std::shared_ptr<CAbsorptancesMultiPane> & t_Abs,
double t_Angle);
double angle() const;
std::shared_ptr<CEquivalentLayerSingleComponentMW> layer() const;
std::shared_ptr<FenestrationCommon::CSeries>
getProperties(FenestrationCommon::Side t_Side,
FenestrationCommon::Property t_Property);
std::shared_ptr<FenestrationCommon::CSeries> Abs(size_t Index);
private:
std::shared_ptr<CEquivalentLayerSingleComponentMW> m_Layer;
std::shared_ptr<CAbsorptancesMultiPane> m_Abs;
double m_Angle;
};
// Handles equivalent properties of MultiLayerOptics glass consists only of specular layers
class CMultiPaneSpecular
{
public:
CMultiPaneSpecular( std::vector< double > const & t_CommonWavelength,
const std::shared_ptr< FenestrationCommon::CSeries > & t_SolarRadiation,
SingleLayerOptics::SpecularLayer & t_Layer );
void addLayer( SingleLayerOptics::SpecularLayer & t_Layer );
double getProperty(FenestrationCommon::Side t_Side,
FenestrationCommon::Property t_Property,
double t_Angle,
double minLambda,
double maxLambda,
FenestrationCommon::IntegrationType t_IntegrationType =
FenestrationCommon::IntegrationType::Trapezoidal,
double normalizationCoefficient = 1);
double
getHemisphericalProperty(FenestrationCommon::Side t_Side,
FenestrationCommon::Property t_Property,
const std::shared_ptr<const std::vector<double>> & t_Angles,
double minLambda,
double maxLambda,
FenestrationCommon::IntegrationType t_IntegrationType =
FenestrationCommon::IntegrationType::Trapezoidal,
double normalizationCoefficient = 1);
// Absorptances of each layer based on angle of incidence
double Abs(size_t Index,
double t_Angle,
double minLambda,
double maxLambda,
FenestrationCommon::IntegrationType t_IntegrationType =
FenestrationCommon::IntegrationType::Trapezoidal,
double normalizationCoefficient = 1);
// Hemispherical absorptances of each layer. Integration is performed over t_Angles.
double AbsHemispherical(size_t Index,
const std::shared_ptr<const std::vector<double>> & t_Angles,
double minLambda,
double maxLambda,
FenestrationCommon::IntegrationType t_IntegrationType =
FenestrationCommon::IntegrationType::Trapezoidal,
double normalizationCoefficient = 1);
private:
// Get correct angular object out of array and if object does not exists, then it just
// creates new one and stores it into array
std::shared_ptr<CEquivalentLayerSingleComponentMWAngle> getAngular(double t_Angle);
// creates equivalent layer properties for certain angle
std::shared_ptr<CEquivalentLayerSingleComponentMWAngle>
createNewAngular(double t_Angle);
// Contains all specular layers (cells) that are added to the model. This way program will
// be able to recalculate equivalent properties for any angle
std::vector<SingleLayerOptics::SpecularLayer> m_Layers;
std::vector<double> m_CommonWavelengths;
std::shared_ptr<FenestrationCommon::CSeries> m_SolarRadiation;
// Results for angle-properties std::pair. If same angle is required twice, then model will
// not calculate it twice. First it will search for results here and if results are not
// available, then it will perform calculation for given angle
std::vector<std::shared_ptr<CEquivalentLayerSingleComponentMWAngle>> m_EquivalentAngle;
};
} // namespace MultiLayerOptics
#endif
| 40.626016
| 99
| 0.634981
|
bakonyidani
|
94fa986787378cf10f900dae5321385b0539cb3d
| 1,041
|
cpp
|
C++
|
sources/Dwarf/AST/AstVariableReference.cpp
|
KonstantinTomashevich/dwarf-scripting-language
|
1cb7e2719ee66c77172d647f33052358dfe36be3
|
[
"MIT"
] | null | null | null |
sources/Dwarf/AST/AstVariableReference.cpp
|
KonstantinTomashevich/dwarf-scripting-language
|
1cb7e2719ee66c77172d647f33052358dfe36be3
|
[
"MIT"
] | null | null | null |
sources/Dwarf/AST/AstVariableReference.cpp
|
KonstantinTomashevich/dwarf-scripting-language
|
1cb7e2719ee66c77172d647f33052358dfe36be3
|
[
"MIT"
] | null | null | null |
#include "AstVariableReference.hpp"
#include <assert.h>
namespace Dwarf
{
AstVariableReference::AstVariableReference (std::string name, AstValue *provider) :
name_ (name),
provider_ (provider)
{
assert (!name_.empty ());
}
AstVariableReference::~AstVariableReference ()
{
delete provider_;
}
std::string AstVariableReference::GetName ()
{
return name_;
}
AstValue *AstVariableReference::GetProvider ()
{
return provider_;
}
std::string AstVariableReference::ToString (int addSpacesIndentation)
{
std::string result;
std::string indent = "";
if (addSpacesIndentation > 0)
for (int index = 0; index < addSpacesIndentation; index++)
indent += " ";
result += indent + "[variable reference ";
result += name_;
if (provider_)
{
result += "\n" + indent + "provider:\n";
result += provider_->ToString (addSpacesIndentation + 4) + "\n";
result += indent + "end of variable reference]";
}
else
result += "]";
return result;
}
}
| 20.82
| 83
| 0.634006
|
KonstantinTomashevich
|
94faee49b23fdc6a8c5ada686f4ce0c259f63930
| 2,879
|
hpp
|
C++
|
RoviSamplePlugin/src/SamplePlugin.hpp
|
balintmaci/RoVi_project
|
29a948aef0d7596e7ba6afab36016b494ba1132e
|
[
"Unlicense"
] | null | null | null |
RoviSamplePlugin/src/SamplePlugin.hpp
|
balintmaci/RoVi_project
|
29a948aef0d7596e7ba6afab36016b494ba1132e
|
[
"Unlicense"
] | null | null | null |
RoviSamplePlugin/src/SamplePlugin.hpp
|
balintmaci/RoVi_project
|
29a948aef0d7596e7ba6afab36016b494ba1132e
|
[
"Unlicense"
] | null | null | null |
#ifndef SAMPLEPLUGIN_HPP
#define SAMPLEPLUGIN_HPP
// RobWork includes
#include <rw/models/WorkCell.hpp>
#include <rw/kinematics/State.hpp>
#include <rwlibs/opengl/RenderImage.hpp>
#include <rwlibs/simulation/GLFrameGrabber.hpp>
#include <rwlibs/simulation/GLFrameGrabber25D.hpp>
#include <rw/rw.hpp>
#include <rwlibs/pathplanners/rrt/RRTPlanner.hpp>
#include <rwlibs/pathplanners/rrt/RRTQToQPlanner.hpp>
#include <rwlibs/proximitystrategies/ProximityStrategyFactory.hpp>
#include <rw/trajectory/LinearInterpolator.hpp>
// RobWorkStudio includes
#include <RobWorkStudioConfig.hpp> // For RWS_USE_QT5 definition
#include <rws/RobWorkStudioPlugin.hpp>
// OpenCV 3
#include <opencv2/opencv.hpp>
// Qt
#include <QTimer>
#include "ui_SamplePlugin.h"
#include <rws/RobWorkStudio.hpp>
#include <QPushButton>
#include <rw/loaders/ImageLoader.hpp>
#include <rw/loaders/WorkCellFactory.hpp>
#include <functional>
using namespace rw::common;
using namespace rw::graphics;
using namespace rw::kinematics;
using namespace rw::loaders;
using namespace rw::models;
using namespace rw::sensor;
using namespace rwlibs::opengl;
using namespace rwlibs::simulation;
using namespace std;
using namespace rw::math;
using namespace rw::pathplanning;
using namespace rw::proximity;
using namespace rw::trajectory;
using namespace rwlibs::pathplanners;
using namespace rwlibs::proximitystrategies;
using namespace rws;
using namespace cv;
using namespace std::placeholders;
class SamplePlugin: public rws::RobWorkStudioPlugin, private Ui::SamplePlugin
{
Q_OBJECT
Q_INTERFACES( rws::RobWorkStudioPlugin )
Q_PLUGIN_METADATA(IID "dk.sdu.mip.Robwork.RobWorkStudioPlugin/0.1" FILE "plugin.json")
public:
SamplePlugin();
virtual ~SamplePlugin();
virtual void open(rw::models::WorkCell* workcell);
virtual void close();
virtual void initialize();
private slots:
void btnPressed();
void timer();
void getImage();
void get25DImage();
void stateChangedListener(const rw::kinematics::State& state);
bool checkCollisions(Device::Ptr device, const State &state, const CollisionDetector &detector, const Q &q);
void createPathRRTConnect(Q from, Q to, double extend, double maxTime);
private:
static cv::Mat toOpenCVImage(const rw::sensor::Image& img);
QTimer* _timer;
QTimer* _timer25D;
rw::models::WorkCell::Ptr _wc;
rw::kinematics::State _state;
rwlibs::opengl::RenderImage *_textureRender, *_bgRender;
rwlibs::simulation::GLFrameGrabber* _framegrabber;
rwlibs::simulation::GLFrameGrabber25D* _framegrabber25D;
std::vector<std::string> _cameras;
std::vector<std::string> _cameras25D;
Device::Ptr _device;
QPath _path;
int _step;
};
#endif /*RINGONHOOKPLUGIN_HPP_*/
| 25.936937
| 113
| 0.727336
|
balintmaci
|
94fb49108c7686359b444c6f4da79ec6eb6845b8
| 419
|
cpp
|
C++
|
cpp_level_2_solutions/2_2_add_two_ints.cpp
|
PacktPublishing/Practical-C-Learn-C-Basics-Step-by-Step
|
553d18984f47ffe5275c67346f64551eef659e2f
|
[
"MIT"
] | 1
|
2022-03-13T06:12:44.000Z
|
2022-03-13T06:12:44.000Z
|
cpp_level_2_solutions/2_2_add_two_ints.cpp
|
PacktPublishing/Practical-C-Learn-C-Basics-Step-by-Step
|
553d18984f47ffe5275c67346f64551eef659e2f
|
[
"MIT"
] | null | null | null |
cpp_level_2_solutions/2_2_add_two_ints.cpp
|
PacktPublishing/Practical-C-Learn-C-Basics-Step-by-Step
|
553d18984f47ffe5275c67346f64551eef659e2f
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int add_two_ints(int number1, int number2)
{
return number1 + number2;
}
int main()
{
int number1, number2;
cout << "Enter number 1: ";
cin >> number1;
cout << "Enter number 2: ";
cin >> number2;
cout << number1 << " + " << number2
<< " = " << add_two_ints(number1, number2)
<< endl;
return 0;
}
| 19.045455
| 56
| 0.520286
|
PacktPublishing
|
94fffca5cfd2b81cde9129fc6ce7cad56885a943
| 790
|
cpp
|
C++
|
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GWindows.cpp
|
austinkeller/pwiz
|
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
|
[
"Apache-2.0"
] | 2
|
2019-12-28T21:24:36.000Z
|
2020-04-18T03:52:05.000Z
|
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GWindows.cpp
|
austinkeller/pwiz
|
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
|
[
"Apache-2.0"
] | null | null | null |
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GWindows.cpp
|
austinkeller/pwiz
|
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (C) 2006, Mike Gashler
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
see http://www.gnu.org/copyleft/lesser.html
*/
#ifdef WINDOWS
#include "GWindows.h"
#include "GString.h"
#include "GError.h"
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <errno.h>
#include <io.h>
#include <time.h>
#include <process.h>
namespace GClasses {
void GWindows::yield()
{
MSG aMsg;
while(PeekMessage(&aMsg, NULL, WM_NULL, WM_NULL, PM_REMOVE))
{
TranslateMessage(&aMsg);
DispatchMessage(&aMsg);
}
}
} // namespace GClasses
#endif // WINDOWS
| 18.809524
| 67
| 0.712658
|
austinkeller
|
a20200110301e45c9d28f9183090dd41f4768738
| 119
|
cpp
|
C++
|
Source/DreamPlace/DreamPlaceGameStateBase.cpp
|
YuanweiZHANG/DreamPlace
|
b005c22e2353e674a0596c078083b82efe9ae733
|
[
"MIT"
] | null | null | null |
Source/DreamPlace/DreamPlaceGameStateBase.cpp
|
YuanweiZHANG/DreamPlace
|
b005c22e2353e674a0596c078083b82efe9ae733
|
[
"MIT"
] | null | null | null |
Source/DreamPlace/DreamPlaceGameStateBase.cpp
|
YuanweiZHANG/DreamPlace
|
b005c22e2353e674a0596c078083b82efe9ae733
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "DreamPlaceGameStateBase.h"
| 19.833333
| 78
| 0.789916
|
YuanweiZHANG
|
a2062d229e19af94da5938ee3d5873e8af47f19f
| 963
|
hpp
|
C++
|
tlx/define/visibility_hidden.hpp
|
GerHobbelt/tlx
|
81a71238b17df27d98a4dff9ceba21bd79fddffb
|
[
"BSL-1.0"
] | 284
|
2017-02-26T08:49:15.000Z
|
2022-03-30T21:55:37.000Z
|
tlx/define/visibility_hidden.hpp
|
xiao2mo/tlx
|
b311126e670753897c1defceeaa75c83d2d9531a
|
[
"BSL-1.0"
] | 24
|
2017-09-05T21:02:41.000Z
|
2022-03-07T10:09:59.000Z
|
tlx/define/visibility_hidden.hpp
|
xiao2mo/tlx
|
b311126e670753897c1defceeaa75c83d2d9531a
|
[
"BSL-1.0"
] | 62
|
2017-02-23T12:29:27.000Z
|
2022-03-31T07:45:59.000Z
|
/*******************************************************************************
* tlx/define/visibility_hidden.hpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2019 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#ifndef TLX_DEFINE_VISIBILITY_HIDDEN_HEADER
#define TLX_DEFINE_VISIBILITY_HIDDEN_HEADER
namespace tlx {
//! \addtogroup tlx_define
//! \{
/******************************************************************************/
// __attribute__ ((visibility ("hidden")))
#if defined(__GNUC__) || defined(__clang__)
#define TLX_VISIBILITY_HIDDEN __attribute__ ((visibility("hidden")))
#else
#define TLX_VISIBILITY_HIDDEN
#endif
//! \}
} // namespace tlx
#endif // !TLX_DEFINE_VISIBILITY_HIDDEN_HEADER
/******************************************************************************/
| 27.514286
| 80
| 0.496366
|
GerHobbelt
|
a20649589052eeb907eead30aa4ec0efeff71dea
| 2,027
|
cc
|
C++
|
tao_compiler/mlir/disc/transforms/disc_strip_shape_constraint_ops.cc
|
JamesTheZ/BladeDISC
|
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
|
[
"Apache-2.0"
] | null | null | null |
tao_compiler/mlir/disc/transforms/disc_strip_shape_constraint_ops.cc
|
JamesTheZ/BladeDISC
|
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
|
[
"Apache-2.0"
] | null | null | null |
tao_compiler/mlir/disc/transforms/disc_strip_shape_constraint_ops.cc
|
JamesTheZ/BladeDISC
|
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file implements logic to strip disc shape constraint ops.
#include "llvm/Support/Debug.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/Support/LogicalResult.h"
#include "tensorflow/compiler/mlir/disc/IR/disc_shape_ops.h"
#include "tensorflow/compiler/mlir/disc/transforms/PassDetail.h"
#include "tensorflow/compiler/mlir/disc/transforms/disc_shape_optimization_utils.h"
namespace mlir {
namespace disc_ral {
namespace {
struct DiscStripShapeConstraintOpsPass
: public DiscStripShapeConstraintOpsPassBase<
DiscStripShapeConstraintOpsPass> {
void runOnOperation() override {
SmallVector<disc_shape::SymbolicDimOp> ops;
getOperation().walk(
[&](disc_shape::SymbolicDimOp op) { ops.push_back(op); });
for (disc_shape::SymbolicDimOp op : ops) {
op->erase();
}
StringRef funcName = SymbolicDimMgr::getShapeConstraintGraphFunctionName();
// first try to remove the old shape constraint graph
if (auto func = getOperation().lookupSymbol<func::FuncOp>(funcName))
func->erase();
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> createStripShapeConstraintOpsPass() {
return std::make_unique<DiscStripShapeConstraintOpsPass>();
}
} // namespace disc_ral
} // namespace mlir
| 36.196429
| 83
| 0.729156
|
JamesTheZ
|
a20817730921ccb27a6936fc99a3bc4af62579aa
| 380
|
cc
|
C++
|
1189/lectures/tools/make/example2/list.cc
|
JohnMai1994/CS246-2018_Fall_Term
|
a95a9cf5bc710131a6e51b863b002efdd425b89c
|
[
"MIT"
] | 2
|
2020-07-13T17:08:29.000Z
|
2021-11-19T15:47:06.000Z
|
1189/lectures/tools/make/example1/list.cc
|
JohnMai1994/CS246-2018_Fall_Term
|
a95a9cf5bc710131a6e51b863b002efdd425b89c
|
[
"MIT"
] | null | null | null |
1189/lectures/tools/make/example1/list.cc
|
JohnMai1994/CS246-2018_Fall_Term
|
a95a9cf5bc710131a6e51b863b002efdd425b89c
|
[
"MIT"
] | 4
|
2021-05-29T22:40:59.000Z
|
2022-03-25T19:19:15.000Z
|
#include "list.h"
#include "node.h"
List::Iterator List::begin() { return Iterator(theList); }
List::Iterator List::end() {return Iterator(nullptr); }
List::~List() { delete theList; }
void List::addToFront(int n) { theList = new Node(n, theList); }
int List::ith(int i) {
Node *cur = theList;
for (int j = 0; j < i && cur; ++j, cur = cur -> next);
return cur->data;
}
| 22.352941
| 64
| 0.621053
|
JohnMai1994
|
a20a1bae04eb55f7b54548c42c85340c822f7f2c
| 2,157
|
cpp
|
C++
|
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
|
ZexinLi0w0/LeetCode
|
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
|
[
"MIT"
] | 1
|
2020-12-03T10:10:15.000Z
|
2020-12-03T10:10:15.000Z
|
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
|
ZexinLi0w0/LeetCode
|
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
|
[
"MIT"
] | null | null | null |
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
|
ZexinLi0w0/LeetCode
|
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
|
[
"MIT"
] | null | null | null |
class Solution {
void generateNumbers(int bits, long temp_num, set<long>& numbers){
if (bits == 0){
numbers.insert(temp_num);
return;
}
// If we have bits available, out of all 10 available bits, we need to do the follwoing:
// For all bits (from 0 to 1 << 9)
// Check if the bit is already set in the temporary number.
// If the bit is set, do nothing, move to the other bit.
// If the bit is not set, mark it as set in the temporary number, decrease the number of available bits
// And call the method recursively.
for (int i = 0; i < 10; ++ i){
int temp_mask = (1 << i);
if (temp_num & temp_mask){
continue; // The bit is set.
}
int tmp = temp_num;
temp_num |= temp_mask;
generateNumbers(bits - 1, temp_num, numbers);
temp_num = tmp;
}
}
// Bitmask for minutes: 0000111111b = 15 + 16 + 32 = 59 = 0x3F
// Bitmask for hours: 1111000000 = 0x3C0
vector<string> extractHoursAndMinutes(set<long>& numbers){
vector<string> res;
// We know that the hours are the first 4 bits and the minutes are the last 6 bits.
for (const auto& elem : numbers){
int minutes = elem & 0x003F;
int hours = (elem & 0x03C0) >> 6;
if (minutes > 59 || hours > 11){
continue;
}
string string_hour = to_string(hours);
string string_minute = to_string(minutes);
if (string_minute.size() == 1){
string_minute = "0" + string_minute;
}
res.push_back(string_hour + ":" + string_minute);
}
return res;
}
public:
vector<string> readBinaryWatch(int num) {
set<long> all_numbers;
generateNumbers(num, 0, all_numbers);
vector<string> result;
result = extractHoursAndMinutes(all_numbers);
// After we have all numbers, map them to the mask for extracting hours and minutes.
return result;
}
};
| 36.559322
| 111
| 0.545665
|
ZexinLi0w0
|
a2125800640f6d634c28e3d9de4de896424ba2d5
| 22,165
|
cpp
|
C++
|
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
|
Constructive-Tyranny/Jupiter-Bot
|
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
|
[
"0BSD"
] | 9
|
2016-02-04T09:54:24.000Z
|
2021-11-25T18:56:44.000Z
|
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
|
Constructive-Tyranny/Jupiter-Bot
|
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
|
[
"0BSD"
] | 8
|
2015-08-04T15:19:53.000Z
|
2021-11-18T19:39:05.000Z
|
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
|
JustinAJ/Jupiter-Bot
|
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
|
[
"0BSD"
] | 15
|
2016-08-22T13:04:25.000Z
|
2022-02-18T16:19:00.000Z
|
/**
* Copyright (C) 2015-2021 Jessica James.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Written by Jessica James <jessica.aj@outlook.com>
*/
#include <iostream>
#include "jessilib/unicode.hpp"
#include "Jupiter/DataBuffer.h"
#include "RenX_LadderDatabase.h"
#include "RenX_Server.h"
#include "RenX_PlayerInfo.h"
#include "RenX_BanDatabase.h"
RenX::LadderDatabase *RenX::default_ladder_database = nullptr;
std::vector<RenX::LadderDatabase*> g_ladder_databases;
std::vector<RenX::LadderDatabase*>& RenX::ladder_databases = g_ladder_databases;
RenX::LadderDatabase::LadderDatabase() {
g_ladder_databases.push_back(this);
if (RenX::default_ladder_database == nullptr) {
RenX::default_ladder_database = this;
}
}
RenX::LadderDatabase::LadderDatabase(std::string_view in_name) : LadderDatabase() {
RenX::LadderDatabase::setName(in_name);
}
RenX::LadderDatabase::~LadderDatabase() {
while (m_head != nullptr) {
m_end = m_head;
m_head = m_head->next;
delete m_end;
}
for (auto itr = g_ladder_databases.begin(); itr != g_ladder_databases.end(); ++itr) {
if (*itr == this) {
g_ladder_databases.erase(itr);
break;
}
}
if (RenX::default_ladder_database == this) {
if (g_ladder_databases.empty()) {
RenX::default_ladder_database = nullptr;
}
else {
RenX::default_ladder_database = g_ladder_databases[0];
}
}
}
void RenX::LadderDatabase::process_data(Jupiter::DataBuffer &buffer, FILE *file, fpos_t pos) {
Entry *entry = new Entry();
// read data from buffer to entry
entry->steam_id = buffer.pop<uint64_t>();
entry->total_score = buffer.pop<uint64_t>();
entry->total_kills = buffer.pop<uint32_t>();
entry->total_deaths = buffer.pop<uint32_t>();
entry->total_headshot_kills = buffer.pop<uint32_t>();
entry->total_vehicle_kills = buffer.pop<uint32_t>();
entry->total_building_kills = buffer.pop<uint32_t>();
entry->total_defence_kills = buffer.pop<uint32_t>();
entry->total_captures = buffer.pop<uint32_t>();
entry->total_game_time = buffer.pop<uint32_t>();
entry->total_games = buffer.pop<uint32_t>();
if (m_read_version == 0)
{
entry->total_gdi_games = buffer.pop<uint32_t>();
entry->total_nod_games = buffer.pop<uint32_t>();
}
entry->total_wins = buffer.pop<uint32_t>();
if (m_read_version == 0)
{
entry->total_gdi_wins = buffer.pop<uint32_t>();
entry->total_nod_wins = buffer.pop<uint32_t>();
}
entry->total_beacon_placements = buffer.pop<uint32_t>();
entry->total_beacon_disarms = buffer.pop<uint32_t>();
entry->total_proxy_placements = buffer.pop<uint32_t>();
entry->total_proxy_disarms = buffer.pop<uint32_t>();
if (m_read_version > 0)
{
entry->total_gdi_games = buffer.pop<uint32_t>();
entry->total_gdi_wins = buffer.pop<uint32_t>();
entry->total_gdi_ties = buffer.pop<uint32_t>();
entry->total_gdi_game_time = buffer.pop<uint32_t>();
entry->total_gdi_score = buffer.pop<uint64_t>();
entry->total_gdi_beacon_placements = buffer.pop<uint32_t>();
entry->total_gdi_beacon_disarms = buffer.pop<uint32_t>();
entry->total_gdi_proxy_placements = buffer.pop<uint32_t>();
entry->total_gdi_proxy_disarms = buffer.pop<uint32_t>();
entry->total_gdi_kills = buffer.pop<uint32_t>();
entry->total_gdi_deaths = buffer.pop<uint32_t>();
entry->total_gdi_vehicle_kills = buffer.pop<uint32_t>();
entry->total_gdi_defence_kills = buffer.pop<uint32_t>();
entry->total_gdi_building_kills = buffer.pop<uint32_t>();
entry->total_gdi_headshots = buffer.pop<uint32_t>();
entry->total_nod_games = buffer.pop<uint32_t>();
entry->total_nod_wins = buffer.pop<uint32_t>();
entry->total_nod_game_time = buffer.pop<uint32_t>();
entry->total_nod_score = buffer.pop<uint64_t>();
entry->total_nod_beacon_placements = buffer.pop<uint32_t>();
entry->total_nod_beacon_disarms = buffer.pop<uint32_t>();
entry->total_nod_proxy_placements = buffer.pop<uint32_t>();
entry->total_nod_proxy_disarms = buffer.pop<uint32_t>();
entry->total_nod_kills = buffer.pop<uint32_t>();
entry->total_nod_deaths = buffer.pop<uint32_t>();
entry->total_nod_vehicle_kills = buffer.pop<uint32_t>();
entry->total_nod_defence_kills = buffer.pop<uint32_t>();
entry->total_nod_building_kills = buffer.pop<uint32_t>();
entry->total_nod_headshots = buffer.pop<uint32_t>();
}
entry->top_score = buffer.pop<uint32_t>();
entry->top_kills = buffer.pop<uint32_t>();
entry->most_deaths = buffer.pop<uint32_t>();
entry->top_headshot_kills = buffer.pop<uint32_t>();
entry->top_vehicle_kills = buffer.pop<uint32_t>();
entry->top_building_kills = buffer.pop<uint32_t>();
entry->top_defence_kills = buffer.pop<uint32_t>();
entry->top_captures = buffer.pop<uint32_t>();
entry->top_game_time = buffer.pop<uint32_t>();
entry->top_beacon_placements = buffer.pop<uint32_t>();
entry->top_beacon_disarms = buffer.pop<uint32_t>();
entry->top_proxy_placements = buffer.pop<uint32_t>();
entry->top_proxy_disarms = buffer.pop<uint32_t>();
entry->most_recent_ip = buffer.pop<uint32_t>();
entry->last_game = buffer.pop<time_t>();
entry->most_recent_name = buffer.pop<std::string>();
// push data to list
if (m_head == nullptr) {
m_head = entry;
m_end = m_head;
}
else {
m_end->next = entry;
entry->prev = m_end;
m_end = entry;
}
entry->rank = ++m_entries;
}
void RenX::LadderDatabase::process_header(FILE *file) {
int chr = fgetc(file);
if (chr != EOF) {
m_read_version = chr;
}
}
void RenX::LadderDatabase::create_header(FILE *file) {
fputc(m_write_version, file);
}
void RenX::LadderDatabase::process_file_finish(FILE *file) {
if (m_read_version != m_write_version) {
std::cout << "Notice: Ladder database is out of date; upgrading..." << std::endl;
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
write(this->getFilename());
std::chrono::steady_clock::duration write_duration = std::chrono::steady_clock::now() - start_time;
// This does not seem anything close to correct...
double time_taken = static_cast<double>(write_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num));
std::cout << "Ladder database upgrade completed in " << time_taken << " seconds" << std::endl;
m_read_version = m_write_version;
}
}
RenX::LadderDatabase::Entry *RenX::LadderDatabase::getHead() const {
return m_head;
}
RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntry(uint64_t steamid) const {
for (Entry *itr = m_head; itr != nullptr; itr = itr->next) {
if (itr->steam_id == steamid) {
return itr;
}
}
return nullptr;
}
std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndex(uint64_t steamid) const {
size_t index = 0;
for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) {
if (itr->steam_id == steamid) {
return std::pair<Entry*, size_t>(itr, index);
}
}
return std::pair<Entry*, size_t>(nullptr, SIZE_MAX);
}
RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByName(std::string_view name) const {
for (Entry *itr = m_head; itr != nullptr; itr = itr->next) {
if (jessilib::equalsi(itr->most_recent_name, name)) {
return itr;
}
}
return nullptr;
}
std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndexByName(std::string_view name) const {
size_t index = 0;
for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) {
if (jessilib::equalsi(itr->most_recent_name, name)) {
return std::pair<Entry*, size_t>(itr, index);
}
}
return std::pair<Entry*, size_t>(nullptr, SIZE_MAX);
}
RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByPartName(std::string_view name) const {
for (Entry *itr = m_head; itr != nullptr; itr = itr->next) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
return itr;
}
}
return nullptr;
}
std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndexByPartName(std::string_view name) const {
size_t index = 0;
for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
return std::pair<RenX::LadderDatabase::Entry*, size_t>(itr, index);
}
}
return std::pair<Entry *, size_t>(nullptr, SIZE_MAX);
}
std::forward_list<RenX::LadderDatabase::Entry> RenX::LadderDatabase::getPlayerEntriesByPartName(std::string_view name, size_t max) const {
std::forward_list<Entry> list;
if (max == 0) {
for (Entry *itr = m_head; itr != nullptr; itr = itr->next) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
list.emplace_front(*itr);
}
}
}
else {
for (Entry* itr = m_head; itr != nullptr; itr = itr->next) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
list.emplace_front(*itr);
if (--max == 0) {
return list;
}
}
}
}
return list;
}
std::forward_list<std::pair<RenX::LadderDatabase::Entry, size_t>> RenX::LadderDatabase::getPlayerEntriesAndIndexByPartName(std::string_view name, size_t max) const {
std::forward_list<std::pair<Entry, size_t>> list;
size_t index = 0;
if (max == 0)
{
for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
list.emplace_front(*itr, index);
}
}
}
else {
for (Entry* itr = m_head; itr != nullptr; itr = itr->next, ++index) {
if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) {
list.emplace_front(*itr, index);
if (--max) {
return list;
}
}
}
}
return list;
}
RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByIndex(size_t index) const {
for (Entry *itr = m_head; itr != nullptr; itr = itr->next, --index) {
if (index == 0) {
return itr;
}
}
return nullptr;
}
size_t RenX::LadderDatabase::getEntries() const {
return m_entries;
}
std::chrono::steady_clock::time_point RenX::LadderDatabase::getLastSortTime() const {
return m_last_sort;
}
void RenX::LadderDatabase::append(Entry *entry) {
++m_entries;
if (m_head == nullptr) {
m_head = entry;
m_end = m_head;
return;
}
m_end->next = entry;
entry->prev = m_end;
m_end = entry;
}
void RenX::LadderDatabase::write(const std::string &filename) {
return write(filename.c_str());
}
void RenX::LadderDatabase::write(const char *filename) {
if (m_entries != 0)
{
FILE *file = fopen(filename, "wb");
if (file != nullptr)
{
size_t rank = 0;
Jupiter::DataBuffer buffer;
create_header(file);
Entry *entry = m_head;
while (entry != nullptr)
{
// update rank
entry->rank = ++rank;
// push data from entry to buffer
buffer.push(entry->steam_id);
buffer.push(entry->total_score);
buffer.push(entry->total_kills);
buffer.push(entry->total_deaths);
buffer.push(entry->total_headshot_kills);
buffer.push(entry->total_vehicle_kills);
buffer.push(entry->total_building_kills);
buffer.push(entry->total_defence_kills);
buffer.push(entry->total_captures);
buffer.push(entry->total_game_time);
buffer.push(entry->total_games);
buffer.push(entry->total_wins);
buffer.push(entry->total_beacon_placements);
buffer.push(entry->total_beacon_disarms);
buffer.push(entry->total_proxy_placements);
buffer.push(entry->total_proxy_disarms);
buffer.push(entry->total_gdi_games);
buffer.push(entry->total_gdi_wins);
buffer.push(entry->total_gdi_ties);
buffer.push(entry->total_gdi_game_time);
buffer.push(entry->total_gdi_score);
buffer.push(entry->total_gdi_beacon_placements);
buffer.push(entry->total_gdi_beacon_disarms);
buffer.push(entry->total_gdi_proxy_placements);
buffer.push(entry->total_gdi_proxy_disarms);
buffer.push(entry->total_gdi_kills);
buffer.push(entry->total_gdi_deaths);
buffer.push(entry->total_gdi_vehicle_kills);
buffer.push(entry->total_gdi_defence_kills);
buffer.push(entry->total_gdi_building_kills);
buffer.push(entry->total_gdi_headshots);
buffer.push(entry->total_nod_games);
buffer.push(entry->total_nod_wins);
buffer.push(entry->total_nod_game_time);
buffer.push(entry->total_nod_score);
buffer.push(entry->total_nod_beacon_placements);
buffer.push(entry->total_nod_beacon_disarms);
buffer.push(entry->total_nod_proxy_placements);
buffer.push(entry->total_nod_proxy_disarms);
buffer.push(entry->total_nod_kills);
buffer.push(entry->total_nod_deaths);
buffer.push(entry->total_nod_vehicle_kills);
buffer.push(entry->total_nod_defence_kills);
buffer.push(entry->total_nod_building_kills);
buffer.push(entry->total_nod_headshots);
buffer.push(entry->top_score);
buffer.push(entry->top_kills);
buffer.push(entry->most_deaths);
buffer.push(entry->top_headshot_kills);
buffer.push(entry->top_vehicle_kills);
buffer.push(entry->top_building_kills);
buffer.push(entry->top_defence_kills);
buffer.push(entry->top_captures);
buffer.push(entry->top_game_time);
buffer.push(entry->top_beacon_placements);
buffer.push(entry->top_beacon_disarms);
buffer.push(entry->top_proxy_placements);
buffer.push(entry->top_proxy_disarms);
buffer.push(entry->most_recent_ip);
buffer.push(entry->last_game);
buffer.push(entry->most_recent_name);
// push buffer to file
buffer.push_to(file);
// iterate
entry = entry->next;
}
fclose(file);
}
}
}
void RenX::LadderDatabase::sort_entries() {
if (m_entries <= 1) {
return;
}
Entry *itr = m_head;
Entry *itr2, *ptr;
// iterate forward (search for out-of-order content)
while (itr->next != nullptr) {
// out-of-order content found
if (itr->next->total_score > itr->total_score) {
// pull content out
ptr = itr->next;
itr->next = ptr->next;
if (itr->next != nullptr) {
itr->next->prev = itr;
}
// iterate backwards from our iterator, and insert
itr2 = itr;
while (true) {
if (itr2->prev == nullptr) {
// push ptr to head
ptr->next = itr2;
ptr->prev = nullptr;
itr2->prev = ptr;
m_head = ptr;
break;
}
itr2 = itr2->prev;
if (itr2->total_score > ptr->total_score) {
// insert ptr after itr2
ptr->next = itr2->next;
ptr->next->prev = ptr;
ptr->prev = itr2;
itr2->next = ptr;
break;
}
}
}
else { // continue iterating
itr = itr->next;
}
}
m_end = itr;
m_last_sort = std::chrono::steady_clock::now();
}
void RenX::LadderDatabase::updateLadder(RenX::Server &server, const RenX::TeamType &team) {
if (server.players.size() != server.getBotCount()) {
// call the PreUpdateLadder event
if (this->OnPreUpdateLadder != nullptr) {
this->OnPreUpdateLadder(*this, server, team);
}
// update player stats in memory
Entry *entry;
for (auto player = server.players.begin(); player != server.players.end(); ++player) {
if (player->steamid != 0 && (player->ban_flags & RenX::BanDatabase::Entry::FLAG_TYPE_LADDER) == 0) {
entry = getPlayerEntry(player->steamid);
if (entry == nullptr) {
entry = new Entry();
append(entry);
entry->steam_id = player->steamid;
}
entry->total_score += static_cast<uint64_t>(player->score);
entry->total_kills += player->kills;
entry->total_deaths += player->deaths;
entry->total_headshot_kills += player->headshots;
entry->total_vehicle_kills += player->vehicleKills;
entry->total_building_kills += player->buildingKills;
entry->total_defence_kills += player->defenceKills;
entry->total_captures += player->captures;
entry->total_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count());
entry->total_beacon_placements += player->beaconPlacements;
entry->total_beacon_disarms += player->beaconDisarms;
entry->total_proxy_placements += player->proxy_placements;
entry->total_proxy_disarms += player->proxy_disarms;
++entry->total_games;
switch (player->team) {
case RenX::TeamType::GDI:
++entry->total_gdi_games;
if (player->team == team)
++entry->total_wins, ++entry->total_gdi_wins;
else if (team == RenX::TeamType::None)
++entry->total_gdi_ties;
entry->total_gdi_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count());
entry->total_gdi_score += static_cast<uint64_t>(player->score);
entry->total_gdi_beacon_placements += player->beaconPlacements;
entry->total_gdi_beacon_disarms += player->beaconDisarms;
entry->total_gdi_proxy_placements += player->proxy_placements;
entry->total_gdi_proxy_disarms += player->proxy_disarms;
entry->total_gdi_kills += player->kills;
entry->total_gdi_deaths += player->deaths;
entry->total_gdi_vehicle_kills += player->vehicleKills;
entry->total_gdi_defence_kills += player->defenceKills;
entry->total_gdi_building_kills += player->buildingKills;
entry->total_gdi_headshots += player->headshots;
break;
case RenX::TeamType::Nod:
++entry->total_nod_games;
if (player->team == team)
++entry->total_wins, ++entry->total_nod_wins;
else if (team == RenX::TeamType::None)
++entry->total_nod_ties;
entry->total_nod_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count());
entry->total_nod_score += static_cast<uint64_t>(player->score);
entry->total_nod_beacon_placements += player->beaconPlacements;
entry->total_nod_beacon_disarms += player->beaconDisarms;
entry->total_nod_proxy_placements += player->proxy_placements;
entry->total_nod_proxy_disarms += player->proxy_disarms;
entry->total_nod_kills += player->kills;
entry->total_nod_deaths += player->deaths;
entry->total_nod_vehicle_kills += player->vehicleKills;
entry->total_nod_defence_kills += player->defenceKills;
entry->total_nod_building_kills += player->buildingKills;
entry->total_nod_headshots += player->headshots;
break;
default:
if (player->team == team)
++entry->total_wins;
break;
}
auto set_if_greater = [](uint32_t &src, const uint32_t &cmp) {
if (cmp > src) {
src = cmp;
}
};
set_if_greater(entry->top_score, static_cast<uint32_t>(player->score));
set_if_greater(entry->top_kills, player->kills);
set_if_greater(entry->most_deaths, player->deaths);
set_if_greater(entry->top_headshot_kills, player->headshots);
set_if_greater(entry->top_vehicle_kills, player->vehicleKills);
set_if_greater(entry->top_building_kills, player->buildingKills);
set_if_greater(entry->top_defence_kills, player->defenceKills);
set_if_greater(entry->top_captures, player->captures);
set_if_greater(entry->top_game_time, static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count()));
set_if_greater(entry->top_beacon_placements, player->beaconPlacements);
set_if_greater(entry->top_beacon_disarms, player->beaconDisarms);
set_if_greater(entry->top_proxy_placements, player->proxy_placements);
set_if_greater(entry->top_proxy_disarms, player->proxy_disarms);
entry->most_recent_ip = player->ip32;
entry->last_game = time(nullptr);
entry->most_recent_name = player->name;
}
}
// sort new stats
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
sort_entries();
std::chrono::steady_clock::duration sort_duration = std::chrono::steady_clock::now() - start_time;
// write new stats
start_time = std::chrono::steady_clock::now();
write(this->getFilename());
std::chrono::steady_clock::duration write_duration = std::chrono::steady_clock::now() - start_time;
if (m_output_times)
{
std::string str = string_printf("Ladder: %zu entries sorted in %f seconds; Database written in %f seconds." ENDL,
getEntries(),
static_cast<double>(sort_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num)),
static_cast<double>(write_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num)));
std::cout << str << std::endl;
server.sendLogChan(str);
}
}
}
void RenX::LadderDatabase::erase() {
if (m_head != nullptr) {
m_entries = 0;
while (m_head->next != nullptr) {
m_head = m_head->next;
delete m_head->prev;
}
delete m_head;
m_head = nullptr;
m_end = nullptr;
}
}
std::string_view RenX::LadderDatabase::getName() const {
return m_name;
}
void RenX::LadderDatabase::setName(std::string_view in_name) {
m_name = in_name;
}
bool RenX::LadderDatabase::getOutputTimes() const {
return m_output_times;
}
void RenX::LadderDatabase::setOutputTimes(bool in_output_times) {
m_output_times = in_output_times;
}
| 34.741379
| 325
| 0.70467
|
Constructive-Tyranny
|
a21368cb25f93ac1d5ea2744906c7339e88fa503
| 6,015
|
cpp
|
C++
|
RealTimeAbstract_Qt version/3 RealTimeAbstract_Qt/RealTimeAbstract_Qt/GeneratedFiles/Release/moc_videoabstract_qtver.cpp
|
billhhh/Maskedman_double_mode
|
8937ddc2d8f154eaaa93b2449dff127f03b488f2
|
[
"MIT"
] | null | null | null |
RealTimeAbstract_Qt version/3 RealTimeAbstract_Qt/RealTimeAbstract_Qt/GeneratedFiles/Release/moc_videoabstract_qtver.cpp
|
billhhh/Maskedman_double_mode
|
8937ddc2d8f154eaaa93b2449dff127f03b488f2
|
[
"MIT"
] | null | null | null |
RealTimeAbstract_Qt version/3 RealTimeAbstract_Qt/RealTimeAbstract_Qt/GeneratedFiles/Release/moc_videoabstract_qtver.cpp
|
billhhh/Maskedman_double_mode
|
8937ddc2d8f154eaaa93b2449dff127f03b488f2
|
[
"MIT"
] | null | null | null |
/****************************************************************************
** Meta object code from reading C++ file 'videoabstract_qtver.h'
**
** Created: Sat Oct 4 11:02:03 2014
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../videoabstract_qtver.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'videoabstract_qtver.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_VideoAbstract_QTver[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
21, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: signature, parameters, type, tag, flags
21, 20, 20, 20, 0x05,
// slots: signature, parameters, type, tag, flags
48, 20, 20, 20, 0x08,
78, 20, 20, 20, 0x08,
107, 20, 20, 20, 0x08,
135, 20, 20, 20, 0x08,
166, 20, 20, 20, 0x08,
193, 20, 20, 20, 0x08,
225, 20, 20, 20, 0x08,
261, 259, 20, 20, 0x08,
283, 20, 20, 20, 0x08,
300, 20, 20, 20, 0x08,
326, 322, 20, 20, 0x08,
368, 20, 20, 20, 0x08,
395, 20, 20, 20, 0x08,
424, 20, 20, 20, 0x08,
454, 20, 20, 20, 0x08,
470, 20, 20, 20, 0x08,
485, 20, 20, 20, 0x08,
507, 20, 20, 20, 0x08,
525, 20, 20, 20, 0x08,
546, 20, 20, 20, 0x08,
0 // eod
};
static const char qt_meta_stringdata_VideoAbstract_QTver[] = {
"VideoAbstract_QTver\0\0sendSwitchToRealTimeForm()\0"
"on_open_file_button_clicked()\0"
"on_analysis_button_clicked()\0"
"on_setting_button_clicked()\0"
"on_pushButton_switch_clicked()\0"
"on_search_button_clicked()\0"
"on_pushButton_playAll_clicked()\0"
"on_show_video_check_box_clicked()\0,\0"
"showVideo(QImage,int)\0openFileFailed()\0"
"updateProcessBar(int)\0,,,\0"
"drawAbstracts(QImage,QString,QString,int)\0"
"updateProcessInfo(QString)\0"
"changeAnalyzeButton(QString)\0"
"changeAnalyzeButtonState(int)\0"
"updateRunTime()\0endTimeCount()\0"
"updateEventCount(int)\0playAbstract(int)\0"
"removeAllAbstracts()\0"
"get_enter_checkbox_state(bool)\0"
};
void VideoAbstract_QTver::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
VideoAbstract_QTver *_t = static_cast<VideoAbstract_QTver *>(_o);
switch (_id) {
case 0: _t->sendSwitchToRealTimeForm(); break;
case 1: _t->on_open_file_button_clicked(); break;
case 2: _t->on_analysis_button_clicked(); break;
case 3: _t->on_setting_button_clicked(); break;
case 4: _t->on_pushButton_switch_clicked(); break;
case 5: _t->on_search_button_clicked(); break;
case 6: _t->on_pushButton_playAll_clicked(); break;
case 7: _t->on_show_video_check_box_clicked(); break;
case 8: _t->showVideo((*reinterpret_cast< QImage(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 9: _t->openFileFailed(); break;
case 10: _t->updateProcessBar((*reinterpret_cast< int(*)>(_a[1]))); break;
case 11: _t->drawAbstracts((*reinterpret_cast< QImage(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4]))); break;
case 12: _t->updateProcessInfo((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 13: _t->changeAnalyzeButton((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 14: _t->changeAnalyzeButtonState((*reinterpret_cast< int(*)>(_a[1]))); break;
case 15: _t->updateRunTime(); break;
case 16: _t->endTimeCount(); break;
case 17: _t->updateEventCount((*reinterpret_cast< int(*)>(_a[1]))); break;
case 18: _t->playAbstract((*reinterpret_cast< int(*)>(_a[1]))); break;
case 19: _t->removeAllAbstracts(); break;
case 20: _t->get_enter_checkbox_state((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData VideoAbstract_QTver::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject VideoAbstract_QTver::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_VideoAbstract_QTver,
qt_meta_data_VideoAbstract_QTver, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &VideoAbstract_QTver::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *VideoAbstract_QTver::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *VideoAbstract_QTver::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_VideoAbstract_QTver))
return static_cast<void*>(const_cast< VideoAbstract_QTver*>(this));
return QWidget::qt_metacast(_clname);
}
int VideoAbstract_QTver::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 21)
qt_static_metacall(this, _c, _id, _a);
_id -= 21;
}
return _id;
}
// SIGNAL 0
void VideoAbstract_QTver::sendSwitchToRealTimeForm()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
QT_END_MOC_NAMESPACE
| 37.830189
| 198
| 0.62128
|
billhhh
|
a219274fdbaeb5d5349d0e396011930fd1ae8130
| 10,875
|
hpp
|
C++
|
include/System/Net/HttpWebResponse.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Net/HttpWebResponse.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Net/HttpWebResponse.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Net.WebResponse
#include "System/Net/WebResponse.hpp"
// Including type: System.Net.HttpStatusCode
#include "System/Net/HttpStatusCode.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Uri
class Uri;
// Forward declaring type: Version
class Version;
}
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: WebHeaderCollection
class WebHeaderCollection;
// Forward declaring type: CookieCollection
class CookieCollection;
// Forward declaring type: CookieContainer
class CookieContainer;
// Forward declaring type: WebConnectionData
class WebConnectionData;
}
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: Stream
class Stream;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Completed forward declares
// Type namespace: System.Net
namespace System::Net {
// Size: 0x78
#pragma pack(push, 1)
// Autogenerated type: System.Net.HttpWebResponse
class HttpWebResponse : public System::Net::WebResponse {
public:
// private System.Uri uri
// Size: 0x8
// Offset: 0x18
System::Uri* uri;
// Field size check
static_assert(sizeof(System::Uri*) == 0x8);
// private System.Net.WebHeaderCollection webHeaders
// Size: 0x8
// Offset: 0x20
System::Net::WebHeaderCollection* webHeaders;
// Field size check
static_assert(sizeof(System::Net::WebHeaderCollection*) == 0x8);
// private System.Net.CookieCollection cookieCollection
// Size: 0x8
// Offset: 0x28
System::Net::CookieCollection* cookieCollection;
// Field size check
static_assert(sizeof(System::Net::CookieCollection*) == 0x8);
// private System.String method
// Size: 0x8
// Offset: 0x30
::Il2CppString* method;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Version version
// Size: 0x8
// Offset: 0x38
System::Version* version;
// Field size check
static_assert(sizeof(System::Version*) == 0x8);
// private System.Net.HttpStatusCode statusCode
// Size: 0x4
// Offset: 0x40
System::Net::HttpStatusCode statusCode;
// Field size check
static_assert(sizeof(System::Net::HttpStatusCode) == 0x4);
// Padding between fields: statusCode and: statusDescription
char __padding5[0x4] = {};
// private System.String statusDescription
// Size: 0x8
// Offset: 0x48
::Il2CppString* statusDescription;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Int64 contentLength
// Size: 0x8
// Offset: 0x50
int64_t contentLength;
// Field size check
static_assert(sizeof(int64_t) == 0x8);
// private System.String contentType
// Size: 0x8
// Offset: 0x58
::Il2CppString* contentType;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Net.CookieContainer cookie_container
// Size: 0x8
// Offset: 0x60
System::Net::CookieContainer* cookie_container;
// Field size check
static_assert(sizeof(System::Net::CookieContainer*) == 0x8);
// private System.Boolean disposed
// Size: 0x1
// Offset: 0x68
bool disposed;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: disposed and: stream
char __padding10[0x7] = {};
// private System.IO.Stream stream
// Size: 0x8
// Offset: 0x70
System::IO::Stream* stream;
// Field size check
static_assert(sizeof(System::IO::Stream*) == 0x8);
// Creating value type constructor for type: HttpWebResponse
HttpWebResponse(System::Uri* uri_ = {}, System::Net::WebHeaderCollection* webHeaders_ = {}, System::Net::CookieCollection* cookieCollection_ = {}, ::Il2CppString* method_ = {}, System::Version* version_ = {}, System::Net::HttpStatusCode statusCode_ = {}, ::Il2CppString* statusDescription_ = {}, int64_t contentLength_ = {}, ::Il2CppString* contentType_ = {}, System::Net::CookieContainer* cookie_container_ = {}, bool disposed_ = {}, System::IO::Stream* stream_ = {}) noexcept : uri{uri_}, webHeaders{webHeaders_}, cookieCollection{cookieCollection_}, method{method_}, version{version_}, statusCode{statusCode_}, statusDescription{statusDescription_}, contentLength{contentLength_}, contentType{contentType_}, cookie_container{cookie_container_}, disposed{disposed_}, stream{stream_} {}
// Deleting conversion operator: operator ::Il2CppObject*
constexpr operator ::Il2CppObject*() const noexcept = delete;
// System.Void .ctor(System.Uri uri, System.String method, System.Net.WebConnectionData data, System.Net.CookieContainer container)
// Offset: 0x163F94C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HttpWebResponse* New_ctor(System::Uri* uri, ::Il2CppString* method, System::Net::WebConnectionData* data, System::Net::CookieContainer* container) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>(uri, method, data, container)));
}
// public System.Net.HttpStatusCode get_StatusCode()
// Offset: 0x1641068
System::Net::HttpStatusCode get_StatusCode();
// public System.String get_StatusDescription()
// Offset: 0x1641070
::Il2CppString* get_StatusDescription();
// System.Void ReadAll()
// Offset: 0x163EE54
void ReadAll();
// private System.Void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
// Offset: 0x1641134
void System_Runtime_Serialization_ISerializable_GetObjectData(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext);
// private System.Void System.IDisposable.Dispose()
// Offset: 0x16412B4
void System_IDisposable_Dispose();
// private System.Void CheckDisposed()
// Offset: 0x1640FBC
void CheckDisposed();
// private System.Void FillCookies()
// Offset: 0x1640AF8
void FillCookies();
// protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
// Offset: 0x1640D10
// Implemented from: System.Net.WebResponse
// Base method: System.Void WebResponse::.ctor(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HttpWebResponse* New_ctor(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>(serializationInfo, streamingContext)));
}
// public override System.Net.WebHeaderCollection get_Headers()
// Offset: 0x1640F90
// Implemented from: System.Net.WebResponse
// Base method: System.Net.WebHeaderCollection WebResponse::get_Headers()
System::Net::WebHeaderCollection* get_Headers();
// public override System.Uri get_ResponseUri()
// Offset: 0x1640F98
// Implemented from: System.Net.WebResponse
// Base method: System.Uri WebResponse::get_ResponseUri()
System::Uri* get_ResponseUri();
// public override System.IO.Stream GetResponseStream()
// Offset: 0x1641094
// Implemented from: System.Net.WebResponse
// Base method: System.IO.Stream WebResponse::GetResponseStream()
System::IO::Stream* GetResponseStream();
// protected override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
// Offset: 0x1641140
// Implemented from: System.Net.WebResponse
// Base method: System.Void WebResponse::GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
void GetObjectData(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext);
// public override System.Void Close()
// Offset: 0x1641290
// Implemented from: System.Net.WebResponse
// Base method: System.Void WebResponse::Close()
void Close();
// protected override System.Void Dispose(System.Boolean disposing)
// Offset: 0x16412C4
// Implemented from: System.Net.WebResponse
// Base method: System.Void WebResponse::Dispose(System.Boolean disposing)
void Dispose(bool disposing);
// public System.Void .ctor()
// Offset: 0x16412D8
// Implemented from: System.Net.WebResponse
// Base method: System.Void WebResponse::.ctor()
// Base method: System.Void MarshalByRefObject::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HttpWebResponse* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>()));
}
}; // System.Net.HttpWebResponse
#pragma pack(pop)
static check_size<sizeof(HttpWebResponse), 112 + sizeof(System::IO::Stream*)> __System_Net_HttpWebResponseSizeCheck;
static_assert(sizeof(HttpWebResponse) == 0x78);
}
DEFINE_IL2CPP_ARG_TYPE(System::Net::HttpWebResponse*, "System.Net", "HttpWebResponse");
| 50.115207
| 792
| 0.713379
|
darknight1050
|
b8cbe36dcdf1dde5ca15ed055ff885b50aa3be44
| 710
|
cpp
|
C++
|
spider/shared/net/tcpconn_handler.cpp
|
wonghoifung/learning-python
|
ad1691be1d185bfff828779a553b2c59d36d16ea
|
[
"MIT"
] | null | null | null |
spider/shared/net/tcpconn_handler.cpp
|
wonghoifung/learning-python
|
ad1691be1d185bfff828779a553b2c59d36d16ea
|
[
"MIT"
] | null | null | null |
spider/shared/net/tcpconn_handler.cpp
|
wonghoifung/learning-python
|
ad1691be1d185bfff828779a553b2c59d36d16ea
|
[
"MIT"
] | null | null | null |
//
// Created by huanghaifeng on 15-9-1.
// Copyright (c) 2015 wonghoifung. All rights reserved.
//
#include "tcpconn_handler.h"
#include "shared/utils/logger.h"
tcpconn_handler::tcpconn_handler()
{
}
tcpconn_handler::~tcpconn_handler()
{
}
void tcpconn_handler::on_highwatermark(tcpconn_ptr conn, size_t size, size_t count)
{
}
void tcpconn_handler::set_default_sockbuf(tcpconn_ptr& conn)
{
int ret = conn->set_sndbuf_size(1024 * 64);
if (0 != ret)
{
logstr("peer(%s), set_sndbuf_size failure, err:%d", conn->remoteaddr().c_str(), ret);
}
ret = conn->set_rcvbuf_size(1024 * 32);
if (0 != ret)
{
logstr("peer(%s), set_rcvbuf_size failure, err:%d", conn->remoteaddr().c_str(), ret);
}
}
| 18.684211
| 88
| 0.690141
|
wonghoifung
|
b8cce46fa44b9e0520c7c6b9d38e8ec00dae1f9b
| 5,678
|
cpp
|
C++
|
coreLibrary_200/source/core/dgSPDMatrix.cpp
|
rastullahs-lockenpracht/newton
|
99b82478f3de9ee7c8d17c8ebefe62e46283d857
|
[
"Zlib"
] | null | null | null |
coreLibrary_200/source/core/dgSPDMatrix.cpp
|
rastullahs-lockenpracht/newton
|
99b82478f3de9ee7c8d17c8ebefe62e46283d857
|
[
"Zlib"
] | null | null | null |
coreLibrary_200/source/core/dgSPDMatrix.cpp
|
rastullahs-lockenpracht/newton
|
99b82478f3de9ee7c8d17c8ebefe62e46283d857
|
[
"Zlib"
] | null | null | null |
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* 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 "dgStdafx.h"
#include "dgMemory.h"
#include "dgSPDMatrix.h"
//static bool CholeskyDecomposition (dgFloat32 **rowPointers, dgInt32 size);
//static void BackAndForwardSustitition (dgFloat32 **rowPointers, dgInt32 size, dgFloat32 *rightsideVector);
/*
bool _CholeskyDecomposition (
void *rowPointers,
dgInt32 rowStrideInBytes,
dgInt32 typeSizeInBytes,
dgInt32 size)
{
dgUnsigned8 *rowArray;
rowArray = (dgUnsigned8*)rowPointers;
if (typeSizeInBytes == sizeof (dgFloat32)) {
dgInt32 i;
dgFloat32 **rows;
rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*));
for (i = 0; i < size; i ++) {
rows[i] = *((dgFloat32 **)rowArray);
rowArray += rowStrideInBytes;
}
return CholeskyDecomposition (rows, size);
} else {
_ASSERTE (0);
_ASSERTE (typeSizeInBytes == sizeof (dgFloat64));
}
return true;
}
*/
/*
void _BackAndForwardSustitition (
void *rightsideVector,
void *rowPointers,
dgInt32 rowStrideInBytes,
dgInt32 typeSizeInBytes,
dgInt32 size)
{
dgUnsigned8 *rowArray;
rowArray = (dgUnsigned8*)rowPointers;
if (typeSizeInBytes == sizeof (dgFloat32)) {
dgInt32 i;
dgFloat32 **rows;
rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*));
for (i = 0; i < size; i ++) {
rows[i] = *((dgFloat32 **)rowArray);
rowArray += rowStrideInBytes;
}
BackAndForwardSustitition (rows, size, (dgFloat32*)rightsideVector);
} else {
_ASSERTE (0);
_ASSERTE (typeSizeInBytes == sizeof (dgFloat64));
}
}
*/
/*
bool _SolveByCholeskyDecomposition (
void *rightsideVector,
void *rowPointers,
dgInt32 rowStrideInBytes,
dgInt32 typeSizeInBytes,
dgInt32 size)
{
dgUnsigned8 *rowArray;
rowArray = (dgUnsigned8*)rowPointers;
if (typeSizeInBytes == sizeof (dgFloat32)) {
dgInt32 i;
dgFloat32 **rows;
rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*));
for (i = 0; i < size; i ++) {
rows[i] = *((dgFloat32 **)rowArray);
rowArray += rowStrideInBytes;
}
if (CholeskyDecomposition (rows, size)) {
BackAndForwardSustitition (rows, size, (dgFloat32*)rightsideVector);
return true;
}
} else {
_ASSERTE (0);
_ASSERTE (typeSizeInBytes == sizeof (dgFloat64));
}
return false;
}
*/
/*
void BackAndForwardSustitition (
dgFloat32 **rows,
dgInt32 size,
dgFloat32 *B)
{
dgInt32 i;
dgInt32 j;
dgFloat32 acc;
//dgSPDMatrix<dgFloat32> M (8);
//M.CholeskyDecomposition();
#ifdef DG_COUNT_FLOAT_OPS
dgInt32 memCount;
dgInt32 floatCount;
memCount = dgGeneralVector<dgFloat32>::GetMemWrites();
floatCount = dgGeneralVector<dgFloat32>::GetFloatOps();
#endif
B[0] = B[0] / rows[0][0];
for (i = 1; i < size; i ++) {
acc = 0.0f;
for (j = 0; j < i; j ++) {
acc = acc + rows[j][i] * B[j];
#ifdef DG_COUNT_FLOAT_OPS
floatCount += 2;
#endif
}
B[i] = (B[i] - acc) / rows[i][i];
#ifdef DG_COUNT_FLOAT_OPS
floatCount += 2;
memCount += 1;
#endif
}
B[size-1] = B[size-1] / rows[size-1][size-1];
for (i = size - 2; i >= 0; i --) {
acc = 0.0f;
dgFloat32 *row;
row = rows[i];
for (j = i + 1; j < size; j ++) {
acc = acc + row[j] * B[j];
#ifdef DG_COUNT_FLOAT_OPS
floatCount += 2;
#endif
}
B[i] = (B[i] - acc) / rows[i][i];
#ifdef DG_COUNT_FLOAT_OPS
floatCount += 2;
memCount += 1;
#endif
}
#ifdef DG_COUNT_FLOAT_OPS
dgGeneralVector<dgFloat32>::SetMemWrites(memCount);
dgGeneralVector<dgFloat32>::SetFloatOps(floatCount);
#endif
}
*/
/*
bool CholeskyDecomposition (dgFloat32 **rows, dgInt32 size)
{
dgInt32 i;
dgInt32 j;
dgInt32 k;
dgFloat32 factor;
#ifdef DG_COUNT_FLOAT_OPS
dgInt32 memCount;
dgInt32 floatCount;
memCount = dgGeneralVector<dgFloat32>::GetMemWrites();
floatCount = dgGeneralVector<dgFloat32>::GetFloatOps();
#endif
for (j = 0; j < size; j++) {
for (k = 0; k < j; k ++ ) {
factor = rows[k][j];
if (dgAbsf (factor) > 1.0e-6f) {
for (i = j; i < size; i ++) {
rows[j][i] -= rows[k][i] * factor;
#ifdef DG_COUNT_FLOAT_OPS
memCount += 1;
floatCount += 2;
#endif
}
}
}
factor = rows[j][j];
if (factor <= 0.0f) {
if (factor <= -5.0e-4f) {
return false;
}
factor = 1.0e-12f;
}
factor = dgSqrt (factor);
rows[j][j] = factor;
factor = 1.0f / factor;
#ifdef DG_COUNT_FLOAT_OPS
memCount += 1;
floatCount += 1;
#endif
for (k = j + 1; k < size; k ++) {
rows[j][k] *= factor;
#ifdef DG_COUNT_FLOAT_OPS
memCount += 1;
floatCount += 1;
#endif
}
}
#ifdef DG_COUNT_FLOAT_OPS
dgGeneralVector<dgFloat32>::SetMemWrites(memCount);
dgGeneralVector<dgFloat32>::SetFloatOps(floatCount);
#endif
return true;
}
*/
| 22.621514
| 109
| 0.645826
|
rastullahs-lockenpracht
|
b8ccf145d567676eab9664e83a4c16491e117826
| 5,253
|
cpp
|
C++
|
Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCCertificateGenerator.cpp
|
jacadcaps/webkitty
|
9aebd2081349f9a7b5d168673c6f676a1450a66d
|
[
"BSD-2-Clause"
] | 6
|
2021-07-05T16:09:39.000Z
|
2022-03-06T22:44:42.000Z
|
Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCCertificateGenerator.cpp
|
jacadcaps/webkitty
|
9aebd2081349f9a7b5d168673c6f676a1450a66d
|
[
"BSD-2-Clause"
] | 7
|
2022-03-15T13:25:39.000Z
|
2022-03-15T13:25:44.000Z
|
Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCCertificateGenerator.cpp
|
jacadcaps/webkitty
|
9aebd2081349f9a7b5d168673c6f676a1450a66d
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (C) 2018 Apple Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS 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 "config.h"
#include "LibWebRTCCertificateGenerator.h"
#if USE(LIBWEBRTC)
#include "JSDOMPromiseDeferred.h"
#include "JSRTCCertificate.h"
#include "LibWebRTCMacros.h"
#include "RTCCertificate.h"
ALLOW_UNUSED_PARAMETERS_BEGIN
#include <webrtc/rtc_base/rtc_certificate_generator.h>
ALLOW_UNUSED_PARAMETERS_END
namespace WebCore {
namespace LibWebRTCCertificateGenerator {
static inline String fromStdString(const std::string& value)
{
return String::fromUTF8(value.data(), value.length());
}
class RTCCertificateGeneratorCallback : public ThreadSafeRefCounted<RTCCertificateGeneratorCallback, WTF::DestructionThread::Main>, public rtc::RTCCertificateGeneratorCallback {
public:
RTCCertificateGeneratorCallback(Ref<SecurityOrigin>&& origin, DOMPromiseDeferred<IDLInterface<RTCCertificate>>&& promise)
: m_origin(WTFMove(origin))
, m_promise(WTFMove(promise))
{
}
void AddRef() const { ref(); }
rtc::RefCountReleaseStatus Release() const
{
auto result = refCount() - 1;
deref();
return result ? rtc::RefCountReleaseStatus::kOtherRefsRemained : rtc::RefCountReleaseStatus::kDroppedLastRef;
}
private:
void OnSuccess(const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) final
{
callOnMainThread([origin = m_origin.releaseNonNull(), promise = WTFMove(m_promise.value()), certificate]() mutable {
Vector<RTCCertificate::DtlsFingerprint> fingerprints;
auto stats = certificate->ssl_certificate().GetStats();
auto* info = stats.get();
while (info) {
StringView fingerprint { reinterpret_cast<const unsigned char*>(info->fingerprint.data()), static_cast<unsigned>(info->fingerprint.length()) };
fingerprints.append({ fromStdString(info->fingerprint_algorithm), fingerprint.convertToASCIILowercase() });
info = info->issuer.get();
};
auto pem = certificate->ToPEM();
promise.resolve(RTCCertificate::create(WTFMove(origin), certificate->Expires(), WTFMove(fingerprints), fromStdString(pem.certificate()), fromStdString(pem.private_key())));
});
}
void OnFailure() final
{
callOnMainThread([promise = WTFMove(m_promise.value())]() mutable {
promise.reject(Exception { TypeError, "Unable to create a certificate"_s});
});
}
RefPtr<SecurityOrigin> m_origin;
Optional<DOMPromiseDeferred<IDLInterface<RTCCertificate>>> m_promise;
};
static inline rtc::KeyParams keyParamsFromCertificateType(const PeerConnectionBackend::CertificateInformation& info)
{
switch (info.type) {
case PeerConnectionBackend::CertificateInformation::Type::ECDSAP256:
return rtc::KeyParams::ECDSA();
case PeerConnectionBackend::CertificateInformation::Type::RSASSAPKCS1v15:
if (info.rsaParameters)
return rtc::KeyParams::RSA(info.rsaParameters->modulusLength, info.rsaParameters->publicExponent);
return rtc::KeyParams::RSA(2048, 65537);
}
RELEASE_ASSERT_NOT_REACHED();
}
void generateCertificate(Ref<SecurityOrigin>&& origin, LibWebRTCProvider& provider, const PeerConnectionBackend::CertificateInformation& info, DOMPromiseDeferred<IDLInterface<RTCCertificate>>&& promise)
{
rtc::scoped_refptr<RTCCertificateGeneratorCallback> callback(new rtc::RefCountedObject<RTCCertificateGeneratorCallback>(WTFMove(origin), WTFMove(promise)));
absl::optional<uint64_t> expiresMs;
if (info.expires)
expiresMs = static_cast<uint64_t>(*info.expires);
provider.prepareCertificateGenerator([info, expiresMs, callback = WTFMove(callback)](auto& generator) mutable {
generator.GenerateCertificateAsync(keyParamsFromCertificateType(info), expiresMs, WTFMove(callback));
});
}
} // namespace LibWebRTCCertificateGenerator
} // namespace WebCore
#endif // USE(LIBWEBRTC)
| 41.362205
| 202
| 0.733295
|
jacadcaps
|
b8d25404da4825927f28a42d9c7e9f05978cdb7d
| 2,014
|
cpp
|
C++
|
src/ck/android/ck/src/main/cpp/com_crickettechnology_audio_Bank.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 23
|
2020-02-23T23:20:22.000Z
|
2021-12-30T16:09:23.000Z
|
src/ck/android/ck/src/main/cpp/com_crickettechnology_audio_Bank.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 3
|
2020-03-17T05:50:40.000Z
|
2020-10-12T18:18:44.000Z
|
src/ck/android/ck/src/main/cpp/com_crickettechnology_audio_Bank.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 10
|
2020-03-02T15:07:32.000Z
|
2022-01-29T03:34:55.000Z
|
#include <jni.h>
#include "ck/bank.h"
#include "ck/core/javastringref_android.h"
extern "C"
{
jboolean Java_com_crickettechnology_audio_Bank_nativeIsLoaded(JNIEnv* env, jclass, jlong inst)
{
CkBank* bank = (CkBank*) inst;
return bank->isLoaded();
}
jboolean Java_com_crickettechnology_audio_Bank_nativeIsFailed(JNIEnv* env, jclass, jlong inst)
{
CkBank* bank = (CkBank*) inst;
return bank->isFailed();
}
jstring Java_com_crickettechnology_audio_Bank_nativeGetName(JNIEnv* env, jclass, jlong inst)
{
CkBank* bank = (CkBank*) inst;
const char* name = bank->getName();
return env->NewStringUTF(name);
}
jint Java_com_crickettechnology_audio_Bank_nativeGetNumSounds(JNIEnv*, jclass, jlong inst)
{
CkBank* bank = (CkBank*) inst;
return bank->getNumSounds();
}
jstring Java_com_crickettechnology_audio_Bank_nativeGetSoundName(JNIEnv* env, jclass, jlong inst, jint index)
{
CkBank* bank = (CkBank*) inst;
const char* name = bank->getSoundName(index);
return env->NewStringUTF(name);
}
jlong Java_com_crickettechnology_audio_Bank_nativeNewBank(JNIEnv* env, jclass, jstring pathStr, jint pathType, jint offset, jint length)
{
Cki::JavaStringRef path(env, pathStr);
CkBank* bank = CkBank::newBank(path.getChars(), (CkPathType) pathType, offset, length);
return (jlong) bank;
}
jlong Java_com_crickettechnology_audio_Bank_nativeNewBankAsync(JNIEnv* env, jclass, jstring pathStr, jint pathType, jint offset, jint length)
{
Cki::JavaStringRef path(env, pathStr);
CkBank* bank = CkBank::newBankAsync(path.getChars(), (CkPathType) pathType, offset, length);
return (jlong) bank;
}
jlong Java_com_crickettechnology_audio_Bank_nativeFind(JNIEnv* env, jclass, jstring nameStr)
{
Cki::JavaStringRef name(env, nameStr);
CkBank* bank = CkBank::find(name.getChars());
return (jlong) bank;
}
void Java_com_crickettechnology_audio_Bank_nativeDestroy(JNIEnv*, jclass, jlong inst)
{
CkBank* bank = (CkBank*) inst;
bank->destroy();
}
}
| 28.771429
| 141
| 0.739821
|
opala-studios
|