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
bd863a4e1b341441b3700fe3931c9bb78c159ee6
1,862
cpp
C++
mmcv/ops/csrc/parrots/pixel_group_parrots.cpp
BIGWangYuDong/mmcv
c46deb0576edaff5cd5a7d384c617478c7a73a70
[ "Apache-2.0" ]
3,748
2018-10-12T08:39:46.000Z
2022-03-31T17:22:55.000Z
mmcv/ops/csrc/parrots/pixel_group_parrots.cpp
BIGWangYuDong/mmcv
c46deb0576edaff5cd5a7d384c617478c7a73a70
[ "Apache-2.0" ]
1,637
2018-10-12T06:06:18.000Z
2022-03-31T02:20:53.000Z
mmcv/ops/csrc/parrots/pixel_group_parrots.cpp
BIGWangYuDong/mmcv
c46deb0576edaff5cd5a7d384c617478c7a73a70
[ "Apache-2.0" ]
1,234
2018-10-12T09:28:20.000Z
2022-03-31T15:56:24.000Z
// Copyright (c) OpenMMLab. All rights reserved #include <parrots/compute/aten.hpp> #include <parrots/extension.hpp> #include <parrots/foundation/ssattrs.hpp> #include "pixel_group_pytorch.h" using namespace parrots; using namespace std; template <typename T> void pixel_group_parrots(T& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { int kernel_region_num; float distance_threshold; SSAttrs(attr) .get<int>("kernel_region_num", kernel_region_num) .get<float>("distance_threshold", distance_threshold) .done(); at::Tensor score; at::Tensor mask; at::Tensor embedding; at::Tensor kernel_label; at::Tensor kernel_contour; score = buildATensor(ctx, ins[0]); mask = buildATensor(ctx, ins[1]); embedding = buildATensor(ctx, ins[2]); kernel_label = buildATensor(ctx, ins[3]); kernel_contour = buildATensor(ctx, ins[4]); auto out = pixel_group(score, mask, embedding, kernel_label, kernel_contour, kernel_region_num, distance_threshold); int n = out.size(); std::vector<float> out_tensor; for (int i = 0; i < n; ++i) out_tensor.push_back(float(out[i].size())); for (int i = 0; i < n; ++i) out_tensor.insert(out_tensor.end(), out[i].begin(), out[i].end()); auto options = torch::TensorOptions().dtype(at::kFloat); auto tensor = torch::zeros({1, out_tensor.size()}, options); tensor.slice(0, 0, 1) = torch::from_blob(out_tensor.data(), {out_tensor.size()}, options); updateDArray(ctx, tensor, outs[0]); } PARROTS_EXTENSION_REGISTER(pixel_group) .attr("kernel_region_num") .attr("distance_threshold") .input(5) .output(1) .apply(pixel_group_parrots<HostContext>) #ifdef MMCV_WITH_CUDA .apply(pixel_group_parrots<CudaContext>) #endif .done();
33.854545
78
0.679914
BIGWangYuDong
bd8cb4c8d122a1aebe81e79a9f19b7fe39a5a6a8
8,467
cpp
C++
src/apps/ojph_expand/ojph_expand.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
src/apps/ojph_expand/ojph_expand.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
src/apps/ojph_expand/ojph_expand.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************/ // This software is released under the 2-Clause BSD license, included // below. // // Copyright (c) 2019, Aous Naman // Copyright (c) 2019, Kakadu Software Pty Ltd, Australia // Copyright (c) 2019, The University of New South Wales, Australia // // 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 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. /****************************************************************************/ // This file is part of the OpenJPH software implementation. // File: ojph_expand.cpp // Author: Aous Naman // Date: 28 August 2019 /****************************************************************************/ #include <ctime> #include <iostream> #include <cstdlib> #include "ojph_arg.h" #include "ojph_mem.h" #include "ojph_img_io.h" #include "ojph_file.h" #include "ojph_codestream.h" #include "ojph_params.h" #include "ojph_message.h" ////////////////////////////////////////////////////////////////////////////// bool get_arguments(int argc, char *argv[], char *&input_filename, char *&output_filename) { ojph::cli_interpreter interpreter; interpreter.init(argc, argv); interpreter.reinterpret("-i", input_filename); interpreter.reinterpret("-o", output_filename); if (interpreter.is_exhausted() == false) { printf("The following arguments were not interpreted:\n"); ojph::argument t = interpreter.get_argument_zero(); t = interpreter.get_next_avail_argument(t); while (t.is_valid()) { printf("%s\n", t.arg); t = interpreter.get_next_avail_argument(t); } return false; } return true; } ///////////////////////////////////////////////////////////////////////////// const char *get_file_extension(const char *filename) { size_t len = strlen(filename); return filename + ojph_max(0, len - 4); } ///////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { char *input_filename = NULL; char *output_filename = NULL; if (argc <= 1) { std::cout << "\nThe following arguments are necessary:\n" " -i input file name\n" " -o output file name (either pgm, ppm, or yuv)\n\n" ; return -1; } if (!get_arguments(argc, argv, input_filename, output_filename)) { return -1; } clock_t begin = clock(); try { ojph::j2c_infile j2c_file; j2c_file.open(input_filename); ojph::codestream codestream; ojph::ppm_out ppm; ojph::yuv_out yuv; ojph::image_out_base *base = NULL; const char *v = get_file_extension(output_filename); if (v) { codestream.read_headers(&j2c_file); ojph::param_siz_t siz = codestream.access_siz(); if (strncmp(".pgm", v, 4) == 0) { if (siz.get_num_components() != 1) OJPH_ERROR(0x020000001, "The file has more than one color component, but .pgm can " "contain only on color component\n"); ppm.configure(siz.get_image_extent().x - siz.get_image_offset().x, siz.get_image_extent().y - siz.get_image_offset().y, siz.get_num_components(), siz.get_bit_depth(0)); ppm.open(output_filename); base = &ppm; } else if (strncmp(".ppm", v, 4) == 0) { codestream.set_planar(false); ojph::param_siz_t siz = codestream.access_siz(); if (siz.get_num_components() != 3) OJPH_ERROR(0x020000002, "The file has %d color components; this cannot be saved to" " a .ppm file\n", siz.get_num_components()); bool all_same = true; ojph::point p = siz.get_downsampling(0); for (int i = 1; i < siz.get_num_components(); ++i) { ojph::point p1 = siz.get_downsampling(i); all_same = all_same && (p1.x == p.x) && (p1.y == p.y); } if (!all_same) OJPH_ERROR(0x020000003, "To save an image to ppm, all the components must have the " "downsampling ratio\n"); ppm.configure(siz.get_image_extent().x - siz.get_image_offset().x, siz.get_image_extent().y - siz.get_image_offset().y, siz.get_num_components(), siz.get_bit_depth(0)); ppm.open(output_filename); base = &ppm; } else if (strncmp(".yuv", v, 4) == 0) { codestream.set_planar(true); ojph::param_siz_t siz = codestream.access_siz(); if (siz.get_num_components() != 3 && siz.get_num_components() != 1) OJPH_ERROR(0x020000004, "The file has %d color components; this cannot be saved to" " a .yuv file\n", siz.get_num_components()); ojph::param_cod_t cod = codestream.access_cod(); if (cod.is_using_color_transform()) OJPH_ERROR(0x020000005, "The current implementation of yuv file object does not " "support saving a file when conversion from yuv to rgb is needed; " "In any case, this is not the normal usage of a yuv file"); ojph::point points[3]; int max_bit_depth = 0; for (int i = 0; i < siz.get_num_components(); ++i) { points[i] = siz.get_downsampling(i); max_bit_depth = ojph_max(max_bit_depth, siz.get_bit_depth(i)); } codestream.set_planar(true); yuv.configure(siz.get_image_extent().x, siz.get_image_offset().x, max_bit_depth, siz.get_num_components(), points); yuv.open(output_filename); base = &yuv; } else OJPH_ERROR(0x020000006, "unknown output file extension; only (pgm, ppm, and yuv) are" " suppoted\n"); } else OJPH_ERROR(0x020000007, "Please supply a proper output filename with a proper three-letter" " extension\n"); codestream.create(); if (codestream.is_planar()) { ojph::param_siz_t siz = codestream.access_siz(); for (int c = 0; c < siz.get_num_components(); ++c) { ojph::point p = siz.get_downsampling(c); int height = ojph_div_ceil(siz.get_image_extent().y, p.y) - ojph_div_ceil(siz.get_image_offset().y, p.y); for (int i = height; i > 0; --i) { int comp_num; ojph::line_buf *line = codestream.pull(comp_num); assert(comp_num == c); base->write(line, comp_num); } } } else { ojph::param_siz_t siz = codestream.access_siz(); int height = siz.get_image_extent().y - siz.get_image_offset().y; for (int i = 0; i < height; ++i) { for (int c = 0; c < siz.get_num_components(); ++c) { int comp_num; ojph::line_buf *line = codestream.pull(comp_num); assert(comp_num == c); base->write(line, comp_num); } } } base->close(); codestream.close(); } catch (const std::exception& e) { const char *p = e.what(); if (strncmp(p, "ojph error", 10) != 0) printf("%s\n", p); exit(-1); } clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; printf("Elapsed time = %f\n", elapsed_secs); return 0; }
34.70082
79
0.590292
jpambrun
bd922daaccc417ac15d3a99e42e68c33da917872
5,404
cpp
C++
Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
515
2015-01-13T05:42:10.000Z
2022-03-29T03:10:01.000Z
Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
425
2015-01-06T05:28:38.000Z
2022-03-08T19:42:18.000Z
Libs/Widgets/Testing/Cpp/ctkMenuComboBoxEventTranslatorPlayerTest1.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
341
2015-01-08T06:18:17.000Z
2022-03-29T21:47:49.000Z
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // Qt includes #include <QAction> #include <QApplication> #include <QDebug> #include <QSignalSpy> #include <QStandardItemModel> #include <QTimer> #include <QTreeView> // CTK includes #include "ctkCallback.h" #include "ctkConfig.h" #include "ctkMenuComboBox.h" #include "ctkMenuComboBoxEventPlayer.h" #include "ctkMenuComboBoxEventTranslator.h" #include "ctkEventTranslatorPlayerWidget.h" // QtTesting includes #include "pqTestUtility.h" // STD includes #include <cstdlib> #include <iostream> namespace { QSignalSpy* Spy1; QSignalSpy* Spy2; QSignalSpy* Spy3; QSignalSpy* Spy4; QSignalSpy* Spy5; QSignalSpy* Spy6; QSignalSpy* Spy7; QSignalSpy* Spy8; //----------------------------------------------------------------------------- void checkFinalWidgetState(void* data) { ctkMenuComboBox* widget = reinterpret_cast<ctkMenuComboBox*>(data); Q_UNUSED(widget); CTKCOMPARE(Spy1->count(), 2); CTKCOMPARE(Spy2->count(), 2); CTKCOMPARE(Spy3->count(), 2); CTKCOMPARE(Spy4->count(), 2); } //----------------------------------------------------------------------------- void checkFinalWidgetState2(void* data) { ctkMenuComboBox* widget = reinterpret_cast<ctkMenuComboBox*>(data); Q_UNUSED(widget); CTKCOMPARE(Spy5->count(), 1); CTKCOMPARE(Spy6->count(), 1); CTKCOMPARE(Spy7->count(), 1); CTKCOMPARE(Spy8->count(), 1); } } //----------------------------------------------------------------------------- int ctkMenuComboBoxEventTranslatorPlayerTest1(int argc, char * argv [] ) { QApplication app(argc, argv); QString xmlDirectory = CTK_SOURCE_DIR "/Libs/Widgets/Testing/Cpp/"; // ------------------------ ctkEventTranslatorPlayerWidget etpWidget; pqTestUtility* testUtility = new pqTestUtility(&etpWidget); etpWidget.setTestUtility(testUtility); etpWidget.addWidgetEventPlayer(new ctkMenuComboBoxEventPlayer); etpWidget.addWidgetEventTranslator(new ctkMenuComboBoxEventTranslator); // Test case 1 - default behavior - Test Completer QWidget* widget = new QWidget(0); QMenu* menu = new QMenu("File", widget); QAction* action1 = new QAction("first", widget); menu->addAction(action1); QMenu* wizards = new QMenu("Wizards", menu); menu->addMenu(wizards); QMenu*informatics = new QMenu("Informatics", menu); menu->addMenu(informatics); QAction* action2 = new QAction("extra choice 1", widget); QAction* action3 = new QAction("extra choice 2", widget); QAction* action4 = new QAction("extra choice 3", widget); menu->addAction(action2); menu->addAction(wizards->menuAction()); menu->addAction(informatics->menuAction()); wizards->addAction(action3); informatics->addAction(action4); QSignalSpy spy1(action1, SIGNAL(triggered())); QSignalSpy spy2(action2, SIGNAL(triggered())); QSignalSpy spy3(action3, SIGNAL(triggered())); QSignalSpy spy4(action4, SIGNAL(triggered())); Spy1 = &spy1; Spy2 = &spy2; Spy3 = &spy3; Spy4 = &spy4; ctkMenuComboBox* menuComboBox = new ctkMenuComboBox(widget); menuComboBox->setMenu(menu); etpWidget.addTestCase(widget, xmlDirectory + "ctkMenuComboBoxEventTranslatorPlayerTest1.xml", &checkFinalWidgetState); // Test case 2 - default behavior - test Menu QWidget* widget2 = new QWidget(0); ctkMenuComboBox* menuComboBox2 = new ctkMenuComboBox(widget2); QMenu* menu2 = new QMenu("File", menuComboBox2); QAction* action5 = new QAction("first", menu2); menu2->addAction(action5); QMenu* wizards2 = new QMenu("Wizards", menu2); menu2->addMenu(wizards2); QMenu*informatics2 = new QMenu("Informatics", menu2); menu2->addMenu(informatics2); QAction* action6 = new QAction("extra choice 1", menu2); QAction* action7 = new QAction("extra choice 2", menu2); QAction* action8 = new QAction("extra choice 3", menu2); menu2->addAction(action6); // menu2->addAction(wizards2->menuAction()); // menu2->addAction(informatics2->menuAction()); wizards2->addAction(action7); informatics2->addAction(action8); QSignalSpy spy5(action5, SIGNAL(triggered())); QSignalSpy spy6(action6, SIGNAL(triggered())); QSignalSpy spy7(action7, SIGNAL(triggered())); QSignalSpy spy8(action8, SIGNAL(triggered())); Spy5 = &spy5; Spy6 = &spy6; Spy7 = &spy7; Spy8 = &spy8; menuComboBox2->setMenu(menu2); etpWidget.addTestCase(widget2, xmlDirectory + "ctkMenuComboBoxEventTranslatorPlayerTest2.xml", &checkFinalWidgetState2); // ------------------------ if (argc < 2 || QString(argv[1]) != "-I") { QTimer::singleShot(0, &etpWidget, SLOT(play())); } etpWidget.show(); return app.exec(); }
30.531073
87
0.6547
kraehlit
bd940e7c4b6d7610e3e7bab80961b0b6adbb6e7f
85
cpp
C++
src/Luddite/ECS/Reflection.cpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
1
2021-06-03T05:46:46.000Z
2021-06-03T05:46:46.000Z
src/Luddite/ECS/Reflection.cpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
src/Luddite/ECS/Reflection.cpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
#include "Luddite/ECS/Reflection.hpp" #include "Luddite/ECS/Modules/Transform3D.hpp"
28.333333
46
0.8
Aquaticholic
bd95838fa9cb565302869384616a7dd0189fb56a
11,570
cpp
C++
WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp
ahidaka/WinUSB_Collection
4a8362707272444a11aacb7d869da32a63baa5e8
[ "Apache-2.0" ]
null
null
null
WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp
ahidaka/WinUSB_Collection
4a8362707272444a11aacb7d869da32a63baa5e8
[ "Apache-2.0" ]
null
null
null
WinUSBFTDI/WinUSBFTDI-C/EnOceanSample/main.cpp
ahidaka/WinUSB_Collection
4a8362707272444a11aacb7d869da32a63baa5e8
[ "Apache-2.0" ]
4
2020-12-13T07:28:40.000Z
2022-01-18T05:55:05.000Z
#include "pch.h" #include <stdio.h> #include <stdlib.h> typedef struct _eep_data { UCHAR ROrg; UCHAR Func; UCHAR Type; USHORT ManID; } EEP_DATA, *PEEP_DATA; enum PacketType { Radio = 0x01, Response = 0x02, RadioSubTel = 0x03, Event = 0x04, CommonCommand = 0x05, SmartAckCommand = 0x06, RmoteManCommand = 0x07, RadioMessage = 0x09, RadioAdvanced = 0x0A }; UCHAR Crc8(PUCHAR Data, INT Count); UCHAR Crc8Ex(PUCHAR Data, INT Offset, INT Count); // // Globals // BOOL UseFilter; ULONG SwitchID; ULONG TempID; // // // VOID BufferFilter(PUCHAR Buffer, ULONG Id) { Buffer[0] = 0x55; // Sync Byte Buffer[1] = 0; // Data Length[0] Buffer[2] = 7; // Data Length[1] Buffer[3] = 0; // Optional Length Buffer[4] = 5; // Packet Type = CO (5) Buffer[5] = Crc8Ex(Buffer, 1, 4); // CRC8H Buffer[6] = 11; // Command Code = CO_WR_FILTER_ADD (11) Buffer[7] = 0; // FilterType = Device ID (0) Buffer[8] = (UCHAR)((Id >> 24) & 0xFF); // ID[0] Buffer[9] = (UCHAR)((Id >> 16) & 0xFF); // ID[1] Buffer[10] = (UCHAR)((Id >> 8) & 0xFF); // ID[2] Buffer[11] = (UCHAR)(Id & 0xFF); // ID[3] Buffer[12] = 0x80; // Filter Kind = apply (0x80) Buffer[13] = Crc8Ex(Buffer, 6, 7); // CRC8D } // // //UsbDeviceWrite( // _In_ PDEVICE_DATA DeviceData, // _In_ UCHAR* Buffer, // _In_ ULONG Length, // _Out_opt_ ULONG* pcbWritten //); BOOL PreparationFilter( _In_ PDEVICE_DATA DeviceData, _In_ BOOL Enable ) { BOOL clearFilter = true; BOOL writeFilter = Enable; ULONG wroteLength = 0; UCHAR buffer[16]; #define CHECK_RESULT(len) \ if (wroteLength != (len)) \ { \ printf("FILTER: length error=%d(%d)", wroteLength, len); \ return FALSE; \ } if (clearFilter) { if (true) { //printf("FILTER: Clear all Filters\n"); buffer[0] = 0x55; // Sync Byte buffer[1] = 0; // Data Length[0] buffer[2] = 1; // Data Length[1] buffer[3] = 0; // Optional Length buffer[4] = 5; // Packet Type = CO (5) buffer[5] = Crc8Ex(buffer, 1, 4); // CRC8H buffer[6] = 13; // Command Code = CO_WR_FILTER_DEL (13) buffer[7] = Crc8Ex(buffer, 6, 1); // CRC8D UsbDeviceWrite(DeviceData, buffer, 8, &wroteLength); CHECK_RESULT(8); Sleep(100); //GetResponse(); } if (writeFilter && SwitchID != 0) { printf("FILTER: SwitchID Add Filter=%08X\n", SwitchID); BufferFilter(buffer, SwitchID); UsbDeviceWrite(DeviceData, buffer, 14, &wroteLength); CHECK_RESULT(14); Sleep(100); } if (writeFilter && TempID != 0) { printf("FILTER: TempID Add Filter=%08X\n", TempID); BufferFilter(buffer, TempID); UsbDeviceWrite(DeviceData, buffer, 14, &wroteLength); CHECK_RESULT(14); Sleep(100); //GetResponse(); } } if (writeFilter) { printf("Enable Filters\n"); buffer[0] = 0x55; // Sync Byte buffer[1] = 0; // Data Length[0] buffer[2] = 3; // Data Length[1] buffer[3] = 0; // Optional Length buffer[4] = 5; // Packet Type = CO (5) buffer[5] = Crc8Ex(buffer, 1, 4); // CRC8H buffer[6] = 14; // Command Code = CO_WR_FILTER_ENABLE (14) buffer[7] = 1; // Filter Enable = ON (1) buffer[8] = 0; // Filter Operator = OR (0) //buffer[8] = 1; // Filter Operator = AND (1) buffer[9] = Crc8Ex(buffer, 6, 3); // CRC8D UsbDeviceWrite(DeviceData, buffer, 10, &wroteLength); CHECK_RESULT(10); Sleep(100); //GetResponse(); } return TRUE; #undef CHECK_RESULT } BOOL MainLoop(PDEVICE_DATA DeviceData) { const int BUFFER_SIZE = 64; UCHAR buffer[BUFFER_SIZE]; ULONG length; BOOL result; BOOL gotHeader; USHORT dataLength; USHORT optionalLength; ULONG readLength; UCHAR packetType = 0; UCHAR crc8h; UCHAR crc8d; UCHAR rOrg; UCHAR dataOffset; UCHAR dataSize; UCHAR id[4]; UCHAR data[4]; UCHAR nu; // printf("Enter MainLoop\n"); do { dataLength = optionalLength = 0; gotHeader = FALSE; result = UsbDeviceRead(DeviceData, buffer, 1, &length); if (!result) { printf("ERROR: !result\n"); return FALSE; } else if (length == 0) { Sleep(1); continue; } else if (buffer[0] != 0x55) { continue; } result = UsbDeviceRead(DeviceData, buffer, 5, &length); if (!result) { printf("ERROR: !result\n"); return FALSE; } else if (length != 5) { Sleep(1); printf("TRY: length != 5\n"); //// continue; } dataLength = buffer[0] << 8 | buffer[1]; optionalLength = buffer[2]; packetType = buffer[3]; crc8h = buffer[4]; gotHeader = crc8h == Crc8(buffer, 4); // printf("CRC8H: crc8h=%02X Calc=%02X\n", crc8h, Crc8(buffer, 4)); //// } while(!gotHeader); // printf("Got Header!\n"); //// readLength = dataLength + optionalLength + 1; if (readLength > BUFFER_SIZE) { // mayne something error but have to keep buffer size readLength = BUFFER_SIZE; } UsbDeviceRead(DeviceData, buffer, readLength, &length); if (!result) { printf("ERROR: !result\n"); return FALSE; } else if (length != readLength) { Sleep(1); return FALSE; } crc8d = buffer[readLength - 1]; if (crc8d != Crc8(buffer, readLength - 1)) { printf("CRC8D error!\n"); } else { // printf("CRC8D OK!\n"); } //printf("CRC8D: crc8d=%02X Calc=%02X\n", crc8d, Crc8(buffer, readLength - 1)); if (packetType == RadioAdvanced) { rOrg = buffer[0]; switch (rOrg) { case 0x62: //Teach-In dataOffset = 2; dataSize = 0; break; case 0x20: //RPS dataOffset = 0; dataSize = 1; break; case 0x22: //4BS dataOffset = 0; dataSize = 4; break; default: // not used dataOffset = 0; dataSize = 0; break; } id[3] = buffer[1 + dataOffset]; id[2] = buffer[2 + dataOffset]; id[1] = buffer[3 + dataOffset]; id[0] = buffer[4 + dataOffset]; switch (rOrg) { case 0x62: //Teach-In case 0x22: //4BS data[0] = buffer[5 + dataOffset]; data[1] = buffer[6 + dataOffset]; data[2] = buffer[7 + dataOffset]; data[3] = buffer[8 + dataOffset]; break; case 0x20: //RPS nu = (buffer[5 + dataOffset] >> 7) & 0x01; data[0] = buffer[5 + dataOffset] & 0x0F; data[1] = 0; // not used data[2] = 0; // not used data[3] = 0; // not used break; default: // not used break; } } return TRUE; } static UCHAR crc8Table[] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3 }; UCHAR Crc8Ex(PUCHAR Data, INT Offset, INT Count) { UCHAR crc = 0; Count += Offset; for (int i = Offset; i < Count; i++) crc = crc8Table[crc ^ Data[i]]; return crc; } UCHAR Crc8(PUCHAR Data, INT Count) { return Crc8Ex(Data, 0, Count); } VOID Usage(_In_ LPTSTR MyName) { printf("Usage: %ws [-f] [Switch-ID] [TempSensor-ID]\n\n", MyName); printf(" -f Use ID Filters for switch and sensors.\n"); printf(" Switch-ID EnOcean Locker Switch ID. '0' is not existing.\n"); printf(" TempSensor-ID EnOcean Temperature sensor ID. '0' is not existing.\n\n"); } LONG __cdecl _tmain( LONG Argc, LPTSTR * Argv ) { DEVICE_DATA deviceData; HRESULT hr; BOOL result; BOOL noDevice; INT argIndex = 0; if (Argc > 1) { if (Argv[1][0] == '-') { if (Argv[1][1] == 'f') { UseFilter = TRUE; argIndex++; } else { Usage(Argv[0]); return 0; } } } if (Argc > (1 + argIndex)) { SwitchID = wcstoul(Argv[1 + argIndex], NULL, 16); printf("SwitchID=%08X(%ws)\n", SwitchID, Argv[1 + argIndex]); } if (Argc > (2 + argIndex)) { TempID = wcstoul(Argv[2 + argIndex], NULL, 16); printf("TempID=%08X(%ws)\n", TempID, Argv[2 + argIndex]); } // // Find a device connected to the system that has WinUSB installed using our // INF // hr = UsbDeviceOpen(&deviceData, &noDevice); if (FAILED(hr)) { if (noDevice) { wprintf(L"Device not connected or driver not installed\n"); } else { wprintf(L"Failed looking for device, HRESULT 0x%x\n", hr); } UsbDeviceClose(&deviceData); return 0; } result = UsbDeviceInitialize(&deviceData, 57600); if (!result) { printf("Error !result\n"); UsbDeviceClose(&deviceData); return 0; } if (!PreparationFilter(&deviceData, UseFilter)) { printf("Error\n"); return 0; } do { result = MainLoop(&deviceData); } while (result); UsbDeviceClose(&deviceData); return 0; }
26.235828
86
0.51599
ahidaka
bd97657c4e1e7d4a0033b492126f2609bd309c34
639
cc
C++
src/core/imap/MCIMAPMessagePart.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
1
2020-10-14T21:44:57.000Z
2020-10-14T21:44:57.000Z
src/core/imap/MCIMAPMessagePart.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
null
null
null
src/core/imap/MCIMAPMessagePart.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
null
null
null
#include "MCIMAPMessagePart.h" using namespace mailcore; IMAPMessagePart::IMAPMessagePart() { init(); } IMAPMessagePart::IMAPMessagePart(IMAPMessagePart * other) : AbstractMessagePart(other) { init(); MC_SAFE_REPLACE_COPY(String, mPartID, other->mPartID); } IMAPMessagePart::~IMAPMessagePart() { MC_SAFE_RELEASE(mPartID); } Object * IMAPMessagePart::copy() { return new IMAPMessagePart(this); } void IMAPMessagePart::init() { mPartID = NULL; } void IMAPMessagePart::setPartID(String * partID) { MC_SAFE_REPLACE_COPY(String, mPartID, partID); } String * IMAPMessagePart::partID() { return mPartID; }
15.975
86
0.723005
zhanleewo
bd97fd78f6dce58444152e74d0fc4c93d312b2b5
4,120
cpp
C++
firmware/modules/core/cSound.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2021-02-09T16:17:43.000Z
2021-08-09T04:02:44.000Z
firmware/modules/core/cSound.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2016-05-17T20:45:10.000Z
2020-03-10T07:03:39.000Z
firmware/modules/core/cSound.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
1
2020-05-24T13:37:55.000Z
2020-05-24T13:37:55.000Z
#include "cMaster.h" #include "cModel.h" #include "cSound.h" #include <chrono> #define LOGLEVEL LEVEL_DEBUG #define LOGNAME "SOUND" #include "cLog.h" namespace sensact { static uint8_t send_buf[10] = {0x7E, 0xFF,0x06,0,0,0,0,0,0,0xEF}; //static bool is_reply = false; // static void fill_uint16_bigend (uint8_t *thebuf, uint16_t data) { *thebuf = (uint8_t)(data>>8); *(thebuf+1) = (uint8_t)data; } //calc checksum (1~6 byte) static uint16_t mp3_get_checksum (uint8_t *thebuf) { uint16_t sum = 0; for (int i=1; i<7; i++) { sum += thebuf[i]; } return -sum; } //fill checksum to send_buf (7~8 byte) static void mp3_fill_checksum () { uint16_t checksum = mp3_get_checksum (send_buf); fill_uint16_bigend (send_buf+7, checksum); } static void send_func () { HAL_UART_Transmit(&BSP::BELL, send_buf, 10, 1000); } static void mp3_send_cmd (uint8_t cmd, uint16_t arg) { send_buf[3] = cmd; fill_uint16_bigend ((send_buf+5), arg); mp3_fill_checksum (); send_func(); } //play mp3 file in mp3 folder in your tf card static void mp3_play (uint16_t num) { mp3_send_cmd (0x12, num); } static void mp3_set_volume (uint16_t volume) { mp3_send_cmd (0x06, volume); } /* static void mp3_send_cmd (uint8_t cmd) { send_buf[3] = cmd; fill_uint16_bigend ((send_buf+5), 0); mp3_fill_checksum (); send_func(); } static void mp3_set_reply (bool state) { is_reply = state; send_buf[4] = is_reply; } static void mp3_play () { mp3_send_cmd (0x0d); } // static void mp3_play_physical (uint16_t num) { mp3_send_cmd (0x03, num); } // static void mp3_play_physical () { mp3_send_cmd (0x03); } // static void mp3_next () { mp3_send_cmd (0x01); } // static void mp3_prev () { mp3_send_cmd (0x02); } //0x06 set volume 0-30 //0x07 set EQ0/1/2/3/4/5 Normal/Pop/Rock/Jazz/Classic/Bass static void mp3_set_EQ (uint16_t eq) { mp3_send_cmd (0x07, eq); } //0x09 set device 1/2/3/4/5 U/SD/AUX/SLEEP/FLASH static void mp3_set_device (uint16_t device) { mp3_send_cmd (0x09, device); } // static void mp3_sleep () { mp3_send_cmd (0x0a); } // static void mp3_reset () { mp3_send_cmd (0x0c); } // // static void mp3_pause () { mp3_send_cmd (0x0e); } // static void mp3_stop () { mp3_send_cmd (0x16); } // static void mp3_get_state () { mp3_send_cmd (0x42); } // static void mp3_get_volume () { mp3_send_cmd (0x43); } // static void mp3_get_u_sum () { mp3_send_cmd (0x47); } // static void mp3_get_tf_sum () { mp3_send_cmd (0x48); } // static void mp3_get_flash_sum () { mp3_send_cmd (0x49); } // static void mp3_get_tf_current () { mp3_send_cmd (0x4c); } // static void mp3_get_u_current () { mp3_send_cmd (0x4b); } // static void mp3_get_flash_current () { mp3_send_cmd (0x4d); } // static void mp3_single_loop (bool state) { mp3_send_cmd (0x19, !state); } //add static void mp3_single_play (uint16_t num) { mp3_play (num); HAL_Delay(10); mp3_single_loop (true); //mp3_send_cmd (0x19, !state); } // static void mp3_DAC (bool state) { mp3_send_cmd (0x1a, !state); } // static void mp3_random_play () { mp3_send_cmd (0x18); } */ eAppCallResult cSound::Setup() { mp3_set_volume(this->lastSetVolume); return BSP::SetDigitalOutput(this->output, BSP::INACTIVE)?eAppCallResult::OK:eAppCallResult::BUS_ERROR; } eAppType cSound::GetAppType() { return eAppType::SOUND; } void cSound::OnSET_SIGNALCommand(uint16_t signal, Time_t now) { uint32_t vol = lastSetVolume; if(this->volumeSchedule!=NULL) { vol = volumeSchedule->GetCurrentValue(); } BSP::SetDigitalOutput(this->output, BSP::ACTIVE); this->autoOffTimeMs=now+30000; if(vol!=lastSetVolume) { mp3_set_volume(vol); HAL_Delay(20); this->lastSetVolume=vol; } mp3_play(signal); } void cSound::OnSTARTCommand(Time_t now) { LOGD("%s OnSTARTCommand called", this->Id); OnSET_SIGNALCommand(1, now); } eAppCallResult cSound::DoEachCycle(Time_t now, uint8_t *statusBuffer, size_t *statusBufferLength) { if(now>this->autoOffTimeMs) { BSP::SetDigitalOutput(this->output, BSP::INACTIVE); this->autoOffTimeMs=TIME_MAX; } UNUSED(statusBuffer); *statusBufferLength=0; return eAppCallResult::OK; } }
15.147059
104
0.699757
klaus-liebler
bd9804ea6a73b6f6b363e71c0180dc839459bacb
4,670
cpp
C++
CrossApp/cocoa/CACalendar.cpp
gohopo/nineck.ca
9601f5ae4c20f8a3ea27b06551556fa5e1eecce3
[ "MIT" ]
794
2015-01-01T04:59:48.000Z
2022-03-09T03:31:13.000Z
CrossApp/cocoa/CACalendar.cpp
gohopo/nineck.ca
9601f5ae4c20f8a3ea27b06551556fa5e1eecce3
[ "MIT" ]
83
2015-01-04T06:00:35.000Z
2021-05-20T08:48:38.000Z
CrossApp/cocoa/CACalendar.cpp
gohopo/nineck.ca
9601f5ae4c20f8a3ea27b06551556fa5e1eecce3
[ "MIT" ]
598
2015-01-02T02:38:13.000Z
2022-03-09T03:31:37.000Z
// // CACalendar.cpp // CrossApp // // Created by dai xinping on 14-8-5. // Copyright (c) 2014年 CrossApp. All rights reserved. // #include "CACalendar.h" #include <cstdlib> #include <iostream> #include <stdio.h> #include <iomanip> #include <ctime> #include <chrono> NS_CC_BEGIN CACalendar::CACalendar() { } CACalendar::~CACalendar() { } CACalendar* CACalendar::create() { CACalendar* cal = new CACalendar(); if (cal) { cal->autorelease(); } return cal; } CACalendar* CACalendar::create(int year, int month, int day) { CACalendar* cal = CACalendar::create(); if (cal) { cal->setCalendar(year, month, day); } return cal; } CACalendar* CACalendar::create(time_t time) { CACalendar* cal = CACalendar::create(); if (cal) { cal->setCalendar(time); } return cal; } void CACalendar::setCalendar(int year, int month, int day) { struct tm tm = {0}; tm.tm_year = year - 1900; tm.tm_mon = month-1; tm.tm_mday = day; std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); m_tDateTime = *std::localtime(&t); } void CACalendar::setCalendar(time_t time) { m_tDateTime = *std::localtime(&time); } int CACalendar::_compareDate(tm date1, tm date2) { if (date1.tm_year == date2.tm_year) { if (date1.tm_mon == date2.tm_mon) { if (date1.tm_mday == date2.tm_mday) { return 0; } else { return date1.tm_mday - date2.tm_mday; } } else { return date1.tm_mon - date2.tm_mon; } } else { return date1.tm_year - date2.tm_year; } return 0; } int CACalendar::_calcDayCount(tm target) { int bInc = _compareDate(target, m_tDateTime); if (bInc == 0) { return 0; } int day = 0; int curr_month = bInc > 0 ? m_tDateTime.tm_mon : target.tm_mon; int curr_year = bInc > 0 ? m_tDateTime.tm_year : target.tm_year; int curr_date = bInc > 0 ? m_tDateTime.tm_mday : target.tm_mday; int dest_month = bInc < 0 ? m_tDateTime.tm_mon : target.tm_mon; int dest_year = bInc < 0 ? m_tDateTime.tm_year : target.tm_year; int dest_date = bInc < 0 ? m_tDateTime.tm_mday : target.tm_mday; while (curr_year != dest_year && curr_month != dest_month) { day += _dayCountOfMonth(curr_year, curr_month+1); curr_month++; if (curr_month == 12) { curr_month = 0; curr_year++; } } day += dest_date - curr_date; return day; } void CACalendar::addYear(int count) { m_tDateTime.tm_year += count; time_t t = std::mktime(&m_tDateTime); m_tDateTime = *std::localtime(&t); } void CACalendar::addMonth(int count) { m_tDateTime.tm_mon += count; time_t t = std::mktime(&m_tDateTime); m_tDateTime = *std::localtime(&t); } void CACalendar::addDay(int count) { m_tDateTime.tm_mday += count; time_t t = std::mktime(&m_tDateTime); m_tDateTime = *std::localtime(&t); } bool CACalendar::_isLeapYear(int y) { return ( (y%4==0 && y%100!=0)|| y%400==0 ) ? true : false; } bool CACalendar::isLeapYear() { return _isLeapYear(m_tDateTime.tm_year); } int CACalendar::_dayCountOfMonth(int year, int month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return _isLeapYear(year) ? 29 : 28; default: return 0; } } int CACalendar::_dayCountOfYear(int year) { return _isLeapYear(year) ? 366 : 365; } int CACalendar::dayCountOfMonth() { return _dayCountOfMonth(m_tDateTime.tm_year + 1900, m_tDateTime.tm_mon); } int CACalendar::dayCountOfYear() { return isLeapYear() ? 366 : 365; } int CACalendar::dayOfMonth() { return m_tDateTime.tm_mday; } int CACalendar::dayOfYear() { return m_tDateTime.tm_yday; } int CACalendar::dayOfWeek() { return m_tDateTime.tm_wday; } int CACalendar::monthOfYear() { return m_tDateTime.tm_mon+1; } void CACalendar::dateByDayOfYear(int year, int day, int& month, int& date) { int num = _isLeapYear(year+1900)? 366 : 365; if (day<num) { month = 0; while (day > 0) { day -= _dayCountOfMonth(year, month++); } if (day == 0) { date = 1; } else if(day < 0){ month--; date = _dayCountOfMonth(year, month) + day + 1; } }else{ month = 0; date = 1; } } NS_CC_END
20.482456
88
0.588223
gohopo
bd990bd8964c2c1c933f7886b7adf94fe51bc1b1
1,384
cpp
C++
src/EPI/ch4/bit_swap.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
src/EPI/ch4/bit_swap.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
src/EPI/ch4/bit_swap.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
#include <bitset> #include <iostream> #include <random> /** * Returns a random integer from the interval [low, high] * * @param low left end of the range (inclusive) * @param high right end of the range (inclusive) * * @return random integer from specified interval [low, high] */ int random_int(const int low, const int high) { static std::random_device rd; static std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(low, high); return dist(gen); } /** * Swaps bits at indices i and j, assuming index 0 is the least significant bit, * for the given value * * @param value number whose bits will be swapped * @param i index of bit * @param j index of bit * * @return the result of swapping bits i and j within a given number */ int swap_bits(int value, const int i, const int j) { if (((value >> i) & 1) != ((value >> j) & 1)) { auto bit_mask = (1 << i) | (1 << j); value ^= bit_mask; } return value; } int main(int argc, char* argv[]) { int val = random_int(1, 1000); std::bitset<16> bit_rep(val); int i = random_int(1, 15); int j = random_int(1, 15); int res = swap_bits(val, i, j); std::bitset<16> new_bit_rep(res); std::cout << "Swapping bits i = " << i << ", j = " << j << " in " << val << ":\n" << "\told: " << bit_rep << '\n' << "\tnew: " << new_bit_rep << '\n'; return 0; }
27.137255
80
0.601879
j-haj
bd9d690dd1d6077aaa7c163f269a9400ed90aea8
1,700
cpp
C++
CODEFORCES/B.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
CODEFORCES/B.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
CODEFORCES/B.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> using namespace std; typedef long long LL; typedef pair<int,int> pii; namespace sieve { #define MAX 10000010 #define LIM 3163 #define PRM 78500 typedef long long LL; unsigned flag[MAX >> 6]; unsigned segment[MAX >> 6]; LL primes[1000010]; #define ifc(n) (flag[n>>6] & (1<<((n>>1)&31))) #define isc(n) (flag[n>>6] |= (1<<((n>>1)&31))) #define seg_ifc(n) (segment[n>>6] & (1<<((n>>1)&31))) #define seg_isc(n) (segment[n>>6] |= (1<<((n>>1)&31))) void make_sieve() { unsigned i,j,k; isc(1); for(i=3;i<=LIM;i+=2) { if(!ifc(i)) for(j=i*i,k=(i<<1);j<MAX;j+=k) isc(j); } primes[0] = 2; for(i=3,k=1;i<MAX;i+=2) if(!ifc(i)) primes[k++] = i; /* for(int i=0;i<100;i++) cout<<primes[i]<<" "; cout<<k<<endl; */ } } using namespace sieve; int arr[100010]; int main() { make_sieve(); int n,k; cin>>n>>k; if(n==k) { cout<<-1<<endl; return 0; } cout<<"2 "; for(int i=2;i<=k+1;i++) cout<<i*i<<" "; int ptr=1; for(int i=k+2;i<=n;i++) { if(!(i&1)) cout<<primes[ptr++]<<" "; else { if(!ifc(i) && i==primes[ptr]) { ptr+=1; cout<<primes[ptr]<<" "; ptr+=1; } else cout<<primes[ptr++]<<" "; } } return 0; }
20.481928
58
0.425294
aqfaridi
bda30c72a1f7fb86c14a32778fa985f41e3fb6b2
29,822
cc
C++
net/quic/quic_sent_packet_manager.cc
SlimKatLegacy/android_external_chromium_org
ee480ef5039d7c561fc66ccf52169ead186f1bea
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-04T02:36:53.000Z
2016-06-25T11:22:17.000Z
net/quic/quic_sent_packet_manager.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/quic/quic_sent_packet_manager.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2015-02-09T08:49:30.000Z
2017-08-26T02:03:34.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/quic/quic_sent_packet_manager.h" #include "base/logging.h" #include "base/stl_util.h" #include "net/quic/congestion_control/pacing_sender.h" #include "net/quic/quic_ack_notifier_manager.h" using std::make_pair; using std::min; // TODO(rtenneti): Remove this. // Do not flip this flag until the flakiness of the // net/tools/quic/end_to_end_test is fixed. // If true, then QUIC connections will track the retransmission history of a // packet so that an ack of a previous transmission will ack the data of all // other transmissions. bool FLAGS_track_retransmission_history = false; // A test-only flag to prevent the RTO from backing off when multiple sequential // tail drops occur. bool FLAGS_limit_rto_increase_for_tests = false; // Do not remove this flag until the Finch-trials described in b/11706275 // are complete. // If true, QUIC connections will support the use of a pacing algorithm when // sending packets, in an attempt to reduce packet loss. The client must also // request pacing for the server to enable it. bool FLAGS_enable_quic_pacing = false; namespace net { namespace { static const int kBitrateSmoothingPeriodMs = 1000; static const int kHistoryPeriodMs = 5000; static const int kDefaultRetransmissionTimeMs = 500; // TCP RFC calls for 1 second RTO however Linux differs from this default and // define the minimum RTO to 200ms, we will use the same until we have data to // support a higher or lower value. static const int kMinRetransmissionTimeMs = 200; static const int kMaxRetransmissionTimeMs = 60000; static const size_t kMaxRetransmissions = 10; // We only retransmit 2 packets per ack. static const size_t kMaxRetransmissionsPerAck = 2; // TCP retransmits after 3 nacks. static const size_t kNumberOfNacksBeforeRetransmission = 3; COMPILE_ASSERT(kHistoryPeriodMs >= kBitrateSmoothingPeriodMs, history_must_be_longer_or_equal_to_the_smoothing_period); } // namespace #define ENDPOINT (is_server_ ? "Server: " : " Client: ") QuicSentPacketManager::HelperInterface::~HelperInterface() { } QuicSentPacketManager::QuicSentPacketManager(bool is_server, HelperInterface* helper, const QuicClock* clock, CongestionFeedbackType type) : is_server_(is_server), helper_(helper), clock_(clock), send_algorithm_(SendAlgorithmInterface::Create(clock, type)), rtt_sample_(QuicTime::Delta::Infinite()), consecutive_rto_count_(0), using_pacing_(false) { } QuicSentPacketManager::~QuicSentPacketManager() { for (UnackedPacketMap::iterator it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { delete it->second.retransmittable_frames; // Only delete previous_transmissions once, for the newest packet. if (it->second.previous_transmissions != NULL && it->first == *it->second.previous_transmissions->rbegin()) { delete it->second.previous_transmissions; } } STLDeleteValues(&packet_history_map_); } void QuicSentPacketManager::SetFromConfig(const QuicConfig& config) { if (config.initial_round_trip_time_us() > 0 && rtt_sample_.IsInfinite()) { // The initial rtt should already be set on the client side. DVLOG_IF(1, !is_server_) << "Client did not set an initial RTT, but did negotiate one."; rtt_sample_ = QuicTime::Delta::FromMicroseconds(config.initial_round_trip_time_us()); } if (config.congestion_control() == kPACE) { MaybeEnablePacing(); } send_algorithm_->SetFromConfig(config, is_server_); } void QuicSentPacketManager::SetMaxPacketSize(QuicByteCount max_packet_size) { send_algorithm_->SetMaxPacketSize(max_packet_size); } void QuicSentPacketManager::OnSerializedPacket( const SerializedPacket& serialized_packet) { if (serialized_packet.retransmittable_frames == NULL && !serialized_packet.packet->is_fec_packet()) { // Don't track ack/congestion feedback packets. return; } ack_notifier_manager_.OnSerializedPacket(serialized_packet); DCHECK(unacked_packets_.empty() || unacked_packets_.rbegin()->first < serialized_packet.sequence_number); unacked_packets_[serialized_packet.sequence_number] = TransmissionInfo(serialized_packet.retransmittable_frames, serialized_packet.sequence_number_length); } void QuicSentPacketManager::OnRetransmittedPacket( QuicPacketSequenceNumber old_sequence_number, QuicPacketSequenceNumber new_sequence_number) { DCHECK(ContainsKey(unacked_packets_, old_sequence_number)); DCHECK(ContainsKey(pending_retransmissions_, old_sequence_number)); DCHECK(unacked_packets_.empty() || unacked_packets_.rbegin()->first < new_sequence_number); pending_retransmissions_.erase(old_sequence_number); UnackedPacketMap::iterator unacked_it = unacked_packets_.find(old_sequence_number); RetransmittableFrames* frames = unacked_it->second.retransmittable_frames; DCHECK(frames); // A notifier may be waiting to hear about ACKs for the original sequence // number. Inform them that the sequence number has changed. ack_notifier_manager_.UpdateSequenceNumber(old_sequence_number, new_sequence_number); // We keep the old packet in the unacked packet list until it, or one of // the retransmissions of it are acked. unacked_it->second.retransmittable_frames = NULL; unacked_packets_[new_sequence_number] = TransmissionInfo(frames, GetSequenceNumberLength(old_sequence_number)); // Keep track of all sequence numbers that this packet // has been transmitted as. SequenceNumberSet* previous_transmissions = unacked_it->second.previous_transmissions; if (previous_transmissions == NULL) { // This is the first retransmission of this packet, so create a new entry. previous_transmissions = new SequenceNumberSet; unacked_it->second.previous_transmissions = previous_transmissions; previous_transmissions->insert(old_sequence_number); } previous_transmissions->insert(new_sequence_number); unacked_packets_[new_sequence_number].previous_transmissions = previous_transmissions; DCHECK(HasRetransmittableFrames(new_sequence_number)); } bool QuicSentPacketManager::OnIncomingAck( const ReceivedPacketInfo& received_info, QuicTime ack_receive_time) { // Determine if the least unacked sequence number is being acked. QuicPacketSequenceNumber least_unacked_sent_before = GetLeastUnackedSentPacket(); bool new_least_unacked = !IsAwaitingPacket(received_info, least_unacked_sent_before); HandleAckForSentPackets(received_info); SequenceNumberSet retransmission_packets = OnIncomingAckFrame(received_info, ack_receive_time); for (SequenceNumberSet::const_iterator it = retransmission_packets.begin(); it != retransmission_packets.end(); ++it) { DCHECK(!ContainsKey(pending_packets_, *it)); MarkForRetransmission(*it, NACK_RETRANSMISSION); } if (new_least_unacked) { consecutive_rto_count_ = 0; } return new_least_unacked; } void QuicSentPacketManager::DiscardUnackedPacket( QuicPacketSequenceNumber sequence_number) { MarkPacketReceivedByPeer(sequence_number); } void QuicSentPacketManager::HandleAckForSentPackets( const ReceivedPacketInfo& received_info) { // Go through the packets we have not received an ack for and see if this // incoming_ack shows they've been seen by the peer. UnackedPacketMap::iterator it = unacked_packets_.begin(); while (it != unacked_packets_.end()) { QuicPacketSequenceNumber sequence_number = it->first; if (sequence_number > received_info.largest_observed) { // These are very new sequence_numbers. break; } if (IsAwaitingPacket(received_info, sequence_number)) { ++it; continue; } // Packet was acked, so remove it from our unacked packet list. DVLOG(1) << ENDPOINT <<"Got an ack for packet " << sequence_number; // If data is associated with the most recent transmission of this // packet, then inform the caller. it = MarkPacketReceivedByPeer(sequence_number); // The AckNotifierManager is informed of every ACKed sequence number. ack_notifier_manager_.OnPacketAcked(sequence_number); } // If we have received a truncated ack, then we need to // clear out some previous transmissions to allow the peer // to actually ACK new packets. if (received_info.is_truncated) { ClearPreviousRetransmissions(received_info.missing_packets.size() / 2); } } void QuicSentPacketManager::ClearPreviousRetransmissions(size_t num_to_clear) { UnackedPacketMap::iterator it = unacked_packets_.begin(); while (it != unacked_packets_.end() && num_to_clear > 0) { QuicPacketSequenceNumber sequence_number = it->first; // If this is not a previous transmission then there is no point // in clearing out any further packets, because it will not affect // the high water mark. SequenceNumberSet* previous_transmissions = it->second.previous_transmissions; if (previous_transmissions == NULL) { break; } QuicPacketSequenceNumber newest_transmission = *previous_transmissions->rbegin(); if (sequence_number == newest_transmission) { break; } DCHECK(it->second.retransmittable_frames == NULL); previous_transmissions->erase(sequence_number); if (previous_transmissions->size() == 1) { unacked_packets_[newest_transmission].previous_transmissions = NULL; delete previous_transmissions; } unacked_packets_.erase(it++); --num_to_clear; } } bool QuicSentPacketManager::HasRetransmittableFrames( QuicPacketSequenceNumber sequence_number) const { if (!ContainsKey(unacked_packets_, sequence_number)) { return false; } return unacked_packets_.find( sequence_number)->second.retransmittable_frames != NULL; } void QuicSentPacketManager::RetransmitUnackedPackets( RetransmissionType retransmission_type) { if (unacked_packets_.empty()) { return; } for (UnackedPacketMap::const_iterator unacked_it = unacked_packets_.begin(); unacked_it != unacked_packets_.end(); ++unacked_it) { const RetransmittableFrames* frames = unacked_it->second.retransmittable_frames; if (frames == NULL) { continue; } if (retransmission_type == ALL_PACKETS || frames->encryption_level() == ENCRYPTION_INITIAL) { // TODO(satyamshekhar): Think about congestion control here. // Specifically, about the retransmission count of packets being sent // proactively to achieve 0 (minimal) RTT. OnPacketAbandoned(unacked_it->first); if (!MarkForRetransmission(unacked_it->first, NACK_RETRANSMISSION)) { DiscardUnackedPacket(unacked_it->first); } } } } bool QuicSentPacketManager::MarkForRetransmission( QuicPacketSequenceNumber sequence_number, TransmissionType transmission_type) { DCHECK(ContainsKey(unacked_packets_, sequence_number)); if (!HasRetransmittableFrames(sequence_number)) { return false; } // If it's already in the retransmission map, don't add it again, just let // the prior retransmission request win out. if (ContainsKey(pending_retransmissions_, sequence_number)) { return true; } pending_retransmissions_[sequence_number] = transmission_type; return true; } bool QuicSentPacketManager::HasPendingRetransmissions() const { return !pending_retransmissions_.empty(); } QuicSentPacketManager::PendingRetransmission QuicSentPacketManager::NextPendingRetransmission() { DCHECK(!pending_retransmissions_.empty()); QuicPacketSequenceNumber sequence_number = pending_retransmissions_.begin()->first; DCHECK(ContainsKey(unacked_packets_, sequence_number)); const RetransmittableFrames* retransmittable_frames = unacked_packets_[sequence_number].retransmittable_frames; DCHECK(retransmittable_frames); return PendingRetransmission(sequence_number, pending_retransmissions_.begin()->second, *retransmittable_frames, GetSequenceNumberLength(sequence_number)); } bool QuicSentPacketManager::IsPreviousTransmission( QuicPacketSequenceNumber sequence_number) const { DCHECK(ContainsKey(unacked_packets_, sequence_number)); UnackedPacketMap::const_iterator it = unacked_packets_.find(sequence_number); if (it->second.previous_transmissions == NULL) { return false; } SequenceNumberSet* previous_transmissions = it->second.previous_transmissions; DCHECK(!previous_transmissions->empty()); return *previous_transmissions->rbegin() != sequence_number; } QuicSentPacketManager::UnackedPacketMap::iterator QuicSentPacketManager::MarkPacketReceivedByPeer( QuicPacketSequenceNumber sequence_number) { DCHECK(ContainsKey(unacked_packets_, sequence_number)); // If this packet has never been retransmitted, then simply drop it. UnackedPacketMap::const_iterator previous_it = unacked_packets_.find(sequence_number); if (previous_it->second.previous_transmissions == NULL) { UnackedPacketMap::iterator next_unacked = unacked_packets_.find(sequence_number); ++next_unacked; DiscardPacket(sequence_number); return next_unacked; } SequenceNumberSet* previous_transmissions = previous_it->second.previous_transmissions; DCHECK(!previous_transmissions->empty()); SequenceNumberSet::reverse_iterator previous_transmissions_it = previous_transmissions->rbegin(); QuicPacketSequenceNumber newest_transmission = *previous_transmissions_it; if (newest_transmission == sequence_number) { DiscardPacket(newest_transmission); } else { // If we have received an ack for a previous transmission of a packet, // we want to keep the "new" transmission of the packet unacked, // but prevent the data from being retransmitted. delete unacked_packets_[newest_transmission].retransmittable_frames; unacked_packets_[newest_transmission].retransmittable_frames = NULL; unacked_packets_[newest_transmission].previous_transmissions = NULL; pending_retransmissions_.erase(newest_transmission); } // Clear out information all previous transmissions. ++previous_transmissions_it; while (previous_transmissions_it != previous_transmissions->rend()) { QuicPacketSequenceNumber previous_transmission = *previous_transmissions_it; ++previous_transmissions_it; DiscardPacket(previous_transmission); } delete previous_transmissions; UnackedPacketMap::iterator next_unacked = unacked_packets_.begin(); while (next_unacked != unacked_packets_.end() && next_unacked->first < sequence_number) { ++next_unacked; } return next_unacked; } void QuicSentPacketManager::DiscardPacket( QuicPacketSequenceNumber sequence_number) { UnackedPacketMap::iterator unacked_it = unacked_packets_.find(sequence_number); // Packet was not meant to be retransmitted. if (unacked_it == unacked_packets_.end()) { return; } // Delete the retransmittable frames. delete unacked_it->second.retransmittable_frames; unacked_packets_.erase(unacked_it); pending_retransmissions_.erase(sequence_number); return; } bool QuicSentPacketManager::IsUnacked( QuicPacketSequenceNumber sequence_number) const { return ContainsKey(unacked_packets_, sequence_number); } QuicSequenceNumberLength QuicSentPacketManager::GetSequenceNumberLength( QuicPacketSequenceNumber sequence_number) const { DCHECK(ContainsKey(unacked_packets_, sequence_number)); return unacked_packets_.find(sequence_number)->second.sequence_number_length; } bool QuicSentPacketManager::HasUnackedPackets() const { return !unacked_packets_.empty(); } size_t QuicSentPacketManager::GetNumRetransmittablePackets() const { size_t num_unacked_packets = 0; for (UnackedPacketMap::const_iterator it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { QuicPacketSequenceNumber sequence_number = it->first; if (HasRetransmittableFrames(sequence_number)) { ++num_unacked_packets; } } return num_unacked_packets; } QuicPacketSequenceNumber QuicSentPacketManager::GetLeastUnackedSentPacket() const { if (unacked_packets_.empty()) { // If there are no unacked packets, set the least unacked packet to // the sequence number of the next packet sent. return helper_->GetNextPacketSequenceNumber(); } return unacked_packets_.begin()->first; } SequenceNumberSet QuicSentPacketManager::GetUnackedPackets() const { SequenceNumberSet unacked_packets; for (UnackedPacketMap::const_iterator it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { unacked_packets.insert(it->first); } return unacked_packets; } void QuicSentPacketManager::OnPacketSent( QuicPacketSequenceNumber sequence_number, QuicTime sent_time, QuicByteCount bytes, TransmissionType transmission_type, HasRetransmittableData has_retransmittable_data) { DCHECK_LT(0u, sequence_number); DCHECK(!ContainsKey(pending_packets_, sequence_number)); if (ContainsKey(unacked_packets_, sequence_number)) { unacked_packets_[sequence_number].sent_time = sent_time; } // Only track packets the send algorithm wants us to track. if (!send_algorithm_->OnPacketSent(sent_time, sequence_number, bytes, transmission_type, has_retransmittable_data)) { return; } packet_history_map_[sequence_number] = new SendAlgorithmInterface::SentPacket( bytes, sent_time, has_retransmittable_data); pending_packets_.insert(sequence_number); CleanupPacketHistory(); } void QuicSentPacketManager::OnRetransmissionTimeout() { // Abandon all pending packets to ensure the congestion window // opens up before we attempt to retransmit packets. QuicTime::Delta retransmission_delay = GetRetransmissionDelay(); QuicTime max_send_time = clock_->ApproximateNow().Subtract(retransmission_delay); for (SequenceNumberSet::iterator it = pending_packets_.begin(); it != pending_packets_.end();) { QuicPacketSequenceNumber sequence_number = *it; DCHECK(ContainsKey(packet_history_map_, sequence_number)); DCHECK(ContainsKey(unacked_packets_, sequence_number)); const TransmissionInfo& transmission_info = unacked_packets_.find(sequence_number)->second; // Abandon retransmittable packet and old non-retransmittable packets. if (transmission_info.retransmittable_frames || transmission_info.sent_time <= max_send_time) { pending_packets_.erase(it++); send_algorithm_->OnPacketAbandoned( sequence_number, packet_history_map_[sequence_number]->bytes_sent()); } else { ++it; } } // Attempt to send all the unacked packets when the RTO fires, let the // congestion manager decide how many to send immediately and the remaining // packets will be queued for future sending. DVLOG(1) << "OnRetransmissionTimeout() fired with " << unacked_packets_.size() << " unacked packets."; // Retransmit any packet with retransmittable frames. bool packets_retransmitted = false; for (UnackedPacketMap::const_iterator it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { if (it->second.retransmittable_frames != NULL) { packets_retransmitted = true; MarkForRetransmission(it->first, RTO_RETRANSMISSION); } } // Only inform the sent packet manager of an RTO if data was retransmitted. if (packets_retransmitted) { ++consecutive_rto_count_; send_algorithm_->OnRetransmissionTimeout(); } } void QuicSentPacketManager::OnPacketAbandoned( QuicPacketSequenceNumber sequence_number) { SequenceNumberSet::iterator it = pending_packets_.find(sequence_number); if (it != pending_packets_.end()) { DCHECK(ContainsKey(packet_history_map_, sequence_number)); send_algorithm_->OnPacketAbandoned( sequence_number, packet_history_map_[sequence_number]->bytes_sent()); pending_packets_.erase(it); } } void QuicSentPacketManager::OnIncomingQuicCongestionFeedbackFrame( const QuicCongestionFeedbackFrame& frame, const QuicTime& feedback_receive_time) { send_algorithm_->OnIncomingQuicCongestionFeedbackFrame( frame, feedback_receive_time, packet_history_map_); } SequenceNumberSet QuicSentPacketManager::OnIncomingAckFrame( const ReceivedPacketInfo& received_info, const QuicTime& ack_receive_time) { MaybeUpdateRTT(received_info, ack_receive_time); // We want to. // * Get all packets lower(including) than largest_observed // from pending_packets_. // * Remove all packets no longer being waited for(ie: acked). // * Send each ACK in the list to send_algorithm_. SequenceNumberSet::iterator it = pending_packets_.begin(); SequenceNumberSet::iterator it_upper = pending_packets_.upper_bound(received_info.largest_observed); SequenceNumberSet retransmission_packets; SequenceNumberSet lost_packets; while (it != it_upper) { QuicPacketSequenceNumber sequence_number = *it; const SendAlgorithmInterface::SentPacket* sent_packet = packet_history_map_[sequence_number]; if (!IsAwaitingPacket(received_info, sequence_number)) { // Not missing, hence implicitly acked. size_t bytes_sent = sent_packet->bytes_sent(); send_algorithm_->OnPacketAcked(sequence_number, bytes_sent, rtt_sample_); pending_packets_.erase(it++); // Must be incremented post to work. continue; } // The peer got packets after this sequence number. This is an explicit // nack. DVLOG(1) << "still missing packet " << sequence_number; DCHECK(ContainsKey(packet_history_map_, sequence_number)); // Consider it multiple nacks when there is a gap between the missing packet // and the largest observed, since the purpose of a nack threshold is to // tolerate re-ordering. This handles both StretchAcks and Forward Acks. // TODO(ianswett): This relies heavily on sequential reception of packets, // and makes an assumption that the congestion control uses TCP style nacks. size_t min_nacks = received_info.largest_observed - sequence_number; packet_history_map_[sequence_number]->Nack(min_nacks); size_t num_nacks_needed = kNumberOfNacksBeforeRetransmission; // Check for early retransmit(RFC5827) when the last packet gets acked and // the there are fewer than 4 pending packets. if (pending_packets_.size() <= kNumberOfNacksBeforeRetransmission && sent_packet->has_retransmittable_data() == HAS_RETRANSMITTABLE_DATA && *pending_packets_.rbegin() == received_info.largest_observed) { num_nacks_needed = received_info.largest_observed - sequence_number; } if (sent_packet->nack_count() < num_nacks_needed) { ++it; continue; } // If the number of retransmissions has maxed out, don't lose or retransmit // any more packets. if (retransmission_packets.size() >= kMaxRetransmissionsPerAck) { ++it; continue; } lost_packets.insert(sequence_number); if (sent_packet->has_retransmittable_data() == HAS_RETRANSMITTABLE_DATA) { retransmission_packets.insert(sequence_number); } ++it; } // Abandon packets after the loop over pending packets, because otherwise it // changes the early retransmit logic and iteration. for (SequenceNumberSet::const_iterator it = lost_packets.begin(); it != lost_packets.end(); ++it) { // TODO(ianswett): OnPacketLost is also called from TCPCubicSender when // an FEC packet is lost, but FEC loss information should be shared among // congestion managers. Additionally, if it's expected the FEC packet may // repair the loss, it should be recorded as a loss to the congestion // manager, but not retransmitted until it's known whether the FEC packet // arrived. send_algorithm_->OnPacketLost(*it, ack_receive_time); OnPacketAbandoned(*it); } return retransmission_packets; } void QuicSentPacketManager::MaybeUpdateRTT( const ReceivedPacketInfo& received_info, const QuicTime& ack_receive_time) { // We calculate the RTT based on the highest ACKed sequence number, the lower // sequence numbers will include the ACK aggregation delay. SendAlgorithmInterface::SentPacketsMap::iterator history_it = packet_history_map_.find(received_info.largest_observed); // TODO(satyamshekhar): largest_observed might be missing. if (history_it == packet_history_map_.end()) { return; } QuicTime::Delta send_delta = ack_receive_time.Subtract( history_it->second->send_timestamp()); if (send_delta > received_info.delta_time_largest_observed) { rtt_sample_ = send_delta.Subtract( received_info.delta_time_largest_observed); } else if (rtt_sample_.IsInfinite()) { // Even though we received information from the peer suggesting // an invalid (negative) RTT, we can use the send delta as an // approximation until we get a better estimate. rtt_sample_ = send_delta; } } QuicTime::Delta QuicSentPacketManager::TimeUntilSend( QuicTime now, TransmissionType transmission_type, HasRetransmittableData retransmittable, IsHandshake handshake) { return send_algorithm_->TimeUntilSend(now, transmission_type, retransmittable, handshake); } // Ensures that the Delayed Ack timer is always set to a value lesser // than the retransmission timer's minimum value (MinRTO). We want the // delayed ack to get back to the QUIC peer before the sender's // retransmission timer triggers. Since we do not know the // reverse-path one-way delay, we assume equal delays for forward and // reverse paths, and ensure that the timer is set to less than half // of the MinRTO. // There may be a value in making this delay adaptive with the help of // the sender and a signaling mechanism -- if the sender uses a // different MinRTO, we may get spurious retransmissions. May not have // any benefits, but if the delayed ack becomes a significant source // of (likely, tail) latency, then consider such a mechanism. const QuicTime::Delta QuicSentPacketManager::DelayedAckTime() { return QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs/2); } const QuicTime::Delta QuicSentPacketManager::GetRetransmissionDelay() const { size_t number_retransmissions = consecutive_rto_count_; if (FLAGS_limit_rto_increase_for_tests) { const size_t kTailDropWindowSize = 5; const size_t kTailDropMaxRetransmissions = 4; if (pending_packets_.size() <= kTailDropWindowSize) { // Avoid exponential backoff of RTO when there are only a few packets // outstanding. This helps avoid the situation where fake packet loss // causes a packet and it's retransmission to be dropped causing // test timouts. if (number_retransmissions <= kTailDropMaxRetransmissions) { number_retransmissions = 0; } else { number_retransmissions -= kTailDropMaxRetransmissions; } } } QuicTime::Delta retransmission_delay = send_algorithm_->RetransmissionDelay(); if (retransmission_delay.IsZero()) { // We are in the initial state, use default timeout values. retransmission_delay = QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs); } // Calculate exponential back off. retransmission_delay = QuicTime::Delta::FromMilliseconds( retransmission_delay.ToMilliseconds() * static_cast<size_t>( (1 << min<size_t>(number_retransmissions, kMaxRetransmissions)))); // TODO(rch): This code should move to |send_algorithm_|. if (retransmission_delay.ToMilliseconds() < kMinRetransmissionTimeMs) { return QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs); } if (retransmission_delay.ToMilliseconds() > kMaxRetransmissionTimeMs) { return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs); } return retransmission_delay; } const QuicTime::Delta QuicSentPacketManager::SmoothedRtt() const { return send_algorithm_->SmoothedRtt(); } QuicBandwidth QuicSentPacketManager::BandwidthEstimate() const { return send_algorithm_->BandwidthEstimate(); } QuicByteCount QuicSentPacketManager::GetCongestionWindow() const { return send_algorithm_->GetCongestionWindow(); } void QuicSentPacketManager::CleanupPacketHistory() { const QuicTime::Delta kHistoryPeriod = QuicTime::Delta::FromMilliseconds(kHistoryPeriodMs); QuicTime now = clock_->ApproximateNow(); SendAlgorithmInterface::SentPacketsMap::iterator history_it = packet_history_map_.begin(); for (; history_it != packet_history_map_.end(); ++history_it) { if (now.Subtract(history_it->second->send_timestamp()) <= kHistoryPeriod) { return; } // Don't remove packets which have not been acked. if (ContainsKey(pending_packets_, history_it->first)) { continue; } delete history_it->second; packet_history_map_.erase(history_it); history_it = packet_history_map_.begin(); } } void QuicSentPacketManager::MaybeEnablePacing() { if (!FLAGS_enable_quic_pacing) { return; } if (using_pacing_) { return; } using_pacing_ = true; send_algorithm_.reset( new PacingSender(send_algorithm_.release(), QuicTime::Delta::FromMicroseconds(1))); } } // namespace net
38.33162
80
0.744652
SlimKatLegacy
bda39f758570a4cdcba2ed24ccb3bef6f85cd6a2
1,369
cpp
C++
tests/char_utils_test.cpp
KOLANICH/octargs
e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef
[ "MIT" ]
4
2020-03-23T16:30:11.000Z
2021-12-21T10:07:38.000Z
tests/char_utils_test.cpp
KOLANICH/octargs
e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef
[ "MIT" ]
32
2020-01-28T22:29:59.000Z
2021-12-21T10:05:36.000Z
tests/char_utils_test.cpp
KOLANICH/octargs
e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef
[ "MIT" ]
1
2021-07-22T16:50:08.000Z
2021-07-22T16:50:08.000Z
#include "gtest/gtest.h" #include <array> #include "../include/octargs/internal/char_utils.hpp" namespace oct { namespace args { TEST(char_utils_test, test_char_is_space) { ASSERT_TRUE(internal::is_space(' ')); ASSERT_TRUE(internal::is_space('\t')); ASSERT_TRUE(internal::is_space('\r')); ASSERT_TRUE(internal::is_space('\n')); ASSERT_TRUE(!internal::is_space('a')); ASSERT_TRUE(!internal::is_space('1')); ASSERT_TRUE(!internal::is_space('#')); } TEST(char_utils_test, test_wchar_is_space) { ASSERT_TRUE(internal::is_space(L' ')); ASSERT_TRUE(internal::is_space(L'\t')); ASSERT_TRUE(internal::is_space(L'\r')); ASSERT_TRUE(internal::is_space(L'\n')); ASSERT_TRUE(!internal::is_space(L'a')); ASSERT_TRUE(!internal::is_space(L'1')); ASSERT_TRUE(!internal::is_space(L'#')); } TEST(char_utils_test, test_char_to_lower) { ASSERT_TRUE(internal::to_lower('c') == 'c'); ASSERT_TRUE(internal::to_lower('C') == 'c'); ASSERT_TRUE(internal::to_lower('1') == '1'); ASSERT_TRUE(internal::to_lower('#') == '#'); } TEST(char_utils_test, test_wchar_to_lower) { ASSERT_TRUE(internal::to_lower(L'c') == L'c'); ASSERT_TRUE(internal::to_lower(L'C') == L'c'); ASSERT_TRUE(internal::to_lower(L'1') == L'1'); ASSERT_TRUE(internal::to_lower(L'#') == L'#'); } } // namespace args } // namespace oct
26.326923
53
0.659606
KOLANICH
bda81d8e98e07b3227e819c1b0ba88bf7e7d2064
1,713
cpp
C++
sleepy_discord/asio_udp.cpp
qualk/sleepy-discord
1a4045326c15b3e3a7461043e29769f8ccb8a2a9
[ "MIT" ]
830
2017-05-29T21:00:17.000Z
2022-03-26T16:07:28.000Z
sleepy_discord/asio_udp.cpp
qualk/sleepy-discord
1a4045326c15b3e3a7461043e29769f8ccb8a2a9
[ "MIT" ]
200
2017-06-27T20:08:49.000Z
2022-03-05T14:37:59.000Z
sleepy_discord/asio_udp.cpp
qualk/sleepy-discord
1a4045326c15b3e3a7461043e29769f8ccb8a2a9
[ "MIT" ]
212
2017-06-27T00:16:27.000Z
2022-03-13T15:48:42.000Z
#include "asio_udp.h" #ifndef NONEXISTENT_ASIO #include "client.h" namespace SleepyDiscord { //Note: you need to be using a ASIOBasedScheduleHandler for this to work ASIOUDPClient::ASIOUDPClient(BaseDiscordClient& client) : ASIOUDPClient(static_cast<ASIOBasedScheduleHandler&>(client.getScheduleHandler()).getIOService()) {} ASIOUDPClient::ASIOUDPClient(asio::io_service& service) : iOService(&service), uDPSocket(*iOService, asio::ip::udp::endpoint(asio::ip::udp::v4(), 0)), resolver (*iOService) { } bool ASIOUDPClient::connect(const std::string & to, const uint16_t port) { if (iOService == nullptr) return false; endpoint = *resolver.resolve({ asio::ip::udp::v4(), to, std::to_string(port) }); return true; } void handle_send( const std::error_code& /*error*/, std::size_t /*bytes_transferred*/, GenericUDPClient::SendHandler handler ) { handler(); } void ASIOUDPClient::send( const uint8_t* _buffer, size_t bufferLength, SendHandler handler ) { if (iOService == nullptr) return; uDPSocket.async_send_to(asio::buffer(_buffer, bufferLength), endpoint, std::bind(&handle_send, std::placeholders::_1, std::placeholders::_2, handler) ); } void ASIOUDPClient::receive(ReceiveHandler handler) { if (iOService == nullptr) return; uDPSocket.async_receive_from(asio::buffer(buffer, bufferSize), endpoint, 0, std::bind( &ASIOUDPClient::handle_receive, this, std::placeholders::_1, std::placeholders::_2, handler ) ); } void ASIOUDPClient::handle_receive( const std::error_code& /*error*/, std::size_t bytes_transferred, ReceiveHandler handler ) { handler(std::vector<uint8_t>(buffer, buffer + bytes_transferred)); } }; #endif
26.765625
99
0.718622
qualk
bdb3a5fa2ec3f063fa908dfde6fee079cfff599c
141
cpp
C++
cpp/linker-generated-array/ArrayEntry2.cpp
so61pi/examples
38e2831cd6517864fc05f499f72fbb4ff6ae27c0
[ "MIT" ]
4
2019-05-01T07:23:53.000Z
2022-03-05T00:05:06.000Z
cpp/linker-generated-array/ArrayEntry2.cpp
so61pi/examples
38e2831cd6517864fc05f499f72fbb4ff6ae27c0
[ "MIT" ]
16
2020-02-24T13:04:12.000Z
2022-02-26T10:19:48.000Z
cpp/linker-generated-array/ArrayEntry2.cpp
so61pi/examples
38e2831cd6517864fc05f499f72fbb4ff6ae27c0
[ "MIT" ]
1
2019-03-30T07:29:58.000Z
2019-03-30T07:29:58.000Z
#include "Entry.h" static Entry const ArrayEntry2 __attribute__((unused, used, section(".array-2-entry-2"))) = { "Entry-2", 200 };
17.625
93
0.64539
so61pi
bdb42deba85d26844a6075972a4d8444b1decc59
13,716
cpp
C++
tests/HandwrittenRuntime/Test_Database2.cpp
ankurvdev/stencil
b6429f8b92947273a5e66d5f10210b960616a89d
[ "BSD-3-Clause" ]
null
null
null
tests/HandwrittenRuntime/Test_Database2.cpp
ankurvdev/stencil
b6429f8b92947273a5e66d5f10210b960616a89d
[ "BSD-3-Clause" ]
null
null
null
tests/HandwrittenRuntime/Test_Database2.cpp
ankurvdev/stencil
b6429f8b92947273a5e66d5f10210b960616a89d
[ "BSD-3-Clause" ]
null
null
null
#include "Test_Database2.h" #include "TestUtils.h" #include <thread> using namespace std::string_literals; using namespace std::chrono_literals; namespace Catch { template <> struct StringMaker<std::filesystem::file_time_type> { static std::string convert(std::filesystem::file_time_type const& ftime) { return std::to_string(ftime.time_since_epoch().count()); } }; } // namespace Catch using DB = TestData::DataStore; template <size_t N, typename T> constexpr uuids::uuid TestUuid(); template <> constexpr uuids::uuid TestUuid<0, TestData::Simple>() { return uuids::uuid::from_string("{00000000-0000-0000-0000-000000000001}").value(); } template <> constexpr uuids::uuid TestUuid<1, TestData::Simple>() { return uuids::uuid::from_string("{00000000-0000-0000-0000-000000000002}").value(); } template <> constexpr uuids::uuid TestUuid<0, TestData::Shared>() { return uuids::uuid::from_string("{00000001-0001-0001-0001-000000000000}").value(); } template <> constexpr uuids::uuid TestUuid<1, TestData::Shared>() { return uuids::uuid::from_string("{00000001-0001-0001-0001-000000000001}").value(); } template <> constexpr uuids::uuid TestUuid<0, TestData::Encrypted>() { return uuids::uuid::from_string("{00000002-0002-0002-0002-000000000000}").value(); } template <> constexpr uuids::uuid TestUuid<1, TestData::Encrypted>() { return uuids::uuid::from_string("{00000002-0002-0002-0002-000000000001}").value(); } template <> constexpr uuids::uuid TestUuid<0, TestData::EncryptedAndShared>() { return uuids::uuid::from_string("{00000003-0003-0003-0003-000000000000}").value(); } template <> constexpr uuids::uuid TestUuid<1, TestData::EncryptedAndShared>() { return uuids::uuid::from_string("{00000003-0003-0003-0003-000000000001}").value(); } template <> constexpr uuids::uuid TestUuid<0, TestData::WithSimpleRef>() { return uuids::uuid::from_string("{00000004-0004-0004-0004-000000000000}").value(); } template <> constexpr uuids::uuid TestUuid<1, TestData::WithSimpleRef>() { return uuids::uuid::from_string("{00000004-0004-0004-0004-000000000001}").value(); } #if TODO_OBJREF template <> constexpr uuids::uuid TestUuid<TestData::WithString>() { return uuids::uuid("{00000005-0005-0005-0005-000000000000}"); }; template <> constexpr uuids::uuid TestUuid<TestData::WithSharedString>() { return uuids::uuid("{00000006-0006-0006-0006-000000000000}"); }; template <> constexpr uuids::uuid TestUuid<TestData::WithSharedData>() { return uuids::uuid("{00000007-0007-0007-0007-000000000000}"); }; template <> constexpr uuids::uuid TestUuid<TestData::WithEncryptedString>() { return uuids::uuid("{00000008-0008-0008-0008-000000000000}"); }; template <> constexpr uuids::uuid TestUuid<TestData::WithEncryptedSharedString>() { return uuids::uuid("{00000009-0009-0009-0009-000000000000}"); }; #endif template <size_t N, typename T> constexpr std::string_view TestValue(); template <> constexpr std::string_view TestValue<0, TestData::Simple>() { return "Simple_0"; } template <> constexpr std::string_view TestValue<1, TestData::Simple>() { return "Simple_1"; } template <> constexpr std::string_view TestValue<0, TestData::Shared>() { return "Shared_0"; } template <> constexpr std::string_view TestValue<1, TestData::Shared>() { return "Shared_1"; } template <> constexpr std::string_view TestValue<0, TestData::Encrypted>() { return "Encrypted_0"; } template <> constexpr std::string_view TestValue<1, TestData::Encrypted>() { return "Encrypted_1"; } template <> constexpr std::string_view TestValue<0, TestData::EncryptedAndShared>() { return "EncryptedAndShared_0"; } template <> constexpr std::string_view TestValue<1, TestData::EncryptedAndShared>() { return "EncryptedAndShared_1"; } template <> constexpr std::string_view TestValue<0, TestData::WithSimpleRef>() { return "WithSimpleRef_0"; } template <> constexpr std::string_view TestValue<1, TestData::WithSimpleRef>() { return "WithSimpleRef_1"; } template <> constexpr std::string_view TestValue<0, Database2::ByteString>() { return "Database2::ByteString_0"; } template <> constexpr std::string_view TestValue<1, Database2::ByteString>() { return "Database2::ByteString_1"; } #if TODO_OBJREF template <> constexpr std::string_view TestValue<TestData::WithString>() { return "WithString"; }; template <> constexpr std::string_view TestValue<TestData::WithSharedString>() { return "WithSharedString"; }; template <> constexpr std::string_view TestValue<TestData::WithSharedData>() { return "WithSharedData"; }; template <> constexpr std::string_view TestValue<TestData::WithEncryptedString>() { return "WithEncryptedString"; }; template <> constexpr std::string_view TestValue<TestData::WithEncryptedSharedString>() { return "WithEncryptedSharedString"; }; #endif template <size_t N, typename TObj> struct ObjTester; template <size_t N, typename... TObjs> auto CreateObjects(DB& db) { auto lock = db.LockForEdit(); using Tuple = std::tuple<ObjTester<N, TObjs>...>; std::vector<std::unique_ptr<Tuple>> arrayoftuples(1000); for (size_t i = 0; i < 1000; i++) { arrayoftuples[i].reset(new Tuple(ObjTester<N, TObjs>{i, {}}...)); std::apply([&](auto&... x) { [[maybe_unused]] auto tmp = std::make_tuple(x.CreateObj(lock, db)...); }, *arrayoftuples[i].get()); } return arrayoftuples; } template <size_t N, typename T> void VerifyObjects(T const& arrayoftuples, DB& db) { auto lock = db.LockForRead(); for (auto& t : arrayoftuples) { std::apply([&](auto&... x) { [[maybe_unused]] auto tmp = std::make_tuple(x.VerifyObj(lock, db)...); }, *t.get()); } } template <size_t N> struct ObjTester<N, Database2::ByteString> { template <typename TLock> bool CreateObj(TLock const& lock, DB& db) { auto [ref1, obj] = db.Create<Database2::ByteString>(lock, TestValue<N, Database2::ByteString>()); ref = ref1; auto obj1 = db.Get(lock, ref); REQUIRE(obj == TestValue<N, Database2::ByteString>()); REQUIRE(obj1 == TestValue<N, Database2::ByteString>()); return true; } template <typename TLock> bool VerifyObj(TLock const& lock, DB& db) { auto obj = db.Get(lock, ref); REQUIRE(obj == TestValue<N, Database2::ByteString>()); return true; } size_t iteration; Database2::Ref<DB, Database2::ByteString> ref{}; }; template <size_t N> struct ObjTester<N, TestData::WithSimpleRef> { using Type = TestData::WithSimpleRef; template <typename TLock> bool CreateObj(TLock const& lock, DB& db) { auto [ref1, obj] = db.Create<TestData::WithSimpleRef>(lock, TestUuid<N, TestData::Simple>(), TestUuid<N, TestData::WithSimpleRef>(), TestUuid<N, TestData::Simple>(), TestValue<N, Database2::ByteString>()); ref = ref1; auto obj1 = db.Get(lock, ref); REQUIRE(obj.uuid == TestUuid<N, Type>()); REQUIRE(obj1.uuid == TestUuid<N, Type>()); return true; } template <typename TLock> bool VerifyObj(TLock const& lock, DB& db) { auto obj = db.Get(lock, ref); REQUIRE(obj.uuid == TestUuid<N, Type>()); // auto subobj = obj.ref1.Get(lock.shared(), db, obj); // REQUIRE(subobj.uuid == TestUuid<TestData::Simple>()); return true; } size_t iteration; Database2::Ref<DB, Type> ref; }; template <typename TObj> void TestCaseForObj() { auto dbFileName = std::to_string(typeid(TObj).hash_code()) + ".bin"s; std::filesystem::remove(dbFileName); { DB db{dbFileName}; ObjTester<0, TObj> tester{0, {}}; tester.CreateObj(db.LockForEdit(), db); tester.VerifyObj(db.LockForRead(), db); } std::filesystem::remove(dbFileName); } #define TEST_CASE_FOR_OBJTYPE(type) \ TEST_CASE("CodeGen::Database2::" #type, "[Unit]") { TestCaseForObj<type>(); } //#define TEST_CASE_FOR_(type, ...) TEST_CASE_FOR_OBJTYPE(type) TEST_CASE_FOR_(__VA_ARGS__) //#define TEST_CASE_FOR__(arg) TEST_CASE_FOR_ arg //#define TEST_CASE_FOR(args) TEST_CASE_FOR__((args)) #define ALL_TESTED_TYPES Database2::ByteString, TestData::WithSimpleRef TEST_CASE_FOR_OBJTYPE(Database2::ByteString) TEST_CASE_FOR_OBJTYPE(TestData::WithSimpleRef) // TEST_CASE_FOR(ALL_TESTED_TYPES); TEST_CASE("CodeGen::Database2::SaveAndLoadFile", "[Database2]") { auto dbFileName = "SaveAndLoadFile.bin"s; if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName); // Constructor With Path Creates New File and Writes Header { { DB datastore{dbFileName}; } REQUIRE(std::filesystem::exists(dbFileName)); REQUIRE(std::filesystem::file_size(dbFileName) == (8192 * 2 + 80)); } // Constructor With Path Reads Existing File but doesnt touch it { auto time = std::filesystem::file_time_type::clock::now(); { DB datastore{dbFileName}; } if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() > time.time_since_epoch().count()) { FAIL("Failed. Database was modified"); } } // Constructor With IStream reads file { auto time = std::filesystem::file_time_type::clock::now(); { DB datastore{std::ifstream(dbFileName)}; CreateObjects<0, ALL_TESTED_TYPES>(datastore); } if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() > time.time_since_epoch().count()) { FAIL("Database changed"); } } // Empty Constructor for in-memory datastore { { DB datastore{DB::InMemory}; CreateObjects<0, ALL_TESTED_TYPES>(datastore); } { // TODO : Verify nothing written } } } TEST_CASE("CodeGen::Database2::SaveAndLoadObjects", "[Database2]") { auto dbFileName = "SaveAndLoadObjects.bin"s; SECTION("Check Objects Write and Read") { if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName); auto state = [&]() { DB datastore{dbFileName}; return CreateObjects<0, ALL_TESTED_TYPES>(datastore); }(); { DB datastore{dbFileName}; VerifyObjects<0>(state, datastore); } // AvailableSlot Initialized to right value on reload { DB datastore{dbFileName}; VerifyObjects<0>(state, datastore); VerifyObjects<1>(CreateObjects<1, ALL_TESTED_TYPES>(datastore), datastore); VerifyObjects<0>(state, datastore); } } SECTION("ChildRef Release marks dirty and saves and reloads") { if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName); auto objs = [&]() { DB datastore{dbFileName}; return CreateObjects<0, TestData::WithSimpleRef>(datastore); }(); auto time = std::filesystem::last_write_time(dbFileName); std::this_thread::sleep_for(10ms); // Looks like the below code is too quick for appreciable difference in modified time { DB datastore{dbFileName}; auto lock = datastore.LockForEdit(); auto& editObj = datastore.Get(lock, std::get<0>(*objs[0]).ref); REQUIRE(editObj.ref1.ref.Valid()); editObj.ref1.Release(lock, datastore); REQUIRE(!editObj.ref1.ref.Valid()); } if (std::filesystem::last_write_time(dbFileName).time_since_epoch().count() < time.time_since_epoch().count()) { FAIL("Database not changed"); } { DB datastore{dbFileName}; auto lock = datastore.LockForRead(); auto& editObj = datastore.Get(lock, std::get<0>(*objs[0]).ref); REQUIRE(!editObj.ref1.ref.Valid()); } } SECTION("Get Edit ref marks the object as dirty") { // FAIL("TODO"); } } TEST_CASE("CodeGen::Database2::UniqueSharedAndSelf", "[Database2]") { auto dbFileName = "UniqueSharedAndSelf.bin"s; if (std::filesystem::exists(dbFileName)) std::filesystem::remove(dbFileName); SECTION("Self") { DB store{dbFileName}; { auto lock = store.LockForEdit(); auto [ref, objstr1] = store.Create<Database2::ByteString>(lock, TestValue<0, Database2::ByteString>()); REQUIRE(ref.page > 0); REQUIRE(ref.slot >= 0); REQUIRE(objstr1 == TestValue<0, Database2::ByteString>()); } { auto lock = store.LockForRead(); size_t count = 0; for ([[maybe_unused]] auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { count++; } REQUIRE(count == 1); } { auto lock = store.LockForEdit(); for (auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { store.Delete(lock, ref); } size_t count = 0; for ([[maybe_unused]] auto const [ref, obj] : store.Objects<Database2::ByteString>(lock)) { count++; } // TODO : REQUIRE(count == 0); // TODO : TEst case for verifying that editlock causes a page dirty } } }
32.657143
137
0.63014
ankurvdev
bdc35da01134734ff93efdc130cb82494fade819
8,169
cpp
C++
src/slider.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/slider.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/slider.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2014 by David White <davewx7@gmail.com> 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 acknowledgement 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 "Canvas.hpp" #include "gui_section.hpp" #include "image_widget.hpp" #include "joystick.hpp" #include "logger.hpp" #include "slider.hpp" #include "widget_factory.hpp" namespace gui { Slider::Slider(int width, ChangeFn onchange, float position, int scale) : width_(width), onchange_(onchange), dragging_(false), position_(position), slider_left_(new GuiSectionWidget("slider_side_left", -1, -1, scale)), slider_right_(new GuiSectionWidget("slider_side_right", -1, -1, scale)), slider_middle_(new GuiSectionWidget("slider_middle", -1, -1, scale)), slider_button_(new GuiSectionWidget("slider_button", -1, -1, scale)) { setEnvironment(); init(); setDim(width_+slider_left_->width()*2, slider_button_->height()); } Slider::Slider(const variant& v, game_logic::FormulaCallable* e) : Widget(v,e), dragging_(false) { ASSERT_LOG(getEnvironment() != 0, "You must specify a callable environment"); onchange_ = std::bind(&Slider::changeDelegate, this, std::placeholders::_1); ffl_handler_ = getEnvironment()->createFormula(v["on_change"]); if(v.has_key("on_drag_end")) { ondragend_ = std::bind(&Slider::dragEndDelegate, this, std::placeholders::_1); ffl_end_handler_ = getEnvironment()->createFormula(v["on_drag_end"]); } position_ = v.has_key("position") ? v["position"].as_float() : 0.0f; slider_left_ = v.has_key("slider_left") ? widget_factory::create(v["slider_left"], e) : new GuiSectionWidget("slider_side_left", -1, -1, 2); slider_right_ = v.has_key("slider_right") ? widget_factory::create(v["slider_right"], e) : new GuiSectionWidget("slider_side_right", -1, -1, 2); slider_middle_ = v.has_key("slider_middle") ? widget_factory::create(v["slider_middle"], e) : new GuiSectionWidget("slider_middle", -1, -1, 2); slider_button_ = v.has_key("slider_button") ? widget_factory::create(v["slider_button"], e) : new GuiSectionWidget("slider_button", -1, -1, 2); init(); setDim(width_+slider_left_->width()*2, slider_button_->height()); } void Slider::init() const { int slider_y = height()/2 - slider_middle_->height()/2; slider_left_->setLoc(0, slider_y); slider_middle_->setLoc(slider_left_->width(), slider_y); slider_middle_->setDim(width_, slider_middle_->height()); slider_right_->setLoc(slider_left_->width()+width_, slider_y); slider_button_->setLoc(slider_left_->width()+static_cast<int>(position_*width_)-slider_button_->width()/2, 0); } bool Slider::inButton(int xloc, int yloc) const { xloc -= getPos().x; yloc -= getPos().y; int button_x = slider_left_->width() + int(position_*width_); return xloc > button_x-40 && xloc < button_x + slider_button_->width()+40 && yloc > -10 && yloc < height()+10; } bool Slider::inSlider(int xloc, int yloc) const { return xloc > x() && xloc < x() + width() && yloc > y() && yloc < y() + height(); } void Slider::handleDraw() const { init(); if(hasFocus()) { KRE::Canvas::getInstance()->drawHollowRect(rect(x()-1, y()-1, width()+2, height()+2), KRE::Color(128,128,128,128)); } slider_left_->draw(x(), y(), getRotation(), getScale()); slider_middle_->draw(x(), y(), getRotation(), getScale()); slider_right_->draw(x(), y(), getRotation(), getScale()); slider_button_->draw(x(), y(), getRotation(), getScale()); } void Slider::changeDelegate(float position) { using namespace game_logic; if(getEnvironment()) { MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable(getEnvironment())); callable->add("position", variant(position)); variant value = ffl_handler_->execute(*getEnvironment()); getEnvironment()->executeCommand(value); } else { LOG_ERROR("slider::changeDelegate() called without environment!"); } } void Slider::dragEndDelegate(float position) { using namespace game_logic; if(getEnvironment()) { MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable(getEnvironment())); callable->add("position", variant(position)); variant value = ffl_end_handler_->execute(*getEnvironment()); getEnvironment()->executeCommand(value); } else { LOG_ERROR("slider::dragEndDelegate() called without environment!"); } } void Slider::handleProcess() { Widget::handleProcess(); if(hasFocus()) { static int control_lockout = 0; if(joystick::left() && !control_lockout) { control_lockout = 5; if(position() <= 1.0f/25.0f) { setPosition(0.0f); } else { setPosition(position() - 1.0f/25.0f); } if(onchange_) { onchange_(position()); } } if(joystick::right() && !control_lockout) { control_lockout = 5; if(position() >= 1.0f-1.0f/25.0f) { setPosition(1.0f); } else { setPosition(position() + 1.0f/25.0f); } if(onchange_) { onchange_(position()); } } if(control_lockout) { --control_lockout; } } } bool Slider::handleEvent(const SDL_Event& event, bool claimed) { if(claimed) { dragging_ = false; } if(event.type == SDL_MOUSEMOTION && dragging_) { const SDL_MouseMotionEvent& e = event.motion; int mouse_x = e.x - getPos().x; int mouse_y = e.y - getPos().y; int rel_x = mouse_x - slider_left_->width(); if (rel_x < 0) rel_x = 0; if (rel_x > width_) rel_x = width_; float pos = static_cast<float>(rel_x)/width_; if (pos != position_) { position_ = pos; onchange_(pos); } return claimMouseEvents(); } else if(event.type == SDL_MOUSEBUTTONDOWN) { const SDL_MouseButtonEvent& e = event.button; if(inButton(e.x,e.y)) { dragging_ = true; return claimMouseEvents(); } } else if(event.type == SDL_MOUSEBUTTONUP && dragging_) { dragging_ = false; claimed = claimMouseEvents(); if(ondragend_) { const SDL_MouseButtonEvent& e = event.button; int mouse_x = e.x - getPos().x; int mouse_y = e.y - getPos().y; int rel_x = mouse_x - slider_left_->width(); if (rel_x < 0) rel_x = 0; if (rel_x > width_) rel_x = width_; float pos = static_cast<float>(rel_x)/width_; ondragend_(pos); } } if(event.type == SDL_KEYDOWN && hasFocus()) { if(event.key.keysym.sym == SDLK_LEFT) { if(position() <= 1.0f/20.0f) { setPosition(0.0f); } else { setPosition(position() - 1.0f/20.0f); } if(onchange_) { onchange_(position()); } claimed = true; } else if(event.key.keysym.sym == SDLK_RIGHT) { if(position() >= 1.0f-1.0f/20.0f) { setPosition(1.0f); } else { setPosition(position() + 1.0f/20.0f); } if(onchange_) { onchange_(position()); } claimed = true; } } return claimed; } WidgetPtr Slider::clone() const { Slider* s = new Slider(*this); if(slider_left_) { s->slider_left_ = slider_left_->clone(); } if(slider_right_) { s->slider_right_ = slider_right_->clone(); } if(slider_middle_) { s->slider_middle_ = slider_middle_->clone(); } if(slider_button_) { s->slider_button_ = slider_button_->clone(); } return WidgetPtr(s); } BEGIN_DEFINE_CALLABLE(Slider, Widget) DEFINE_FIELD(position, "decimal") return variant(obj.position()); DEFINE_SET_FIELD obj.setPosition(value.as_float()); END_DEFINE_CALLABLE(Slider) }
29.813869
118
0.667524
gamobink
bdc594d2bcb8a9dd1c4b649c1faab9278d4d980e
20,614
cc
C++
extensions/pyre/grid/grids.cc
PyreFramework/pyre
345c7449a3416eea1c1affa74fb32faff30a6aaa
[ "BSD-3-Clause" ]
null
null
null
extensions/pyre/grid/grids.cc
PyreFramework/pyre
345c7449a3416eea1c1affa74fb32faff30a6aaa
[ "BSD-3-Clause" ]
null
null
null
extensions/pyre/grid/grids.cc
PyreFramework/pyre
345c7449a3416eea1c1affa74fb32faff30a6aaa
[ "BSD-3-Clause" ]
null
null
null
// -*- c++ -*- // // michael a.g. aïvázis <michael.aivazis@para-sim.com> // (c) 1998-2022 all rights reserved // externals #include "external.h" // namespace setup #include "forward.h" // my instantiations #include "grids.h" // wrappers over {pyre::grid::grid_t} template expansions // build the submodule void pyre::py::grid::grids(py::module & m) { // 2d const maps byteConstMapGrid2D(m); int16ConstMapGrid2D(m); int32ConstMapGrid2D(m); int64ConstMapGrid2D(m); floatConstMapGrid2D(m); doubleConstMapGrid2D(m); complexFloatConstMapGrid2D(m); complexDoubleConstMapGrid2D(m); // 3d const maps byteConstMapGrid3D(m); int16ConstMapGrid3D(m); int32ConstMapGrid3D(m); int64ConstMapGrid3D(m); floatConstMapGrid3D(m); doubleConstMapGrid3D(m); complexFloatConstMapGrid3D(m); complexDoubleConstMapGrid3D(m); // 4d const maps byteConstMapGrid4D(m); int16ConstMapGrid4D(m); int32ConstMapGrid4D(m); int64ConstMapGrid4D(m); floatConstMapGrid4D(m); doubleConstMapGrid4D(m); complexFloatConstMapGrid4D(m); complexDoubleConstMapGrid4D(m); // all done return; } // grid instantiations // 2d void pyre::py::grid::byteConstMapGrid2D(py::module & m) { // type aliases using cell_t = char; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ByteConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of bytes"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int16ConstMapGrid2D(py::module & m) { // type aliases using cell_t = int16_t; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int16ConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of {int16_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int32ConstMapGrid2D(py::module & m) { // type aliases using cell_t = int32_t; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int32ConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of {int32_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int64ConstMapGrid2D(py::module & m) { // type aliases using cell_t = int64_t; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int64ConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of {int64_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::floatConstMapGrid2D(py::module & m) { // type aliases using cell_t = float; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "FloatConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::doubleConstMapGrid2D(py::module & m) { // type aliases using cell_t = double; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "DoubleConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexFloatConstMapGrid2D(py::module & m) { // type aliases using cell_t = std::complex<float>; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexFloatConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of complex floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexDoubleConstMapGrid2D(py::module & m) { // type aliases using cell_t = std::complex<double>; using packing_t = pyre::grid::canonical_t<2>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexDoubleConstMapGrid2D", // docstring "a 2d grid backed by a read-only map of complex doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } // 3d void pyre::py::grid::byteConstMapGrid3D(py::module & m) { // type aliases using cell_t = char; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ByteConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of bytes"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int16ConstMapGrid3D(py::module & m) { // type aliases using cell_t = int16_t; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int16ConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of {int16_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int32ConstMapGrid3D(py::module & m) { // type aliases using cell_t = int32_t; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int32ConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of {int32_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int64ConstMapGrid3D(py::module & m) { // type aliases using cell_t = int64_t; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int64ConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of {int64_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::floatConstMapGrid3D(py::module & m) { // type aliases using cell_t = float; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "FloatConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::doubleConstMapGrid3D(py::module & m) { // type aliases using cell_t = double; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "DoubleConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexFloatConstMapGrid3D(py::module & m) { // type aliases using cell_t = std::complex<float>; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexFloatConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of complex floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexDoubleConstMapGrid3D(py::module & m) { // type aliases using cell_t = std::complex<double>; using packing_t = pyre::grid::canonical_t<3>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexDoubleConstMapGrid3D", // docstring "a 3d grid backed by a read-only map of complex doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } // 4d void pyre::py::grid::byteConstMapGrid4D(py::module & m) { // type aliases using cell_t = char; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ByteConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of bytes"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int16ConstMapGrid4D(py::module & m) { // type aliases using cell_t = int16_t; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int16ConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of {int16_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int32ConstMapGrid4D(py::module & m) { // type aliases using cell_t = int32_t; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int32ConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of {int32_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::int64ConstMapGrid4D(py::module & m) { // type aliases using cell_t = int64_t; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "Int64ConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of {int64_t}"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::floatConstMapGrid4D(py::module & m) { // type aliases using cell_t = float; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "FloatConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::doubleConstMapGrid4D(py::module & m) { // type aliases using cell_t = double; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "DoubleConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexFloatConstMapGrid4D(py::module & m) { // type aliases using cell_t = std::complex<float>; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexFloatConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of complex floats"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } void pyre::py::grid::complexDoubleConstMapGrid4D(py::module & m) { // type aliases using cell_t = std::complex<double>; using packing_t = pyre::grid::canonical_t<4>; using storage_t = pyre::memory::constmap_t<cell_t>; using grid_t = pyre::grid::grid_t<packing_t, storage_t>; // build the class record auto cls = py::class_<grid_t>( // in scope m, // class name "ComplexDoubleConstMapGrid4D", // docstring "a 4d grid backed by a read-only map of complex doubles"); // the map specific interface constmapInterface(cls); // the grid interface constgridInterface(cls); // all done return; } // the map specific constructors template <class gridT> void pyre::py::grid::constmapInterface(py::class_<gridT> & cls) { // constructors cls.def( // the implementation py::init<typename gridT::packing_const_reference, typename gridT::storage_pointer>(), // "packing"_a, "storage"_a, // the docstring "make a new grid over the {storage} with the given {packing} strategy"); // all done return; } // the const grid interface decorator template <class gridT> void pyre::py::grid::constgridInterface(py::class_<gridT> & cls) { // accessors // layout cls.def_property_readonly( // the name of the method "layout", // the implementation &gridT::layout, // the docstring "access my layout"); // data access // by index cls.def( // the name of the method "__getitem__", // the implementation [](const gridT & self, typename gridT::index_const_reference index) { // get the value at the given {index} return self.at(index); }, // the signature "index"_a, // the docstring "get the value at the specified {index}"); // by tuple cls.def( // the name of the method "__getitem__", // the implementation [](const gridT & self, const std::vector<typename gridT::index_type::rank_type> & index) { // make an index auto idx = typename gridT::index_type(); // fill it std::copy(index.begin(), index.end(), idx.begin()); // get the value at the given {index} and return it return self.at(idx); }, // the signature "index"_a, // the docstring "get the value at the specified {index}"); // by offset cls.def( // the name of the method "__getitem__", // the implementation [](const gridT & self, typename gridT::difference_type offset) { // get the value at the given {offset} return self.at(offset); }, // the signature "offset"_a, // the docstring "get the value at the specified {offset}"); // all done return; } // the grid interface decorator template <class gridT> void pyre::py::grid::gridInterface(py::class_<gridT> & cls) { // data access // by index cls.def( // the name of the method "__setitem__", // the implementation [](const gridT & self, typename gridT::index_const_reference index, typename gridT::value_type value) -> void { // set the value at the given {index} self.at(index) = value; // all done }, // the signature "index"_a, // the docstring "get the value at the specified {index}"); // by offset cls.def( // the name of the method "__setitem__", // the implementation [](const gridT & self, typename gridT::difference_type offset, typename gridT::value_type value) -> void { // set the value at the given {offset} self.at(offset) = value; // all done return; }, // the signature "offset"_a, // the docstring "get the value at the specified {offset}"); // all done return; } // end of file
23.886443
98
0.608518
PyreFramework
bdc9f53a41d25d29c68ac43c89e298c78de3f1cc
13,138
cpp
C++
Antario/Features/Aimbot.cpp
NoelWriter/mirrorcsgo
bb527561df68cff5283472d5fed0492c58c2a078
[ "MIT" ]
1
2020-02-23T17:35:51.000Z
2020-02-23T17:35:51.000Z
Antario/Features/Aimbot.cpp
NoelWriter/mirrorcsgo
bb527561df68cff5283472d5fed0492c58c2a078
[ "MIT" ]
null
null
null
Antario/Features/Aimbot.cpp
NoelWriter/mirrorcsgo
bb527561df68cff5283472d5fed0492c58c2a078
[ "MIT" ]
null
null
null
#include "Aimbot.h" #include <Windows.h> #include "..\Utils\Utils.h" #include "..\Utils\GlobalVars.h" #include "..\Hooks.h" #include "..\SDK\Studio.hpp" #include "..\Utils\Interfaces.h" #include "Backtrack.h" #include "Ragewall.h" #include "..\SDK\CGlobalVarsBase.h" // Declare classes Aimbot g_Aimbot; // Movefix variables float m_oldforward, m_oldsidemove; QAngle m_oldangle; // Aimbot variables C_BaseEntity *target; void Aimbot::DoAimbot(CUserCmd* pCmd) { if (g_Settings.bAimbotEnable && g_Settings.bRagebotEnable) return; if (g_Settings.bRagebotEnable) { DoRageAimbot(pCmd); return; } if (g_Settings.bAimbotEnable) { DoLegitAimbot(pCmd); return; } } void Aimbot::DoRageAimbot(CUserCmd* pCmd) { // Check if player is in game if (!g::pLocalEntity || !g_pEngine->IsInGame()) return; // Check if player is alive if (!g::pLocalEntity || g::pLocalEntity->IsDormant() || !g::pLocalEntity->IsAlive()) return; // Get some other variables auto weapon = g::pActiveWeapon; if (!weapon) return; int bestHitbox = 8; bool isAttacking = (pCmd->buttons & IN_ATTACK || g_Settings.bRagebotAutoFire); if (!isAttacking) return; // Dont aimbot when we have a knife or grenade in our hands if (weapon->isGrenade() || weapon->GetCSWpnData()->weapon_type() == 0) return; g_RageWall.TargetEntities(pCmd); } void Aimbot::DoLegitAimbot(CUserCmd* pCmd) { // Check if player is in game if (!g::pLocalEntity || !g_pEngine->IsInGame()) return; // Check if player is alive if (!g::pLocalEntity || g::pLocalEntity->IsDormant() || !g::pLocalEntity->IsAlive()) return; // Get some other variables auto weapon = g::pActiveWeapon; if (!weapon) return; int bestHitbox = 7; bool isAttacking = (pCmd->buttons & IN_ATTACK); if (!isAttacking) return; if (weapon->isGrenade() || weapon->GetCSWpnData()->weapon_type() == 0) return; // Get a new target Vector targetHitbox; C_BaseEntity *target = GetBestTarget(targetHitbox); // Check if target is Null if (!target) return; // Check if target is behind smoke if (target->IsBehindSmoke(target))//&& g_Settings.bSmokeCheck) return; // TODO: Custom hitbox selection bestHitbox = getHitbox(weapon); // Let's check if wee can see the player, if we can, we aim. CGameTrace tr; g_RageWall.traceIt(g::pLocalEntity->GetEyePosition(), target->GetBonePos(bestHitbox), MASK_SHOT | CONTENTS_GRATE, g::pLocalEntity, &tr); if (tr.fraction > 0.97f && tr.fraction != 1.f) AimAt(pCmd, target, bestHitbox); } bool isLocked = false; C_BaseEntity* Aimbot::GetBestTarget(Vector& outBestPos) { // Init some variables C_BaseEntity* target = nullptr; int curBestTarget; float currentFov; float weaponFov; float bestFov = 360; float bestDistance = 8128.f; // Variables we need later auto weapon = g::pActiveWeapon; if (!weapon) return nullptr; auto localTeam = g::pLocalEntity->GetTeam(); if (!isLocked && g::bestTarget == 0) { // Itterate through all the players in the server for (int i = 1; i <= g_pEngine->GetMaxClients(); ++i) { // Get the entity from the player we are currently itterating on C_BaseEntity* pPlayerEntity = g_pEntityList->GetClientEntity(i); // Various checks if (!pPlayerEntity || !pPlayerEntity->IsAlive() || pPlayerEntity->IsDormant() || pPlayerEntity == g::pLocalEntity || pPlayerEntity->GetTeam() == localTeam) continue; // Get Fov for each weapon if (g_Settings.bAimbotEnable) weaponFov = getFov(weapon); else weaponFov = g_Settings.bRagebotFov; // Get positions from me and target Vector myPos = g::pLocalEntity->GetBonePos(8); Vector pEntPos = pPlayerEntity->GetBonePos(8); // Calculate angle between me and target QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos); // Calculate recoil values to compensate aimbot currentFov = get_fov(g::pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle); // Get Distance between me and target auto currentDistance = Get3D_Distance(myPos, pEntPos); // Check if the target is closer to the crosshair and if the target is in range of FOV if (currentFov < weaponFov && (bestFov == NULL || currentFov < bestFov)) { bestFov = currentFov; curBestTarget = i; target = pPlayerEntity; } // Check for distance also if (currentFov <= weaponFov && currentDistance < bestDistance && (currentFov < bestFov || bestFov == NULL)) { bestFov = currentFov; curBestTarget = i; target = pPlayerEntity; bestDistance = currentDistance; } } if (g::bestTarget > 0) { isLocked = true; g::bestTarget = curBestTarget; } } if (g::bestTarget > 0) return g_pEntityList->GetClientEntity(g::bestTarget); else return target; } bool Aimbot::AutoShoot(CUserCmd* pCmd, C_BaseEntity* BestTarget) { C_BaseCombatWeapon* pWeapon = g::pActiveWeapon; if (!pWeapon) return false; float flServerTime = g::pLocalEntity->GetTickBase() * g_pGlobalVars->intervalPerTick; bool canShoot = !(pWeapon->GetNextPrimaryAttack() > flServerTime) && !(pCmd->buttons & IN_RELOAD); if (Hitchance(pWeapon, 20) > 20 && !(pCmd->buttons & IN_ATTACK) && canShoot) pCmd->buttons |= IN_ATTACK; else return false; return true; } float Aimbot::Hitchance(C_BaseCombatWeapon* pWeapon, float hitChance) { float hitchance = 101; if (!pWeapon) return 0; if (hitChance > 0) { float inaccuracy = pWeapon->GetInaccuracy(); if (inaccuracy == 0) inaccuracy = 0.0000001f; inaccuracy = 1 / inaccuracy; hitchance = inaccuracy; } return hitchance; } /* bool Aimbot::CanHitTarget(C_BaseEntity* pTarget) { Vector newShittyDistance; bool hasPenetratedWall = false; Vector bestHitboxPos; auto pEnt = pTarget; Vector hitboxPos; studiohdr_t* pStudioHdr = g_pMdlInfo->GetStudiomodel2(pEnt->GetModel()); std::vector<int> hitboxes; if (!pStudioHdr) return false; Vector vParent, vChild, sParent, sChild; for (int j = 0; j < pStudioHdr->numbones; j++) { mstudiobone_t* pBone = pStudioHdr->GetBone(j); if (pBone && (pBone->flags & BONE_USED_BY_HITBOX) && (pBone->parent != -1)) { hitboxes.push_back(j); hitboxes.push_back(pBone->parent); } } for (const int &hitbox : hitboxes) { Vector pTargetPos = pTarget->GetBonePos(hitbox); if (g_RageWall.CanHit(pTargetPos)) return true; } return false; }*/ float Aimbot::getFov(C_BaseCombatWeapon* weapon) { if (weapon->isSniper()) return g_Settings.bAimbotFovSniper; if (weapon->isRifle()) return g_Settings.bAimbotFovRifle; if (weapon->isPistol()) return g_Settings.bAimbotFovPistol; return g_Settings.bAimbotFovRifle; } float Aimbot::getSmooth(C_BaseCombatWeapon* weapon) { if (weapon->isSniper()) return g_Settings.bAimbotSmoothSniper; if (weapon->isRifle()) return g_Settings.bAimbotSmoothRifle; if (weapon->isPistol()) return g_Settings.bAimbotSmoothPistol; return g_Settings.bAimbotFovRifle; } int Aimbot::getHitbox(C_BaseCombatWeapon* weapon) { int curSelected = 3; if (weapon->isSniper()) curSelected = g_Settings.bAimbotHitboxSniper; if (weapon->isRifle()) curSelected = g_Settings.bAimbotHitboxRifle; if (weapon->isPistol()) curSelected = g_Settings.bAimbotHitboxPistol; switch (curSelected) { case 0: return 8; case 1: return 4; case 2: return 6; default: return 8; } } void Aimbot::AimAtVec(CUserCmd* pCmd, C_BaseEntity* pEnt, Vector hitbox) { if (!g::pLocalEntity || !g_pEngine->IsInGame()) return; auto weapon = g::pActiveWeapon; if (!weapon) return; if (weapon->GetAmmo() == 0 || pCmd->buttons & IN_RELOAD) return; auto localTeam = g::pLocalEntity->GetTeam(); if (!pEnt || !pEnt->IsAlive() || pEnt->IsDormant() || pEnt == g::pLocalEntity || pEnt->GetTeam() == localTeam || pEnt->IsImmune()) return; Vector pHitboxServerDistance; bool doBacktrack = false; QAngle tempAimAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pEnt->GetBonePos(8)); float bestFov = get_fov(pCmd->viewangles, tempAimAngle); float curWeaponFov = getFov(g::pActiveWeapon); Vector actualHitBox = hitbox; Vector myPos = g::pLocalEntity->GetEyePosition(); // If we have a better tick to aim at, move our target to that tick if (doBacktrack) actualHitBox -= pHitboxServerDistance; Vector pEntPos = actualHitBox; // Velocity Compensation pEntPos += pEnt->GetVelocity() * g_pGlobalVars->intervalPerTick; // Get angle we are supposed to aim at QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos); if (g::pLocalEntity->GetPunchAngles().Length() > 0) aimAngle -= g::pLocalEntity->GetPunchAngles() * 2; // Make sure we dont aim out of bounds otherwise we'll get untrusted Utils::ClampViewAngles(aimAngle); // Get the difference between aim angle and your viewangle QAngle deltaAngle = pCmd->viewangles - aimAngle; // Make sure we dont aim out of bounds otherwise we'll get untrusted Utils::ClampViewAngles(deltaAngle); // Get the fov auto fov = get_fov(pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle); QAngle finalAngle; finalAngle = pCmd->viewangles - deltaAngle; Utils::ClampViewAngles(finalAngle); float currentFov; currentFov = g_Settings.bRagebotFov; if (fov <= currentFov) { if (!g_Settings.bRagebotSilent) { g_pEngine->SetViewAngles(finalAngle); } pCmd->viewangles = finalAngle; } } void Aimbot::AimAt(CUserCmd* pCmd, C_BaseEntity* pEnt, int hitbox) { if (!g::pLocalEntity || !g_pEngine->IsInGame()) return; auto weapon = g::pActiveWeapon; if (!weapon) return; if (weapon->GetAmmo() == 0 || pCmd->buttons & IN_RELOAD) return; auto localTeam = g::pLocalEntity->GetTeam(); if (!pEnt || !pEnt->IsAlive() || pEnt->IsDormant() || pEnt == g::pLocalEntity || pEnt->GetTeam() == localTeam || pEnt->IsImmune()) return; Vector pHitboxServerDistance; bool doBacktrack = false; QAngle tempAimAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pEnt->GetBonePos(8)); float bestFov = get_fov(pCmd->viewangles, tempAimAngle); float curWeaponFov = getFov(g::pActiveWeapon); if (g_Settings.bAimbotBacktrack && g_Settings.bAimbotEnable) { // Loop through backtracking ticks for (int i = 0; i < g_Settings.bAimbotBacktrackTicks; i++) { Vector pHitboxPos = l_SavedTicks[pEnt->EntIndex()][i].hitboxPos; QAngle pHitboxAngle = Utils::CalcAngle(g::pLocalEntity->GetBonePos(8), pHitboxPos); auto newFov = g_Aimbot.get_fov(pCmd->viewangles, pHitboxAngle); if (l_SavedTicks[pEnt->EntIndex()][i].simtime <= g::pLocalEntity->GetSimulationTime() - 1) continue; // Is our fov closer to the tick we are currently itterating on? if (newFov < curWeaponFov && newFov < bestFov) { bestFov = newFov; doBacktrack = true; pHitboxServerDistance = Vector(sqrt((pHitboxPos.x - pEnt->GetBonePos(8).x) * (pHitboxPos.x - pEnt->GetBonePos(8).x)), sqrt((pHitboxPos.y - pEnt->GetBonePos(8).y) * (pHitboxPos.y - pEnt->GetBonePos(8).y)), 0); } } } Vector actualHitBox = pEnt->GetBonePos(hitbox); Vector myPos = g::pLocalEntity->GetEyePosition(); // If we have a better tick to aim at, move our target to that tick if (doBacktrack) actualHitBox -= pHitboxServerDistance; Vector pEntPos = actualHitBox; // Velocity Compensation pEntPos += pEnt->GetVelocity() * g_pGlobalVars->intervalPerTick; // Get angle we are supposed to aim at QAngle aimAngle = Utils::CalcAngle(myPos, pEntPos); if (g::pLocalEntity->GetPunchAngles().Length() > 0) aimAngle -= g::pLocalEntity->GetPunchAngles() * 2; // Make sure we dont aim out of bounds otherwise we'll get untrusted Utils::ClampViewAngles(aimAngle); // Get the difference between aim angle and your viewangle QAngle deltaAngle = pCmd->viewangles - aimAngle; // Make sure we dont aim out of bounds otherwise we'll get untrusted Utils::ClampViewAngles(deltaAngle); // Get the fov auto fov = get_fov(pCmd->viewangles + g::pLocalEntity->GetPunchAngles() * 2, aimAngle); QAngle finalAngle; // TODO: Custom smoothing based on settings / weapon here float currentSmooth; if (g_Settings.bAimbotEnable) currentSmooth = getSmooth(weapon); else currentSmooth = 1.f; finalAngle = pCmd->viewangles - deltaAngle / currentSmooth; Utils::ClampViewAngles(finalAngle); float currentFov; if (g_Settings.bAimbotEnable) currentFov = getFov(weapon); else currentFov = g_Settings.bRagebotFov; if (fov <= currentFov) { if (!g_Settings.bRagebotSilent) { g_pEngine->SetViewAngles(finalAngle); } pCmd->viewangles = finalAngle; } } float Aimbot::Get3D_Distance(Vector src, Vector dst) { return sqrt(powf(src[0] - dst[0], 2.f) + powf(src[1] - dst[1], 2.f) + powf(src[2] - dst[2], 2.f)); } void Aimbot::MakeVector(QAngle angle, Vector& vector) { float pitch = float(angle[0] * PI / 180); float yaw = float(angle[1] * PI / 180); float tmp = float(cos(pitch)); vector[0] = float(-tmp * -cos(yaw)); vector[1] = float(sin(yaw)*tmp); vector[2] = float(-sin(pitch)); } float Aimbot::get_fov(const QAngle &viewAngles, const QAngle &aimAngles) { Vector ang, aim; MakeVector(viewAngles, aim); MakeVector(aimAngles, ang); return RAD2DEG(acos(aim.Dot(ang) / aim.LengthSqr())); }
25.560311
212
0.702923
NoelWriter
bdcf0f01282935ff7d2ab422e5bd939e63177e61
168
hpp
C++
samples/dependency/mod1.hpp
tlammi/rtfw
7a993e83b4d4e6ba7179219fd3667f42a2ae07e6
[ "MIT" ]
null
null
null
samples/dependency/mod1.hpp
tlammi/rtfw
7a993e83b4d4e6ba7179219fd3667f42a2ae07e6
[ "MIT" ]
null
null
null
samples/dependency/mod1.hpp
tlammi/rtfw
7a993e83b4d4e6ba7179219fd3667f42a2ae07e6
[ "MIT" ]
null
null
null
#pragma once #include "rtfw/module.hpp" struct Mod1{ static rtfw::Config config(){ return {}; } Mod1(const rtfw::Config& conf); ~Mod1(); int foo() const; };
11.2
32
0.630952
tlammi
bdcf8103512a939066841b0b34a20d00468ab4d8
426
cpp
C++
Codigos de ejercicios en cpp/Programa 7.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 7.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 7.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<conio.h> using namespace std; int main() { int numi,i=0,j,d=1; double numf; cout<<"introdusca el numero con decimales"<<endl; cin>>numf; numi=numf; cout<<"los decimales son: "<<numf-numi<<endl; while(numi!=numf) { numf=numf*10; numi=numf; i++; } for(j=0;j<i;j++) { d=d*10; } numi=numi/d; numf=numf-(numi*d); cout<<"pasados a enteros: "<<numf<<endl; getch(); return 0; }
14.689655
50
0.617371
EulisesBrazon
bdcfaa5bf8f2dcc3f0fbd772617a3b1ccf2e1d73
278
cpp
C++
acmicpc.net/source/1094.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
acmicpc.net/source/1094.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
acmicpc.net/source/1094.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// 1094. 막대기 // 2019.05.14 // 수학, 시뮬레이션 #include<iostream> using namespace std; int ans; int main() { int x; cin >> x; // 주어진 수를 이진법으로 나타냈을 때 1의 갯수가 정답이 된다. for (int i = 0; i < 7; i++) { if (x % 2 == 1) { ans++; } x /= 2; } cout << ans << endl; return 0; }
11.12
38
0.5
tdm1223
bdcfb0daf2af74f715cf7c4e3cc6754f2282e048
2,578
cpp
C++
src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp
stan-dev/nomad
a21149ef9f4d53a198e6fdb06cfd0363d3df69e7
[ "BSD-3-Clause" ]
23
2015-12-11T20:06:57.000Z
2021-01-15T18:59:58.000Z
src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp
stan-dev/nomad
a21149ef9f4d53a198e6fdb06cfd0363d3df69e7
[ "BSD-3-Clause" ]
2
2015-12-15T08:12:01.000Z
2016-07-17T01:36:56.000Z
src/test/scalar/functions/nonsmooth_functions/fmax_test.cpp
stan-dev/nomad
a21149ef9f4d53a198e6fdb06cfd0363d3df69e7
[ "BSD-3-Clause" ]
2
2017-10-13T17:40:34.000Z
2021-03-08T19:17:51.000Z
#include <gtest/gtest.h> #include <math.h> #include <string> #include <src/autodiff/base_functor.hpp> #include <src/scalar/functions.hpp> #include <src/test/io_validation.hpp> #include <src/test/finite_difference.hpp> template <typename T> class fmax_vv_eval_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { return fmax(nomad::tests::construct_unsafe_var<T>(x[0]), nomad::tests::construct_unsafe_var<T>(x[1])); } static std::string name() { return "fmax_vv"; } }; template <typename T> class fmax_vd_eval_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { return fmax(nomad::tests::construct_unsafe_var<T>(x[0]), x[1]); } static std::string name() { return "fmax_vd"; } }; template <typename T> class fmax_dv_eval_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { return fmax(x[0], nomad::tests::construct_unsafe_var<T>(x[1])); } static std::string name() { return "fmax_dv"; } }; template <typename T> class fmax_vv_grad_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { T v1 = x[0]; T v2 = x[1]; return fmax(exp(v1), exp(v2)); } static std::string name() { return "fmax_vv"; } }; template <typename T> class fmax_vd_grad_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { return fmax(exp(T(x[0])), exp(0.5)); } static std::string name() { return "fmax_vd"; } }; template <typename T> class fmax_dv_grad_func: public nomad::base_functor<T> { public: T operator()(const Eigen::VectorXd& x) const { return fmax(exp(0.5), exp(T(x[0]))); } static std::string name() { return "fmax_dv"; } }; TEST(ScalarNonSmoothFunctions, Fmax) { nomad::eigen_idx_t d = 2; Eigen::VectorXd x1(d); x1[0] = 0.75; x1[1] = 0.25; nomad::tests::test_validation<fmax_vv_eval_func>(x1); nomad::tests::test_validation<fmax_vd_eval_func>(x1); nomad::tests::test_validation<fmax_dv_eval_func>(x1); nomad::tests::test_derivatives<fmax_vv_grad_func>(x1); x1 *= -1; nomad::tests::test_derivatives<fmax_vv_grad_func>(x1); Eigen::VectorXd x2 = Eigen::VectorXd::Ones(1); x2[0] = 0.75; nomad::tests::test_derivatives<fmax_vd_grad_func>(x2); nomad::tests::test_derivatives<fmax_dv_grad_func>(x2); x2[0] = 0.25; nomad::tests::test_derivatives<fmax_vd_grad_func>(x2); nomad::tests::test_derivatives<fmax_dv_grad_func>(x2); }
26.57732
61
0.674166
stan-dev
bdd07f3e25045c2a320767f0cc7ebb9dd36c64db
1,349
cpp
C++
Olympiad Solutions/URI/2155.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/URI/2155.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/URI/2155.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/2155 #include <cstdio> #include <cmath> #include <vector> #include <algorithm> using namespace std; const double EPS = 1e-5; vector<int> resposta; double menor; int TC,X[10],Y[10]; int main(){ scanf("%d",&TC); for(int tc = 1;tc <= TC;tc++){ menor = 1e9; scanf("%d %d",&X[4],&Y[4]); vector<int> brute; for(int i=1;i<=6;i++){ int x,y,id; scanf("%d %d %d",&id,&x,&y); X[id] = x; Y[id] = y; } brute.push_back(1); brute.push_back(2); brute.push_back(3); brute.push_back(5); brute.push_back(6); brute.push_back(7); do{ double temp = hypot(X[4] - X[brute[0]], Y[4] - Y[brute[0]]) + hypot(X[4] - X[brute[5]], Y[4] - Y[brute[5]]); for(int i=0;i+1<6;i++){ temp += hypot(X[brute[i]] - X[brute[i+1]],Y[brute[i]] - Y[brute[i+1]]); } if(temp + EPS <= menor){ menor = temp; resposta = brute; } else if(fabs(temp - menor) < EPS){ if(brute < resposta){ resposta = brute; } } //printf("4->"); //for(int i=0;i<6;i++){ // printf("%d->",brute[i]); //} //printf("4: %.5lf\n",temp); }while(next_permutation(brute.begin(),brute.end())); printf("Caso %d:\n",tc); printf("4->"); for(int i=0;i<6;i++){ printf("%d->",resposta[i]); } printf("4: %.5lf\n",menor); } return 0; }
22.864407
111
0.547813
Ashwanigupta9125
7524e0acb600b2a45b765da97e5fdbbbe1ba34c3
780
hpp
C++
OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp
gco/oraclesolaris-contrib
f9905a8758a50a44720f5500e19b5f2528c6b6c8
[ "UPL-1.0" ]
null
null
null
OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp
gco/oraclesolaris-contrib
f9905a8758a50a44720f5500e19b5f2528c6b6c8
[ "UPL-1.0" ]
null
null
null
OracleSolaris_OpenJDK_Builder/patches-17/patch-src_hotspot_os__cpu_solaris__x86_prefetch__solaris__x86.inline.hpp
gco/oraclesolaris-contrib
f9905a8758a50a44720f5500e19b5f2528c6b6c8
[ "UPL-1.0" ]
null
null
null
$NetBSD$ Support SunOS/gcc. --- src/hotspot/os_cpu/solaris_x86/prefetch_solaris_x86.inline.hpp.orig 2019-01-08 12:44:56.000000000 +0000 +++ src/hotspot/os_cpu/solaris_x86/prefetch_solaris_x86.inline.hpp @@ -34,14 +34,22 @@ extern "C" { inline void Prefetch::read (void *loc, intx interval) { #ifdef AMD64 +# ifdef SPARC_WORKS _Prefetch_read(loc, interval); +# else + __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval)); +# endif #endif // AMD64 } // Use of this method should be gated by VM_Version::has_prefetchw. inline void Prefetch::write(void *loc, intx interval) { #ifdef AMD64 +# ifdef SPARC_WORKS _Prefetch_write(loc, interval); +# else + __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval)); +# endif #endif // AMD64 }
26
107
0.669231
gco
75257ec45114719315a6b0b30fe555553cb0b65e
1,492
cpp
C++
UtilityAdapter.cpp
RideReport/ActivityPredictionPipeline
6a018c0e1d6313628f15848abad3cf67d7bb89b3
[ "MIT" ]
1
2021-03-02T22:46:49.000Z
2021-03-02T22:46:49.000Z
UtilityAdapter.cpp
RideReport/ActivityPredictionPipeline
6a018c0e1d6313628f15848abad3cf67d7bb89b3
[ "MIT" ]
1
2021-03-25T23:31:37.000Z
2021-03-25T23:31:37.000Z
UtilityAdapter.cpp
RideReport/ActivityPredictionPipeline
6a018c0e1d6313628f15848abad3cf67d7bb89b3
[ "MIT" ]
null
null
null
#include "UtilityAdapter.hpp" #include "util.hpp" #include "ActivityPredictor/Utility.cpp" #include <vector> using namespace std; UtilityAdapter::UtilityAdapter() { } UtilityAdapter::~UtilityAdapter() { } py::object UtilityAdapter::interpolateSplineRegular( py::list& inputX, py::list& inputY, float newSpacing, int outputLength, float initialOffset) { if (py::len(inputX) != py::len(inputY)) { throw length_error("Cannot interpolate X and Y different lengths"); } auto inputXVec = vectorFromList<float>(inputX); auto inputYVec = vectorFromList<float>(inputY); auto outputVec = vector<float>(outputLength, 0.0); bool successful = ::interpolateSplineRegular( inputXVec.data(), inputYVec.data(), inputXVec.size(), outputVec.data(), outputLength, newSpacing, initialOffset); if (!successful) { throw range_error("Insufficient data to interpolate up to desired length"); } return listFromVector(outputVec); } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(UtilityAdapter_interpolateSplineRegular_overloads, UtilityAdapter::interpolateSplineRegular, 4, 5); BOOST_PYTHON_MODULE(utilityadapter) { py::class_<UtilityAdapter>("UtilityAdapter", py::init<>()) .def("interpolateSplineRegular", &UtilityAdapter::interpolateSplineRegular, UtilityAdapter_interpolateSplineRegular_overloads( py::args("initialOffset"), "" )) ; }
29.84
138
0.691689
RideReport
7525cd500fbb8b24fd11dcd145610a42237a65ea
602
cpp
C++
1518_num_water_bottles/num_water_bottles.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
1518_num_water_bottles/num_water_bottles.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
1518_num_water_bottles/num_water_bottles.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
/* * @Date: 2021-12-17 08:27:08 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-12-17 08:28:14 */ #include <cassert> class Solution { public: int numWaterBottles(int numBottles, int numExchange) { return numBottles >= numExchange ? (numBottles - numExchange) / (numExchange - 1) + 1 + numBottles : numBottles; } }; int main() { assert(Solution().numWaterBottles(9, 3) == 13); assert(Solution().numWaterBottles(15, 4) == 19); assert(Solution().numWaterBottles(5, 5) == 6); assert(Solution().numWaterBottles(2, 3) == 2); }
25.083333
80
0.631229
Mengsen-W
7525d8877b6baa99806313d5b32e5d590cddfc32
1,714
cpp
C++
PAT-Advanced/PAT1067-SortWithSwap(0,i).cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1067-SortWithSwap(0,i).cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1067-SortWithSwap(0,i).cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
// PAT1067-SortWithSwap(0,i).cpp // Ad // Init: 19Sep07 // Score: 19/25 // Time: 60' // Runtime: 3 ms #include <algorithm> #include <iostream> #include <vector> using namespace std; size_t sortBySwap0(vector<int> &numbers); bool isSorted(vector<int> &numbers, vector<int>::iterator &next); // Main ------------------------------------------------------------------ int main() { int numNumbers = 0; cin >> numNumbers; vector<int> numbers; for (int i = 0; i < numNumbers; ++i) { int n = 0; cin >> n; numbers.push_back(n); } cout << sortBySwap0(numbers) << endl; return 0; } // Function -------------------------------------------------------------- size_t sortBySwap0(vector<int> &numbers) { if (numbers.empty()) return 0; size_t cnt = 0; auto itr0 = find(numbers.begin(), numbers.end(), 0); size_t idx0 = itr0 - numbers.begin(); for (size_t i = 0; i < numbers.size() * 2; ++i) { vector<int>::iterator next = numbers.end(); if (isSorted(numbers, next)) break; if (idx0 != 0) { auto tmp = find(numbers.begin(), numbers.end(), idx0); iter_swap(itr0, tmp); itr0 = tmp; } else { iter_swap(itr0, next); itr0 = next; } idx0 = itr0 - numbers.begin(); ++cnt; } return cnt; } bool isSorted(vector<int> &numbers, vector<int>::iterator &next) { for (size_t i = 0; i < numbers.size(); ++i) if (numbers[i] != i) { next = numbers.begin() + i; return false; } next = numbers.end(); return true; }
19.930233
74
0.476663
Ad147
7525ee335dccc6d83d77e2e2b127f5e275e24764
1,140
hpp
C++
graphseg/include/graphseg/graph/segment_graph.hpp
Shikugawa/graphseg-cpp
9415b768b9e5d903e1a7eb37c81a777e4fe178b6
[ "MIT" ]
3
2019-09-22T02:53:25.000Z
2021-09-11T00:11:02.000Z
graphseg/include/graphseg/graph/segment_graph.hpp
Shikugawa/graphseg-cpp
9415b768b9e5d903e1a7eb37c81a777e4fe178b6
[ "MIT" ]
12
2019-06-18T15:24:13.000Z
2020-01-13T01:28:43.000Z
graphseg/include/graphseg/graph/segment_graph.hpp
Shikugawa/graphseg-cpp
9415b768b9e5d903e1a7eb37c81a777e4fe178b6
[ "MIT" ]
1
2019-09-21T12:33:40.000Z
2019-09-21T12:33:40.000Z
#ifndef GRAPHSEG_CPP_GRAPHSEG_GRAPH_SEGMENT_GRAPH_HPP #define GRAPHSEG_CPP_GRAPHSEG_GRAPH_SEGMENT_GRAPH_HPP #include "graphseg/language.hpp" #include "graphseg/sentence.hpp" #include <vector> namespace GraphSeg::graph { using namespace GraphSeg; /// <summary> /// This abstruct class must be inherited if graph handles sentence /// </summary> template <class T, Lang LangType = Lang::EN> class SegmentGraph { public: using SentenceType = Sentence<LangType>; private: GRAPHSEG_INLINE_CONST T &Derived() const & { return static_cast<const T &>(*this); } T &&Derived() && { return static_cast<T &&>(*this); } public: /// <summary> /// get specified sentence /// </summary> GRAPHSEG_INLINE_CONST SentenceType &GetSentence(size_t idx) const & { return sentences[idx]; } protected: SegmentGraph(const std::vector<SentenceType> &_sentences) : sentences(_sentences) {} SegmentGraph(std::vector<SentenceType> &&_sentences) : sentences(std::move(_sentences)) {} /// <summary> /// all of sentences /// </summary> std::vector<SentenceType> sentences; }; } // namespace GraphSeg::graph #endif
23.75
71
0.711404
Shikugawa
7525f6edd892f2295f908348079655f1af062b87
3,904
cpp
C++
unittests/test_description_t.cpp
lysevi/solidarity
c4febebce2247b5ab628bea226aa5e7e4805a1e5
[ "Apache-2.0" ]
1
2019-08-16T06:52:10.000Z
2019-08-16T06:52:10.000Z
unittests/test_description_t.cpp
lysevi/solidarity
c4febebce2247b5ab628bea226aa5e7e4805a1e5
[ "Apache-2.0" ]
10
2019-05-14T13:25:41.000Z
2019-08-19T07:05:07.000Z
unittests/test_description_t.cpp
lysevi/solidarity
c4febebce2247b5ab628bea226aa5e7e4805a1e5
[ "Apache-2.0" ]
null
null
null
#include "test_description_t.h" void test_description_t::init(size_t cluster_size, bool add_listener_handler) { std::vector<unsigned short> ports(cluster_size); std::iota(ports.begin(), ports.end(), (unsigned short)(8000)); std::cerr << "start nodes" << std::endl; unsigned short client_port = 10000; for (auto p : ports) { std::vector<unsigned short> out_ports; out_ports.reserve(ports.size() - 1); std::copy_if(ports.begin(), ports.end(), std::back_inserter(out_ports), [p](const auto v) { return v != p; }); EXPECT_EQ(out_ports.size(), ports.size() - 1); std::vector<std::string> out_addrs; out_addrs.reserve(out_ports.size()); std::transform(out_ports.begin(), out_ports.end(), std::back_inserter(out_addrs), [](const auto prt) { return solidarity::utils::strings::to_string("localhost:", prt); }); solidarity::node::params_t params; params.port = p; params.client_port = client_port++; params.thread_count = 1; params.cluster = out_addrs; params.name = solidarity::utils::strings::to_string("node_", p); std::cerr << params.name << " starting..." << std::endl; auto log_prefix = solidarity::utils::strings::to_string(params.name, "> "); auto node_logger = std::make_shared<solidarity::utils::logging::prefix_logger>( solidarity::utils::logging::logger_manager::instance()->get_shared_logger(), log_prefix); auto state_machines = get_state_machines(); std::unordered_map<uint32_t, solidarity::abstract_state_machine *> for_ctor( state_machines.size()); for (auto &sms_kv : state_machines) { for_ctor.insert({sms_kv.first, sms_kv.second.get()}); } auto n = std::make_shared<solidarity::node>(node_logger, params, for_ctor); n->start(); if (add_listener_handler) { n->add_event_handler([](const solidarity::client_event_t &ev) { if (ev.kind == solidarity::client_event_t::event_kind::COMMAND_STATUS) { std::stringstream ss; ss << "command " << solidarity::to_string(ev); std::cerr << ss.str() << std::endl; } }); } solidarity::client::params_t cpar( solidarity::utils::strings::to_string("client_", params.name)); cpar.threads_count = 1; cpar.host = "localhost"; cpar.port = params.client_port; auto c = std::make_shared<solidarity::client>(cpar); c->connect(); while (!c->is_connected()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } EXPECT_EQ(n->connections_count(), size_t(1)); consumers[params.name] = state_machines; nodes[params.name] = n; clients[params.name] = c; } } std::unordered_set<solidarity::node_name> test_description_t::wait_election() { std::cerr << "wait election" << std::endl; std::unordered_set<solidarity::node_name> leaders; while (true) { leaders.clear(); for (auto &kv : nodes) { if (kv.second->state().node_kind == solidarity::NODE_KIND::LEADER) { leaders.insert(kv.second->self_name()); } } if (leaders.size() == 1) { auto leader_name = *leaders.begin(); bool election_complete = true; for (auto &kv : nodes) { auto state = kv.second->state(); auto nkind = state.node_kind; if (nkind != solidarity::NODE_KIND::LEADER && nkind != solidarity::NODE_KIND::FOLLOWER) { election_complete = false; break; } if ((nkind == solidarity::NODE_KIND::LEADER || nkind == solidarity::NODE_KIND::FOLLOWER) && state.leader != leader_name) { election_complete = false; break; } } if (election_complete) { break; } } } return leaders; }
34.245614
85
0.605533
lysevi
75281987192fa1e36b360f492c8b9003ad1f48e8
1,657
cpp
C++
src/glstates.cpp
praxik/mapgen
1073b48973811b167fd1e765f0c2a4704312ed0e
[ "Apache-2.0" ]
null
null
null
src/glstates.cpp
praxik/mapgen
1073b48973811b167fd1e765f0c2a4704312ed0e
[ "Apache-2.0" ]
null
null
null
src/glstates.cpp
praxik/mapgen
1073b48973811b167fd1e765f0c2a4704312ed0e
[ "Apache-2.0" ]
null
null
null
#include "glstates.h" //============================================================================ //============================================================================ GlStates::GlStates() { } //============================================================================ //============================================================================ GlStates::~GlStates() { popAll(); } //============================================================================ //============================================================================ void GlStates::push(GLenum state, GLboolean enable) { GLboolean stateCur = glIsEnabled(state); State s(state, stateCur, stateCur != enable); _states.push_front(s); if (!s.set) return; set(s.type, enable); } //============================================================================ //============================================================================ void GlStates::pop() { State s = _states.front(); _states.pop_front(); if (!s.set) return; set(s.type, s.enabledPrev); } //============================================================================ //============================================================================ void GlStates::popAll() { while (_states.size() > 0) { pop(); } } //============================================================================ //============================================================================ void GlStates::set(GLenum state, GLboolean enable) { if (enable) { glEnable(state); } else { glDisable(state); } }
26.301587
78
0.244418
praxik
752bef9c0139ec3a06c1ccbe5a86cc96d62f4f75
1,468
cpp
C++
generator_kf/kanonizator_gen.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
null
null
null
generator_kf/kanonizator_gen.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
4
2020-09-07T15:54:45.000Z
2020-09-27T16:47:16.000Z
generator_kf/kanonizator_gen.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
null
null
null
#include "kanonizator_gen.h" #include "massivy_gen.h" int kanonizator::chform; kvadrat kanonizator::formy[]; bool kanonizator::operator()(const int X[]){ for(int i = 0; i < por; i++){ formy[0][i * (por + 1)] = i; formy[0][ (i + 1) * (por - 1)] = diag[lin][i]; } for(int i = 0, t; i < n; i++){ t = 0; if(X[i] & 0x300) t += 8; if(X[i] & 0xf0) t += 4; if(X[i] & 0xcc) t += 2; if(X[i] & 0x2aa) t += 1; formy[0][(rc[i] >> 4) * por + (rc[i] & 0xf)] = t; } if(lin < ch_klass2){ chform = 2; simmetr(); if(formy[1] < formy[0]) return false; } else chform = 1; int kol = ukaz[lin] & 0x1f, ind = ukaz[lin] >> 5; for(int i = 0; i < kol; i++) if(!obrabotka(&trans_tabl[ind + i][0], &trans_tabl[ind + i][por])) return false; return true; } bool kanonizator::obrabotka(const int* perest, const int* ob_perest){ int x, minz, index = 0, count[2], spisok[2][max_chform]; for(int i = 0; i < chform; i++) spisok[0][i] = i; count[0] = chform; for(int i = 0; i < por - 1; i++) for(int j = 0; j < por - 1; j++){ if(j == i || j == por - 1 - i) continue; minz = formy[0][i * por + j]; count[index ^ 1] = 0; for(int k = 0; k < count[index]; k++){ if(minz > (x = ob_perest[formy[spisok[index][k]][perest[i] * por + perest[j]]])){ return false; } else if(minz == x) spisok[index ^ 1][count[index ^ 1]++] = spisok[index][k]; } if(!count[index ^= 1]) return true; } return true; }
29.959184
85
0.523842
tomasbrod
752c533e5117d7424a117759df77b30c9b5487e8
14,123
hpp
C++
Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp
BrewJS/HAC.js
998f82cbfe5ed245825b0ad8252f09691788dc6c
[ "MIT" ]
103
2018-07-10T10:51:36.000Z
2022-03-24T15:55:35.000Z
Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp
BrewJS/HAC.js
998f82cbfe5ed245825b0ad8252f09691788dc6c
[ "MIT" ]
5
2018-07-10T10:55:24.000Z
2019-04-12T13:04:46.000Z
Tools/bjs.u/External/include/stratosphere/ipc/ipc_service_session.hpp
BrewJS/HAC.js
998f82cbfe5ed245825b0ad8252f09691788dc6c
[ "MIT" ]
15
2018-07-10T10:16:25.000Z
2022-03-31T12:50:12.000Z
/* * Copyright (c) 2018 Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <switch.h> #include "../iwaitable.hpp" #include "ipc_service_object.hpp" #include "ipc_serialization.hpp" enum HipcControlCommand : u32 { HipcControlCommand_ConvertCurrentObjectToDomain = 0, HipcControlCommand_CopyFromCurrentDomain = 1, HipcControlCommand_CloneCurrentObject = 2, HipcControlCommand_QueryPointerBufferSize = 3, HipcControlCommand_CloneCurrentObjectEx = 4 }; #define RESULT_DEFER_SESSION (0x6580A) class ServiceSession : public IWaitable { protected: Handle session_handle; std::vector<unsigned char> pointer_buffer; ServiceObjectHolder obj_holder; ServiceObjectHolder control_holder = ServiceObjectHolder(std::make_shared<IHipcControlService>(this)); u8 backup_tls[0x100]; ServiceSession(Handle s_h) : session_handle(s_h) { } public: template<typename T> ServiceSession(Handle s_h, size_t pbs) : session_handle(s_h), pointer_buffer(pbs), obj_holder(std::make_shared<T>()) { } ServiceSession(Handle s_h, size_t pbs, ServiceObjectHolder &&h) : session_handle(s_h), pointer_buffer(pbs), obj_holder(std::move(h)) { } virtual ~ServiceSession() override { svcCloseHandle(this->session_handle); } SessionManagerBase *GetSessionManager() { return static_cast<SessionManagerBase *>(this->GetManager()); } DomainManager *GetDomainManager() { return static_cast<DomainManager *>(this->GetSessionManager()); } Result Receive() { int handle_index; /* Prepare pointer buffer... */ IpcCommand c; ipcInitialize(&c); if (this->pointer_buffer.size() > 0) { ipcAddRecvStatic(&c, this->pointer_buffer.data(), this->pointer_buffer.size(), 0); ipcPrepareHeader(&c, 0); /* Fix libnx bug in serverside C descriptor handling. */ ((u32 *)armGetTls())[1] &= 0xFFFFC3FF; ((u32 *)armGetTls())[1] |= (2) << 10; } else { ipcPrepareHeader(&c, 0); } /* Receive. */ Result rc = svcReplyAndReceive(&handle_index, &this->session_handle, 1, 0, U64_MAX); if (R_SUCCEEDED(rc)) { std::memcpy(this->backup_tls, armGetTls(), sizeof(this->backup_tls)); } return rc; } Result Reply() { int handle_index; return svcReplyAndReceive(&handle_index, &this->session_handle, 0, this->session_handle, 0); } /* For preparing basic replies. */ Result PrepareBasicResponse(IpcResponseContext *ctx, Result rc) { ipcInitialize(&ctx->reply); struct { u64 magic; u64 result; } *raw = (decltype(raw))ipcPrepareHeader(&ctx->reply, sizeof(*raw)); raw->magic = SFCO_MAGIC; raw->result = rc; return raw->result; } Result PrepareBasicDomainResponse(IpcResponseContext *ctx, Result rc) { ipcInitialize(&ctx->reply); struct { DomainResponseHeader hdr; u64 magic; u64 result; } *raw = (decltype(raw))ipcPrepareHeader(&ctx->reply, sizeof(*raw)); raw->hdr = (DomainResponseHeader){0}; raw->magic = SFCO_MAGIC; raw->result = rc; return raw->result; } /* For making a new response context. */ void InitializeResponseContext(IpcResponseContext *ctx) { std::memset(ctx, 0, sizeof(*ctx)); ctx->manager = this->GetSessionManager(); ctx->obj_holder = &this->obj_holder; ctx->pb = this->pointer_buffer.data(); ctx->pb_size = this->pointer_buffer.size(); } /* IWaitable */ virtual Handle GetHandle() { return this->session_handle; } virtual Result GetResponse(IpcResponseContext *ctx) { Result rc = 0xF601; FirmwareVersion fw = GetRuntimeFirmwareVersion(); const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable(); size_t entry_count = ctx->obj_holder->GetDispatchTableEntryCount(); if (IsDomainObject(ctx->obj_holder)) { switch (ctx->request.InMessageType) { case DomainMessageType_Invalid: return 0xF601; case DomainMessageType_Close: return PrepareBasicDomainResponse(ctx, ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId)); case DomainMessageType_SendMessage: { auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId); if (sub_obj == nullptr) { return PrepareBasicDomainResponse(ctx, 0x3D80B); } dispatch_table = sub_obj->GetDispatchTable(); entry_count = sub_obj->GetDispatchTableEntryCount(); } } } for (size_t i = 0; i < entry_count; i++) { if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) { rc = dispatch_table[i].handler(ctx); break; } } return rc; } virtual Result HandleReceived() { IpcResponseContext ctx; this->InitializeResponseContext(&ctx); ctx.cmd_type = (IpcCommandType)(*(u16 *)(armGetTls())); ctx.rc = 0; /* Parse based on command type. */ switch (ctx.cmd_type) { case IpcCommandType_Invalid: case IpcCommandType_LegacyRequest: case IpcCommandType_LegacyControl: return 0xF601; case IpcCommandType_Close: { /* Clean up gracefully. */ PrepareBasicResponse(&ctx, 0); this->Reply(); } return 0xF601; case IpcCommandType_Control: case IpcCommandType_ControlWithContext: ctx.rc = ipcParse(&ctx.request); ctx.obj_holder = &this->control_holder; break; case IpcCommandType_Request: case IpcCommandType_RequestWithContext: if (IsDomainObject(&this->obj_holder)) { ctx.rc = ipcParseDomainRequest(&ctx.request); } else { ctx.rc = ipcParse(&ctx.request); } break; default: return 0xF601; } if (R_SUCCEEDED(ctx.rc)) { ctx.cmd_id = ((u32 *)ctx.request.Raw)[2]; this->PreProcessRequest(&ctx); ctx.rc = this->GetResponse(&ctx); } if (ctx.rc == RESULT_DEFER_SESSION) { /* Session defer. */ this->SetDeferred(true); } else if (ctx.rc == 0xF601) { /* Session close, nothing to do. */ } else { if (R_SUCCEEDED(ctx.rc)) { this->PostProcessResponse(&ctx); } ctx.rc = this->Reply(); if (ctx.rc == 0xEA01) { ctx.rc = 0x0; } this->CleanupResponse(&ctx); } return ctx.rc; } virtual Result HandleDeferred() override { memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls)); Result rc = this->HandleReceived(); if (rc != RESULT_DEFER_SESSION) { this->SetDeferred(false); } return rc; } virtual Result HandleSignaled(u64 timeout) { Result rc; if (R_SUCCEEDED(rc = this->Receive())) { rc = this->HandleReceived(); } return rc; } virtual void PreProcessRequest(IpcResponseContext *ctx) { /* ... */ (void)(ctx); } virtual void PostProcessResponse(IpcResponseContext *ctx) { /* ... */ (void)(ctx); } virtual void CleanupResponse(IpcResponseContext *ctx) { std::memset(this->backup_tls, 0, sizeof(this->backup_tls)); } public: class IHipcControlService : public IServiceObject { private: ServiceSession *session; public: explicit IHipcControlService(ServiceSession *s) : session(s) { } virtual ~IHipcControlService() override { } Result ConvertCurrentObjectToDomain(Out<u32> object_id) { /* Allocate new domain. */ auto new_domain = this->session->GetDomainManager()->AllocateDomain(); if (new_domain == nullptr) { return 0x1900B; } /* Reserve an object in the domain for our session. */ u32 reserved_id; Result rc = new_domain->ReserveObject(&reserved_id); if (R_FAILED(rc)) { return rc; } new_domain->SetObject(reserved_id, std::move(this->session->obj_holder)); this->session->obj_holder = std::move(ServiceObjectHolder(std::move(new_domain))); /* Return the object id. */ object_id.SetValue(reserved_id); return 0; } Result CopyFromCurrentDomain(Out<MovedHandle> out_h, u32 id) { auto domain = this->session->obj_holder.GetServiceObject<IDomainObject>(); if (domain == nullptr) { return 0x3D60B; } auto object = domain->GetObject(id); if (object == nullptr) { return 0x3D80B; } Handle server_h, client_h; if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { /* N aborts here. Should we error code? */ std::abort(); } this->session->GetSessionManager()->AddSession(server_h, std::move(object->Clone())); out_h.SetValue(client_h); return 0; } void CloneCurrentObject(Out<MovedHandle> out_h) { Handle server_h, client_h; if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { /* N aborts here. Should we error code? */ std::abort(); } this->session->GetSessionManager()->AddSession(server_h, std::move(this->session->obj_holder.Clone())); out_h.SetValue(client_h); } void QueryPointerBufferSize(Out<u16> size) { size.SetValue(this->session->pointer_buffer.size()); } void CloneCurrentObjectEx(Out<MovedHandle> out_h, u32 which) { /* TODO: Figure out what this u32 controls. */ return CloneCurrentObject(out_h); } public: DEFINE_SERVICE_DISPATCH_TABLE { MakeServiceCommandMeta<HipcControlCommand_ConvertCurrentObjectToDomain, &ServiceSession::IHipcControlService::ConvertCurrentObjectToDomain>(), MakeServiceCommandMeta<HipcControlCommand_CopyFromCurrentDomain, &ServiceSession::IHipcControlService::CopyFromCurrentDomain>(), MakeServiceCommandMeta<HipcControlCommand_CloneCurrentObject, &ServiceSession::IHipcControlService::CloneCurrentObject>(), MakeServiceCommandMeta<HipcControlCommand_QueryPointerBufferSize, &ServiceSession::IHipcControlService::QueryPointerBufferSize>(), MakeServiceCommandMeta<HipcControlCommand_CloneCurrentObjectEx, &ServiceSession::IHipcControlService::CloneCurrentObjectEx>(), }; }; };
39.560224
162
0.509311
BrewJS
752eaa39f006be3d52a790b98bde796b2ff5940c
1,074
cpp
C++
src/output_files.cpp
KevinBoxuGao/temperatureTimeAdjustor
2e8941bf7217d21afdc21c9ce217cd30d6b85238
[ "MIT" ]
null
null
null
src/output_files.cpp
KevinBoxuGao/temperatureTimeAdjustor
2e8941bf7217d21afdc21c9ce217cd30d6b85238
[ "MIT" ]
null
null
null
src/output_files.cpp
KevinBoxuGao/temperatureTimeAdjustor
2e8941bf7217d21afdc21c9ce217cd30d6b85238
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include "output_files.h" OutputFiles::OutputFiles(std::vector<std::string> base_data) { base_data_template = base_data; } void OutputFiles::Adjust(const std::string file_name) { std::ofstream output("output/"+file_name+".txt"); std::ifstream temperature_file; std::string file_line; temperature_file.open("input/TemperatureChanges/" + file_name + ".csv"); if(temperature_file.is_open()) { for(int i = 0; i < 9; i++) { getline(temperature_file, file_line); } for(unsigned int x = 0; x < base_data_template.size(); x++) { std::string substr; getline(temperature_file, file_line); std::istringstream iss(file_line); for(int x = 0; x < 4; x++) { getline(iss, substr, ','); } output << base_data_template[x] << substr << std::endl; } } else{ std::cout << "missing temperature file" << std::endl; } }
29.027027
76
0.588454
KevinBoxuGao
752ef4801fa2b7e66302ee2220b535a4e80006c4
18,894
cpp
C++
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_stats.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_stats.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_stats.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/* Foundation for the statistics modules. * * Contents: * 1. The stats API. * 5. License and copyright information. * * SRE, Tue Jul 19 10:57:44 2005 * SVN $Id: esl_stats.c 341 2009-06-01 12:21:15Z eddys $ */ #include <hmmer3/easel/esl_config.h> #include <math.h> #include <hmmer3/easel/easel.h> #include "esl_stats.h" /* Function: esl_stats_DMean() * Synopsis: Calculates mean and $\sigma^2$ for samples $x_i$. * Incept: SRE, Tue Jul 19 11:04:00 2005 [St. Louis] * * Purpose: Calculates the sample mean and $s^2$, the unbiased * estimator of the population variance, for a * sample of <n> numbers <x[0]..x[n-1]>, and optionally * returns either or both through <ret_mean> and * <ret_var>. * * <esl_stats_FMean()> and <esl_stats_IMean()> do the same, * for float and integer vectors. * * Args: x - samples x[0]..x[n-1] * n - number of samples * opt_mean - optRETURN: mean * opt_var - optRETURN: estimate of population variance * * Returns: <eslOK> on success. */ int esl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var) { double sum = 0.; double sqsum = 0.; int i; for (i = 0; i < n; i++) { sum += x[i]; sqsum += x[i]*x[i]; } if (opt_mean != NULL) *opt_mean = sum / (double) n; if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1); return eslOK; } int esl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var) { double sum = 0.; double sqsum = 0.; int i; for (i = 0; i < n; i++) { sum += x[i]; sqsum += x[i]*x[i]; } if (opt_mean != NULL) *opt_mean = sum / (double) n; if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1); return eslOK; } int esl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var) { double sum = 0.; double sqsum = 0.; int i; for (i = 0; i < n; i++) { sum += x[i]; sqsum += x[i]*x[i]; } if (opt_mean != NULL) *opt_mean = sum / (double) n; if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1); return eslOK; } /* Function: esl_stats_LogGamma() * Synopsis: Calculates $\log \Gamma(x)$. * Incept: SRE, Tue Nov 2 13:47:01 2004 [St. Louis] * * Purpose: Returns natural log of $\Gamma(x)$, for $x > 0$. * * Credit: Adapted from a public domain implementation in the * NCBI core math library. Thanks to John Spouge and * the NCBI. (According to NCBI, that's Dr. John * "Gammas Galore" Spouge to you, pal.) * * Args: x : argument, x > 0.0 * ret_answer : RETURN: the answer * * Returns: Put the answer in <ret_answer>; returns <eslOK>. * * Throws: <eslERANGE> if $x <= 0$. */ int esl_stats_LogGamma(double x, double *ret_answer) { int i; double xx, tx; double tmp, value; static const double cof[11] = { 4.694580336184385e+04, -1.560605207784446e+05, 2.065049568014106e+05, -1.388934775095388e+05, 5.031796415085709e+04, -9.601592329182778e+03, 8.785855930895250e+02, -3.155153906098611e+01, 2.908143421162229e-01, -2.319827630494973e-04, 1.251639670050933e-10 }; /* Protect against invalid x<=0 */ if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_LogGamma()"); xx = x - 1.0; tx = tmp = xx + 11.0; value = 1.0; for (i = 10; i >= 0; i--) /* sum least significant terms first */ { value += cof[i] / tmp; tmp -= 1.0; } value = log(value); tx += 0.5; value += 0.918938533 + (xx+0.5)*log(tx) - tx; *ret_answer = value; return eslOK; } /* Function: esl_stats_Psi() * Synopsis: Calculates $\Psi(x)$ (the digamma function). * Incept: SRE, Tue Nov 15 13:57:59 2005 [St. Louis] * * Purpose: Computes $\Psi(x)$ (the "digamma" function), which is * the derivative of log of the Gamma function: * $d/dx \log \Gamma(x) = \frac{\Gamma'(x)}{\Gamma(x)} = \Psi(x)$. * Argument $x$ is $> 0$. * * This is J.M. Bernardo's "Algorithm AS103", * Appl. Stat. 25:315-317 (1976). */ int esl_stats_Psi(double x, double *ret_answer) { double answer = 0.; double x2; if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_Psi()"); /* For small x, Psi(x) ~= -0.5772 - 1/x + O(x), we're done. */ if (x <= 1e-5) { *ret_answer = -eslCONST_EULER - 1./x; return eslOK; } /* For medium x, use Psi(1+x) = \Psi(x) + 1/x to c.o.v. x, * big enough for Stirling approximation to work... */ while (x < 8.5) { answer = answer - 1./x; x += 1.; } /* For large X, use Stirling approximation */ x2 = 1./x; answer += log(x) - 0.5 * x2; x2 = x2*x2; answer -= (1./12.)*x2; answer += (1./120.)*x2*x2; answer -= (1./252.)*x2*x2*x2; *ret_answer = answer; return eslOK; } /* Function: esl_stats_IncompleteGamma() * Synopsis: Calculates the incomplete Gamma function. * * Purpose: Returns $P(a,x)$ and $Q(a,x)$ where: * * \begin{eqnarray*} * P(a,x) & = & \frac{1}{\Gamma(a)} \int_{0}^{x} t^{a-1} e^{-t} dt \\ * & = & \frac{\gamma(a,x)}{\Gamma(a)} \\ * Q(a,x) & = & \frac{1}{\Gamma(a)} \int_{x}^{\infty} t^{a-1} e^{-t} dt\\ * & = & 1 - P(a,x) \\ * \end{eqnarray*} * * $P(a,x)$ is the CDF of a gamma density with $\lambda = 1$, * and $Q(a,x)$ is the survival function. * * For $x \simeq 0$, $P(a,x) \simeq 0$ and $Q(a,x) \simeq 1$; and * $P(a,x)$ is less prone to roundoff error. * * The opposite is the case for large $x >> a$, where * $P(a,x) \simeq 1$ and $Q(a,x) \simeq 0$; there, $Q(a,x)$ is * less prone to roundoff error. * * Method: Based on ideas from Numerical Recipes in C, Press et al., * Cambridge University Press, 1988. * * Args: a - for instance, degrees of freedom / 2 [a > 0] * x - for instance, chi-squared statistic / 2 [x >= 0] * ret_pax - RETURN: P(a,x) * ret_qax - RETURN: Q(a,x) * * Return: <eslOK> on success. * * Throws: <eslERANGE> if <a> or <x> is out of accepted range. * <eslENOHALT> if approximation fails to converge. */ int esl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax) { int iter; /* iteration counter */ double pax; /* P(a,x) */ double qax; /* Q(a,x) */ if (a <= 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): a must be > 0"); if (x < 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): x must be >= 0"); /* For x > a + 1 the following gives rapid convergence; * calculate Q(a,x) = \frac{\Gamma(a,x)}{\Gamma(a)}, * using a continued fraction development for \Gamma(a,x). */ if (x > a+1) { double oldp; /* previous value of p */ double nu0, nu1; /* numerators for continued fraction calc */ double de0, de1; /* denominators for continued fraction calc */ nu0 = 0.; /* A_0 = 0 */ de0 = 1.; /* B_0 = 1 */ nu1 = 1.; /* A_1 = 1 */ de1 = x; /* B_1 = x */ oldp = nu1; for (iter = 1; iter < 100; iter++) { /* Continued fraction development: * set A_j = b_j A_j-1 + a_j A_j-2 * B_j = b_j B_j-1 + a_j B_j-2 * We start with A_2, B_2. */ /* j = even: a_j = iter-a, b_j = 1 */ /* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */ nu0 = nu1 + ((double)iter - a) * nu0; de0 = de1 + ((double)iter - a) * de0; /* j = odd: a_j = iter, b_j = x */ /* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */ nu1 = x * nu0 + (double) iter * nu1; de1 = x * de0 + (double) iter * de1; /* rescale */ if (de1 != 0.) { nu0 /= de1; de0 /= de1; nu1 /= de1; de1 = 1.; } /* check for convergence */ if (fabs((nu1-oldp)/nu1) < 1.e-7) { esl_stats_LogGamma(a, &qax); qax = nu1 * exp(a * log(x) - x - qax); if (ret_pax != NULL) *ret_pax = 1 - qax; if (ret_qax != NULL) *ret_qax = qax; return eslOK; } oldp = nu1; } ESL_EXCEPTION(eslENOHALT, "esl_stats_IncompleteGamma(): fraction failed to converge"); } else /* x <= a+1 */ { double p; /* current sum */ double val; /* current value used in sum */ /* For x <= a+1 we use a convergent series instead: * P(a,x) = \frac{\gamma(a,x)}{\Gamma(a)}, * where * \gamma(a,x) = e^{-x}x^a \sum_{n=0}{\infty} \frac{\Gamma{a}}{\Gamma{a+1+n}} x^n * which looks appalling but the sum is in fact rearrangeable to * a simple series without the \Gamma functions: * = \frac{1}{a} + \frac{x}{a(a+1)} + \frac{x^2}{a(a+1)(a+2)} ... * and it's obvious that this should converge nicely for x <= a+1. */ p = val = 1. / a; for (iter = 1; iter < 10000; iter++) { val *= x / (a+(double)iter); p += val; if (fabs(val/p) < 1.e-7) { esl_stats_LogGamma(a, &pax); pax = p * exp(a * log(x) - x - pax); if (ret_pax != NULL) *ret_pax = pax; if (ret_qax != NULL) *ret_qax = 1. - pax; return eslOK; } } ESL_EXCEPTION(eslENOHALT, "esl_stats_IncompleteGamma(): series failed to converge"); } /*NOTREACHED*/ return eslOK; } /* Function: esl_stats_ChiSquaredTest() * Synopsis: Calculates a $\chi^2$ P-value. * Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis] * * Purpose: Calculate the probability that a chi-squared statistic * with <v> degrees of freedom would exceed the observed * chi-squared value <x>; return it in <ret_answer>. If * this probability is less than some small threshold (say, * 0.05 or 0.01), then we may reject the hypothesis we're * testing. * * Args: v - degrees of freedom * x - observed chi-squared value * ret_answer - RETURN: P(\chi^2 > x) * * Returns: <eslOK> on success. * * Throws: <eslERANGE> if <v> or <x> are out of valid range. * <eslENOHALT> if iterative calculation fails. */ int esl_stats_ChiSquaredTest(int v, double x, double *ret_answer) { return esl_stats_IncompleteGamma((double)v/2, x/2, NULL, ret_answer); } /* Function: esl_stats_LinearRegression() * Synopsis: Fit data to a straight line. * Incept: SRE, Sat May 26 11:33:46 2007 [Janelia] * * Purpose: Fit <n> points <x[i]>, <y[i]> to a straight line * $y = a + bx$ by linear regression. * * The $x_i$ are taken to be known, and the $y_i$ are taken * to be observed quantities associated with a sampling * error $\sigma_i$. If known, the standard deviations * $\sigma_i$ for $y_i$ are provided in the <sigma> array. * If they are unknown, pass <sigma = NULL>, and the * routine will proceed with the assumption that $\sigma_i * = 1$ for all $i$. * * The maximum likelihood estimates for $a$ and $b$ are * optionally returned in <opt_a> and <opt_b>. * * The estimated standard deviations of $a$ and $b$ and * their estimated covariance are optionally returned in * <opt_sigma_a>, <opt_sigma_b>, and <opt_cov_ab>. * * The Pearson correlation coefficient is optionally * returned in <opt_cc>. * * The $\chi^2$ P-value for the regression fit is * optionally returned in <opt_Q>. This P-value may only be * obtained when the $\sigma_i$ are known. If <sigma> is * passed as <NULL> and <opt_Q> is requested, <*opt_Q> is * set to 1.0. * * This routine follows the description and algorithm in * \citep[pp.661-666]{Press93}. * * <n> must be greater than 2; at least two x[i] must * differ; and if <sigma> is provided, all <sigma[i]> must * be $>0$. If any of these conditions isn't met, the * routine throws <eslEINVAL>. * * Args: x - x[0..n-1] * y - y[0..n-1] * sigma - sample error in observed y_i * n - number of data points * opt_a - optRETURN: intercept estimate * opt_b - optRETURN: slope estimate * opt_sigma_a - optRETURN: error in estimate of a * opt_sigma_b - optRETURN: error in estimate of b * opt_cov_ab - optRETURN: covariance of a,b estimates * opt_cc - optRETURN: Pearson correlation coefficient for x,y * opt_Q - optRETURN: X^2 P-value for linear fit * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation error; * <eslEINVAL> if a contract condition isn't met; * <eslENORESULT> if the chi-squared test fails. * In these cases, all optional return values are set to 0. */ int esl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n, double *opt_a, double *opt_b, double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab, double *opt_cc, double *opt_Q) { int status; double *t = NULL; double S, Sx, Sy, Stt; double Sxy, Sxx, Syy; double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q; double xdev, ydev; double tmp; int i; /* Contract checks. */ if (n <= 2) ESL_XEXCEPTION(eslEINVAL, "n must be > 2 for linear regression fitting"); if (sigma != NULL) for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, "sigma[%d] <= 0", i); status = eslEINVAL; for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; } if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, "all x[i] are 0."); /* Allocations */ ESL_ALLOC_WITH_TYPE(t, double*, sizeof(double) * n); /* S = \sum_{i=1}{n} \frac{1}{\sigma_i^2}. (S > 0.) */ if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); } else S = (double) n; /* S_x = \sum_{i=1}{n} \frac{x[i]}{ \sigma_i^2} (Sx real.) */ for (Sx = 0., i = 0; i < n; i++) { if (sigma == NULL) Sx += x[i]; else Sx += x[i] / (sigma[i] * sigma[i]); } /* S_y = \sum_{i=1}{n} \frac{y[i]}{\sigma_i^2} (Sy real.) */ for (Sy = 0., i = 0; i < n; i++) { if (sigma == NULL) Sy += y[i]; else Sy += y[i] / (sigma[i] * sigma[i]); } /* t_i = \frac{1}{\sigma_i} \left( x_i - \frac{S_x}{S} \right) (t_i real) */ for (i = 0; i < n; i++) { t[i] = x[i] - Sx/S; if (sigma != NULL) t[i] /= sigma[i]; } /* S_{tt} = \sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */ for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; } /* b = \frac{1}{S_{tt}} \sum_{i=1}^{N} \frac{t_i y_i}{\sigma_i} */ for (b = 0., i = 0; i < n; i++) { if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; } else { b += t[i]*y[i]; } } b /= Stt; /* a = \frac{ S_y - S_x b } {S} */ a = (Sy - Sx * b) / S; /* \sigma_a^2 = \frac{1}{S} \left( 1 + \frac{ S_x^2 }{S S_{tt}} \right) */ sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S); /* \sigma_b = \frac{1}{S_{tt}} */ sigma_b = sqrt (1. / Stt); /* Cov(a,b) = - \frac{S_x}{S S_{tt}} */ cov_ab = -Sx / (S * Stt); /* Pearson correlation coefficient */ Sxy = Sxx = Syy = 0.; for (i = 0; i < n; i++) { if (sigma != NULL) { xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n); ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n); } else { xdev = x[i] - (Sx / n); ydev = y[i] - (Sy / n); } Sxy += xdev * ydev; Sxx += xdev * xdev; Syy += ydev * ydev; } cc = Sxy / (sqrt(Sxx) * sqrt(Syy)); /* \chi^2 */ for (X2 = 0., i = 0; i < n; i++) { tmp = y[i] - a - b*x[i]; if (sigma != NULL) tmp /= sigma[i]; X2 += tmp*tmp; } /* We can calculate a goodness of fit if we know the \sigma_i */ if (sigma != NULL) { if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; } } else Q = 1.0; /* If we didn't use \sigma_i, adjust the sigmas for a,b */ if (sigma == NULL) { tmp = sqrt(X2 / (double)(n-2)); sigma_a *= tmp; sigma_b *= tmp; } /* Done. Set up for normal return. */ free(t); if (opt_a != NULL) *opt_a = a; if (opt_b != NULL) *opt_b = b; if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a; if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b; if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab; if (opt_cc != NULL) *opt_cc = cc; if (opt_Q != NULL) *opt_Q = Q; return eslOK; ERROR: if (t != NULL) free(t); if (opt_a != NULL) *opt_a = 0.; if (opt_b != NULL) *opt_b = 0.; if (opt_sigma_a != NULL) *opt_sigma_a = 0.; if (opt_sigma_b != NULL) *opt_sigma_b = 0.; if (opt_cov_ab != NULL) *opt_cov_ab = 0.; if (opt_cc != NULL) *opt_cc = 0.; if (opt_Q != NULL) *opt_Q = 0.; return status; } /*---------------- end of API implementation --------------------*/ /***************************************************************** * Easel - a library of C functions for biological sequence analysis * Version h3.0; March 2010 * Copyright (C) 2010 Howard Hughes Medical Institute. * Other copyrights also apply. See the COPYRIGHT file for a full list. * * Easel is distributed under the Janelia Farm Software License, a BSD * license. See the LICENSE file for more details. *****************************************************************/
33.921005
99
0.502011
iganna
7530917c3844fce27baf17f6adea6b26be9d4b49
711
hh
C++
pes.timed/utilities.hh
petercfontana/TimeSolver
fb3bc660af90f58255e2526bee9a36fc9357deb0
[ "MIT" ]
4
2018-12-19T14:30:27.000Z
2022-03-20T20:19:20.000Z
pes.timed/utilities.hh
petercfontana/TimeSolver
fb3bc660af90f58255e2526bee9a36fc9357deb0
[ "MIT" ]
null
null
null
pes.timed/utilities.hh
petercfontana/TimeSolver
fb3bc660af90f58255e2526bee9a36fc9357deb0
[ "MIT" ]
2
2019-04-24T03:18:20.000Z
2019-09-13T07:49:00.000Z
/** * Utility functions. * * @author Jeroen Keiren * @copyright MIT Licence, see the accompanying LICENCE.txt. */ #ifndef UTILITIES_HH #define UTILITIES_HH #include <algorithm> #include <vector> inline bool is_power_of_two(std::size_t n) { if (n == 0) { return false; } else { return (n & (n - 1)) == 0; } } template<typename T> void delete_vector_elements(std::vector<T*>& vec) { std::for_each(vec.begin(), vec.end(), [](T* t) { delete t; }); } template<typename T> void deep_copy(std::vector<T*>& out, const std::vector<T*>& in) { out.reserve(out.size()+in.size()); std::for_each(in.begin(), in.end(), [&](T* t) { out.emplace_back(new T(*t)); }); } #endif // UTILITIES_HH
19.216216
82
0.625879
petercfontana
75322367403aaca015a42f6e39d6753e1577dc63
523
cpp
C++
cf/1076-A.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
cf/1076-A.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
cf/1076-A.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define inf 0x3f3f3f #define mem(a,b) memset( a,b,sizeof a) int main() { std::ios::sync_with_stdio(false); int n; cin>>n; { string s; int flag=0; cin>>s; for(int i=1;i<n;i++) { if(s[i]<s[i-1]) { s.erase(i-1,1); flag=1; break; } } if(!flag) s.erase(n-1,1); cout<<s<<endl; } return 0; }
16.870968
39
0.422562
PIPIKAI
753684b0b912c8ed8363f4832c72102bf0f02363
286
cpp
C++
04_coding_tasks/test/test_015_3Sum.cpp
JWidder/CodingCPP
00dbf5b0b201299597dfca5c4566d160f780db4f
[ "MIT" ]
null
null
null
04_coding_tasks/test/test_015_3Sum.cpp
JWidder/CodingCPP
00dbf5b0b201299597dfca5c4566d160f780db4f
[ "MIT" ]
2
2021-09-27T04:15:22.000Z
2021-10-09T04:53:33.000Z
04_coding_tasks/test/test_015_3Sum.cpp
JWidder/CodingCPP
00dbf5b0b201299597dfca5c4566d160f780db4f
[ "MIT" ]
1
2021-09-08T14:18:28.000Z
2021-09-08T14:18:28.000Z
#include <vector> #include "pch.h" #include "LibSolution.h" using namespace std; using namespace leetcode; TEST(Test_015_3Sum,test_input) { auto test_value = std::vector<vector<int>>(); std::vector<vector<int>> result = threeSum(vector<int>()); EXPECT_EQ(result, test_value); }
17.875
59
0.723776
JWidder
7537688857c28cfdf4f8e8a83ed13a9e75d4d8f7
2,646
cpp
C++
underworld/libUnderworld/Underworld/Function/src/FEMCoordinate.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
underworld/libUnderworld/Underworld/Function/src/FEMCoordinate.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
underworld/libUnderworld/Underworld/Function/src/FEMCoordinate.cpp
rbeucher/underworld2
76991c475ac565e092e99a364370fbae15bb40ac
[ "CC-BY-4.0" ]
null
null
null
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <stdexcept> #include <mpi.h> #include <petsc.h> extern "C" { #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> } #include "FEMCoordinate.hpp" FEMCoordinate::FEMCoordinate( void* mesh, std::shared_ptr<IO_double> localCoord ) : IO_double( _Check_GetDimSize(mesh), FunctionIO::Vector), _localCoord_sp(localCoord), _localCoord(NULL), _mesh(mesh), _index(0), _valueCalculated(false) { if( _localCoord_sp->iotype() != FunctionIO::Vector) throw std::invalid_argument("Provided local coordinate must be of 'Vector' type."); if(!Stg_Class_IsInstance( mesh, FeMesh_Type )) throw std::invalid_argument("Provided 'object' does not appear to be of 'FeMesh' type."); _localCoord = _localCoord_sp.get(); }; unsigned FEMCoordinate::_Check_GetDimSize(void* mesh){ if(!Stg_Class_IsInstance( mesh, FeMesh_Type )) throw std::invalid_argument("Provided 'object' does not appear to be of 'FeMesh' type."); return Mesh_GetDimSize(mesh); } double& FEMCoordinate::at(size_t idx) { throw std::runtime_error("The FEMCoordinate 'value' should never be set explicitly."); } const double FEMCoordinate::at(size_t idx) const { if (!_valueCalculated) _calculate_value(); return IO_double::at(idx); } double* FEMCoordinate::data() { throw std::runtime_error("Non const access to underlying data is not permitted for 'FEMCoordinate' objects."); return NULL; } const double* FEMCoordinate::data() const { if (!_valueCalculated) _calculate_value(); return IO_double::data(); } void FEMCoordinate::_calculate_value() const { FeMesh_CoordLocalToGlobal( _mesh, _index, const_cast<const IO_double*>(_localCoord)->data(), _vector.data() ); _valueCalculated = false; }
31.879518
156
0.584278
rbeucher
753fa5393f2d98fc97880bd2303ab884c682b90e
14,527
cc
C++
test/rebuild_graphs.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
test/rebuild_graphs.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
test/rebuild_graphs.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2013-2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include <sys/stat.h> #include <QDateTime> #include <QFileInfo> #include <QSqlError> #include <QSqlQuery> #include <QVariant> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iostream> #include <map> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "test/config.hh" #include "test/engine.hh" #include "test/generate.hh" #include "test/misc.hh" #include "test/rrd_file.hh" #include "test/vars.hh" using namespace com::centreon::broker; #define DB_NAME "broker_rebuild_graphs" #define HOST_COUNT 2 #define SERVICES_BY_HOST 6 // Local structure. struct metric_info { time_t first_entry; bool is_infinity; }; /** * Check that graphs can be properly rebuild. * * @return EXIT_SUCCESS on success. */ int main() { // Error flag. bool error(true); // Variables that need cleaning. std::list<command> commands; std::list<host> hosts; std::list<service> services; std::string cbmod_config_path(tmpnam(NULL)); std::string engine_config_path(tmpnam(NULL)); std::string metrics_path(tmpnam(NULL)); std::string status_path(tmpnam(NULL)); engine daemon; test_db db; // Log. std::clog << "status directory: " << status_path << "\n" << "metrics directory: " << metrics_path << std::endl; try { // Prepare database. db.open(DB_NAME); // Create RRD paths. mkdir(metrics_path.c_str(), S_IRWXU); mkdir(status_path.c_str(), S_IRWXU); // Write cbmod configuration file. { std::ofstream ofs; ofs.open(cbmod_config_path.c_str(), std::ios_base::out | std::ios_base::trunc); if (ofs.fail()) throw(exceptions::msg() << "cannot open cbmod configuration file '" << cbmod_config_path.c_str() << "'"); ofs << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" << "<centreonbroker>\n" << " <include>" PROJECT_SOURCE_DIR "/test/cfg/broker_modules.xml</include>\n" << " <instance>42</instance>\n" << " <instance_name>MyBroker</instance_name>\n" << " <!--\n" << " <logger>\n" << " <type>file</type>\n" << " <name>cbmod.log</name>\n" << " <config>1</config>\n" << " <debug>1</debug>\n" << " <error>1</error>\n" << " <info>1</info>\n" << " <level>3</level>\n" << " </logger>\n" << " -->\n" << " <output>\n" << " <name>EngineToStorageUnitTest</name>\n" << " <type>storage</type>\n" << " <db_type>" DB_TYPE "</db_type>\n" << " <db_host>" DB_HOST "</db_host>\n" << " <db_port>" DB_PORT "</db_port>\n" << " <db_user>" DB_USER "</db_user>\n" << " <db_password>" DB_PASSWORD "</db_password>\n" << " <db_name>" DB_NAME "</db_name>\n" << " <queries_per_transaction>0</queries_per_transaction>\n" << " <length>2592000</length>\n" << " " "<rebuild_check_interval>" MONITORING_ENGINE_INTERVAL_LENGTH_STR "</rebuild_check_interval>\n" << " </output>\n" << " <output>\n" << " <name>StorageToRRDUnitTest</name>\n" << " <type>rrd</type>\n" << " <metrics_path>" << metrics_path << "</metrics_path>\n" << " <status_path>" << status_path << "</status_path>\n" << " </output>\n" << "</centreonbroker>\n"; ofs.close(); } // Prepare monitoring engine configuration parameters. generate_commands(commands, 2); { command* cmd(&commands.front()); char const* cmdline; cmdline = MY_PLUGIN_PATH " 0 \"output1|metric=100\""; cmd->command_line = new char[strlen(cmdline) + 1]; strcpy(cmd->command_line, cmdline); cmd = &*(++commands.begin()); cmdline = MY_PLUGIN_PATH " 0 \"output2|metric=inf\""; cmd->command_line = new char[strlen(cmdline) + 1]; strcpy(cmd->command_line, cmdline); } int i(0); generate_hosts(hosts, HOST_COUNT); for (std::list<host>::iterator it(hosts.begin()), end(hosts.end()); it != end; ++it) { it->host_check_command = new char[2]; strcpy(it->host_check_command, (++i % 2 ? "1" : "2")); } i = 0; generate_services(services, hosts, SERVICES_BY_HOST); for (std::list<service>::iterator it(services.begin()), end(services.end()); it != end; ++it) { it->service_check_command = new char[2]; strcpy(it->service_check_command, (++i % 2 ? "1" : "2")); } std::string engine_additional; { std::ostringstream oss; oss << "broker_module=" << CBMOD_PATH << " " << cbmod_config_path; engine_additional = oss.str(); } // Insert entries in index_data. { QSqlQuery q(*db.centreon_db()); for (uint32_t i(1); i <= HOST_COUNT * SERVICES_BY_HOST; ++i) { std::ostringstream query; query << "INSERT INTO rt_index_data (host_id, service_id)" << " VALUES(" << (i - 1) / SERVICES_BY_HOST + 1 << ", " << i << ")"; if (!q.exec(query.str().c_str())) throw(exceptions::msg() << "cannot create index of service (" << (i - 1) / SERVICES_BY_HOST + 1 << ", " << i << ")"); } } // Generate monitoring engine configuration files. config_write(engine_config_path.c_str(), engine_additional.c_str(), &hosts, &services, &commands); // Start monitoring engine. std::string engine_config_file(engine_config_path); engine_config_file.append("/nagios.cfg"); daemon.set_config_file(engine_config_file); daemon.start(); sleep_for(30); // Get index list. std::map<uint32_t, time_t> indexes; { QSqlQuery q(*db.centreon_db()); if (!q.exec("SELECT index_id FROM rt_index_data")) throw(exceptions::msg() << "cannot get index list: " << qPrintable(q.lastError().text())); while (q.next()) indexes[q.value(0).toUInt()]; if (indexes.size() != HOST_COUNT * SERVICES_BY_HOST) throw(exceptions::msg() << "not enough entries in rt_index_data: got " << indexes.size() << ", expected " << HOST_COUNT * SERVICES_BY_HOST); } // For each index, get the first entry time. for (std::map<uint32_t, time_t>::iterator it(indexes.begin()), end(indexes.end()); it != end; ++it) { std::ostringstream file_path; file_path << status_path << "/" << it->first << ".rrd"; rrd_file graph; graph.load(file_path.str().c_str()); if (graph.get_rras().empty() || graph.get_rras().front().empty()) throw(exceptions::msg() << "not enough data in status graph '" << file_path.str().c_str() << "'"); it->second = graph.get_rras().front().begin()->first; } // Get metrics list. std::map<uint32_t, metric_info> metrics; { std::ostringstream query; query << "SELECT m.metric_id" << " FROM rt_metrics AS m LEFT JOIN rt_index_data AS i" << " ON m.index_id = i.index_id" << " ORDER BY i.host_id, i.service_id"; QSqlQuery q(*db.centreon_db()); if (!q.exec(query.str().c_str())) throw(exceptions::msg() << "cannot get metric list: " << qPrintable(q.lastError().text())); i = 0; while (q.next()) metrics[q.value(0).toUInt()].is_infinity = !(++i % 2); if (metrics.size() != HOST_COUNT * SERVICES_BY_HOST) throw(exceptions::msg() << "not enough entries in rt_metrics: got " << metrics.size() << ", expected " << HOST_COUNT * SERVICES_BY_HOST); } // For each metric, get the first entry time. for (std::map<uint32_t, metric_info>::iterator it(metrics.begin()), end(metrics.end()); it != end; ++it) { std::ostringstream file_path; file_path << metrics_path << "/" << it->first << ".rrd"; rrd_file graph; graph.load(file_path.str().c_str()); if (graph.get_rras().empty() || graph.get_rras().front().empty()) throw(exceptions::msg() << "not enough data in metrics graph '" << file_path.str().c_str() << "'"); it->second.first_entry = graph.get_rras().front().begin()->first; } // Graphs must have been recreated from this time. time_t recreated_limit(time(NULL)); std::clog << "recreation limit: " << recreated_limit << std::endl; // Launch rebuild. { QSqlQuery q(*db.centreon_db()); if (!q.exec("UPDATE rt_index_data SET must_be_rebuild=1")) throw(exceptions::msg() << "cannot launch rebuild from DB: " << qPrintable(q.lastError().text())); sleep_for(15); } // Check that rebuild successfully executed. { QSqlQuery q(*db.centreon_db()); if (!q.exec("SELECT COUNT(*)" " FROM rt_index_data" " WHERE must_be_rebuild!=0") || !q.next()) throw(exceptions::msg() << "cannot check that rebuild successfully executed"); if (q.value(0).toUInt()) throw(exceptions::msg() << "rebuild did not succeed, " << q.value(0).toUInt() << " indexes are still waiting/being rebuild"); } // Check status graphs. for (std::map<uint32_t, time_t>::iterator it(indexes.begin()), end(indexes.end()); it != end; ++it) { // Check file properties. std::ostringstream file_path; file_path << status_path << "/" << it->first << ".rrd"; QFileInfo info(file_path.str().c_str()); if (!info.exists()) throw(exceptions::msg() << "status file '" << file_path.str().c_str() << "' does not exist"); else if (static_cast<time_t>(info.created().toTime_t()) < recreated_limit) throw(exceptions::msg() << "status file '" << file_path.str().c_str() << "' was created at " << info.created().toTime_t() << " whereas recreation limit is " << recreated_limit); // Check file content. time_t data_low(it->second - 2592000 / 5 / MONITORING_ENGINE_INTERVAL_LENGTH); time_t data_high(it->second + 2592000 * 5 * MONITORING_ENGINE_INTERVAL_LENGTH); rrd_file graph; graph.load(file_path.str().c_str()); if (graph.get_rras().empty() || graph.get_rras().front().empty()) throw(exceptions::msg() << "status file '" << file_path.str().c_str() << "' does not have any data after rebuild"); else if ((graph.get_rras().front().begin()->first < data_low) || (graph.get_rras().front().begin()->first > data_high)) throw(exceptions::msg() << "data time mismatch in status file '" << file_path.str().c_str() << "': got " << graph.get_rras().front().begin()->first << ", expected " << data_low << ":" << data_high); } // Check metrics graphs. for (std::map<uint32_t, metric_info>::iterator it(metrics.begin()), end(metrics.end()); it != end; ++it) { // Check file properties. std::ostringstream file_path; file_path << metrics_path << "/" << it->first << ".rrd"; QFileInfo info(file_path.str().c_str()); if (!info.exists()) throw(exceptions::msg() << "metric file '" << file_path.str().c_str() << "' does not exist"); else if (static_cast<time_t>(info.created().toTime_t()) < recreated_limit) throw(exceptions::msg() << "metric file '" << file_path.str().c_str() << "' was created at " << info.created().toTime_t() << " whereas recreation limit is " << recreated_limit); // Check file content. time_t data_low(it->second.first_entry - 2592000 / 5 / MONITORING_ENGINE_INTERVAL_LENGTH); time_t data_high(it->second.first_entry + 2592000 * 5 * MONITORING_ENGINE_INTERVAL_LENGTH); rrd_file graph; graph.load(file_path.str().c_str()); if (graph.get_rras().empty() || graph.get_rras().front().empty()) throw(exceptions::msg() << "metric file '" << file_path.str().c_str() << "' does not have any data after rebuild"); else if ((graph.get_rras().front().begin()->first < data_low) || (graph.get_rras().front().end()->first > data_high)) throw(exceptions::msg() << "data time mismatch in metric file '" << file_path.str().c_str() << "': got " << graph.get_rras().front().begin()->first << ", expected " << data_low << ":" << data_high); else if (it->second.is_infinity && !isinf(graph.get_rras().front().begin()->second)) throw(exceptions::msg() << "graph rebuild does not handle infinity of file '" << file_path.str().c_str() << "' (" << graph.get_rras().front().begin()->second << ")"); } // Success. error = false; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } // Cleanup. daemon.stop(); config_remove(engine_config_path.c_str()); ::remove(cbmod_config_path.c_str()); free_hosts(hosts); free_services(services); recursive_remove(metrics_path); recursive_remove(status_path); // Return check result. return (error ? EXIT_FAILURE : EXIT_SUCCESS); }
37.634715
80
0.560129
centreon-lab
7545c681e53b1ebe28e8935987ae09cadcf6336a
272
cc
C++
src/sampler/smart_random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
762
2020-01-16T02:44:50.000Z
2022-03-30T10:03:36.000Z
src/sampler/smart_random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
161
2020-01-20T07:47:38.000Z
2022-03-11T15:19:10.000Z
src/sampler/smart_random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
77
2020-01-23T17:47:20.000Z
2022-03-28T10:12:19.000Z
/*! * Copyright (c) 2019 by Contributors if not otherwise specified * \file smart_random_sampler.cc * \brief Smart random sampler for faster video random access */ #include "smart_random_sampler.h" namespace decord { namespace sampler { } // sampler } // decord
19.428571
65
0.727941
TheTimmy
7548b8d28cfaf93f262dc4fb920fd71abdd5f27c
72,073
cpp
C++
libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp
DongJiHui/deeplearning4j
bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854
[ "Apache-2.0" ]
null
null
null
libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp
DongJiHui/deeplearning4j
bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854
[ "Apache-2.0" ]
null
null
null
libnd4j/tests_cpu/layers_tests/DeclarableOpsTests8.cpp
DongJiHui/deeplearning4j
bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854
[ "Apache-2.0" ]
null
null
null
// // @author Yurii Shyrma (iuriish@yahoo.com), created on 10.06.2018 // #include "testlayers.h" #include <ops/declarable/CustomOperations.h> #include <NDArray.h> // #include <array/NDArrayList.h> using namespace nd4j; class DeclarableOpsTests8 : public testing::Test { public: DeclarableOpsTests8() { printf("\n"); fflush(stdout); } }; //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test1) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f}); NDArray<float> exp('c', {4}, {602.2222f, 727.13885f, 993.5555f, 755.8889f}); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test2) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f}); NDArray<float> exp('c', {1,1,4}, {602.2222f, 727.13885f, 993.5555f, 755.8889f}); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {1.}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test3) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f}); NDArray<float> exp('c', {3}, {900.9375f, 969.8594f, 424.1875f}); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test4) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f}); NDArray<float> exp('c', {1,3,1}, {900.9375f, 969.8594f, 424.1875f}); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {1.}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test5) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.f}); NDArray<float> exp(788.6927f); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test6) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp(788.6927f); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVariance_test7) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {1,1,1}, {788.6927f}); nd4j::ops::reduce_variance<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test1) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {4}, {24.54022f, 26.96551f, 31.52072f, 27.49343f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test2) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {1,1,4}, {24.54022f, 26.96551f, 31.52072f, 27.49343f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {1.}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test3) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {3}, {30.01562f, 31.14257f, 20.59581f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test4) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {1,3,1}, {30.01562f, 31.14257f, 20.59581f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {1.}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test5) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp(28.08367f); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test6) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp(28.08367f); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test7) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {1,1,1}, {28.08367f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {1.f}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDev_test8) { NDArray<float> x('c', {2,3,4}, {27.f,34.f,5.f,4.f,54.f,6.f,65.f,8.f,37.f,45.f,8.f,67.f,96.f,10.f,65.f,41.f,33.f,85.f,92.f,24.f,25.f,55.f,49.f,76.}); NDArray<float> exp('c', {4}, {26.88246f, 29.53924f, 34.52921f, 30.11755f}); nd4j::ops::reduce_stdev<float> op; auto result = op.execute({&x}, {0.f,1.f}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVarianceBP_test1) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {1,1}, {0.5f}); NDArray<float> gradO2(0.5f); NDArray<float> exp12('c', {3,4}, {-0.5f, -0.4090909f, -0.3181818f, -0.22727273f, -0.13636364f, -0.045454547f, 0.045454547f, 0.13636364f, 0.22727273f, 0.3181818f, 0.4090909f, 0.5f}); NDArray<float> exp34('c', {3,4}, {-0.45833334f, -0.375f, -0.29166666f, -0.20833333f, -0.125f, -0.041666668f, 0.041666668f, 0.125f, 0.20833333f, 0.29166666f, 0.375f, 0.45833334f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_variance_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,1}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,0}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVarianceBP_test2) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {1,4}, {1.f,2.f,3.f,4.f}); NDArray<float> gradO2('c', {4}, {1.f,2.f,3.f,4.f}); NDArray<float> exp12('c', {3,4}, {-2.666667f, -5.333333f, -8.000000f, -10.666667f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 2.666667f, 5.333333f, 8.000000f, 10.666667f}); NDArray<float> exp34('c', {3,4}, {-4.000000f, -8.000000f, -12.000000f, -16.000000f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 4.000000f, 8.000000f, 12.000000f, 16.000000f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_variance_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,0}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,1}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceVarianceBP_test3) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {3,1}, {1.f,2.f,3.f}); NDArray<float> gradO2('c', {3}, {1.f,2.f,3.f}); NDArray<float> exp12('c', {3,4}, {-0.750000f, -0.250000f, 0.250000f, 0.750000f, -1.500000f, -0.500000f, 0.500000f, 1.500000f, -2.250000f, -0.750000f, 0.750000f, 2.250000f}); NDArray<float> exp34('c', {3,4}, {-1.000000f, -0.333333f, 0.333333f, 1.000000f, -2.000000f, -0.666667f, 0.666667f, 2.000000f, -3.000000f, -1.000000f, 1.000000f, 3.000000f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_variance_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,0}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,1}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDevBP_test1) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {1,1}, {0.5f}); NDArray<float> gradO2(0.5f); NDArray<float> exp12('c', {3,4}, {-0.069337524f, -0.056730703f, -0.04412388f, -0.031517055f, -0.018910235f, -0.0063034114f, 0.0063034114f, 0.018910235f, 0.031517055f, 0.04412388f, 0.056730703f, 0.069337524f}); NDArray<float> exp34('c', {3,4}, {-0.06638563f, -0.05431551f, -0.0422454f, -0.030175284f, -0.01810517f, -0.006035057f, 0.006035057f, 0.01810517f, 0.030175284f, 0.0422454f, 0.05431551f, 0.06638563f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_stdev_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,1}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); // output->printIndexedBuffer(); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,0}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDevBP_test2) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {1,4}, {1.f,2.f,3.f,4.f}); NDArray<float> gradO2('c', {4}, {1.f,2.f,3.f,4.f}); NDArray<float> exp12('c', {3,4}, {-0.4082483f, -0.8164966f, -1.2247449f, -1.6329932f, 0.0, 0.0, 0.0, 0.0, 0.4082483f, 0.8164966f, 1.2247449f, 1.6329932f}); NDArray<float> exp34('c', {3,4}, {-0.5f, -1.0f, -1.5f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 1.0f, 1.5f, 2.0f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_stdev_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,0}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,1}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceStDevBP_test3) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {3,1}, {1.f,2.f,3.f}); NDArray<float> gradO2('c', {3}, {1.f,2.f,3.f}); NDArray<float> exp12('c', {3,4}, {-0.3354102f, -0.1118034f, 0.1118034f, 0.3354102f, -0.6708204f, -0.2236068f, 0.2236068f, 0.6708204f, -1.0062306f, -0.3354102f, 0.3354102f, 1.0062306f}); NDArray<float> exp34('c', {3,4}, {-0.38729835f, -0.12909944f, 0.12909944f, 0.38729835f, -0.7745967f, -0.2581989f, 0.2581989f, 0.7745967f, -1.161895f, -0.38729835f, 0.38729835f, 1.161895f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_stdev_bp<float> op; auto result = op.execute({&x, &gradO2}, {0,0}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,0}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp12.isSameShape(output)); ASSERT_TRUE(exp12.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {0,1}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; result = op.execute({&x, &gradO1}, {1,1}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp34.isSameShape(output)); ASSERT_TRUE(exp34.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_1) { NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.}); NDArray<float> exp(120.f); //************************************// nd4j::ops::reduce_sum<float> op; auto result = op.execute({&input}, {}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); //z->printIndexedBuffer("Result is "); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_2) { NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.}); NDArray<float> exp({15.f, 40.f, 65.f}); //************************************// nd4j::ops::reduce_sum<float> op; auto result = op.execute({&input}, {}, {1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_1) { NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.}); NDArray<float> exp(1307674368000.f); //************************************// nd4j::ops::reduce_prod<float> op; auto result = op.execute({&input}, {}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); //z->printIndexedBuffer("Result is "); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_2) { NDArray<float> input('c', {3, 5}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.}); NDArray<float> exp({120.f, 30240.f, 360360.f}); //************************************// nd4j::ops::reduce_prod<float> op; auto result = op.execute({&input}, {}, {1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_01) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {4}, {66.f, 72.f, 78.f, 84.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_02) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,4}, {66.f, 72.f, 78.f, 84.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_3) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {3}, {68.f, 100.f, 132.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_4) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,3,1}, {68.f, 100.f, 132.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_5) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp(300.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_6) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp(300.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_7) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,1}, {300.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_sum<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_01) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp('c', {2}, {10395.f, 46080.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_02) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp('c', {1,1,2}, {10395.f, 46080.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_3) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp('c', {3}, {112.f, 1080.f, 3960.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_4) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp('c', {1,3,1}, {112.f, 1080.f, 3960.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_5) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp(479001600.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_6) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp(479001600.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_7) { NDArray<float> x('c', {2,3,2}); NDArray<float> exp('c', {1, 1, 1}, {479001600.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_prod<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {1.f, 2.f, 3.f, 4.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {}, {0, 1}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_2) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,1,4}, {1.f, 2.f, 3.f, 4.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {1.f, 5.f, 9.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,3,1}, {1.f, 5.f, 9.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(1.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(1.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Min_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {1.f}); NDArrayFactory<float>::linspace(1, x); x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_min<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {21.f, 22.f, 23.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); output->printIndexedBuffer("Result is"); output->printShapeInfo("Output shape"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_2) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,4}, {21.f, 22.f, 23.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {16.f, 20.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,3,1}, {16.f, 20.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(24.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(24.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Max_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {24.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_max<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {1.f, 2.f, 3.f, 4.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot_bp<float> op; auto result = op.execute({&x, &exp}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(x.isSameShape(output)); // ASSERT_TRUE(exp.equalsTo(output)); delete result; } /* //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_2) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,1,4}, {1.f, 2.f, 3.f, 4.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {112.f, 1080.f, 3960.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,3,1}, {112.f, 1080.f, 3960.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(479001600.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(479001600.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Dot_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {479001600.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_dot<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } */ TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {66.f, 72.f, 78.f, 84.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_2) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,4}, {66.f, 72.f, 78.f, 84.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {68.f, 100.f, 132.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,3,1}, {68.f, 100.f, 132.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(300.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(300.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm1_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {300.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_norm1<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {31.7175f, 33.823071f, 35.97221f, 38.15757f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_2) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,4}, {31.7175f, 33.823071f, 35.97221f, 38.15757f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {1.}, {0, 1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {29.597298f, 39.344631f, 49.759422f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,3,1}, {29.597298f, 39.344631f, 49.759422f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {1.}, {0, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(70.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(70.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Norm2_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {70.f}); NDArrayFactory<float>::linspace(1, x); // x.printIndexedBuffer("Input with shape (2, 3, 4) is"); nd4j::ops::reduce_norm2<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {21.f, 22.f, 23.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_2) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,1,4}, {21.f, 22.f, 23.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {1.f}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {16.f, 20.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {}, {0,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 3, 1}, {16.f, 20.f, 24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {1.f}, {0,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(24.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(24.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {}, {0, 1, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_NormMax_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {24.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_norm_max<float> op; auto result = op.execute({&x}, {1.f}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_1) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {4}, {1006.f, 1144.f, 1294.f, 1456.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_2) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1,1,4}, {1006.f, 1144.f, 1294.f, 1456.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {1.f}, {0,1}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_3) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {3}, {876.f, 1548.f, 2476.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {}, {0,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_4) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 3, 1}, {876.f, 1548.f, 2476.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {1.f}, {0,2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_5) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(4900.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_6) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp(4900.f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {}, {0, 1, 2}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_SquaredNorm_7) { NDArray<float> x('c', {2, 3, 4}); NDArray<float> exp('c', {1, 1, 1}, {4900.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_sqnorm<float> op; auto result = op.execute({&x}, {1.f}, {}); auto output = result->at(0); // output->printIndexedBuffer("Result is"); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_1) { NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.}); NDArray<float> eps(0.5f); NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,0.5f}); //************************************// nd4j::ops::reduce_sum_bp<float> op; auto result = op.execute({&input, &eps}, {}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); // z->printShapeInfo(); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_2) { NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.}); NDArray<float> eps('c', {1, 1}, {0.5f}); NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,0.5f}); //************************************// nd4j::ops::reduce_sum_bp<float> op; auto result = op.execute({&input, &eps}, {1.f}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); // z->printShapeInfo(); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_3) { NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.}); NDArray<float> eps('c', {4}, {1.f, 2.f, 3.f, 4.f}); NDArray<float> exp('c', {3, 4}, {1.f, 2.f, 3.f, 4.f, 1.f, 2.f, 3.f, 4.f, 1.f, 2.f, 3.f, 4.f}); //************************************// nd4j::ops::reduce_sum_bp<float> op; auto result = op.execute({&input, &eps}, {}, {0}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); // z->printShapeInfo(); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Sum_BP_4) { NDArray<float> input('c', {3, 4}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.}); NDArray<float> eps('c', {1, 4}, {1.f, 2.f, 3.f, 4.f}); NDArray<float> exp('c', {3, 4}, {1.f, 2.f, 3.f, 4.f, 1.f, 2.f, 3.f, 4.f, 1.f, 2.f, 3.f, 4.f}); //************************************// nd4j::ops::reduce_sum_bp<float> op; auto result = op.execute({&input, &eps}, {1.f}, {0}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); // z->printShapeInfo(); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, Test_Reduce_Prod_BP_1) { NDArray<float> input('c', {3, 5}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f}); NDArray<float> eps(1307674368000.f); //************************************// // NDArray<float> exp('c', {3, 4}, {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,0.5f}); //************************************// NDArray<float> exp('c', {3, 5}, {1710012166826558903812096.f, 855006083413279451906048.f, 570004067618451974258688.f, 427503041706639725953024.f, 342002454982589992140800.f, 285002033809225987129344.f, 244287457550765131825152.f, 213751520853319862976512.f, 190001355872817324752896.f, 171001227491294996070400.f, 155455648254341989531648.f, 142501016904612993564672.f, 131539399526781282156544.f, 122143728775382565912576.f, 114000815325130245799936.f}); nd4j::ops::reduce_prod_bp<float> op; auto result = op.execute({&input, &eps}, {}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); // z->printIndexedBuffer("Result is "); // z->printShapeInfo(); ASSERT_TRUE(exp.equalsTo(z)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test1) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {4}, {11.f, 12.f, 13.f, 14.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test2) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,4}, {11.f, 12.f, 13.f, 14.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {1.}, {0,1}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test3) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {3}, {8.5f, 12.5f, 16.5f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test4) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,3,1}, {8.5f, 12.5f, 16.5f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {1.f}, {0,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test5) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp(12.5f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {}, {}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test6) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp(12.5f); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMean_test7) { NDArray<float> x('c', {2,3,4}); NDArray<float> exp('c', {1,1,1}, {12.5f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean<float> op; auto result = op.execute({&x}, {1.}, {0,1,2}); auto output = result->at(0); ASSERT_EQ(ND4J_STATUS_OK, result->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMeanBP_test1) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1(0.5f); NDArray<float> gradO2('c', {1,1}, {0.5f}); NDArray<float> exp('c', {3,4}, {1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24, 1./24}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean_bp<float> op; auto result = op.execute({&x, &gradO1}, {0}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {1}, {}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMeanBP_test3) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {4}, {1.f, 2.f, 3.f, 4.f}); NDArray<float> gradO2('c', {1,4}, {1.f, 2.f, 3.f, 4.f}); NDArray<float> exp('c', {3,4}, {1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f, 1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f, 1.f/3.f, 2.f/3.f, 1.f, 4.f/3.f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean_bp<float> op; auto result = op.execute({&x, &gradO1}, {0}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {1}, {0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } //////////////////////////////////////////////////////////////////////////////// TEST_F(DeclarableOpsTests8, reduceMeanBP_test5) { NDArray<float> x('c', {3,4}); NDArray<float> gradO1('c', {3}, {1.f, 2.f, 3.f}); NDArray<float> gradO2('c', {3,1}, {1.f, 2.f, 3.f}); NDArray<float> exp('c', {3,4}, {0.25f, 0.25f, 0.25f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.75f, 0.75f, 0.75f, 0.75f}); NDArrayFactory<float>::linspace(1, x); nd4j::ops::reduce_mean_bp<float> op; auto result = op.execute({&x, &gradO1}, {0}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; result = op.execute({&x, &gradO2}, {1}, {1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; }
32.83508
218
0.537316
DongJiHui
754db7453767ee9b479c44bcdf3863c1d8d05b5a
2,674
cpp
C++
engine/src/Component/MeshComponents/Skeleton.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
5
2017-01-20T00:23:23.000Z
2018-07-17T07:48:04.000Z
engine/src/Component/MeshComponents/Skeleton.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
null
null
null
engine/src/Component/MeshComponents/Skeleton.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
2
2017-01-24T05:09:37.000Z
2021-02-18T14:42:00.000Z
#include "Skeleton.h" #include "Util/Logger.h" #include <glm/gtc/type_ptr.hpp> using namespace MoonEngine; Bone::Bone(std::string name, int boneIdx, glm::mat4 offsetTransform): name(name), offsetTransform(offsetTransform), localAnimTransform(1.0), animTransform(1.0), idx(boneIdx) { } void Bone::setAnimatedTransform(glm::mat4 transform) { this->localAnimTransform = transform; } Skeleton::Skeleton(): Component() { } Skeleton::Skeleton(AssimpModelInfo & info): Component() { importBonesFromAssimp(info); } Skeleton::~Skeleton() { } int Skeleton::getNumBones() { return bones.size(); } void Skeleton::importBonesFromAssimp(AssimpBoneInfo & node, AssimpModelInfo & info, BoneTreeNode & thisNode) { int boneIdx = addBone(node); thisNode.boneIdx = boneIdx; for(int i = 0; i < node.childBones.size(); i++) { thisNode.children.push_back(BoneTreeNode()); AssimpBoneInfo childInfo = info.getBoneInfo(node.childBones[i]); importBonesFromAssimp(childInfo, info, thisNode.children.back()); } } void Skeleton::importBonesFromAssimp(AssimpModelInfo & importInfo) { rootInverseTransform = importInfo.getRootInverseTransform(); AssimpBoneInfo rootInfo = importInfo.getBoneInfo(0); boneRoot.children.push_back(BoneTreeNode()); importBonesFromAssimp(rootInfo,importInfo, boneRoot.children.back()); } Bone * const Skeleton::getBone(std::string boneName) { auto boneId = boneMap.find(boneName); if(boneId == boneMap.end()) { LOG(ERROR, "No Bone named " + boneName + "In skeleton!"); return nullptr; } else { return &bones[boneId->second]; } } /** * Returns index of added bone */ int Skeleton::addBone(AssimpBoneInfo & info) { LOG(INFO, "Adding bone " + info.boneName); Bone bone(info.boneName,bones.size(),info.offsetMatrix); bones.push_back(bone); boneMap[info.boneName] = bone.getIndex(); return bone.getIndex(); } void Skeleton::finalizeAnimation(BoneTreeNode & node, glm::mat4 parentMtx) { glm::mat4 aMtx = parentMtx * bones[node.boneIdx].localAnimTransform; bones[node.boneIdx].animTransform = aMtx; for (std::vector<BoneTreeNode>::iterator i = node.children.begin(); i != node.children.end(); ++i) { finalizeAnimation(*i, aMtx); } } void Skeleton::finalizeAnimation() { for (std::vector<BoneTreeNode>::iterator i = boneRoot.children.begin(); i != boneRoot.children.end(); ++i) { finalizeAnimation(*i,rootInverseTransform); } } std::shared_ptr<Component> Skeleton::clone() const { return std::make_shared<Skeleton>(*this); }
23.051724
110
0.677636
kyle-piddington
75509c46638cb4b7864fb3e59fdd4b16bb0b3c22
2,894
cpp
C++
qlo/objects/obj_correlation_hw.cpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
5
2016-07-13T14:05:01.000Z
2022-01-24T15:15:17.000Z
qlo/objects/obj_correlation_hw.cpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
null
null
null
qlo/objects/obj_correlation_hw.cpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
12
2016-01-28T07:18:28.000Z
2021-11-15T03:48:52.000Z
// BEGIN buffer b_lib_grp_cpp #include <qlo/objects/obj_correlation.hpp> #include <ql/legacy/libormarketmodels/lmlinexpcorrmodel.hpp> #include <ql/models/marketmodels/correlations/cotswapfromfwdcorrelation.hpp> #include <ql/models/marketmodels/correlations/timehomogeneousforwardcorrelation.hpp> #include <ql/models/marketmodels/correlations/expcorrelations.hpp> #include <ql/models/marketmodels/historicalforwardratesanalysis.hpp> #include <ql/models/marketmodels/historicalratesanalysis.hpp> #include <qlo/enumerations/factories/historicalforwardratesanalysisfactory.hpp> QuantLibAddin::HistoricalForwardRatesAnalysis::HistoricalForwardRatesAnalysis( const boost::shared_ptr<reposit::ValueObject>& properties, // BEGIN typemap rp_tm_default boost::shared_ptr< QuantLib::SequenceStatistics > const &SequenceStats, QuantLib::Date const &StartDate, QuantLib::Date const &EndDate, QuantLib::Period const &Step, boost::shared_ptr< QuantLib::IborIndex > const &IborIndex, QuantLib::Period const &InitialGap, QuantLib::Period const &Horizon, std::vector< boost::shared_ptr< QuantLib::IborIndex > > const &IborIndexes, std::vector< boost::shared_ptr< QuantLib::SwapIndex > > const &SwapIndexes, QuantLib::DayCounter const &DayCounter, std::string const &TraitsID, std::string const &InterpolatorID, QuantLib::Real BootstrapAccuracy, // END typemap rp_tm_default bool permanent) : reposit::LibraryObject<QuantLib::HistoricalForwardRatesAnalysis>(properties, permanent) { libraryObject_ = reposit::Create<boost::shared_ptr< QuantLib::HistoricalForwardRatesAnalysis> >()( TraitsID, InterpolatorID, SequenceStats, StartDate, EndDate, Step, IborIndex, InitialGap, Horizon, IborIndexes, SwapIndexes, DayCounter, BootstrapAccuracy); } QuantLibAddin::TimeHomogeneousForwardCorrelation::TimeHomogeneousForwardCorrelation( const boost::shared_ptr<reposit::ValueObject>& properties, // BEGIN typemap rp_tm_default QuantLib::Matrix const &FwdCorrMatrix, std::vector< QuantLib::Time > const &RateTimes, // END typemap rp_tm_default bool permanent) : PiecewiseConstantCorrelation(properties, permanent) { QL_REQUIRE(!RateTimes.empty(), "rate times vector is empty!"); libraryObject_ = boost::shared_ptr<QuantLib::PiecewiseConstantCorrelation>(new QuantLib::TimeHomogeneousForwardCorrelation( // BEGIN typemap rp_tm_default FwdCorrMatrix, RateTimes // END typemap rp_tm_default )); } // END buffer b_lib_grp_cpp
40.760563
127
0.681064
eehlers
7550c1f3aa84e96d53e506d0a5367d6d41ef9d00
3,475
cpp
C++
Visual Mercutio/zBaseLib/PSS_CommandLine.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zBaseLib/PSS_CommandLine.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zBaseLib/PSS_CommandLine.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_CommandLine -----------------------------------------------------* **************************************************************************** * Description : Provides an encapsulated command line * * Developer : Processsoft * ****************************************************************************/ #include <StdAfx.h> #include "PSS_CommandLine.h" // processsoft #include "PSS_FileLauncher.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Serialization //--------------------------------------------------------------------------- IMPLEMENT_SERIAL(PSS_CommandLine, CObject, g_DefVersion) //--------------------------------------------------------------------------- // PSS_CommandLine //--------------------------------------------------------------------------- PSS_CommandLine::PSS_CommandLine(const CString& commandLine, const CString& startupDir, const CString& arguments, DWORD priority) : m_pProcessInfo(NULL), m_CommandLine(commandLine), m_StartupDir(startupDir), m_Arguments(arguments), m_Priority(priority), m_HasBeenLaunched(FALSE) {} //--------------------------------------------------------------------------- PSS_CommandLine::PSS_CommandLine(const PSS_CommandLine& other) : m_pProcessInfo(NULL), m_Priority(0), m_HasBeenLaunched(FALSE) { *this = other; } //--------------------------------------------------------------------------- PSS_CommandLine::~PSS_CommandLine() { if (m_pProcessInfo) delete m_pProcessInfo; } //--------------------------------------------------------------------------- const PSS_CommandLine& PSS_CommandLine::operator = (const PSS_CommandLine& other) { m_CommandLine = other.m_CommandLine; m_StartupDir = other.m_StartupDir; m_Arguments = other.m_Arguments; m_Priority = other.m_Priority; return *this; } //--------------------------------------------------------------------------- void PSS_CommandLine::Initialize(const CString& commandLine, const CString& startupDir, const CString& arguments, DWORD priority) { m_CommandLine = commandLine; m_StartupDir = startupDir; m_Arguments = arguments; m_Priority = priority; } //--------------------------------------------------------------------------- BOOL PSS_CommandLine::Launch() { PSS_FileLauncher fileLauncher(m_CommandLine, PSS_FileLauncher::IE_FM_Open, m_Arguments, m_StartupDir); return fileLauncher.Launch(); } //--------------------------------------------------------------------------- void PSS_CommandLine::Serialize(CArchive& ar) { if (ar.IsStoring()) { // write the elements ar << m_CommandLine; ar << m_StartupDir; ar << m_Arguments; ar << m_Priority; } else { // read the elements ar >> m_CommandLine; ar >> m_StartupDir; ar >> m_Arguments; ar >> m_Priority; } } //---------------------------------------------------------------------------
35.10101
106
0.410072
Jeanmilost
75549c50168b16f8a7826162a16824d7a2a3f06b
3,513
cc
C++
RecoVertex/KinematicFitPrimitives/src/TransientTrackKinematicParticle.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoVertex/KinematicFitPrimitives/src/TransientTrackKinematicParticle.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoVertex/KinematicFitPrimitives/src/TransientTrackKinematicParticle.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "RecoVertex/KinematicFitPrimitives/interface/TransientTrackKinematicParticle.h" #include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h" using namespace reco; TransientTrackKinematicParticle::TransientTrackKinematicParticle (const KinematicState& kineState, float& chiSquared, float& degreesOfFr, KinematicConstraint * lastConstraint, ReferenceCountingPointer<KinematicParticle> previousParticle, KinematicStatePropagator * pr, const TransientTrack * initialTrack) { theField = kineState.magneticField(); if(previousParticle.get() == nullptr) { initState = kineState; }else{initState = previousParticle->initialState();} cState = kineState; inTrack = initialTrack; pState = previousParticle; chi2 = chiSquared; ndf = degreesOfFr; lConstraint = lastConstraint; if(pr!=nullptr) { propagator = pr->clone(); }else{ propagator = new TrackKinematicStatePropagator(); } tree = nullptr; } TransientTrackKinematicParticle::~TransientTrackKinematicParticle() {delete propagator;} bool TransientTrackKinematicParticle::operator==(const KinematicParticle& other)const { bool dc = false; //first looking if this is an object of the same type const KinematicParticle * lp = &other; const TransientTrackKinematicParticle * lPart = dynamic_cast<const TransientTrackKinematicParticle * >(lp); if(lPart != nullptr){ //then comparing particle with their initial TransientTracks if((initialTransientTrack())&&(lPart->initialTransientTrack())) { if(initialTransientTrack() == lPart->initialTransientTrack()) dc = true; }else{if(initialState() == lPart->initialState()) dc = true;} } return dc; } bool TransientTrackKinematicParticle::operator==(const ReferenceCountingPointer<KinematicParticle>& other) const { bool res = false; if(*this == *other) res = true; return res; } bool TransientTrackKinematicParticle::operator!=(const KinematicParticle& other)const { if (*this == other){ return false; }else{return true;} } KinematicState TransientTrackKinematicParticle::stateAtPoint(const GlobalPoint& point)const { GlobalPoint iP = cState.kinematicParameters().position(); if((iP.x() == point.x())&&(iP.y() == point.y())&&(iP.z() == point.z())) { return cState ; }else{return propagator->propagateToTheTransversePCA(cState,point);} } //FreeTrajectoryState TransientTrackKinematicParticle::initialStateFTS() const //{return initState.freeTrajectoryState();} const TransientTrack * TransientTrackKinematicParticle::initialTransientTrack() const {return inTrack;} ReferenceCountingPointer<KinematicParticle> TransientTrackKinematicParticle::refittedParticle(const KinematicState& state, float chi2, float ndf, KinematicConstraint * cons)const { TransientTrackKinematicParticle * ncp = const_cast<TransientTrackKinematicParticle * >(this); return ReferenceCountingPointer<KinematicParticle>(new TransientTrackKinematicParticle(state,chi2,ndf,cons, ReferenceCountingPointer<KinematicParticle>(ncp), propagator, initialTransientTrack())); } TransientTrackKinematicParticle::RefCountedLinearizedTrackState TransientTrackKinematicParticle::particleLinearizedTrackState(const GlobalPoint& point)const { TransientTrackKinematicParticle * cr = const_cast<TransientTrackKinematicParticle * >(this); RefCountedKinematicParticle lp = ReferenceCountingPointer<KinematicParticle>(cr); return linFactory.linearizedTrackState(point,lp); }
35.846939
122
0.769143
nistefan
7555fbe32477355e35b71e315e4754e44783a59b
4,357
cpp
C++
libnaucrates/src/parser/CParseHandlerQueryOutput.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
1
2019-03-05T10:08:56.000Z
2019-03-05T10:08:56.000Z
libnaucrates/src/parser/CParseHandlerQueryOutput.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libnaucrates/src/parser/CParseHandlerQueryOutput.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CParseHandlerQueryOutput.cpp // // @doc: // Implementation of the SAX parse handler class parsing the list of // output column references in a DXL query. //--------------------------------------------------------------------------- #include "naucrates/dxl/parser/CParseHandlerQueryOutput.h" #include "naucrates/dxl/parser/CParseHandlerScalarIdent.h" #include "naucrates/dxl/parser/CParseHandlerFactory.h" #include "naucrates/dxl/operators/CDXLOperatorFactory.h" using namespace gpdxl; XERCES_CPP_NAMESPACE_USE //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::CParseHandlerQueryOutput // // @doc: // Constructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::CParseHandlerQueryOutput ( IMemoryPool *pmp, CParseHandlerManager *pphm, CParseHandlerBase *pphRoot ) : CParseHandlerBase(pmp, pphm, pphRoot), m_pdrgpdxln(NULL) { } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::~CParseHandlerQueryOutput // // @doc: // Destructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::~CParseHandlerQueryOutput() { m_pdrgpdxln->Release(); } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::PdrgpdxlnOutputCols // // @doc: // Return the list of query output columns // //--------------------------------------------------------------------------- DrgPdxln * CParseHandlerQueryOutput::PdrgpdxlnOutputCols() { GPOS_ASSERT(NULL != m_pdrgpdxln); return m_pdrgpdxln; } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::StartElement // // @doc: // Invoked by Xerces to process an opening tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::StartElement ( const XMLCh* const xmlszUri, const XMLCh* const xmlszLocalname, const XMLCh* const xmlszQname, const Attributes& attrs ) { if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), xmlszLocalname)) { // start the query output section in the DXL document GPOS_ASSERT(NULL == m_pdrgpdxln); m_pdrgpdxln = GPOS_NEW(m_pmp) DrgPdxln(m_pmp); } else if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenScalarIdent), xmlszLocalname)) { // we must have seen a proj list already and initialized the proj list node GPOS_ASSERT(NULL != m_pdrgpdxln); // start new scalar ident element CParseHandlerBase *pphChild = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenScalarIdent), m_pphm, this); m_pphm->ActivateParseHandler(pphChild); // store parse handler this->Append(pphChild); pphChild->startElement(xmlszUri, xmlszLocalname, xmlszQname, attrs); } else { CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); } } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::EndElement // // @doc: // Invoked by Xerces to process a closing tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::EndElement ( const XMLCh* const, // xmlszUri, const XMLCh* const xmlszLocalname, const XMLCh* const // xmlszQname ) { if(0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), xmlszLocalname)) { CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); } const ULONG ulSize = this->UlLength(); for (ULONG ul = 0; ul < ulSize; ul++) { CParseHandlerScalarIdent *pphChild = dynamic_cast<CParseHandlerScalarIdent *>((*this)[ul]); GPOS_ASSERT(NULL != pphChild); CDXLNode *pdxlnIdent = pphChild->Pdxln(); pdxlnIdent->AddRef(); m_pdrgpdxln->Append(pdxlnIdent); } // deactivate handler m_pphm->DeactivateHandler(); } // EOF
27.402516
126
0.585495
khannaekta
755ad07141cddf984ead1963498ce2c26f79700d
506
hpp
C++
src/hashes/PCompressG.hpp
funkysash/catena-variants
5baf9c34b96e495a52f8ded6612187c7f0033efb
[ "MIT" ]
4
2015-04-18T14:33:27.000Z
2016-02-20T11:11:25.000Z
src/hashes/PCompressG.hpp
funkysash/catena-variants
5baf9c34b96e495a52f8ded6612187c7f0033efb
[ "MIT" ]
null
null
null
src/hashes/PCompressG.hpp
funkysash/catena-variants
5baf9c34b96e495a52f8ded6612187c7f0033efb
[ "MIT" ]
3
2015-04-18T07:10:43.000Z
2018-03-26T13:55:16.000Z
#pragma once #include "../hashfast.hpp" namespace Catena_Variants{ class PCompressG : public HashFast<PCompressG> { public: PCompressG(); ~PCompressG() = default; PCompressG(PCompressG const&) = default; PCompressG& operator=(PCompressG const&) = default; virtual void Hash(int vindex, const uint8_t* i1, const uint8_t* i2, uint8_t* hash); /* Does nothing */ virtual void ResetState(); virtual uint16_t getHlenFast()const; private: uint16_t const H_LEN_FAST = 64; }; }
16.866667
70
0.699605
funkysash
755cd3720a4409d5bb29bba57511e2c3d301de1e
36,420
cpp
C++
src/llbox.cpp
pullmoll/lualept
bfe6da74088e23fc895faa30dfb1cbde9d42a53d
[ "BSD-3-Clause" ]
2
2018-05-17T12:05:43.000Z
2018-11-22T14:59:23.000Z
src/llbox.cpp
pullmoll/lualept
bfe6da74088e23fc895faa30dfb1cbde9d42a53d
[ "BSD-3-Clause" ]
null
null
null
src/llbox.cpp
pullmoll/lualept
bfe6da74088e23fc895faa30dfb1cbde9d42a53d
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ * Copyright (c) Jürgen Buchmüller <pullmoll@t-online.de> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #include "modules.h" /** * \file llbox.cpp * \class Box * * A box: a quad of l_int32 (x, y, w, h). */ /** Set TNAME to the class name used in this source file */ #define TNAME LL_BOX /** Define a function's name (_fun) with prefix Box */ #define LL_FUNC(x) FUNC(TNAME "." x) /** * \brief Destroy a Box* (%box). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * * Leptonica's Notes: * (1) Decrements the ref count and, if 0, destroys the box. * (2) Always nulls the input ptr. * </pre> * \param L Lua state. * \return 0 for nothing on the Lua stack. */ static int Destroy(lua_State *L) { LL_FUNC("Destroy"); Box *box = ll_take_udata<Box>(_fun, L, 1, TNAME); DBG(LOG_DESTROY, "%s: '%s' %s = %p, %s = %d\n", _fun, TNAME, "box", reinterpret_cast<void *>(box), "refcount", boxGetRefcount(box)); boxDestroy(&box); return 0; } /** * \brief Printable string for a Box* (%box). * \param L Lua state. * \return 1 string on the Lua stack. */ static int toString(lua_State *L) { LL_FUNC("toString"); char *str = ll_calloc<char>(_fun, L, LL_STRBUFF); Box *box = ll_check_Box(_fun, L, 1); luaL_Buffer B; l_int32 x, y, w, h; luaL_buffinit(L, &B); if (!box) { luaL_addstring(&B, "nil"); } else { snprintf(str, LL_STRBUFF, TNAME "*: %p", reinterpret_cast<void *>(box)); luaL_addstring(&B, str); if (boxGetGeometry(box, &x, &y, &w, &h)) { snprintf(str, LL_STRBUFF, "\n invalid"); } else { snprintf(str, LL_STRBUFF, "\n %s = %d, %s = %d, %s = %d, %s = %d, %s = %d", "x", x, "y", y, "w", w, "h", h, "area", w * h); } luaL_addstring(&B, str); } luaL_pushresult(&B); ll_free(str); return 1; } /** * \brief Test equality of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int Equal(lua_State *L) { LL_FUNC("Equal"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 same = FALSE; if (boxEqual(box1, box2, &same)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, same); } /** * \brief Adjust sides of a Box* (%boxs). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxd). * Arg #2 (i.e. self) is expected to be a Box* (boxs). * Arg #3 is expected to be a l_int32 (delleft). * Arg #4 is expected to be a l_int32 (delright). * Arg #5 is expected to be a l_int32 (deltop). * Arg #6 is expected to be a l_int32 (delbot). * * Leptonica's Notes: * (1) Set boxd == NULL to get new box; boxd == boxs for in-place; * or otherwise to resize existing boxd. * (2) For usage, suggest one of these: * boxd = boxAdjustSides(NULL, boxs, ...); // new * boxAdjustSides(boxs, boxs, ...); // in-place * boxAdjustSides(boxd, boxs, ...); // other * (3) New box dimensions are cropped at left and top to x >= 0 and y >= 0. * (4) For example, to expand in-place by 20 pixels on each side, use * boxAdjustSides(box, box, -20, 20, -20, 20); * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int AdjustSides(lua_State *L) { LL_FUNC("AdjustSides"); Box *boxd = ll_opt_Box(_fun, L, 1); Box *boxs = ll_check_Box(_fun, L, 2); l_int32 delleft = ll_opt_l_int32(_fun, L, 3, 0); l_int32 delright = ll_opt_l_int32(_fun, L, 4, 0); l_int32 deltop = ll_opt_l_int32(_fun, L, 5, 0); l_int32 delbot = ll_opt_l_int32(_fun, L, 6, 0); Box *box = boxAdjustSides(boxd, boxs, delleft, delright, deltop, delbot); ll_push_Box(_fun, L, box); return 1; } /** * \brief Get the bounding region of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * * Leptonica's Notes: * (1) This is the geometric union of the two rectangles. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int BoundingRegion(lua_State *L) { LL_FUNC("BoundingRegion"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); Box *box = boxBoundingRegion(box1, box2); ll_push_Box(_fun, L, box); return 1; } /** * \brief Change the Box* reference count. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 (i.e. self) is expected to be a l_int32 (delta). * </pre> * \param L Lua state. * \return 1 boolean on the stack. */ static int ChangeRefcount(lua_State *L) { LL_FUNC("ChangeRefcount"); Box *box = ll_check_Box(_fun, L, 1); l_int32 delta = ll_check_l_int32(_fun, L, 2); return ll_push_boolean(_fun, L, 0 == boxChangeRefcount(box, delta)); } /** * \brief Clip a Box* (%boxs) rectangle to width and height (%wi, %hi). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 is expected to be a l_int32 (wi). * Arg #3 is expected to be a l_int32 (hi). * * Leptonica's Notes: * (1) This can be used to clip a rectangle to an image. * The clipping rectangle is assumed to have a UL corner at (0, 0), * and a LR corner at (wi - 1, hi - 1). * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int ClipToRectangle(lua_State *L) { LL_FUNC("ClipToRectangle"); Box *boxs = ll_check_Box(_fun, L, 1); l_int32 wi = ll_check_l_int32(_fun, L, 2); l_int32 hi = ll_check_l_int32(_fun, L, 3); Box *box = boxClipToRectangle(boxs, wi, hi); return ll_push_Box(_fun, L, box); } /** * \brief Clip a Box* (%boxs) rectangle to width and height (w,h). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * * Leptonica's Notes: * (1) The return value should be checked. If it is 1, the * returned parameter values are bogus. * (2) This simplifies the selection of pixel locations within * a given rectangle: * for (i = ystart; i < yend; i++ { * ... * for (j = xstart; j < xend; j++ { * .... * </pre> * \param L Lua state. * \return 6 integers on the Lua stack (%xstart, %ystart, %xend, %yend, %bw, %bh). */ static int ClipToRectangleParams(lua_State *L) { LL_FUNC("ClipToRectangleParams"); Box *boxs = ll_check_Box(_fun, L, 1); l_int32 w = ll_check_l_int32(_fun, L, 2); l_int32 h = ll_check_l_int32(_fun, L, 3); l_int32 xstart = 0; l_int32 ystart = 0; l_int32 xend = 0; l_int32 yend = 0; l_int32 bw = 0; l_int32 bh = 0; if (boxClipToRectangleParams(boxs, w, h, &xstart, &ystart, &xend, &yend, &bw, &bh)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, xstart); ll_push_l_int32(_fun, L, ystart); ll_push_l_int32(_fun, L, xend); ll_push_l_int32(_fun, L, yend); ll_push_l_int32(_fun, L, bw); ll_push_l_int32(_fun, L, bh); return 6; } /** * \brief Clone a Box* (%boxs). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int Clone(lua_State *L) { LL_FUNC("Clone"); Box *boxs = ll_check_Box(_fun, L, 1); Box *box = boxClone(boxs); return ll_push_Box(_fun, L, box); } /** * \brief Compare the size of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * Arg #3 is expected to be a string describing the type of comparison (type). * * Leptonica's Notes: * (1) We're re-using the SORT enum for these comparisons. * </pre> * \param L Lua state. * \return 1 string on the Lua stack. */ static int CompareSize(lua_State *L) { LL_FUNC("CompareSize"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 type = ll_check_sort_by(_fun, L, 3, L_SORT_BY_WIDTH); l_int32 rel = 0; if (boxCompareSize(box1, box2, type, &rel)) return ll_push_nil(_fun, L); ll_push_string(_fun, L, ll_string_relation(rel)); return 1; } /** * \brief Check if a Box* (%box1) contains another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int Contains(lua_State *L) { LL_FUNC("Contains"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 contains = 0; if (boxContains(box1, box2, &contains)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, contains); } /** * \brief Check if a Box* (%box) contains a point (%x, %y). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * Arg #2 is expected to be a l_float32 (x). * Arg #3 is expected to be a l_float32 (y). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int ContainsPt(lua_State *L) { LL_FUNC("ContainsPt"); Box *box = ll_check_Box(_fun, L, 1); l_float32 x = ll_check_l_float32(_fun, L, 2); l_float32 y = ll_check_l_float32(_fun, L, 3); l_int32 contains = FALSE; if (boxContainsPt(box, x, y, &contains)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, contains); } /** * \brief Convert corners (%ncorners) of a Box* (%box) to a Pta* (%pta). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * Arg #2 is expected to be a l_int32 (ncorners). * * Leptonica's Notes: * (1) If ncorners == 2, we select the UL and LR corners. * Otherwise we save all 4 corners in this order: UL, UR, LL, LR. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int ConvertToPta(lua_State *L) { LL_FUNC("ConvertToPta"); Box *box = ll_check_Box(_fun, L, 1); l_int32 ncorners = ll_check_l_int32(_fun, L, 2); Pta *pta = boxConvertToPta(box, ncorners); return ll_push_Pta(_fun, L, pta); } /** * \brief Copy a Box* (%boxs). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int Copy(lua_State *L) { LL_FUNC("Copy"); Box *boxs = ll_check_Box(_fun, L, 1); Box *box = boxCopy(boxs); return ll_push_Box(_fun, L, box); } /** * \brief Create a new Box*. * <pre> * Arg #1 is expected to be a l_int32 (x). * Arg #2 is expected to be a l_int32 (y). * Arg #3 is expected to be a l_int32 (w). * Arg #4 is expected to be a l_int32 (h). * * Leptonica's Notes: * (1) This clips the box to the +quad. If no part of the * box is in the +quad, this returns NULL. * (2) We allow you to make a box with w = 0 and/or h = 0. * This does not represent a valid region, but it is useful * as a placeholder in a boxa for which the index of the * box in the boxa is important. This is an atypical * situation; usually you want to put only valid boxes with * nonzero width and height in a boxa. If you have a boxa * with invalid boxes, the accessor boxaGetValidBox() * will return NULL on each invalid box. * (3) If you want to create only valid boxes, use boxCreateValid(), * which returns NULL if either w or h is 0. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int Create(lua_State *L) { LL_FUNC("Create"); l_int32 x = ll_opt_l_int32(_fun, L, 1, 0); l_int32 y = ll_opt_l_int32(_fun, L, 2, 0); l_int32 w = ll_opt_l_int32(_fun, L, 3, 1); l_int32 h = ll_opt_l_int32(_fun, L, 4, 1); Box *box = boxCreate(x, y, w, h); return ll_push_Box(_fun, L, box); } /** * \brief Create a new Box* (%box) if the parameters are valid. * <pre> * Arg #1 is expected to be a l_int32 (x). * Arg #2 is expected to be a l_int32 (y). * Arg #3 is expected to be a l_int32 (w). * Arg #4 is expected to be a l_int32 (h). * * Leptonica's Notes: * (1) This returns NULL if either w = 0 or h = 0. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int CreateValid(lua_State *L) { LL_FUNC("CreateValid"); l_int32 x, y, w, h; Box *box; x = ll_opt_l_int32(_fun, L, 1, 0); y = ll_opt_l_int32(_fun, L, 2, 0); w = ll_opt_l_int32(_fun, L, 3, 1); h = ll_opt_l_int32(_fun, L, 4, 1); box = boxCreateValid(x, y, w, h); return ll_push_Box(_fun, L, box); } /** * \brief Get the center of a Box* (%box). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * </pre> * \param L Lua state. * \return 2 numbers on the Lua stack (%cx, %cy). */ static int GetCenter(lua_State *L) { LL_FUNC("GetCenter"); Box *box = ll_check_Box(_fun, L, 1); l_float32 cx = 0.0f; l_float32 cy = 0.0f; if (boxGetCenter(box, &cx, &cy)) return ll_push_nil(_fun, L); ll_push_l_float32(_fun, L, cx); ll_push_l_float32(_fun, L, cy); return 2; } /** * \brief Get the Box* geometry. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * </pre> * \param L Lua state. * \return 4 for four integers (or nil on error) on the stack. */ static int GetGeometry(lua_State *L) { LL_FUNC("GetGeometry"); Box *box = ll_check_Box(_fun, L, 1); l_int32 x, y, w, h; if (boxGetGeometry(box, &x, &y, &w, &h)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, x); ll_push_l_int32(_fun, L, y); ll_push_l_int32(_fun, L, w); ll_push_l_int32(_fun, L, h); return 4; } /** * \brief Get the Box* reference count. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * </pre> * \param L Lua state. * \return 1 integers (or nil on error) on the stack. */ static int GetRefcount(lua_State *L) { LL_FUNC("GetRefcount"); Box *box = ll_check_Box(_fun, L, 1); ll_push_l_int32(_fun, L, boxGetRefcount(box)); return 1; } /** * \brief Get the BOX side locations (left, right, top, bottom). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * * Leptonica's Notes: * (1) All returned values are within the box. * </pre> * \param L Lua state. * \return 4 for four integers (or nil on error) on the stack. */ static int GetSideLocations(lua_State *L) { LL_FUNC("GetSideLocations"); Box *box = ll_check_Box(_fun, L, 1); l_int32 l, r, t, b; if (boxGetSideLocations(box, &l, &r, &t, &b)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, l); ll_push_l_int32(_fun, L, r); ll_push_l_int32(_fun, L, t); ll_push_l_int32(_fun, L, b); return 4; } /** * \brief Intersect a Box* (%box) by a line (%x, %y). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * Arg #2 is expected to be a l_int32 (x). * Arg #3 is expected to be a l_int32 (y). * Arg #4 is expected to be a l_float32 (slope). * * Leptonica's Notes: * (1) If the intersection is at only one point (a corner), the * coordinates are returned in (x1, y1). * (2) Represent a vertical line by one with a large but finite slope. * </pre> * \param L Lua state. * \return 5 integers on the Lua stack (%x1, %y1, %x2, %y2, %n). */ static int IntersectByLine(lua_State *L) { LL_FUNC("IntersectByLine"); Box *box = ll_check_Box(_fun, L, 1); l_int32 x = ll_check_l_int32(_fun, L, 2); l_int32 y = ll_check_l_int32(_fun, L, 3); l_float32 slope = ll_check_l_float32(_fun, L, 4); l_int32 x1 = 0; l_int32 y1 = 0; l_int32 x2 = 0; l_int32 y2 = 0; l_int32 n = 0; if (boxIntersectByLine(box, x, y, slope, &x1, &y1, &x2, &y2, &n)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, x1); ll_push_l_int32(_fun, L, y1); ll_push_l_int32(_fun, L, x2); ll_push_l_int32(_fun, L, y2); ll_push_l_int32(_fun, L, n); return 5; } /** * \brief Check if a Box* (%box1) intersects another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int Intersects(lua_State *L) { LL_FUNC("Intersects"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 intersects = 0; if (boxIntersects(box1, box2, &intersects)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, intersects); } /** * \brief Check if a Box* is valid. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int IsValid(lua_State *L) { LL_FUNC("IsValid"); Box *box = ll_check_Box(_fun, L, 1); l_int32 valid = 0; if (boxIsValid(box, &valid)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, valid); } /** * \brief Get the overlap area of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * </pre> * \param L Lua state. * \return 1 integer on the Lua stack. */ static int OverlapArea(lua_State *L) { LL_FUNC("OverlapArea"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 area = 0.0f; if (boxOverlapArea(box1, box2, &area)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, area); return 1; } /** * \brief Get the overlap fraction of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * * Leptonica's Notes: * (1) The result depends on the order of the input boxes, * because the overlap is taken as a fraction of box2. * </pre> * \param L Lua state. * \return 1 number on the Lua stack. */ static int OverlapFraction(lua_State *L) { LL_FUNC("OverlapFraction"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_float32 fract = 0.0f; if (boxOverlapFraction(box1, box2, &fract)) return ll_push_nil(_fun, L); return ll_push_l_float32(_fun, L, fract); } /** * \brief Get the overlap region of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * * Leptonica's Notes: * (1) This is the geometric intersection of the two rectangles. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int OverlapRegion(lua_State *L) { LL_FUNC("OverlapRegion"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); Box *box = boxOverlapRegion(box1, box2); ll_push_Box(_fun, L, box); return 1; } /** * \brief Print info about a Box* (%box) to a Lua stream (%stream). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * Arg #2 is expected to be a luaL_Stream io handle (stream). * * Leptonica's Notes: * (1) This outputs debug info. Use serialization functions to * write to file if you want to read the data back. * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int PrintStreamInfo(lua_State *L) { LL_FUNC("PrintStreamInfo"); Box *box = ll_check_Box(_fun, L, 1); luaL_Stream *stream = ll_check_stream(_fun, L, 2); return ll_push_boolean(_fun, L, 0 == boxPrintStreamInfo(stream->f, box)); } /** * \brief Relocate one side of a Box* (%boxs). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * * Leptonica's Notes: * (1) Set boxd == NULL to get new box; boxd == boxs for in-place; * or otherwise to resize existing boxd. * (2) For usage, suggest one of these: * boxd = boxRelocateOneSide(NULL, boxs, ...); // new * boxRelocateOneSide(boxs, boxs, ...); // in-place * boxRelocateOneSide(boxd, boxs, ...); // other * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int RelocateOneSide(lua_State *L) { LL_FUNC("RelocateOneSide"); Box *boxs = ll_check_Box(_fun, L, 1); l_int32 loc = ll_check_l_int32(_fun, L, 2); l_int32 sideflag = ll_check_from_side(_fun, L, 3, L_FROM_LEFT); Box *boxd = boxRelocateOneSide(nullptr, boxs, loc, sideflag); ll_push_Box(_fun, L, boxd); return 1; } /** * \brief Rotate a Box* (%boxs) orthogonally. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 is expected to be a l_int32 (w). * Arg #3 is expected to be a l_int32 (h). * Arg #4 is expected to be a rotation angle (rotation). * * Leptonica's Notes: * (1) Rotate the image with the embedded box by the specified amount. * (2) After rotation, the rotated box is always measured with * respect to the UL corner of the image. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int RotateOrth(lua_State *L) { LL_FUNC("RotateOrth"); Box *boxs = ll_check_Box(_fun, L, 1); l_int32 w = ll_check_l_int32(_fun, L, 2); l_int32 h = ll_check_l_int32(_fun, L, 3); l_int32 rotation = ll_check_rotation(_fun, L, 4, 0); Box *box = boxRotateOrth(boxs, w, h, rotation); return ll_push_Box(_fun, L, box); } /** * \brief Get the separation distances of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * * Leptonica's Notes: * (1) This measures horizontal and vertical separation of the * two boxes. If the boxes are touching but have no pixels * in common, the separation is 0. If the boxes overlap by * a distance d, the returned separation is -d. * </pre> * \param L Lua state. * \return 2 integers on the Lua stack. */ static int SeparationDistance(lua_State *L) { LL_FUNC("SeparationDistance"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 h_sep = 0; l_int32 v_sep = 0; if (boxSeparationDistance(box1, box2, &h_sep, &v_sep)) return ll_push_nil(_fun, L); ll_push_l_int32(_fun, L, h_sep); ll_push_l_int32(_fun, L, v_sep); return 2; } /** * \brief Set the Box* (%box) geometry. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 is expected to be a lua_Integer (x). * Arg #3 is expected to be a lua_Integer (y). * Arg #4 is expected to be a lua_Integer (w). * Arg #5 is expected to be a lua_Integer (h). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int SetGeometry(lua_State *L) { LL_FUNC("SetGeometry"); Box *box = ll_check_Box(_fun, L, 1); l_int32 x = ll_opt_l_int32(_fun, L, 2, 0); l_int32 y = ll_opt_l_int32(_fun, L, 3, 0); l_int32 w = ll_opt_l_int32(_fun, L, 4, 1); l_int32 h = ll_opt_l_int32(_fun, L, 5, 1); return ll_push_boolean(_fun, L, 0 == boxSetGeometry(box, x, y, w, h)); } /** * \brief Set the Box* (%box) side locations (%l, %r, %t, %b). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box). * Arg #2 is expected to be a lua_Integer (l). * Arg #3 is expected to be a lua_Integer (r). * Arg #4 is expected to be a lua_Integer (t). * Arg #5 is expected to be a lua_Integer (b). * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int SetSideLocations(lua_State *L) { LL_FUNC("SetSideLocations"); Box *box = ll_check_Box(_fun, L, 1); l_int32 l = ll_opt_l_int32(_fun, L, 2, 0); l_int32 r = ll_opt_l_int32(_fun, L, 3, 0); l_int32 t = ll_opt_l_int32(_fun, L, 4, 0); l_int32 b = ll_opt_l_int32(_fun, L, 5, 0); return ll_push_boolean(_fun, L, 0 == boxSetSideLocations(box, l, r, t, b)); } /** * \brief Test similarity of a Box* (%box1) and another Box* (%box2). * <pre> * Arg #1 (i.e. self) is expected to be a Box* (box1). * Arg #2 is expected to be another Box* (box2). * Arg #3 is expected to be a l_int32 (leftdiff). * Arg #4 is expected to be a l_int32 (rightdiff). * Arg #5 is expected to be a l_int32 (topdiff). * Arg #6 is expected to be a l_int32 (botdiff). * * Leptonica's Notes: * (1) The values of leftdiff (etc) are the maximum allowed deviations * between the locations of the left (etc) sides. If any side * pairs differ by more than this amount, the boxes are not similar. * </pre> * \param L Lua state. * \return 1 boolean on the Lua stack. */ static int Similar(lua_State *L) { LL_FUNC("Similar"); Box *box1 = ll_check_Box(_fun, L, 1); Box *box2 = ll_check_Box(_fun, L, 2); l_int32 leftdiff = ll_check_l_int32(_fun, L, 3); l_int32 rightdiff = ll_opt_l_int32(_fun, L, 4, leftdiff); l_int32 topdiff = ll_opt_l_int32(_fun, L, 5, rightdiff); l_int32 botdiff = ll_opt_l_int32(_fun, L, 6, topdiff); l_int32 similar = FALSE; if (boxSimilar(box1, box2, leftdiff, rightdiff, topdiff, botdiff, &similar)) return ll_push_nil(_fun, L); return ll_push_boolean(_fun, L, similar); } /** * \brief Transform a Box* (%boxs) by shifting and scaling. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 is expected to be a l_int32 (shiftx). * Arg #3 is expected to be a l_int32 (shifty). * Arg #4 is an optional l_float32 (scalex). * Arg #5 is an optional l_float32 (scaley). * * Leptonica's Notes: * (1) This is a very simple function that first shifts, then scales. * (2) If the box is invalid, a new invalid box is returned. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int Transform(lua_State *L) { LL_FUNC("Transform"); Box *boxs = ll_check_Box(_fun, L, 1); l_int32 shiftx = ll_check_l_int32(_fun, L, 2); l_int32 shifty = ll_check_l_int32(_fun, L, 3); l_float32 scalex = ll_opt_l_float32(_fun, L, 4, 1.0f); l_float32 scaley = ll_opt_l_float32(_fun, L, 5, 1.0f); Box *box = boxTransform(boxs, shiftx, shifty, scalex, scaley); ll_push_Box(_fun, L, box); return 1; } /** * \brief Ordered transform a Box* (%boxs) by shifting, scaling, and rotation.. * <pre> * Arg #1 (i.e. self) is expected to be a Box* (boxs). * Arg #2 is an optional l_int32 (shiftx). * Arg #3 is an optional l_int32 (shifty). * Arg #4 is an optional l_float32 (scalex). * Arg #5 is an optional l_float32 (scaley). * Arg #6 is an optional l_int32 (xcen). * Arg #7 is an optional l_int32 (ycen). * Arg #8 is an optional l_float32 (angle). * Arg #9 is an optional string describing the transform order (order). * * Leptonica's Notes: * (1) This allows a sequence of linear transforms, composed of * shift, scaling and rotation, where the order of the * transforms is specified. * (2) The rotation is taken about a point specified by (xcen, ycen). * Let the components of the vector from the center of rotation * to the box center be (xdif, ydif): * xdif = (bx + 0.5 * bw) - xcen * ydif = (by + 0.5 * bh) - ycen * Then the box center after rotation has new components: * bxcen = xcen + xdif * cosa + ydif * sina * bycen = ycen + ydif * cosa - xdif * sina * where cosa and sina are the cos and sin of the angle, * and the enclosing box for the rotated box has size: * rw = |bw * cosa| + |bh * sina| * rh = |bh * cosa| + |bw * sina| * where bw and bh are the unrotated width and height. * Then the box UL corner (rx, ry) is * rx = bxcen - 0.5 * rw * ry = bycen - 0.5 * rh * (3) The center of rotation specified by args %xcen and %ycen * is the point BEFORE any translation or scaling. If the * rotation is not the first operation, this function finds * the actual center at the time of rotation. It does this * by making the following assumptions: * (1) Any scaling is with respect to the UL corner, so * that the center location scales accordingly. * (2) A translation does not affect the center of * the image; it just moves the boxes. * We always use assumption (1). However, assumption (2) * will be incorrect if the apparent translation is due * to a clipping operation that, in effect, moves the * origin of the image. In that case, you should NOT use * these simple functions. Instead, use the functions * in affinecompose.c, where the rotation center can be * computed from the actual clipping due to translation * of the image origin. * </pre> * \param L Lua state. * \return 1 Box* on the Lua stack. */ static int TransformOrdered(lua_State *L) { LL_FUNC("TransformOrdered"); Box *boxs = ll_check_Box(_fun, L, 1); l_float32 xc, yc; l_int32 ok = boxGetCenter(boxs, &xc, &yc); l_int32 shiftx = ll_opt_l_int32(_fun, L, 2, 0); l_int32 shifty = ll_opt_l_int32(_fun, L, 3, 0); l_float32 scalex = ll_opt_l_float32(_fun, L, 4, 1.0f); l_float32 scaley = ll_opt_l_float32(_fun, L, 5, 1.0f); l_int32 xcen = ll_opt_l_int32(_fun, L, 6, ok ? static_cast<l_int32>(xc) : 0); l_int32 ycen = ll_opt_l_int32(_fun, L, 7, ok ? static_cast<l_int32>(yc) : 0); l_float32 angle = ll_opt_l_float32(_fun, L, 8, 0.0f); l_int32 order = ll_check_trans_order(_fun, L, 9, L_TR_SC_RO); Box *box = boxTransformOrdered(boxs, shiftx, shifty, scalex, scaley, xcen, ycen, angle, order); return ll_push_Box(_fun, L, box); } /** * \brief Check Lua stack at index %arg for user data of class Box*. * \param _fun calling function's name * \param L Lua state. * \param arg index where to find the user data (usually 1) * \return pointer to the Box* contained in the user data. */ Box * ll_check_Box(const char *_fun, lua_State *L, int arg) { return *ll_check_udata<Box>(_fun, L, arg, TNAME); } /** * \brief Optionally expect a Box* at index %arg on the Lua stack. * \param _fun calling function's name * \param L Lua state. * \param arg index where to find the user data (usually 1) * \return pointer to the Box* contained in the user data. */ Box * ll_opt_Box(const char *_fun, lua_State *L, int arg) { if (!ll_isudata(_fun, L, arg, TNAME)) return nullptr; return ll_check_Box(_fun, L, arg); } /** * \brief Push Box* user data to the Lua stack and set its meta table. * \param _fun calling function's name * \param L Lua state. * \param box pointer to the BOX * \return 1 Box* on the Lua stack. */ int ll_push_Box(const char *_fun, lua_State *L, Box *box) { if (!box) return ll_push_nil(_fun, L); return ll_push_udata(_fun, L, TNAME, box); } /** * \brief Create and push a new Box*. * \param L Lua state. * \return 1 Box* on the Lua stack. */ int ll_new_Box(lua_State *L) { FUNC("ll_new_Box"); Box *box = nullptr; l_int32 x = 0, y = 0, w = 0, h = 0; if (ll_isudata(_fun, L, 1, LL_BOX)) { Box *boxs = ll_opt_Box(_fun, L, 1); DBG(LOG_NEW_PARAM, "%s: create for %s* = %p\n", _fun, TNAME, reinterpret_cast<void *>(boxs)); box = boxCopy(boxs); } if (!box && ll_isinteger(_fun, L, 1)) { x = ll_opt_l_int32(_fun, L, 1, 0); y = ll_opt_l_int32(_fun, L, 2, 0); w = ll_opt_l_int32(_fun, L, 3, 1); h = ll_opt_l_int32(_fun, L, 4, 1); DBG(LOG_NEW_PARAM, "%s: create for %s = %d, %s = %d, %s = %d, %s = %d\n", _fun, "x", x, "y", y, "w", w, "h", h); box = boxCreate(x, y, w, h); } if (!box) { x = y = w = h = 0; DBG(LOG_NEW_PARAM, "%s: create for %s = %d, %s = %d, %s = %d, %s = %d\n", _fun, "x", x, "y", y, "w", w, "h", h); box = boxCreate(x, y, w, h); } DBG(LOG_NEW_CLASS, "%s: created %s* %p\n", _fun, TNAME, reinterpret_cast<void *>(box)); return ll_push_Box(_fun, L, box); } /** * \brief Register the Box* methods and functions in the Box meta table. * \param L Lua state. * \return 1 table on the Lua stack. */ int ll_open_Box(lua_State *L) { static const luaL_Reg methods[] = { {"__gc", Destroy}, {"__new", ll_new_Box}, {"__tostring", toString}, {"__eq", Equal}, {"__band", OverlapRegion}, /* box = box1 & box2 */ {"__bor", BoundingRegion}, /* box = box1 | box2 */ {"AdjustSides", AdjustSides}, {"BoundingRegion", BoundingRegion}, {"ChangeRefcount", ChangeRefcount}, {"ClipToRectangle", ClipToRectangle}, {"ClipToRectangleParams", ClipToRectangleParams}, {"Clone", Clone}, {"CompareSize", CompareSize}, {"Contains", Contains}, {"ContainsPt", ContainsPt}, {"ConvertToPta", ConvertToPta}, {"Copy", Copy}, {"Create", Create}, {"CreateValid", CreateValid}, {"Destroy", Destroy}, {"Equal", Equal}, {"GetCenter", GetCenter}, {"GetGeometry", GetGeometry}, {"GetRefcount", GetRefcount}, {"GetSideLocations", GetSideLocations}, {"IntersectByLine", IntersectByLine}, {"Intersects", Intersects}, {"IsValid", IsValid}, {"OverlapArea", OverlapArea}, {"OverlapFraction", OverlapFraction}, {"OverlapRegion", OverlapRegion}, {"PrintStreamInfo", PrintStreamInfo}, {"RelocateOneSide", RelocateOneSide}, {"RotateOrth", RotateOrth}, {"SeparationDistance", SeparationDistance}, {"SetGeometry", SetGeometry}, {"SetSideLocations", SetSideLocations}, {"Similar", Similar}, {"Transform", Transform}, {"TransformOrdered", TransformOrdered}, LUA_SENTINEL }; LO_FUNC(TNAME); ll_set_global_cfunct(_fun, L, TNAME, ll_new_Box); ll_register_class(_fun, L, TNAME, methods); return 1; }
31.947368
99
0.602663
pullmoll
755df6c09e2897a81c198066f2d04534be599859
464
hpp
C++
src/xpcc/communication/ros.hpp
roboterclubaachen/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
161
2015-01-13T15:52:06.000Z
2020-02-13T01:26:04.000Z
src/xpcc/communication/ros.hpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
281
2015-01-06T12:46:40.000Z
2019-01-06T13:06:57.000Z
src/xpcc/communication/ros.hpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
51
2015-03-03T19:56:12.000Z
2020-03-22T02:13:36.000Z
// coding: utf-8 /* Copyright (c) 2017, Sascha Schade (strongly-typed) * All Rights Reserved. * * The file is part of the xpcc library and is released under the 3-clause BSD * license. See the file `LICENSE` for the full license governing this code. */ // ---------------------------------------------------------------------------- /** * @ingroup communication * @defgroup ros_comm ROS communication (rosserial) */ #include "ros/ros_xpcc_hardware.hpp"
29
79
0.592672
roboterclubaachen
755e6cbfc63ea35c5b2feac071c653d0304a3916
1,685
cpp
C++
Year2/S1/DataStructureClass/1/magic.cpp
Avvco/myRepository
ae369c9a8161f6bef3c19fd00ee4b04e186a8bcc
[ "BSD-3-Clause" ]
null
null
null
Year2/S1/DataStructureClass/1/magic.cpp
Avvco/myRepository
ae369c9a8161f6bef3c19fd00ee4b04e186a8bcc
[ "BSD-3-Clause" ]
null
null
null
Year2/S1/DataStructureClass/1/magic.cpp
Avvco/myRepository
ae369c9a8161f6bef3c19fd00ee4b04e186a8bcc
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void magic (int n) // create a magic square of size n, n is odd { const int MaxSize = 51; // maximum square size int square[MaxSize][MaxSize], k, l; // check correctness of n if ((n > MaxSize) || (n < 1)) {cerr << "Error!..n out of range \n"; return;} else if (!(n%2)) {cerr << "Error!..n is even \n"; return;} // n is odd. Coxeter's rule can be used for (int i = 0; i < n; i++) // initialize square to 0 for (int j = 0; j < n; j++) square[i][j] = 0; square[0][(n-1)/2] = 1; // middle of first row // i and j are current position int key = 2; int i = 0; int j = (n-1)/2; while (key <= n*n) { // move up and left if (i-1 < 0) k = n-1; else k = i-1; if (j-1 < 0) l = n-1; else l = j-1; if (square[k][l]) i = (i+1)%n; else { // square[k][l] is unoccupied i = k; j = l; } square[i][j] = key; key++; } // end of while // output the magic square //cout << "magic square of size " << n << endl; for ( i = 0; i < n; i++) { for ( j = 0; j < n; j++) cout << square[i][j] << " "; cout << endl; } } int main() { int times = 50; int n; cout << "Input an odd number > 0" << endl; cin >> n; clock_t start, end; start = clock(); for (int i = 0; i < times; i++) { magic(n); } magic(n); end = clock(); double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << endl << endl; cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; cout << "Average Time taken by program is : " << fixed << time_taken / times << setprecision(5); cout << " sec " << endl; }
25.923077
98
0.523442
Avvco
7561fb5f651de22dd8052cf17263ddc627770736
1,404
hpp
C++
code/editors/xrWeatherEditor/property_editor_color.hpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/editors/xrWeatherEditor/property_editor_color.hpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/editors/xrWeatherEditor/property_editor_color.hpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
//////////////////////////////////////////////////////////////////////////// // Module : property_editor_color.hpp // Created : 12.12.2007 // Modified : 12.12.2007 // Author : Dmitriy Iassenev // Description : property editor color class //////////////////////////////////////////////////////////////////////////// #ifndef PROPERTY_EDITOR_COLOR_HPP_INCLUDED #define PROPERTY_EDITOR_COLOR_HPP_INCLUDED public ref class property_editor_color : public System::Drawing::Design::UITypeEditor { private: typedef System::Drawing::Design::UITypeEditor inherited; typedef System::ComponentModel::ITypeDescriptorContext ITypeDescriptorContext; typedef System::Drawing::Design::PaintValueEventArgs PaintValueEventArgs; public: virtual bool GetPaintValueSupported (ITypeDescriptorContext^ context) override; virtual void PaintValue (PaintValueEventArgs^ arguments) override; public: typedef System::Drawing::Design::UITypeEditorEditStyle UITypeEditorEditStyle; typedef System::IServiceProvider IServiceProvider; typedef System::Object Object; virtual UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext^ context) override; virtual Object^ EditValue ( ITypeDescriptorContext^ context, IServiceProvider^ provider, Object^ value ) override; }; // ref class property_editor_color #endif // ifndef PROPERTY_EDITOR_COLOR_HPP_INCLUDED
40.114286
87
0.698006
Rikoshet-234
7563163af8aa1eb81c91b01fbda4c734f33d5f9b
5,114
cpp
C++
src/MyMeshFactory.cpp
nicholaschiasson/N3DIL
5b598b340c4850cb06f92194f48aa10c76a578aa
[ "MIT" ]
null
null
null
src/MyMeshFactory.cpp
nicholaschiasson/N3DIL
5b598b340c4850cb06f92194f48aa10c76a578aa
[ "MIT" ]
5
2015-10-19T03:35:56.000Z
2015-11-03T22:19:26.000Z
src/MyMeshFactory.cpp
nicholaschiasson/N3DIL
5b598b340c4850cb06f92194f48aa10c76a578aa
[ "MIT" ]
null
null
null
#include "MyMeshFactory.h" #include "MyIncludes.h" #include "MyShaderManager.h" #include <GL/glew.h> #include <vector> std::map<const char *, MyIndexedVertexArray *> *MyMeshFactory::meshes = new std::map<const char *, MyIndexedVertexArray *>(); MyIndexedVertexArray * MyMeshFactory::CreateQuad(const char * meshName, MyColorRGBA color1, MyColorRGBA color2, MyColorRGBA color3, MyColorRGBA color4) { if (meshes->find(meshName) != meshes->end()) { return 0; } MyVertex4D *vertices = new MyVertex4D[6](); MyVector3D normal = MyVector3D(0.0f, 0.0f, 1.0f); MyVertex4D v1 = MyVertex4D(-0.5f, -0.5f, 0.0f, 1.0f, color1); MyVertex4D v2 = MyVertex4D(0.5f, -0.5f, 0.0f, 1.0f, color2); MyVertex4D v3 = MyVertex4D(0.5f, 0.5f, 0.0f, 1.0f, color3); MyVertex4D v4 = MyVertex4D(-0.5f, 0.5f, 0.0f, 1.0f, color4); v1.SetNormal(normal); v2.SetNormal(normal); v3.SetNormal(normal); v4.SetNormal(normal); vertices[0] = v1; vertices[1] = v2; vertices[2] = v3; vertices[3] = v1; vertices[4] = v3; vertices[5] = v4; (*meshes)[meshName] = new MyIndexedVertexArray(vertices, 6); (*meshes)[meshName]->Initialize(); return (*meshes)[meshName]; } MyIndexedVertexArray * MyMeshFactory::CreateSphere(const char *meshName, int latitudeSamples, int longitudeSamples, MyColorRGBA color1, MyColorRGBA color2) { if (meshes->find(meshName) != meshes->end()) { return 0; } MyVertex4D *v = new MyVertex4D[latitudeSamples * longitudeSamples](); MyVertex4D *vertices = new MyVertex4D[6 * (latitudeSamples * longitudeSamples)](); float theta, phi; int k = 0; for (int i = 0; i < longitudeSamples; i++) { theta = (2 * MyMath::MY_PI_F) * i / (longitudeSamples - 1); for (int j = 0; j < latitudeSamples; j++) { phi = MyMath::MY_PI_F * j / (latitudeSamples - 1); MyVector3D normal = MyVector3D(-sin(theta) * sin(phi), cos(phi), cos(theta) * sin(phi)); float t = (float)j / latitudeSamples; MyColorRGBA color = MyColorRGBA(LerpF(color1.GetRed(), color2.GetRed(), t), LerpF(color1.GetGreen(), color2.GetGreen(), t), LerpF(color1.GetBlue(), color2.GetBlue(), t), LerpF(color1.GetAlpha(), color2.GetAlpha(), t)); MyVector4D position = normal * 0.5f; MyVertex4D vertex = MyVertex4D(position, color); vertex.SetNormal(normal); vertex.SetTextureCoord(1.0f - ((float)i / (float)longitudeSamples), (float)j / (float)latitudeSamples); v[k++] = vertex; } } k = 0; for (int i = 0; i < longitudeSamples; i++) { for (int j = 0; j < (latitudeSamples - 1); j++) { vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + j]; vertices[k++] = v[i * latitudeSamples + (j + 1)]; vertices[k++] = v[i * latitudeSamples + j]; vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + j]; vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + (j + 1)]; vertices[k++] = v[i * latitudeSamples + (j + 1)]; } } (*meshes)[meshName] = new MyIndexedVertexArray(vertices, 6 * (latitudeSamples * longitudeSamples)); (*meshes)[meshName]->Initialize(); MyDeleteArray(v); return (*meshes)[meshName]; } MyIndexedVertexArray * MyMeshFactory::CreateSphere(const char *meshName, MyColorRGBA solidColor, int latitudeSamples, int longitudeSamples) { if (meshes->find(meshName) != meshes->end()) { return 0; } MyVertex4D *v = new MyVertex4D[latitudeSamples * longitudeSamples](); MyVertex4D *vertices = new MyVertex4D[6 * (latitudeSamples * longitudeSamples)](); float theta, phi; int k = 0; for (int i = 0; i < longitudeSamples; i++) { theta = (2 * MyMath::MY_PI_F) * i / (longitudeSamples - 1); for (int j = 0; j < latitudeSamples; j++) { phi = MyMath::MY_PI_F * j / (latitudeSamples - 1); MyVector3D normal = MyVector3D(-sin(theta) * sin(phi), cos(phi), cos(theta) * sin(phi)); MyVector4D position = normal * 0.5f; MyVertex4D vertex = MyVertex4D(position, solidColor); vertex.SetNormal(normal); vertex.SetTextureCoord(1.0f - ((float)i / (float)longitudeSamples), (float)j / (float)latitudeSamples); v[k++] = vertex; } } k = 0; for (int i = 0; i < longitudeSamples; i++) { for (int j = 0; j < (latitudeSamples - 1); j++) { vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + j]; vertices[k++] = v[i * latitudeSamples + (j + 1)]; vertices[k++] = v[i * latitudeSamples + j]; vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + j]; vertices[k++] = v[((i + 1) % longitudeSamples) * latitudeSamples + (j + 1)]; vertices[k++] = v[i * latitudeSamples + (j + 1)]; } } (*meshes)[meshName] = new MyIndexedVertexArray(vertices, 6 * (latitudeSamples * longitudeSamples)); (*meshes)[meshName]->Initialize(); MyDeleteArray(v); return (*meshes)[meshName]; } MyIndexedVertexArray * MyMeshFactory::GetMesh(const char * meshName) { if (meshes->find(meshName) != meshes->end()) { return (*meshes)[meshName]; } return nullptr; } void MyMeshFactory::Cleanup() { for (std::map<const char *, MyIndexedVertexArray *>::iterator it = meshes->begin(); it != meshes->end(); ++it) { MyDelete(it->second); } meshes->clear(); MyDelete(meshes); }
30.440476
155
0.655847
nicholaschiasson
75651d4ca257edd91258e6281cbc0b49b6f8543c
718
cpp
C++
leetcode.com/Weekly Contest 217/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/Weekly Contest 217/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/Weekly Contest 217/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <bits/stdc++.h> using namespace std; static int x = []() { ios::sync_with_stdio(false); cin.tie(0); return 0; }(); typedef long long ll; int d[200100]; class Solution { public: int minMoves(vector<int>& nums, int limit) { memset(d, 0, sizeof(d)); int n = nums.size(); for (int i = 0; i < n / 2; ++i) { int l = 1 + min(nums[i], nums[n - i - 1]); int r = limit + max(nums[i], nums[n - i - 1]); int m = nums[i] + nums[n - i - 1]; d[l] += -1; d[r + 1] += 1; d[m] += -1; d[m + 1] += 1; } int res = n; int cur = n; for (int i = 2; i < limit * 2 + 2; ++i) { cur += d[i]; res = min(res, cur); } return res; } };
19.405405
52
0.456825
sky-bro
7566112585d82dcc28f739100d28e45b5eb655f6
659
cpp
C++
C++/scope/initializer/factor/Factor.cpp
fantaosha/SCOPE
30519b52822d04fb7b5bf6f45e73227ad4260738
[ "MIT" ]
26
2021-10-10T18:34:38.000Z
2022-03-03T03:00:40.000Z
C++/scope/initializer/factor/Factor.cpp
fantaosha/SCOPE
30519b52822d04fb7b5bf6f45e73227ad4260738
[ "MIT" ]
3
2021-12-24T07:28:11.000Z
2022-02-02T21:26:55.000Z
C++/scope/initializer/factor/Factor.cpp
fantaosha/SCOPE
30519b52822d04fb7b5bf6f45e73227ad4260738
[ "MIT" ]
7
2021-11-06T15:23:08.000Z
2022-02-28T03:40:03.000Z
#include <scope/initializer/factor/Factor.h> namespace scope { namespace Initializer { Factor::Evaluation::Evaluation() : status(Status::INVALID) {} int Factor::Evaluation::reset() { status = Status::INVALID; return 0; } int Factor::Evaluation::clear() { reset(); error.resize(0); return 0; } Factor::Linearization::Linearization() : status(Status::INVALID) {} int Factor::Linearization::reset() { status = Status::INVALID; return 0; } int Factor::Linearization::clear() { reset(); return 0; } Factor::Factor(const std::string &name, int index) : mIndex(index), mName(name) {} } // namespace Initializer } // namespace scope
16.897436
67
0.679818
fantaosha
7566b292f5f7309c950ee83a1a94b9ae354b8e38
709
cpp
C++
C++/CheckPalindrome.cpp
keshavgbpecdelhi/HacktoberFest-2021
0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8
[ "MIT" ]
7
2021-10-01T05:10:17.000Z
2021-10-30T07:19:27.000Z
C++/CheckPalindrome.cpp
keshavgbpecdelhi/HacktoberFest-2021
0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8
[ "MIT" ]
32
2021-10-01T06:08:04.000Z
2021-11-03T11:12:22.000Z
C++/CheckPalindrome.cpp
keshavgbpecdelhi/HacktoberFest-2021
0ac2ed4c575750bb5ceb79e0d1fc519d7e6054f8
[ "MIT" ]
20
2021-10-01T06:06:44.000Z
2021-10-31T05:31:49.000Z
#include <iostream> #include <cstring> using namespace std; #include <cstring> bool helper(char input[], int start, int end) { if (start >= end) { return true; } if (input[start] != input[end]) { return false; } bool smallcheck = helper(input, start + 1, end - 1); return smallcheck; } bool checkPalindrome(char input[]) { int len = strlen(input); int start = 0, end = len - 1; return helper(input, start + 1, end - 1); } int main() { char input[50]; cin >> input; if (checkPalindrome(input)) { cout << "true" << endl; } else { cout << "false" << endl; } }
17.292683
57
0.507757
keshavgbpecdelhi
7568d34b86c115cac9c3fc9bc91f05f92c81063a
9,568
cxx
C++
ltnc/compiler/LtncStmtCompiler.cxx
JeneLitsch/LitanCompiler
be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18
[ "MIT" ]
null
null
null
ltnc/compiler/LtncStmtCompiler.cxx
JeneLitsch/LitanCompiler
be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18
[ "MIT" ]
null
null
null
ltnc/compiler/LtncStmtCompiler.cxx
JeneLitsch/LitanCompiler
be11dfd6f1a31a41a3bda2d41b1bfaa5066c9f18
[ "MIT" ]
null
null
null
#include "LtncStmtCompiler.hxx" #include <iostream> std::string ltnc::StmtCompiler::compileProgram(CompilerPack & compPkg, std::shared_ptr<Program> program){ compPkg.getScopes().addFunctionScope(FxSignature(Type::VOI, "", {})); for(const auto & function : program->functions) { compPkg.registerFunction(function); } std::string code; code += "-> MAIN \n"; code += this->compileEval(compPkg, std::make_shared<StmtExpr>(std::make_shared<ExprCall>("main"))); code += "exit \n"; for(const auto & function : program->functions) { code += this->compileFunction(compPkg, function); } return code; } std::string ltnc::StmtCompiler::compileStmt(CompilerPack & compPkg, std::shared_ptr<Stmt> stmt){ if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtAssign>(stmt)) { return this->compileAssign(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtBlock>(stmt)) { return this->compileBlock(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtIf>(stmt)) { return this->compileIf(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtFor>(stmt)) { return this->compileFor(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtRepeat>(stmt)) { return this->compileRepeat(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtWhile>(stmt)) { return this->compileWhile(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtPrint>(stmt)) { return this->compilePrint(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtExpr>(stmt)) { return this->compileEval(compPkg, stmt_); } if(auto stmt_ = std::dynamic_pointer_cast<ltnc::StmtReturn>(stmt)) { return this->compileReturn(compPkg, stmt_); } return ""; } std::string ltnc::StmtCompiler::compilePrint(CompilerPack & compPkg, std::shared_ptr<StmtPrint> stmt) { auto expr = exprCompiler.compileExpr(compPkg, stmt->expr); switch (expr.type.type) { case Type::INT: return expr.code + "print\n"; case Type::FLT: return expr.code + "print 1\n"; default: throw std::runtime_error("[should never occur] Error while compiling print"); } } std::string ltnc::StmtCompiler::compileAssign(CompilerPack & compPkg, std::shared_ptr<StmtAssign> stmt){ auto expr = exprCompiler.compileExpr(compPkg, stmt->expr); Var var = compPkg.getScopes().get().getVar(stmt->name); if(expr.type != var.type) throw std::runtime_error("Types do not match: " + expr.code); return this->comment("assign to int var " + stmt->name) + expr.code + "store " + std::to_string(var.addr) + "\n"; } std::string ltnc::StmtCompiler::compileRepeat(CompilerPack & compPkg, std::shared_ptr<StmtRepeat> stmt) { // From and to expression ExprInfo expr = this->exprCompiler.compileExpr(compPkg, stmt->expr); if(expr.type != Type::INT){ throw std::runtime_error("Upper bound of for loop needs to be a integer expression."); } compPkg.getScopes().addBlockScope(); // iteration variable // create code inside loop std::string codeStmt = this->compileBlock(compPkg, stmt->stmt); compPkg.getScopes().remove(); if(expr.constant) { std::int64_t amount = std::get<std::int64_t>(expr.constant->value); if(amount <= 0) { std::cout << ">> [Warning] repeat loop: needs to be bigger than 0" << std::endl; } std::string code; bool shouldBeOptimized = (this->getOptimizationLevel() == 1 && amount < 128) || (this->getOptimizationLevel() == 2 && amount < 256) || (this->getOptimizationLevel() >= 3 && amount < 1024); // unrolling if(shouldBeOptimized) { for(int idx = 0; idx <= amount; idx++) { code += codeStmt; } return code; } } // create code return "newi 0\n" + expr.code + "loop::range \n" + "loop::idx \n" + codeStmt + "loop::cont \n"; } std::string ltnc::StmtCompiler::compileFor(CompilerPack & compPkg, std::shared_ptr<StmtFor> stmt) { // From and to expression ExprInfo from = this->exprCompiler.compileExpr(compPkg, stmt->exprFrom); ExprInfo to = this->exprCompiler.compileExpr(compPkg, stmt->exprTo); if(from.type != Type::INT){ throw std::runtime_error("Lower bound of for loop needs to be a integer expression."); } if(to.type != Type::INT){ throw std::runtime_error("Upper bound of for loop needs to be a integer expression."); } compPkg.getScopes().addBlockScope(); // iteration variable Var counter = compPkg.getScopes().get().registerVar(stmt->name, Type::INT); // create code inside loop std::string codeStmt = this->compileBlock(compPkg, stmt->stmt); compPkg.getScopes().remove(); if(from.constant && to.constant) { std::int64_t lowerBound = std::get<std::int64_t>(from.constant->value); std::int64_t upperBound = std::get<std::int64_t>(to.constant->value); if(lowerBound > upperBound) { std::cout << ">> [Warning] for loop: Lower constant boundary needs to smaller than the upper Limit" << std::endl; } std::int64_t delta = std::abs(lowerBound - upperBound); std::string code; bool shouldBeOptimized = (this->getOptimizationLevel() == 1 && delta < 128) || (this->getOptimizationLevel() == 2 && delta < 256) || (this->getOptimizationLevel() >= 3 && delta < 1024); // unrolling if(shouldBeOptimized) { for(int idx = lowerBound; idx <= upperBound; idx++) { code += "newi " + std::to_string(idx) + "\n"; code += "store " + std::to_string(counter.addr) + "\n"; code += codeStmt; } return code; } } // create code return from.code + to.code + "loop::range \n" + "loop::idx \n" + "store " + std::to_string(counter.addr) + "\n" + codeStmt + "loop::cont \n"; } std::string ltnc::StmtCompiler::compileWhile(CompilerPack & compPkg, std::shared_ptr<StmtWhile> stmt) { auto codeExpr = this->exprCompiler.compileExpr(compPkg, stmt->expr); auto codeStmt = this->compileStmt(compPkg, stmt->stmt); auto endMark = compPkg.makeJumpMark("LOOP_END"); auto loopMark = compPkg.makeJumpMark("LOOP"); return "-> " + loopMark + "\n" + codeExpr.code + "ifnot\n" + "goto " + endMark + "\n" + codeStmt + "goto " + loopMark + "\n" + "-> " + endMark + "\n"; } std::string ltnc::StmtCompiler::compileBlock(CompilerPack & compPkg, std::shared_ptr<StmtBlock> block) { compPkg.getScopes().addBlockScope(); std::string code; for(const auto & decl : block->declarations) { Var var = compPkg.getScopes().get().registerVar(decl->name, decl->type); } for(const auto & stmt : block->statements) { code+= this->compileStmt(compPkg, stmt); } compPkg.getScopes().remove(); return code; } std::string ltnc::StmtCompiler::compileIf(CompilerPack & compPkg, std::shared_ptr<StmtIf> stmt) { // make jump marks std::string jmIf = compPkg.makeJumpMark("IF"); std::string jmElse = compPkg.makeJumpMark("ELSE"); std::string jmEnd = compPkg.makeJumpMark("END_IF"); std::string condition = this->exprCompiler.compileExpr(compPkg, stmt->condition).code; std::string codeIf = this->compileStmt(compPkg, stmt->stmtIf); if(stmt->stmtElse) { std::string codeElse = this->compileStmt(compPkg, stmt->stmtElse); return condition + "ifnx" + "\n" + "goto " + jmIf + "\n" + "goto " + jmElse + "\n" + "-> " + jmIf + "\n" + codeIf + "goto " + jmEnd + "\n" + "-> " + jmElse + "\n" + codeElse + "goto " + jmEnd + "\n" + "-> " + jmEnd + "\n"; } else { return condition + "ifnx" + "\n" + "goto " + jmIf + "\n" + "goto " + jmEnd + "\n" + "-> " + jmIf + "\n" + codeIf + "-> " + jmEnd + "\n"; } } std::string ltnc::StmtCompiler::compileFunction(CompilerPack & compPkg, std::shared_ptr<DeclFunction> decl) { FxInfo fxInfo = *compPkg.matchFunction(decl->signature); compPkg.getScopes().addFunctionScope(fxInfo.signature); // register parameter for(const Param & param : decl->signature.params) { compPkg.getScopes().get().registerVar(param.name, param.type); } // create code; std::string code; code += this->comment(decl->signature.name + " " + std::to_string(decl->signature.params.size()) + " -> " + std::to_string(static_cast<int>(decl->signature.returnType.type))); code += "-> " + fxInfo.jumpMark + "\n"; // load params into memory (backwards because LIFO) for(auto param = decl->signature.params.rbegin(); param != decl->signature.params.rend(); ++param) { // store parameter; code += this->comment("store parameter " + param->name); code += "store " + std::to_string(compPkg.getScopes().get().getVar((*param).name).addr) + "\n"; } code += this->compileStmt(compPkg, decl->body); compPkg.getScopes().remove(); return code; } std::string ltnc::StmtCompiler::compileEval(CompilerPack & compPkg, std::shared_ptr<StmtExpr> stmt) { ExprInfo exprInfo = this->exprCompiler.compileExpr(compPkg, stmt->expr); std::string code; code += exprInfo.code + "\n"; if(exprInfo.type == Type::INT || exprInfo.type == Type::FLT) { code += "scrap \n"; } return code; } std::string ltnc::StmtCompiler::compileReturn(CompilerPack & compPkg, std::shared_ptr<StmtReturn> stmt) { std::string code = ""; FxSignature signature = compPkg.getScopes().get().getFxSignature(); if(stmt->expr) { ExprInfo exprInfo = this->exprCompiler.compileExpr(compPkg, stmt->expr); if(exprInfo.type != signature.returnType) { throw std::runtime_error("Type of return statement do not match return type of function"); } code += exprInfo.code; } else { if(Type::VOI != signature.returnType) { throw std::runtime_error("Type of return statement do not match return type of function"); } } code += "return \n"; return code; }
31.166124
176
0.670778
JeneLitsch
7569814fe03bd52b1f908481feb674ec9ab60a40
431
hpp
C++
src/queries/decl_inserter.hpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
src/queries/decl_inserter.hpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
src/queries/decl_inserter.hpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
#pragma once #include "../node.hpp" #include "../visitor.hpp" namespace dragon { class DeclarationToContainerInserter : public Visitor { Root decl; public: void insert(Handle declaration, Handle container) { assert(declaration.valid()); decl = declaration; container->accept(*this); assert(!decl.valid()); } public: virtual void visit( Assembly &n ); virtual void visit( sema::Namespace &n ); }; }
18.73913
54
0.677494
wojtex
756a61b072edec80aaafb8086774d89542624af5
4,260
cc
C++
packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc
Videofy/shaka-packager
33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-13T03:50:58.000Z
2021-01-13T03:50:58.000Z
packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc
Videofy/shaka-packager
33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
packager/media/crypto/sample_aes_ec3_cryptor_unittest.cc
Videofy/shaka-packager
33792ca2daae5d3fdcd7a8f72ddb3d2455db2ece
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/crypto/sample_aes_ec3_cryptor.h" #include <gmock/gmock.h> #include <gtest/gtest.h> using ::testing::_; using ::testing::Invoke; using ::testing::Return; namespace shaka { namespace media { class MockAesCryptor : public AesCryptor { public: MockAesCryptor() : AesCryptor(kDontUseConstantIv) {} MOCK_METHOD2(InitializeWithIv, bool(const std::vector<uint8_t>& key, const std::vector<uint8_t>& iv)); MOCK_METHOD4(CryptInternal, bool(const uint8_t* text, size_t text_size, uint8_t* crypt_text, size_t* crypt_text_size)); MOCK_METHOD0(SetIvInternal, void()); }; class SampleAesEc3CryptorTest : public ::testing::Test { public: SampleAesEc3CryptorTest() : mock_cryptor_(new MockAesCryptor), ec3_cryptor_(std::unique_ptr<MockAesCryptor>(mock_cryptor_)) {} void SetUp() { std::vector<uint8_t> key(16, 'k'); std::vector<uint8_t> iv(8, 'i'); EXPECT_CALL(*mock_cryptor_, InitializeWithIv(key, iv)) .WillOnce(Return(true)); EXPECT_TRUE(ec3_cryptor_.InitializeWithIv(key, iv)); EXPECT_EQ(iv, ec3_cryptor_.iv()); } protected: MockAesCryptor* mock_cryptor_; // Owned by |ec3_cryptor_|. SampleAesEc3Cryptor ec3_cryptor_; }; TEST_F(SampleAesEc3CryptorTest, Crypt) { const std::vector<uint8_t> text = { // First syncframe with 20 bytes. 0x0B, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, // Second syncframe with 26 bytes. 0x0B, 0x77, 0x00, 0x0C, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, // Third syncframe with 16 bytes. 0x0B, 0x77, 0x00, 0x07, 0x15, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36}; EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _)) .WillRepeatedly(Invoke([](const uint8_t* text, size_t text_size, uint8_t* crypt_text, size_t* crypt_text_size) { *crypt_text_size = text_size; for (size_t i = 0; i < text_size; ++i) { *crypt_text++ = *text++ + 0x40; } return true; })); const std::vector<uint8_t> expected_crypt_text = { // First syncframe with 20 bytes. 0x0B, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x57, 0x58, 0x59, 0x60, // Second syncframe with 26 bytes. 0x0B, 0x77, 0x00, 0x0C, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, // Third syncframe with 16 bytes. 0x0B, 0x77, 0x00, 0x07, 0x15, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36}; std::vector<uint8_t> crypt_text; ASSERT_TRUE(ec3_cryptor_.Crypt(text, &crypt_text)); EXPECT_EQ(expected_crypt_text, crypt_text); } TEST_F(SampleAesEc3CryptorTest, InvalidEc3Syncword) { const std::vector<uint8_t> text = {0x0C, 0x77, 0x00, 0x09, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20}; EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _)) .WillRepeatedly(Return(true)); std::vector<uint8_t> crypt_text; ASSERT_FALSE(ec3_cryptor_.Crypt(text, &crypt_text)); } TEST_F(SampleAesEc3CryptorTest, InvalidEc3SyncframeSize) { const std::vector<uint8_t> text = {0x0B, 0x77, 0x00, 0x0A, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20}; EXPECT_CALL(*mock_cryptor_, CryptInternal(_, _, _, _)) .WillRepeatedly(Return(true)); std::vector<uint8_t> crypt_text; ASSERT_FALSE(ec3_cryptor_.Crypt(text, &crypt_text)); } } // namespace media } // namespace shaka
35.5
79
0.634507
Videofy
756b02f53e20da847b4df56d9776986cb471d084
615
cpp
C++
sort/shellSort.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
1
2018-05-09T03:12:06.000Z
2018-05-09T03:12:06.000Z
sort/shellSort.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
null
null
null
sort/shellSort.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
1
2021-04-23T13:37:41.000Z
2021-04-23T13:37:41.000Z
#include <vector> /* introduction: 希尔排序是对直接插入排序的改进 problem: 用希尔排序法,将数组nums从小到大排序 idea: 首先要理解直接插入排序的过程,当需要做很多次移动时, 直接插入排序的效率和嵌套循环法接近 其次,避免这种大量移动操作,希尔排序把数组切分成多个片段, 每次排序使得每个片段内部有序;大的片段再做插入排序的时候, 就不需要大量移动,当然少量移动是必须的 */ void shellSort(vector<int> &nums){ int n = nums.size(); // 最外层的循环,变量gap可以来自用户输入,也可以用公式这么迭代 for(int gap=n/2; gap>0; gap/=2) { for(int i=gap; i<n; ++i) { int tmp = nums[i]; int j; for(j=i; j>=gap && nums[j-gap] > nums[j]; j-=gap) nums[j] = nums[j-gap]; nums[j] = tmp; } } }
20.5
61
0.557724
auniquesun
756cc73054eed2306d800f1605884d9d15d4f5c5
21,664
cpp
C++
tinyxml/ticpp.cpp
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
tinyxml/ticpp.cpp
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
tinyxml/ticpp.cpp
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
/* http://code.google.com/p/ticpp/ Copyright (c) 2006 Ryan Pusztai, Ryan Mulder 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. */ // customization to force use of ticpp #ifndef TIXML_USE_TICPP #define TIXML_USE_TICPP #endif // end customization #ifdef TIXML_USE_TICPP #include "ticpp.h" #include "ticpprc.h" #include "tinyxml.h" #include <sstream> using namespace ticpp; Attribute::Attribute() { SetTiXmlPointer( new TiXmlAttribute() ); m_impRC->InitRef(); } Attribute::Attribute( TiXmlAttribute* attribute ) { SetTiXmlPointer( attribute ); m_impRC->IncRef(); } Attribute::Attribute( const std::string& name, const std::string& value ) { SetTiXmlPointer( new TiXmlAttribute( name, value ) ); m_impRC->InitRef(); } void Attribute::operator=( const Attribute& copy ) { // Dropping the reference to the old object this->m_impRC->DecRef(); // Pointing to the new Object SetTiXmlPointer( copy.m_tiXmlPointer ); // The internal tixml pointer changed in the above line this->m_impRC->IncRef(); } Attribute::Attribute( const Attribute& copy ) : Base() { // Dropping the reference to the old object this->m_impRC->DecRef(); // Pointing to the new Object SetTiXmlPointer( copy.m_tiXmlPointer ); // The internal tixml pointer changed in the above line this->m_impRC->IncRef(); } Attribute::~Attribute() { m_impRC->DecRef(); } std::string Attribute::Value() { ValidatePointer(); return m_tiXmlPointer->ValueStr(); } std::string Attribute::Name() { ValidatePointer(); return m_tiXmlPointer->Name(); } Attribute* Attribute::Next( bool throwIfNoAttribute ) { ValidatePointer(); TiXmlAttribute* attribute = m_tiXmlPointer->Next(); if ( NULL == attribute ) { if ( throwIfNoAttribute ) { THROW( "No more attributes found" ) } else { return NULL; } } Attribute* temp = new Attribute( attribute ); m_spawnedWrappers.push_back( temp ); return temp; } Attribute* Attribute::Previous( bool throwIfNoAttribute ) { ValidatePointer(); TiXmlAttribute* attribute = m_tiXmlPointer->Previous(); if ( NULL == attribute ) { if ( throwIfNoAttribute ) { THROW( "No more attributes found" ) } else { return NULL; } } Attribute* temp = new Attribute( attribute ); m_spawnedWrappers.push_back( temp ); return temp; } void Attribute::IterateNext( const std::string&, Attribute** next ) { *next = Next( false ); } void Attribute::IteratePrevious( const std::string&, Attribute** previous ) { *previous = Previous( false ); } void Attribute::Print( FILE* file, int depth ) { ValidatePointer(); m_tiXmlPointer->Print( file, depth ); } void Attribute::SetTiXmlPointer( TiXmlAttribute* newPointer ) { m_tiXmlPointer = newPointer; SetImpRC( newPointer ); } //***************************************************************************** Node* Node::NodeFactory( TiXmlNode* tiXmlNode, bool throwIfNull, bool rememberSpawnedWrapper ) { if ( NULL == tiXmlNode ) { if ( throwIfNull ) { THROW( "tiXmlNode is NULL" ) } else { return NULL; } } Node* temp; switch ( tiXmlNode->Type() ) { case TiXmlNode::DOCUMENT: temp = new Document( tiXmlNode->ToDocument() ); break; case TiXmlNode::ELEMENT: temp = new Element( tiXmlNode->ToElement() ); break; case TiXmlNode::COMMENT: temp = new Comment( tiXmlNode->ToComment() ); break; case TiXmlNode::TEXT: temp = new Text( tiXmlNode->ToText() ); break; case TiXmlNode::DECLARATION: temp = new Declaration( tiXmlNode->ToDeclaration() ); break; default: THROW( "Type is unsupported" ) } if ( rememberSpawnedWrapper ) { m_spawnedWrappers.push_back( temp ); } return temp; } std::string Node::Value() { return GetTiXmlPointer()->ValueStr(); } void Node::Clear() { GetTiXmlPointer()->Clear(); } Node* Node::Parent( bool throwIfNoParent ) { TiXmlNode* parent = GetTiXmlPointer()->Parent(); if ( ( NULL == parent ) && throwIfNoParent ) { THROW( "No parent exists" ); } return NodeFactory( parent, false ); } Node* Node::FirstChild( bool throwIfNoChildren ) { return FirstChild( "", throwIfNoChildren ); } Node* Node::FirstChild( const std::string& value, bool throwIfNoChildren ) { return FirstChild( value.c_str(), throwIfNoChildren ); } Node* Node::FirstChild( const char* value, bool throwIfNoChildren ) { TiXmlNode* childNode; if ( 0 == strlen( value ) ) { childNode = GetTiXmlPointer()->FirstChild(); } else { childNode = GetTiXmlPointer()->FirstChild( value ); } if ( ( NULL == childNode ) && throwIfNoChildren ) { THROW( "Child with the value of \"" << value << "\" not found" ); } return NodeFactory( childNode, false ); } Node* Node::LastChild( bool throwIfNoChildren ) { return LastChild( "", throwIfNoChildren ); } Node* Node::LastChild( const std::string& value, bool throwIfNoChildren ) { return LastChild( value.c_str(), throwIfNoChildren ); } Node* Node::LastChild( const char* value, bool throwIfNoChildren ) { TiXmlNode* childNode; if ( 0 == strlen( value ) ) { childNode = GetTiXmlPointer()->LastChild(); } else { childNode = GetTiXmlPointer()->LastChild( value ); } if ( ( NULL == childNode ) && throwIfNoChildren ) { THROW( "Child with the value of \"" << value << "\" not found" ); } return NodeFactory( childNode, false ); } Node* Node::IterateChildren ( Node* previous ) { TiXmlNode* pointer; if ( NULL == previous ) { pointer = GetTiXmlPointer()->IterateChildren( NULL ); } else { pointer = GetTiXmlPointer()->IterateChildren( previous->GetTiXmlPointer() ); } return NodeFactory( pointer, false ); } Node* Node::IterateChildren( const std::string& value, Node* previous ) { TiXmlNode* pointer; if ( NULL == previous ) { pointer = GetTiXmlPointer()->IterateChildren( value, NULL ); } else { pointer = GetTiXmlPointer()->IterateChildren( value, previous->GetTiXmlPointer() ); } return NodeFactory( pointer, false ); } Node* Node::InsertEndChild( Node& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { THROW( "Node is a Document and can't be inserted" ); } // Increment reference count when adding to the tree addThis.m_impRC->IncRef(); TiXmlNode* pointer = GetTiXmlPointer()->InsertEndChild( *addThis.GetTiXmlPointer() ); if ( NULL == pointer ) { THROW( "Node can't be inserted" ); } return NodeFactory( pointer ); } Node* Node::LinkEndChild( Node* childNode ) { if ( childNode->Type() == TiXmlNode::DOCUMENT ) { THROW( "Node is a Document and can't be linked" ); } // Increment reference count when adding to the tree childNode->m_impRC->IncRef(); if ( NULL == GetTiXmlPointer()->LinkEndChild( childNode->GetTiXmlPointer() ) ) { THROW( "Node can't be linked" ); } return childNode; } Node* Node::InsertBeforeChild( Node* beforeThis, Node& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { THROW( "Node is a Document and can't be inserted" ); } // Increment reference count when adding to the tree addThis.m_impRC->IncRef(); TiXmlNode* pointer = GetTiXmlPointer()->InsertBeforeChild( beforeThis->GetTiXmlPointer(), *addThis.GetTiXmlPointer() ); if ( NULL == pointer ) { THROW( "Node can't be inserted" ); } return NodeFactory( pointer ); } Node* Node::InsertAfterChild( Node* afterThis, Node& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { THROW( "Node is a Document and can't be inserted" ); } // Increment reference count when adding to the tree addThis.m_impRC->IncRef(); TiXmlNode* pointer = GetTiXmlPointer()->InsertAfterChild( afterThis->GetTiXmlPointer(), *addThis.GetTiXmlPointer() ); if ( NULL == pointer ) { THROW( "Node can't be inserted" ); } return NodeFactory( pointer ); } Node* Node::ReplaceChild( Node* replaceThis, Node& withThis ) { if ( withThis.Type() == TiXmlNode::DOCUMENT ) { THROW( "Node is a Document and can't be inserted" ); } // Increment reference count when adding to the tree withThis.m_impRC->IncRef(); TiXmlNode* pointer = GetTiXmlPointer()->ReplaceChild( replaceThis->GetTiXmlPointer(), *withThis.GetTiXmlPointer() ); if ( NULL == pointer ) { THROW( "Node can't be inserted" ); } return NodeFactory( pointer ); } void Node::RemoveChild( Node* removeThis ) { if ( !GetTiXmlPointer()->RemoveChild( removeThis->GetTiXmlPointer() ) ) { THROW( "Node to remove (" << removeThis->Value() << ") is not a child of this Node (" << Value() << ")" ) } } Node* Node::PreviousSibling( bool throwIfNoSiblings ) { return PreviousSibling( "", throwIfNoSiblings ); } Node* Node::PreviousSibling( const std::string& value, bool throwIfNoSiblings ) { return PreviousSibling( value.c_str(), throwIfNoSiblings ); } Node* Node::PreviousSibling( const char* value, bool throwIfNoSiblings ) { TiXmlNode* sibling; if ( 0 == strlen( value ) ) { sibling = GetTiXmlPointer()->PreviousSibling(); } else { sibling = GetTiXmlPointer()->PreviousSibling( value ); } if ( ( NULL == sibling ) && throwIfNoSiblings ) { THROW( "No Siblings found with value, '" << value << "', Prior to this Node (" << Value() << ")" ) } return NodeFactory( sibling, false ); } Node* Node::NextSibling( bool throwIfNoSiblings ) { return NextSibling( "", throwIfNoSiblings ); } Node* Node::NextSibling( const std::string& value, bool throwIfNoSiblings ) { return NextSibling( value.c_str(), throwIfNoSiblings ); } Node* Node::NextSibling( const char* value, bool throwIfNoSiblings ) { TiXmlNode* sibling; if ( 0 == strlen( value ) ) { sibling = GetTiXmlPointer()->NextSibling(); } else { sibling = GetTiXmlPointer()->NextSibling( value ); } if ( ( NULL == sibling ) && throwIfNoSiblings ) { THROW( "No Siblings found with value, '" << value << "', After this Node (" << Value() << ")" ) } return NodeFactory( sibling, false ); } Element* Node::NextSiblingElement( bool throwIfNoSiblings ) { return NextSiblingElement( "", throwIfNoSiblings ); } Element* Node::NextSiblingElement( const std::string& value, bool throwIfNoSiblings ) { return NextSiblingElement( value.c_str(), throwIfNoSiblings ); } Element* Node::NextSiblingElement( const char* value, bool throwIfNoSiblings ) { TiXmlElement* sibling; if ( 0 == strlen( value ) ) { sibling = GetTiXmlPointer()->NextSiblingElement(); } else { sibling = GetTiXmlPointer()->NextSiblingElement( value ); } if ( NULL == sibling ) { if ( throwIfNoSiblings ) { THROW( "No Element Siblings found with value, '" << value << "', After this Node (" << Value() << ")" ) } else { return NULL; } } Element* temp = new Element( sibling ); m_spawnedWrappers.push_back( temp ); return temp; } Element* Node::FirstChildElement( bool throwIfNoChildren ) { return FirstChildElement( "", throwIfNoChildren ); } Element* Node::FirstChildElement( const std::string& value, bool throwIfNoChildren ) { return FirstChildElement( value.c_str(), throwIfNoChildren ); } Element* Node::FirstChildElement( const char* value, bool throwIfNoChildren ) { TiXmlElement* element; if ( 0 == strlen( value ) ) { element = GetTiXmlPointer()->FirstChildElement(); } else { element = GetTiXmlPointer()->FirstChildElement( value ); } if ( NULL == element ) { if( throwIfNoChildren ) { THROW( "Element (" << Value() << ") does NOT contain a child with the value of '" << value << "'" ) } else { return NULL; } } Element* temp = new Element( element ); m_spawnedWrappers.push_back( temp ); return temp; } int Node::Type() { return GetTiXmlPointer()->Type(); } Document* Node::GetDocument( bool throwIfNoDocument ) { TiXmlDocument* doc = GetTiXmlPointer()->GetDocument(); if ( NULL == doc ) { if( throwIfNoDocument ) { THROW( "This node (" << Value() << ") is not linked under a document" ) } else { return NULL; } } Document* temp = new Document( doc ); m_spawnedWrappers.push_back( temp ); return temp; } bool Node::NoChildren() { return GetTiXmlPointer()->NoChildren(); } Document* Node::ToDocument() { TiXmlDocument* doc = GetTiXmlPointer()->ToDocument(); if ( NULL == doc ) { THROW( "This node (" << Value() << ") is not a Document" ) } Document* temp = new Document( doc ); m_spawnedWrappers.push_back( temp ); return temp; } Element* Node::ToElement() { TiXmlElement* doc = GetTiXmlPointer()->ToElement(); if ( NULL == doc ) { THROW( "This node (" << Value() << ") is not a Element" ) } Element* temp = new Element( doc ); m_spawnedWrappers.push_back( temp ); return temp; } Comment* Node::ToComment() { TiXmlComment* doc = GetTiXmlPointer()->ToComment(); if ( NULL == doc ) { THROW( "This node (" << Value() << ") is not a Comment" ) } Comment* temp = new Comment( doc ); m_spawnedWrappers.push_back( temp ); return temp; } Text* Node::ToText() { TiXmlText* doc = GetTiXmlPointer()->ToText(); if ( NULL == doc ) { THROW( "This node (" << Value() << ") is not a Text" ) } Text* temp = new Text( doc ); m_spawnedWrappers.push_back( temp ); return temp; } Declaration* Node::ToDeclaration() { TiXmlDeclaration* doc = GetTiXmlPointer()->ToDeclaration(); if ( NULL == doc ) { THROW( "This node (" << Value() << ") is not a Declaration" ) } Declaration* temp = new Declaration( doc ); m_spawnedWrappers.push_back( temp ); return temp; } std::auto_ptr< Node > Node::Clone() { TiXmlNode* node = GetTiXmlPointer()->Clone(); if ( NULL == node ) { THROW( "Node could not be cloned" ); } std::auto_ptr< Node > temp( NodeFactory( node, false, false ) ); // Take ownership of the memory from TiXml temp->m_impRC->InitRef(); return temp; } //***************************************************************************** Comment::Comment() : NodeImp< TiXmlComment >( new TiXmlComment() ) { m_impRC->InitRef(); } Comment::Comment( TiXmlComment* comment ) : NodeImp< TiXmlComment >( comment ) { } Comment::Comment( const std::string& comment ) : NodeImp< TiXmlComment >( new TiXmlComment() ) { m_impRC->InitRef(); m_tiXmlPointer->SetValue( comment ); } //***************************************************************************** Text::Text() : NodeImp< TiXmlText >( new TiXmlText("") ) { m_impRC->InitRef(); } Text::Text( const std::string& value ) : NodeImp< TiXmlText >( new TiXmlText( value ) ) { m_impRC->InitRef(); } Text::Text( TiXmlText* text ) : NodeImp< TiXmlText >( text ) { } //***************************************************************************** Document::Document() : NodeImp< TiXmlDocument >( new TiXmlDocument() ) { m_impRC->InitRef(); } Document::Document( TiXmlDocument* document ) : NodeImp< TiXmlDocument >( document ) { } Document::Document( const char* documentName ) : NodeImp< TiXmlDocument >( new TiXmlDocument( documentName ) ) { m_impRC->InitRef(); } Document::Document( const std::string& documentName ) : NodeImp< TiXmlDocument >( new TiXmlDocument( documentName ) ) { m_impRC->InitRef(); } std::string Document::GetAsString() { return m_tiXmlPointer->GetAsString(); } void Document::LoadFile( TiXmlEncoding encoding ) { if ( !m_tiXmlPointer->LoadFile( encoding ) ) { THROW( "Couldn't load " << m_tiXmlPointer->Value() ); } } void Document::SaveFile( void ) const { if ( !m_tiXmlPointer->SaveFile() ) { THROW( "Couldn't save " << m_tiXmlPointer->Value() ); } } void Document::LoadFile( const std::string& filename, TiXmlEncoding encoding ) { if ( !m_tiXmlPointer->LoadFile( filename.c_str(), encoding ) ) { THROW( "Couldn't load " << filename ); } } void Document::SaveFile( const std::string& filename ) const { if ( !m_tiXmlPointer->SaveFile( filename.c_str() ) ) { THROW( "Couldn't save " << filename ); } } //***************************************************************************** Element::Element() : NodeImp< TiXmlElement >( new TiXmlElement( "DefaultValueCausedByCreatingAnElementWithNoParameters" ) ) { m_impRC->InitRef(); } Element::Element( const std::string& value ) : NodeImp< TiXmlElement >( new TiXmlElement( value ) ) { m_impRC->InitRef(); } Element::Element( TiXmlElement* element ) : NodeImp< TiXmlElement >( element ) { } Attribute* Element::FirstAttribute( bool throwIfNoAttributes ) { ValidatePointer(); TiXmlAttribute* attribute = m_tiXmlPointer->FirstAttribute(); if ( ( NULL == attribute ) && throwIfNoAttributes ) { THROW( "This Element (" << Value() << ") has no attributes" ) } if ( NULL == attribute ) { if( throwIfNoAttributes ) { THROW( "Element (" << Value() << ") has no attributes" ) } else { return NULL; } } Attribute* temp = new Attribute( attribute ); m_spawnedWrappers.push_back( temp ); return temp; } Attribute* Element::LastAttribute( bool throwIfNoAttributes ) { ValidatePointer(); TiXmlAttribute* attribute = m_tiXmlPointer->LastAttribute(); if ( ( NULL == attribute ) && throwIfNoAttributes ) { THROW( "This Element (" << Value() << ") has no attributes" ) } if ( NULL == attribute ) { if( throwIfNoAttributes ) { THROW( "Element (" << Value() << ") has no attributes" ) } else { return NULL; } } Attribute* temp = new Attribute( attribute ); m_spawnedWrappers.push_back( temp ); return temp; } bool Element::GetAttributeImp( const std::string& name, std::string* value ) { ValidatePointer(); // Get value from TinyXML, if the attribute exists const char* retVal = m_tiXmlPointer->Attribute( name.c_str() ); // TinyXML returns NULL if the attribute doesn't exist if ( NULL == retVal ) { return false; } else { *value = retVal; return true; } } bool Element::GetTextImp( std::string* value ) { ValidatePointer(); // Get value from TinyXML, if the attribute exists const char* retVal = m_tiXmlPointer->GetText(); // TinyXML returns NULL if the attribute doesn't exist if ( NULL == retVal ) { return false; } else { *value = retVal; return true; } } //***************************************************************************** Declaration::Declaration() : NodeImp< TiXmlDeclaration >( new TiXmlDeclaration() ) { m_impRC->InitRef(); } Declaration::Declaration( TiXmlDeclaration* declaration ) : NodeImp< TiXmlDeclaration >( declaration ) { } Declaration::Declaration( const std::string& version, const std::string& encoding, const std::string& standalone ) : NodeImp< TiXmlDeclaration >( new TiXmlDeclaration( version, encoding, standalone ) ) { m_impRC->InitRef(); } std::string Declaration::Version( void ) { return m_tiXmlPointer->Version(); } std::string Declaration::Encoding( void ) { return m_tiXmlPointer->Encoding(); } std::string Declaration::Standalone( void ) { return m_tiXmlPointer->Standalone(); } //***************************************************************************** Exception::Exception(const std::string &details) : m_details( details ) { } //***************************************************************************** TiCppRC::TiCppRC() { // Spawn reference counter for this object m_tiRC = new TiCppRCImp( this ); } TiCppRC::~TiCppRC() { // Set pointer held by reference counter to NULL this->m_tiRC->Nullify(); // Decrement reference - so reference counter will delete itself if necessary this->m_tiRC->DecRef(); } //***************************************************************************** TiCppRCImp::TiCppRCImp( TiCppRC* tiCppRC ) : m_count( 1 ), m_tiCppRC ( tiCppRC ) { } void TiCppRCImp::IncRef() { m_count++; } void TiCppRCImp::DecRef() { m_count--; if ( 0 == m_count ) { delete m_tiCppRC; delete this; } } void TiCppRCImp::InitRef() { m_count = 1; } void TiCppRCImp::Nullify() { m_tiCppRC = NULL; } TiCppRC* TiCppRCImp::Get() { return m_tiCppRC; } bool TiCppRCImp::IsNull() { return NULL == m_tiCppRC; } #endif // TIXML_USE_TICPP
21.816717
121
0.627723
blazeroni
756cd09cc0f9cd3a7c6976d9afe11ce8c618ec29
2,448
cpp
C++
src/CMacierzKw.cpp
MarutTomasz/ZadanieSzablonDlaRownan
17e311c18d6cc999896d1d0612ee21c79cae3ec5
[ "MIT" ]
null
null
null
src/CMacierzKw.cpp
MarutTomasz/ZadanieSzablonDlaRownan
17e311c18d6cc999896d1d0612ee21c79cae3ec5
[ "MIT" ]
null
null
null
src/CMacierzKw.cpp
MarutTomasz/ZadanieSzablonDlaRownan
17e311c18d6cc999896d1d0612ee21c79cae3ec5
[ "MIT" ]
null
null
null
#include "SMacierzKw.cpp" // NA STALE RZECZYWISTE template class MacierzKw<Wektor,double,5>; template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,double,5> &M); template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,double,5> &M); template MacierzKw<Wektor,double,5> operator * (double liczba, const MacierzKw<Wektor,double,5> &M); // TYMCZASOWO template class MacierzKw<Wektor,double,4>; template class MacierzKw<Wektor,double,3>; template class MacierzKw<Wektor,double,2>; template class MacierzKw<Wektor,double,1>; template MacierzKw<Wektor,double,4> pomniejsz_macierz(const MacierzKw<Wektor,double,5> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,double,3> pomniejsz_macierz(const MacierzKw<Wektor,double,4> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,double,2> pomniejsz_macierz(const MacierzKw<Wektor,double,3> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,double,1> pomniejsz_macierz(const MacierzKw<Wektor,double,2> &M, unsigned int index1, unsigned int index2); // NA STALE ZESPOLONE template class MacierzKw<Wektor,LZespolona,5>; template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,LZespolona,5> &M); template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,LZespolona,5> &M); template MacierzKw<Wektor,LZespolona,5> operator * (LZespolona liczba, const MacierzKw<Wektor,LZespolona,5> &M); // TYMCZASOWO template class MacierzKw<Wektor,LZespolona,4>; template class MacierzKw<Wektor,LZespolona,3>; template class MacierzKw<Wektor,LZespolona,2>; template class MacierzKw<Wektor,LZespolona,1>; template MacierzKw<Wektor,LZespolona,1> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,2> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,LZespolona,2> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,3> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,LZespolona,3> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,4> &M, unsigned int index1, unsigned int index2); template MacierzKw<Wektor,LZespolona,4> pomniejsz_macierz(const MacierzKw<Wektor,LZespolona,5> &M, unsigned int index1, unsigned int index2); template std::istream & operator >> (std::istream &strm, MacierzKw<Wektor,LZespolona,2> &M); template std::ostream & operator << (std::ostream &strm, const MacierzKw<Wektor,LZespolona,2> &M);
56.930233
141
0.786356
MarutTomasz
756e2ee22783eb8f303db5cce4e715651441929c
2,251
hpp
C++
Sockets/include/Sockets/TcpClientSocket.hpp
sanjeev-kumar-m/BrokerDataServer
2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e
[ "MIT" ]
null
null
null
Sockets/include/Sockets/TcpClientSocket.hpp
sanjeev-kumar-m/BrokerDataServer
2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e
[ "MIT" ]
null
null
null
Sockets/include/Sockets/TcpClientSocket.hpp
sanjeev-kumar-m/BrokerDataServer
2db8a1bd4bd04a9dadcb4c1762f11a8e1e52d46e
[ "MIT" ]
null
null
null
#pragma once /** * @file TcpClientSocket.hpp * * This file declare Sockets::TcpClientSocket class */ #define SNJ_MAKE_NONCOPYABLE(c)\ private: \ c(const c&) noexcept = delete;\ c& operator=(const c&) noexcept = delete #define SNJ_MAKE_NONMOVABLE(c)\ private: \ c(c&&) noexcept = delete; \ c& operator=(c&&) noexcept = delete #include <memory> #include <sys/socket.h> namespace Sockets { class TcpClientSocket { public: //Life cycle functions ~TcpClientSocket() = default; SNJ_MAKE_NONCOPYABLE(TcpClientSocket); SNJ_MAKE_NONMOVABLE(TcpClientSocket); public: //This is the constructor TcpClientSocket(); /** * This function is used to bind the port number * to the socket */ bool Open(); /** * This function is used to connect the client * socket to the server socket * * @param[in] t_address * address of the server to connect * * @param[in] t_port * port number of the process on the * server to connect * * @return * boolean value indicating whether connectin * to the server was sucessfull or not */ bool Connect(uint32_t t_address, uint16_t t_port); /** * This function returns the socket descriptor * * @return * socket descriptor integer value */ inline int SocketDescriptor() { return _m_socket_descriptor; } /** * This function is used to set the socket * to be non-blocking */ void setNonBlocking(); /** * This function reads the data from the socket * and copy that to buffer. * * @param[in] t_buffer * pointer to the buffer where the read * data to be copied * * @param[in] t_read_size * amount of bytes to be read from the socket * * @return retval * actual number of bytes read from the buffer */ size_t ReadN(char *t_buffer, size_t t_read_size); /** * This function closes opened socket */ void Close(); private: /** * This holds socket descriptor, when the socket * is opened */ int _m_socket_descriptor; }; }
22.068627
54
0.594847
sanjeev-kumar-m
756f670964911aa43db3ffecb19b90d49ec24ce8
3,163
hpp
C++
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/sdv/rsd/get_mdr_data_region_status.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/sdv/rsd/get_mdr_data_region_status.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/sdv/rsd/get_mdr_data_region_status.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright Copyright (c) 2017-2019 Intel Corporation. * * 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. * * @brief Get mdr data region status command declaration for 2.2 platform * * @file ipmi/command/sdv/rsd/get_mdr_data_region_status.hpp */ #pragma once #include "ipmi/command/sdv/get_mdr_data_region_status.hpp" #include "ipmi/command/sdv/enums.hpp" namespace ipmi { namespace command { namespace sdv { namespace rsd { using GetMdrStatusLegacyReq = ipmi::command::sdv::request::GetMdrDataRegionStatus; using GetMdrStatusLegacyRes = ipmi::command::sdv::response::GetMdrDataRegionStatus; namespace request { /*! * @brief Represents request message for MdrRegionRead command with altered Net Function and Rackscale byte */ class GetMdrDataRegionStatus : public GetMdrStatusLegacyReq { public: /*! @brief Default constructor. */ GetMdrDataRegionStatus(); GetMdrDataRegionStatus(const GetMdrDataRegionStatus&) = default; GetMdrDataRegionStatus(GetMdrDataRegionStatus&&) = default; /*! @brief Destructor. */ virtual ~GetMdrDataRegionStatus(); private: static const constexpr std::size_t DATA_REGION_OFFSET = 1; void pack(IpmiInterface::ByteBuffer& data) const override; }; } namespace response { /*! * @brief Represents response message for MdrRegionRead command with altered Net Function and Rackscale byte */ class GetMdrDataRegionStatus : public GetMdrStatusLegacyRes { public: /*! @brief Default constructor. */ GetMdrDataRegionStatus(); GetMdrDataRegionStatus(const GetMdrDataRegionStatus&) = default; GetMdrDataRegionStatus(GetMdrDataRegionStatus&&) = default; /*! @brief Destructor. */ virtual ~GetMdrDataRegionStatus(); /*! * @brief Check if RackScale extension byte is present in the response. * @return True if extension byte is present, false otherwise. */ bool is_rackscale_extension_byte_present() const { return m_is_rackscale_extension_byte_present; } private: static constexpr std::size_t RESPONSE_SIZE = 12; static constexpr std::size_t MDR_VERSION_OFFSET = 2; static constexpr std::size_t DATA_REGION_ID_OFFSET = 3; static constexpr std::size_t DATA_VALIDATION_OFFSET = 4; static constexpr std::size_t DATA_UPDATE_COUNT_OFFSET = 5; static constexpr std::size_t LOCK_STATUS_OFFSET = 6; static constexpr std::size_t REGION_SIZE_OFFSET = 7; static constexpr std::size_t REGION_SIZE_USED_OFFSET = 9; static constexpr std::size_t REGION_CHECKSUM_OFFSET = 11; void unpack(const IpmiInterface::ByteBuffer& data) override; bool m_is_rackscale_extension_byte_present{false}; }; } } } } }
31.949495
108
0.751502
opencomputeproject
75719231b1fba36f05c18ad5341bd59d35278aa9
1,720
cpp
C++
apal_cxx/src/cahn_hilliard.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
apal_cxx/src/cahn_hilliard.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
15
2019-05-23T07:18:19.000Z
2019-12-17T08:01:10.000Z
apal_cxx/src/cahn_hilliard.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
#include "cahn_hilliard.hpp" #include <cmath> using namespace std; CahnHilliard::CahnHilliard(const vector<double> &coefficients): coeff(coefficients){}; double CahnHilliard::evaluate(double x) const{ double res = 0.0; unsigned int N = coeff.size(); for (unsigned int i=0;i<coeff.size();i++){ res += pow(x, N-i-1)*coeff[i]; } if (has_bounds){ res += penalty*regularization(x); } return res; } double CahnHilliard::deriv(double x) const{ double res = 0.0; unsigned int N = coeff.size(); for (unsigned int i=0;i<N-1;i++){ res += (N-i-1)*pow(x, N-i-2)*coeff[i]; } if (has_bounds){ res += penalty*regularization_deriv(x); } return res; } void CahnHilliard::set_bounds(double lower, double upper){ has_bounds = true; lower_bound = lower; upper_bound = upper; } bool CahnHilliard::is_outside_range(double x) const{ return x >= upper_bound || x < lower_bound; } double CahnHilliard::regularization(double x) const{ if (!is_outside_range(x)){ return 0.0; } double range = upper_bound - lower_bound; double scale = rng_scale*range; if (x >= upper_bound){ return exp((x-upper_bound)/scale); } else if (x < lower_bound){ return exp((lower_bound-x)/scale); } return 0.0; } double CahnHilliard::regularization_deriv(double x) const{ if (!is_outside_range(x)){ return 0.0; } double range = upper_bound - lower_bound; double scale = rng_scale*range; if (x > upper_bound){ return exp((x-upper_bound)/scale)/scale; } else if(x < lower_bound){ return -exp((lower_bound-x)/scale)/scale; } return 0.0; }
22.933333
86
0.619186
davidkleiven
7573d27b822f9ed4aafa3b1abcb6da87c02d5fbe
3,759
cxx
C++
Code/Applications/Utilities/DiffOperMain.cxx
NIRALUser/AtlasWerks
a074ca208ab41a6ed89c1f0b70004998f7397681
[ "BSD-3-Clause" ]
3
2016-04-26T05:06:06.000Z
2020-08-01T09:46:54.000Z
Code/Applications/Utilities/DiffOperMain.cxx
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
1
2018-11-27T21:53:48.000Z
2019-05-13T15:21:31.000Z
Code/Applications/Utilities/DiffOperMain.cxx
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
2
2019-01-24T02:07:17.000Z
2019-12-11T17:27:42.000Z
/* ================================================================ * * AtlasWerks Project * * Copyright (c) Sarang C. Joshi, Bradley C. Davis, J. Samuel Preston, * Linh K. Ha. All rights reserved. See Copyright.txt or for details. * * This software is distributed WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the above copyright notice for more information. * * ================================================================ */ #include "DiffOper.h" #include "ImagePreprocessor.h" #include "CmdLineParser.h" #include "KernelParam.h" #include "KernelFactory.h" #include "ApplicationUtils.h" #ifdef CUDA_ENABLED #include "cudaInterface.h" #include "DiffOperGPU.h" #include "CUDAUtilities.h" #endif /** * \page DiffOper * * Simple frontend for applying differential operator to a vector field */ class DiffOperParamFile : public CompoundParam { public: DiffOperParamFile() : CompoundParam("ParameterFile", "top-level node", PARAM_REQUIRED) { this->AddChild(ValueParam<std::string>("InputVectorField", "vector field to which the differential operator is to be applied", PARAM_REQUIRED, "")); this->AddChild(ValueParam<std::string>("OutputFileName", "Filname of result vector field", PARAM_REQUIRED, "")); this->AddChild(KernelParam("Kernel")); this->AddChild(ValueParam<bool>("UseGPU", "use GPU version of DiffOper?", PARAM_COMMON, false)); this->AddChild(ValueParam<bool>("ApplyInverse", "Apply K, not L?", PARAM_COMMON, true)); } ValueParamAccessorMacro(std::string, InputVectorField) ValueParamAccessorMacro(std::string, OutputFileName) ParamAccessorMacro(KernelParam, Kernel) ValueParamAccessorMacro(bool, UseGPU) ValueParamAccessorMacro(bool, ApplyInverse) CopyFunctionMacro(DiffOperParamFile) }; int main(int argc, char ** argv) { DiffOperParamFile pf; try{ CmdLineParser parser(pf); parser.Parse(argc,argv); }catch(ParamException &pe){ std::cerr << "Error parsing arguments:" << std::endl; std::cerr << " " << pe.what() << std::endl; std::exit(-1); } VectorField v; SizeType size; OriginType origin; SpacingType spacing; ApplicationUtils::LoadHFieldITK(pf.InputVectorField().c_str(), origin, spacing, v); size = v.getSize(); if(pf.UseGPU()){ #ifdef CUDA_ENABLED cplVector3DArray dV; allocateDeviceVector3DArray(dV, size.productOfElements()); CUDAUtilities::CopyVectorFieldToDevice(v, dV, true); LOGNODE(logDEBUG) << "Using GPU Kernel"; KernelInterfaceGPU *mdKernel = KernelFactory::NewGPUKernel(pf.Kernel()); mdKernel->SetSize(size, spacing, pf.Kernel()); if(pf.ApplyInverse()){ LOGNODE(logDEBUG) << "Applying Inverse Kernel"; mdKernel->ApplyInverseOperator(dV); }else{ LOGNODE(logDEBUG) << "Applying Forward Kernel"; mdKernel->ApplyOperator(dV); } CUDAUtilities::CopyVectorFieldFromDevice(dV, v, true); delete mdKernel; #else // !CUDA_ENABLED throw AtlasWerksException(__FILE__, __LINE__, "Error, GPU code not built. Select USE_CUDA in CMake settings."); #endif // CUDA_ENABLED }else{ LOGNODE(logDEBUG) << "Using CPU Kernel"; KernelInterface *mKernel = KernelFactory::NewKernel(pf.Kernel(), size, spacing); mKernel->CopyIn(v); if(pf.ApplyInverse()){ LOGNODE(logDEBUG) << "Applying Inverse Kernel"; mKernel->ApplyInverseOperator(); }else{ LOGNODE(logDEBUG) << "Applying Forward Kernel"; mKernel->ApplyOperator(); } mKernel->CopyOut(v); delete mKernel; } ApplicationUtils::SaveHFieldITK(pf.OutputFileName().c_str(), v, origin, spacing); LOGNODE(logDEBUG) << "Done writing results"; }
30.811475
152
0.675712
NIRALUser
75767d931443362c32668b37eea2f87147f4bf51
1,467
hpp
C++
vgl_compute_api/template/advance.hpp
afanasyev-ilya/VectorGraphLibrary
caf2013260fc89b3afd0a5f5006a2aa85fc290e7
[ "Apache-2.0" ]
8
2020-11-27T15:43:52.000Z
2021-09-28T14:22:04.000Z
vgl_compute_api/template/advance.hpp
afanasyev-ilya/VectorGraphLibrary
caf2013260fc89b3afd0a5f5006a2aa85fc290e7
[ "Apache-2.0" ]
1
2021-03-04T18:55:12.000Z
2021-03-04T18:55:12.000Z
vgl_compute_api/template/advance.hpp
afanasyev-ilya/VectorGraphLibrary
caf2013260fc89b3afd0a5f5006a2aa85fc290e7
[ "Apache-2.0" ]
null
null
null
#pragma once ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename EdgeOperation, typename VertexPreprocessOperation, typename VertexPostprocessOperation, typename CollectiveEdgeOperation, typename CollectiveVertexPreprocessOperation, typename CollectiveVertexPostprocessOperation, typename GraphContainer, typename FrontierContainer> void GraphAbstractionsTEMPLATE::advance_worker(GraphContainer &_graph, FrontierContainer &_frontier, EdgeOperation &&edge_op, VertexPreprocessOperation &&vertex_preprocess_op, VertexPostprocessOperation &&vertex_postprocess_op, CollectiveEdgeOperation &&collective_edge_op, CollectiveVertexPreprocessOperation &&collective_vertex_preprocess_op, CollectiveVertexPostprocessOperation &&collective_vertex_postprocess_op, bool _inner_mpi_processing) { throw "Error in GraphAbstractionsTEMPLATE::advance_worker : not implemented yet"; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
66.681818
124
0.504431
afanasyev-ilya
757694c82c162d4ec357dbe70e8f57109ac12453
19,209
cpp
C++
mainwindow.cpp
adricatena/EA3-ControlHorno-
fcb0c8a6edddc09f2b03c83e97331ceddac9987e
[ "MIT" ]
null
null
null
mainwindow.cpp
adricatena/EA3-ControlHorno-
fcb0c8a6edddc09f2b03c83e97331ceddac9987e
[ "MIT" ]
null
null
null
mainwindow.cpp
adricatena/EA3-ControlHorno-
fcb0c8a6edddc09f2b03c83e97331ceddac9987e
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "qcustomplot.h" //------------Variables generales---------- QByteArray pedido_com, datos_com; QString SetPoint; int n = 0, h = 0, l = 0, j = 0, r = 0, k = 0, w = 0, q = 0, f = 0; float i = 0; bool ok, Boton = false, SP_Send = false, SP_Seted = false, BUG_Seted = false, flag_conn = false, flag_test = false; //---------------------------------------- //-----------Variables PID--------------- int control; float Ts = 1, Kr, Ti, Td; float a, b, c; float TEMPERATURA_LIMITE; float rT=0, yT=0, eT=0, iT=0, dT=0, uT=0, iT0 = 0, eT0 = 0, yant = 25, xant = 0, xdat = 0; float max = 122, min = 1; //--------------------------------------- //---------Variables PID 2--------------- float pT = 0, e_k = 0, e_k_1 = 0, e_k_2 = 0, uT_1 = 0; //--------------------------------------- //--------Variables para graficar-------- QVector<double> xg(201), yg(201), zg(201), wg(201); // initialize with entries 0..1000 //--------------------------------------- MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); serial = new QSerialPort(this); Serial_Conf(); //función que se encarga de configurar la comunicación serie connect(serial,SIGNAL(readyRead()),this,SLOT(Serial_Pedir())); //enlazamos la función de lectura de dato por serie a una señal de lectura //ui->Set_Point->setVisible(false); ui->SetPoint->setEnabled(false); ui->Spin_Kr->setEnabled(false); ui->Spin_Ti->setEnabled(false); ui->Spin_Td->setEnabled(false); ui->Temp_Prog->setValue(30); ui->Bot_Debug->setIcon(QIcon(":/pics/bug1.png")); ui->Bot_Debug->setEnabled(false); ui->groupBox_6->setVisible(false); ui->groupBox_7->setVisible(false); ui->checkBox->setChecked(false); ui->Bot_Envio->setEnabled(false); ui->Edit_Envio->setEnabled(false); ui->pushButton_3->setEnabled(false); ui->pushButton_4->setEnabled(false); ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png")); flag_conn = false; MainWindow::SetupGraph(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::Serial_Conf() { serial->setPortName("COM3"); //puerto com por el que nos comunicaremos con la placa adquisidora serial->setBaudRate(QSerialPort::Baud1200); //configuramos los baudios para conexión serie serial->setDataBits(QSerialPort::Data8); //cantidad de bits por dato serial->setParity(QSerialPort::NoParity); //paridad serial->setStopBits(QSerialPort::OneStop); //bit de stop serial->setFlowControl(QSerialPort::NoFlowControl); //control de flujo } void MainWindow::Serial_Conect() { if((serial->open(QIODevice::ReadWrite))) //indicador de conexión serie establecida { //ui->Set_Point->setEnabled(true); //ui->SetPoint->setEnabled(true); //ui->Spin_Kr->setEnabled(true); //ui->Spin_Ti->setEnabled(true); //ui->Spin_Td->setEnabled(true); ui->Temp_Prog->setValue(30); ui->Bot_Debug->setEnabled(true); ui->groupBox_6->setEnabled(true); ui->groupBox_7->setEnabled(true); ui->pushButton_3->setEnabled(false); ui->pushButton_4->setEnabled(true); ui->pushButton_4->setText("Iniciar"); ui->Conectar_Com->setIcon(QIcon(":/pics/usbcon.png")); flag_conn = true; Iniciar_Horno(); } else Serial_Error(); } void MainWindow::Iniciar_Horno(void){ char m = 0xFD; pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); k = 1; SP_Seted = false; } void MainWindow::Serial_Desconect() { //ui->Set_Point->setEnabled(false); ui->SetPoint->setEnabled(false); ui->Spin_Kr->setEnabled(false); ui->Spin_Ti->setEnabled(false); ui->Spin_Td->setEnabled(false); ui->Bot_Debug->setEnabled(false); ui->groupBox_6->setEnabled(false); ui->groupBox_7->setEnabled(false); ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png")); flag_conn = false; k = 0; serial->close(); } void MainWindow::Serial_Error(){ //mensaje en caso de error de conexión QMessageBox error; error.setText("Verifique la conexión de la placa."); error.setIcon(QMessageBox::Warning); error.exec(); } void MainWindow::Serial_Pedir() //función encargada de pedir datos a la placa { if(SP_Seted){ k++; ui->label_25->setText(QString::number(k)); serial->waitForReadyRead(10); if(serial->bytesAvailable() > 0) //en caso de bytes disponibles para lectura, lee datos_com = serial->readAll(); QString Temp; Temp.clear(); Temp.append(datos_com.toHex()); int x = 0; x = Temp.toInt(&ok,16); // Valor decimal de la temperatura leida if((x > 100)&&(x != 0x7E)) x = xant; xant = x; ui->Dato_PIC->setText(datos_com); // Label agregado para testear dato recibido a 1200 Baud ui->label_10->setText(datos_com.toHex()); ui->label_12->setText(QString::number(Temp.toInt(&ok,16))); if(x == 0x7E){ // Me pide PID o Setpoint f++; ui->Pedido_SP->setText(QString::number(f)); Enviar_SP(); } else{ int y = 0; ui->Temp_Hex->setText(QString::number(x)); if (x < 30) y = 30; else if (x > 80) y = 80; else y = x; ui->Temp_Prog->setValue(y); yT = (float)x; CalcularPID(); //----------------------------------------- // QThread::msleep(300); datos_com.clear(); //------Respuesta al pedido por USART------ if((SP_Seted) && (x != 127)&&(!SP_Send)) // ((!flag_test) && (SP_Seted)) Enviar(); Graficar(); } if(i < 200) i ++; else { i = 0; ui->plot->graph(0)->removeDataBefore(250); ui->plot->graph(1)->removeDataBefore(250); } } } void MainWindow::Enviar() { if(!BUG_Seted){ char m; if(k == 1){ // Revisar condición m = TEMPERATURA_LIMITE; k = 1; } // else if(SP_Send == true){ // //m = TEMPERATURA_LIMITE; // m=0xFD; // SP_Send = false; //} else{ m = control; } pedido_com.clear(); pedido_com.append(m); //acá va m en vez de xant // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); } } void MainWindow::Enviar_SP(){ char m = TEMPERATURA_LIMITE; pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); } void MainWindow::CalcularPID() { a = Kr; b = (Kr * Ts) / Ti; c = (Kr * Td) / Ts; rT = TEMPERATURA_LIMITE; e_k = rT - yT; pT = a * (e_k - e_k_1); iT = b * e_k; dT = c * (e_k_2 * e_k_1 + e_k_2); uT = uT_1 + pT + iT + dT; if (uT > max) uT = max; else{ if(uT < min) uT = min; } control = (int)uT; // Dato calculado para enviar ui->Label_yT->setText(QString::number(yT)); ui->Label_Kr->setText(QString::number(a)); ui->Label_Ti->setText(QString::number(b)); ui->Label_Td->setText(QString::number(c)); ui->Label_ek->setText(QString::number(e_k)); ui->Label_ek1->setText(QString::number(e_k_1)); ui->Label_ek2->setText(QString::number(e_k_2)); ui->Label_uT->setText(QString::number(uT)); ui->Label_uT1->setText(QString::number(uT_1)); ui->Label_rt->setText(QString::number(rT)); iT0 = iT; eT0 = eT; uT_1 = uT; e_k_2 = e_k_1; e_k_1 = e_k; ui->DATO->setText(QString::number(control)); } void MainWindow::Graficar() { //------------Gráfica Funcional------------- // if((yT - yant) > 10) //probando horno de los vagos // yT = yant; ui->plot->graph(0)->addData(i, yT); //setData(xg, yg); ui->plot->graph(1)->addData(i, TEMPERATURA_LIMITE); //setData(xg, zg); ui->plot->graph(1)->setPen(QPen(Qt::red)); ui->plot->replot(); } void MainWindow::SetupGraph() { ui->plot->addGraph(); ui->plot->graph(0)->setName("Estado del Sistema"); ui->plot->graph(0)->setPen(QPen(Qt::blue)); ui->plot->addGraph(); ui->plot->graph(1)->setName("Set Point"); ui->plot->graph(1)->setPen(QPen(Qt::red)); //ui->plot->addGraph(); //ui->plot->graph(2)->setName("Señal de Control"); //ui->plot->graph(2)->setPen(QPen(Qt::black)); ui->plot->axisRect()->setupFullAxesBox(); ui->plot->legend->setVisible(true); ui->plot->xAxis->setLabel("Samples"); ui->plot->yAxis->setLabel("T ºC"); ui->plot->xAxis->setRange(0, 249); ui->plot->yAxis->setRange(-10, 150); } void MainWindow::on_Conectar_Com_clicked() { if(!flag_conn){ Serial_Conect(); Boton = true; //ui->Set_Point->setEnabled(false); } else{ Serial_Desconect(); //ui->Set_Point->setEnabled(true); } } void MainWindow::on_Desconectar_Com_clicked() { Serial_Desconect(); } void MainWindow::on_Set_Point_clicked() { flag_test = true; TEMPERATURA_LIMITE = (int)ui->SetPoint->value(); // Ajuste del valor de ºC a mV i = 0; ui->plot->graph(0)->removeDataBefore(250); ui->plot->graph(1)->removeDataBefore(250); iT0 = 0; eT0 = 0; Kr = ui->Spin_Kr->value(); Ti = ui->Spin_Ti->value(); Td = ui->Spin_Td->value(); uT_1 = 0; e_k_2 = 0; e_k_1 = 0; e_k = 0; uT = 0; if(!SP_Seted){ Enviar_SP(); SP_Seted = true; } } void MainWindow::Reinicio(){ if(SP_Send == false){ char m = 0xFD; pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); SP_Send = true; } else{ char m = TEMPERATURA_LIMITE; pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); SP_Send = false; } } void MainWindow::on_Bot_Envio_clicked() { flag_test = false; char m = ui->Edit_Envio->text().toInt(&ok,16);//QString::number(ui->Edit_Envio->text().toInt(&ok)); pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete ui->Dato_PC->clear(); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(pedido_com.toHex()); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); } void MainWindow::on_checkBox_clicked() { if(ui->checkBox->isChecked()){ ui->Bot_Envio->setEnabled(true); ui->Edit_Envio->setEnabled(true); BUG_Seted = true; } else{ ui->Bot_Envio->setEnabled(false); ui->Edit_Envio->setEnabled(false); BUG_Seted = false; Enviar(); } } void MainWindow::on_Bot_Debug_clicked() { if(ui->groupBox_6->isVisible()){ ui->groupBox_6->setVisible(false); ui->groupBox_6->setEnabled(true); ui->groupBox_7->setVisible(false); ui->groupBox_7->setEnabled(true); ui->layoutWidget->setSizeIncrement(747,688); ui->Bot_Debug->setIcon(QIcon(":/pics/bug1.png")); } else{ ui->groupBox_6->setVisible(true); ui->groupBox_7->setVisible(true); ui->Bot_Debug->setIcon(QIcon(":/pics/bug2.png")); } } void MainWindow::on_pushButton_clicked() { char m; flag_test = true; m = 252; ui->check_calib->setText("Ajuste PC"); // ui->pushButton_2->setText("Siguiente"); pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); } void MainWindow::on_pushButton_2_clicked() { char m; flag_test = true; m = 254; ui->check_calib->setText("Ajuste Horno"); // ui->pushButton_2->setText("Siguiente"); pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); } void MainWindow::on_pushButton_3_clicked() { if((serial->open(QIODevice::ReadWrite))) //indicador de conexión serie establecida { //ui->Set_Point->setEnabled(false); ui->SetPoint->setEnabled(false); ui->Spin_Kr->setEnabled(false); ui->Spin_Ti->setEnabled(false); ui->Spin_Td->setEnabled(false); ui->pushButton_4->setEnabled(true); ui->pushButton_4->setText("Detener"); ui->pushButton_3->setEnabled(false); //ui->Bot_Debug->setEnabled(false); //ui->groupBox_6->setEnabled(false); //ui->groupBox_7->setEnabled(false); //ui->Conectar_Com->setIcon(QIcon(":/pics/orange-usb-connected-256.png")); flag_conn = true; char m = 0xFD; pedido_com.clear(); pedido_com.append(m); // antes era una A - convertimos el dato solicitado para que la placa lo interprete QString Out; Out.clear(); Out.append(pedido_com.toHex()); ui->Dato_PC->setText(pedido_com); // Label para testear la respuesta de la PC ui->label_6->setText(Out); ui->label_8->setText(QString::number(ui->label_6->text().toInt(&ok,16))); serial->write(pedido_com); //escribimos en el buffer serial->waitForBytesWritten(30); flag_test = true; TEMPERATURA_LIMITE = (int)ui->SetPoint->value(); // Ajuste del valor de ºC a mV i = 0; ui->plot->graph(0)->removeDataBefore(250); ui->plot->graph(1)->removeDataBefore(250); iT0 = 0; eT0 = 0; Kr = ui->Spin_Kr->value(); Ti = ui->Spin_Ti->value(); Td = ui->Spin_Td->value(); uT_1 = 0; e_k_2 = 0; e_k_1 = 0; e_k = 0; uT = 0; if(!SP_Seted){ Enviar_SP(); SP_Seted = true; } //ui->Set_Point->setEnabled(false); } } void MainWindow::on_pushButton_4_clicked() { if((flag_conn)&&(Boton == true)){ //ui->Set_Point->setEnabled(true); ui->SetPoint->setEnabled(true); ui->Spin_Kr->setEnabled(true); ui->Spin_Ti->setEnabled(true); ui->Spin_Td->setEnabled(true); ui->Temp_Prog->setValue(30); ui->Bot_Debug->setEnabled(true); ui->groupBox_6->setEnabled(true); ui->pushButton_3->setEnabled(true); ui->pushButton_4->setEnabled(false); //ui->groupBox_7->setEnabled(true); //ui->Conectar_Com->setIcon(QIcon(":/pics/red-usb-disconnected-256.png")); flag_conn = false; k = 0; SP_Seted = false; //ui->Set_Point->setEnabled(true); serial->close(); }}
36.728489
165
0.544641
adricatena
757c539a328d5eea7fef40c39262bb64741accd5
1,257
cpp
C++
C++/1679.MaxNumberOfK-SumPairs.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
C++/1679.MaxNumberOfK-SumPairs.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
C++/1679.MaxNumberOfK-SumPairs.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
/*class Solution { public: int maxOperations(vector<int>& nums, int k) { int ops = 0; sort(begin(nums), end(nums)); int start = 0; int end = nums.size()-1; while(start<end) { int temp = nums[start]+nums[end]; if(temp==k) { ops++; start++; end--; } else if(temp<k) start++; else end--; } return ops; } }; /* TC: O(nlongn) SC: O(1) */ class Solution { public: int maxOperations(vector<int>& nums, int k) { int ops = 0; int temp; unordered_map<int, int> m; for(int i=0; i<nums.size(); i++) { //fixing 1 value as nums[i] and looking for k-nums[i] in the map temp = k-nums[i]; //if the value exists, incrementing the operations count and decrementing the value from map if(m[temp]>0) { ops++; m[temp]--; } //if not, adding nums[i] value to the map else m[nums[i]]++; } return ops; } }; /* TC: O(n) SC: O(n) */
20.274194
104
0.405728
SSKale1
757d59b96b2afcc57f24535990100505d52adc8e
6,238
cpp
C++
Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp
SecurityInnovation/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
35
2015-05-16T06:36:47.000Z
2021-08-31T15:32:09.000Z
Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
3
2015-06-18T06:16:51.000Z
2017-11-16T23:23:59.000Z
Test/Automation/ResourceTest/Helper_dll/Helper_dll.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
10
2015-04-07T14:45:48.000Z
2021-11-14T15:14:45.000Z
// Helper_dll.cpp : Defines the entry point for the DLL application. // #include "Helper_dll.h" #include <commctrl.h> #include <string> BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } HELPER_DLL_API int GetListViewItemNumber (HWND listViewHWnd) { return ListView_GetItemCount (listViewHWnd); } // GetListViewItemNumber HELPER_DLL_API char** EnumListViewItemTexts (DWORD processID, HWND listViewHWnd) { const int textSize = 100; int i = 0; int count = ListView_GetItemCount (listViewHWnd); HANDLE hProcess = OpenProcess (STANDARD_RIGHTS_REQUIRED | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); char *pTextProcess = (char *) VirtualAllocEx (hProcess, NULL, textSize, MEM_COMMIT, PAGE_READWRITE); LV_ITEM *pListViewItemProcess = (LV_ITEM *) VirtualAllocEx (hProcess, NULL, sizeof (LV_ITEM), MEM_COMMIT, PAGE_READWRITE); char** itemTexts = new char*[count]; for (i=0; i<count; i++) { BOOL result = FALSE; char pszText[textSize]; // std::string message; ZeroMemory (pszText, textSize * sizeof (char)); unsigned long bytesRead = 0; unsigned long bytesWritten = 0; LV_ITEM listViewItem; ZeroMemory (&listViewItem, sizeof (listViewItem)); listViewItem.mask = LVIF_TEXT; listViewItem.iItem = i; listViewItem.iSubItem = 0; listViewItem.cchTextMax = textSize; listViewItem.pszText = pTextProcess; result = WriteProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesWritten); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "WriteProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; break; } result = ListView_GetItem (listViewHWnd, pListViewItemProcess); if (!result) { MessageBox (NULL, "ListView_GetItem failed", "ListView_GetItem Error", MB_OK); break; } result = ReadProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesRead); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; break; } result = ReadProcessMemory (hProcess, listViewItem.pszText, pszText, textSize, &bytesRead); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; break; } /* message = i; message += "/"; message += count; message += ": "; message += pszText; MessageBox (NULL, message, "itemtext", MB_OK); */ // MessageBox (NULL, pszText, "itemtext", MB_OK); itemTexts[i] = new char[bytesRead+1]; strncpy (itemTexts[i], pszText, bytesRead); itemTexts[i][bytesRead] = '\0'; } // for (0 <= i < count) return itemTexts; } // EnumListViewItemTexts HELPER_DLL_API char* GetListViewItemText (DWORD processID, HWND listViewHWnd, int itemNum) { const int textSize = 100; HANDLE hProcess = OpenProcess (STANDARD_RIGHTS_REQUIRED | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); char *pTextProcess = (char *) VirtualAllocEx (hProcess, NULL, textSize, MEM_COMMIT, PAGE_READWRITE); LV_ITEM *pListViewItemProcess = (LV_ITEM *) VirtualAllocEx (hProcess, NULL, sizeof (LV_ITEM), MEM_COMMIT, PAGE_READWRITE); BOOL result = FALSE; char pszText[textSize]; ZeroMemory (pszText, textSize * sizeof (char)); unsigned long bytesRead = 0; unsigned long bytesWritten = 0; LV_ITEM listViewItem; ZeroMemory (&listViewItem, sizeof (listViewItem)); listViewItem.mask = LVIF_TEXT; listViewItem.iItem = itemNum; listViewItem.iSubItem = 0; listViewItem.cchTextMax = textSize; listViewItem.pszText = pTextProcess; result = WriteProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesWritten); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "WriteProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; return NULL; } result = ListView_GetItem (listViewHWnd, pListViewItemProcess); if (!result) { MessageBox (NULL, "ListView_GetItem failed", "ListView_GetItem Error", MB_OK); return NULL; } result = ReadProcessMemory (hProcess, pListViewItemProcess, &listViewItem, sizeof (listViewItem), &bytesRead); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; return NULL; } result = ReadProcessMemory (hProcess, listViewItem.pszText, pszText, textSize, &bytesRead); if (!result) { char *msg = NULL; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL); MessageBox (NULL, msg, "ReadProcessMemory Error", MB_OK); LocalFree (msg); msg = NULL; return NULL; } char *itemText = new char[bytesRead+1]; ZeroMemory (itemText, (bytesRead + 1) * sizeof (char)); strncpy (itemText, pszText, bytesRead); return itemText; } // GetListViewItemText
33.718919
201
0.730683
SecurityInnovation
757d70ec3f31ffdac6aeb7da598032de7bdd2dd0
3,344
cpp
C++
src/concepts.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
src/concepts.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
src/concepts.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
#include "concepts.hpp" #include <unordered_map> #include <cmath> using namespace quickcalc; namespace { constexpr double QC_FALSE = 0.0; constexpr double QC_TRUE = 1.0; constexpr double QC_EPSILON = 1e-15; // C++17 doesn't define a pi constant, so we'll use our own constexpr double QC_PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164063; double qcIf(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } double param0 = exec.evaluate(params[0].get()); // false if (abs(param0) < QC_EPSILON) { if (params.size() >= 3) { return exec.evaluate(params[2].get()); } else { return param0; } } else { return exec.evaluate(params[1].get()); } } double qcEq(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return abs(exec.evaluate(params[0].get()) - exec.evaluate(params[1].get())) < QC_EPSILON; } double qcNe(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return abs(exec.evaluate(params[0].get()) - exec.evaluate(params[1].get())) >= QC_EPSILON; } double qcGt(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return exec.evaluate(params[0].get()) > exec.evaluate(params[1].get()); } double qcLt(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return exec.evaluate(params[0].get()) < exec.evaluate(params[1].get()); } double qcGe(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return exec.evaluate(params[0].get()) >= exec.evaluate(params[1].get()); } double qcLe(Executor &exec, const std::vector<ExprNode::ptr> &params) { if (params.size() < 2) { return NAN; } return exec.evaluate(params[0].get()) <= exec.evaluate(params[1].get()); } double qcTrue(Executor &exec, const std::vector<ExprNode::ptr> &params) { return QC_TRUE; } double qcFalse(Executor &exec, const std::vector<ExprNode::ptr> &params) { return QC_FALSE; } double qcEpsilon(Executor &exec, const std::vector<ExprNode::ptr> &params) { return QC_EPSILON; } double qcPi(Executor &exec, const std::vector<ExprNode::ptr> &params) { return QC_PI; } std::unordered_map<std::string, ExecutorState::Func> functions = { { "if", &qcIf }, { "eq", &qcEq }, { "ne", &qcNe }, { "gt", &qcGt }, { "lt", &qcLt }, { "ge", &qcGe }, { "le", &qcLe }, { "TRUE", &qcTrue }, { "true", &qcTrue }, { "FALSE", &qcFalse }, { "false", &qcFalse }, { "EPSILON", &qcEpsilon }, { "PI", &qcPi }, }; } void quickcalc::loadConcepts(ExecutorState &state) { for (auto &func : functions) { state.setFunction(func.first, func.second); } }
29.857143
105
0.546651
WillCoates
757f61db691e31831d70cb2a3caf1aecd9bc9107
1,954
cpp
C++
fboss/agent/hw/switch_asics/CredoF104Asic.cpp
ekmixon/fboss
56de7da7763bae1b67e28f92323534b21abc129b
[ "BSD-3-Clause" ]
834
2015-03-10T18:12:28.000Z
2022-03-31T20:16:17.000Z
fboss/agent/hw/switch_asics/CredoF104Asic.cpp
ekmixon/fboss
56de7da7763bae1b67e28f92323534b21abc129b
[ "BSD-3-Clause" ]
82
2015-04-07T08:48:29.000Z
2022-03-11T21:56:58.000Z
fboss/agent/hw/switch_asics/CredoF104Asic.cpp
ekmixon/fboss
56de7da7763bae1b67e28f92323534b21abc129b
[ "BSD-3-Clause" ]
296
2015-03-11T03:45:37.000Z
2022-03-14T22:54:22.000Z
// Copyright 2004-present Facebook. All Rights Reserved. #include "fboss/agent/hw/switch_asics/CredoF104Asic.h" #include "fboss/agent/FbossError.h" namespace facebook::fboss { bool CredoF104Asic::isSupported(Feature feature) const { switch (feature) { case HwAsic::Feature::MACSEC: case HwAsic::Feature::REMOVE_PORTS_FOR_COLDBOOT: case HwAsic::Feature::EMPTY_ACL_MATCHER: return true; default: return false; } return false; } std::set<cfg::StreamType> CredoF104Asic::getQueueStreamTypes( bool /* cpu */) const { throw FbossError("CredoF104Asic doesn't support queue feature"); } int CredoF104Asic::getDefaultNumPortQueues( cfg::StreamType /* streamType */, bool /* cpu */) const { throw FbossError("CredoF104Asic doesn't support queue feature"); } uint64_t CredoF104Asic::getDefaultReservedBytes( cfg::StreamType /* streamType */, bool /* cpu */) const { throw FbossError("CredoF104Asic doesn't support queue feature"); } cfg::MMUScalingFactor CredoF104Asic::getDefaultScalingFactor( cfg::StreamType /* streamType */, bool /* cpu */) const { throw FbossError("CredoF104Asic doesn't support queue feature"); } uint32_t CredoF104Asic::getMaxMirrors() const { throw FbossError("CredoF104Asic doesn't support mirror feature"); } uint16_t CredoF104Asic::getMirrorTruncateSize() const { throw FbossError("CredoF104Asic doesn't support mirror feature"); } uint32_t CredoF104Asic::getMaxLabelStackDepth() const { throw FbossError("CredoF104Asic doesn't support label feature"); }; uint64_t CredoF104Asic::getMMUSizeBytes() const { throw FbossError("CredoF104Asic doesn't support MMU feature"); }; int CredoF104Asic::getMaxNumLogicalPorts() const { throw FbossError("CredoF104Asic doesn't support logical ports feature"); } uint32_t CredoF104Asic::getMaxWideEcmpSize() const { throw FbossError("CredoF104Asic doesn't support ecmp feature"); } }; // namespace facebook::fboss
32.566667
74
0.748209
ekmixon
7581db2587f589f531c5f9eadccdbc415a036ec9
904
cpp
C++
tests/test_main.cpp
dvetutnev/tst_concurrent_fs_access
ed7d218c3031e016765fb6a67489c49baf794fdd
[ "MIT" ]
null
null
null
tests/test_main.cpp
dvetutnev/tst_concurrent_fs_access
ed7d218c3031e016765fb6a67489c49baf794fdd
[ "MIT" ]
null
null
null
tests/test_main.cpp
dvetutnev/tst_concurrent_fs_access
ed7d218c3031e016765fb6a67489c49baf794fdd
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <boost/locale/generator.hpp> #include <boost/filesystem/path.hpp> #include <iostream> #include <locale> #include <cstdlib> #include <ctime> struct separated : std::numpunct<char> { virtual std::string do_grouping() const { return "\03"; } }; int main(int argc, char** argv) { { // Setup default locale const boost::locale::generator gen; const std::locale loc = gen.generate(std::locale(), ""); std::locale::global(loc); std::cout.imbue(loc); std::wcout.imbue(loc); boost::filesystem::path::imbue(loc); } ::testing::InitGoogleTest(&argc, argv); std::locale separatedLocale{std::cout.getloc(), new separated}; std::cout.imbue(separatedLocale); std::srand(static_cast<unsigned int>(std::time(nullptr))); return RUN_ALL_TESTS(); }
23.179487
68
0.608407
dvetutnev
7583b3a28127b9261c8fffb0e9d0d738586a89a8
3,133
cpp
C++
test/client_performance_test.cpp
penggan666/miniob
23a3c30e06b06958f70aa9dc2c31e70354e2b708
[ "Apache-2.0" ]
1
2022-03-02T03:41:13.000Z
2022-03-02T03:41:13.000Z
test/client_performance_test.cpp
Wind-Gone/OceanBase-Contest-Miniob
b16d6b2c6785abf99eb816ff8c7417bafd1ddf96
[ "MIT" ]
null
null
null
test/client_performance_test.cpp
Wind-Gone/OceanBase-Contest-Miniob
b16d6b2c6785abf99eb816ff8c7417bafd1ddf96
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved. miniob is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ // // Created by Longda on 2021 // #include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "common/defs.h" #include "common/metrics/metrics.h" #include "common/metrics/metrics_registry.h" #include "common/metrics/console_reporter.h" #define MAX_MEM_BUFFER_SIZE 8192 #define PORT_DEFAULT 66789 using namespace common; char *server_host = (char *)LOCAL_HOST; void *test_server(void *param) { Meter *tps_meter = (Meter *)param; std::cout << "Begin to connect server. " << std::endl; int sockfd, sendbytes; // char send[MAXLINE]; char send_buf[MAX_MEM_BUFFER_SIZE] = {0}; char recv_buf[MAX_MEM_BUFFER_SIZE] = {0}; snprintf(send_buf, sizeof(send_buf), "%s", "select count(*) from test"); // char buf[MAXDATASIZE]; struct hostent *host; struct sockaddr_in serv_addr; if ((host = gethostbyname(server_host)) == NULL) { perror("gethostbyname"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket error \n"); exit(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons((uint16_t)PORT_DEFAULT); serv_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(serv_addr.sin_zero), 8); if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) { perror("Failed to connect \n"); exit(1); } while (true) { if ((sendbytes = send(sockfd, send_buf, strlen(send_buf) + 1, 0)) == -1) { perror("send error \n"); exit(1); } memset(recv_buf, 0, sizeof(recv_buf)); int len = recv(sockfd, recv_buf, sizeof(recv_buf), 0); if (len < 0) { printf("connection exception\n"); break; } if (len == 0) { printf("Connection has been closed\n"); break; } tps_meter->inc(); } close(sockfd); return NULL; } int main(int argc, char *argv[]) { if (argc >= 2) { server_host = argv[1]; } MetricsRegistry &metric_registry = get_metrics_registry(); ConsoleReporter *console_reporter = get_console_reporter(); metric_registry.add_reporter(console_reporter); Meter *tps_meter = new Meter(); metric_registry.register_metric("client.sendtps", tps_meter); for (int i = 0; i < 8; i++) { pthread_t pid; pthread_create(&pid, NULL, test_server, tps_meter); } while (1) { sleep(60); metric_registry.snapshot(); metric_registry.report(); } return 0; }
25.471545
111
0.673795
penggan666
758a31c0af23360e53d7a26e9beb6315892c4cb9
548
cpp
C++
Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp
atul070/interview
505444570bba6e9d5672272eea5f3784834d2d9e
[ "Apache-2.0" ]
1
2020-10-18T22:06:12.000Z
2020-10-18T22:06:12.000Z
Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp
atul070/interview
505444570bba6e9d5672272eea5f3784834d2d9e
[ "Apache-2.0" ]
null
null
null
Interview Preparation Kit - CPP/01. Warm-up Challenges/002. Counting Valleys.cpp
atul070/interview
505444570bba6e9d5672272eea5f3784834d2d9e
[ "Apache-2.0" ]
null
null
null
// Problem: https://www.hackerrank.com/challenges/counting-valleys/problem // Score: 15 #include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; string str; cin >> str; int ans = 0; int current_level = 0; for (char c: str){ if (c == 'D') { if (current_level == 0){ ans++; } current_level--; } else if (c == 'U') current_level++; } cout << ans; return 0; }
15.657143
75
0.452555
atul070
758dabfa6a951d27c84c1942f757adac38e03b30
6,531
cpp
C++
iOS/CustomAudioUnit.cpp
DaCao/Sonic
0bc327b97560c83cb6cc22b2b2a1e399554194d8
[ "MIT" ]
null
null
null
iOS/CustomAudioUnit.cpp
DaCao/Sonic
0bc327b97560c83cb6cc22b2b2a1e399554194d8
[ "MIT" ]
null
null
null
iOS/CustomAudioUnit.cpp
DaCao/Sonic
0bc327b97560c83cb6cc22b2b2a1e399554194d8
[ "MIT" ]
null
null
null
// // CustomAudioUnit.cpp // Demo // // Created by Philadelphia Game Lab on 6/11/14. // Copyright (c) 2014 Philadelphia Game Lab. All rights reserved. // #include "CustomAudioUnit.h" #define BUF_SIZE 512 #define BIT_DEPTH 16 #define SAMPLE_RATE 44100 static OSStatus recordingCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { //Please dont remove the following commented code //The following code will be used if we use recording callback //TODO: Use inRefCon to access our interface object to do stuff //Then use inNumberFrames to figure out how much data is available and make that much space available in buffers in AudioBufferList //AudioBufferList list; //list.mNumberBuffers = 1; //list.mBuffers[0].mData = sampleBuffer; //list.mBuffers[0].mDataByteSize = 2* inNumberFrames; //list.mBuffers[0].mNumberChannels = 1; //AudioUnitRender([audioInterface audioUnitInstance], ioActionFlags, inTimeStamp, 1, inNumberFrames, &list); return noErr; } static OSStatus playbackCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { //Please dont remove the following commented code //The following code will be used for immediate debugging //Notes: ioData contains buffers (may be more than one) //Fill them up as much as you can. Remember to set the size value in each buffer to match how much data is in each buffer. //ioData->mBuffers[i].mNumberChannels is no. of channels per buffer //*ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence; //for (UInt32 i=0; i<ioData->mNumberBuffers; ++i) { // memset(ioData->mBuffers[i].mData, 10000, ioData->mBuffers[i].mDataByteSize); // std::cout<<"\naksjdhka " << ioData->mBuffers[i].mDataByteSize <<" i=" << i <<" "<<inBusNumber; // //} //clock_t t1, t2; //t1 = clock(); mixer3D->performMix((short *)ioData->mBuffers[0].mData, (short *) ioData->mBuffers[1].mData); //t2 = clock(); //cout<<"The time consumption is "<<((double)(t2-t1))/CLOCKS_PER_SEC<<endl; return noErr; } void CustomAudioUnit::init () { mixer3D = new Mixer3D(BUF_SIZE, SAMPLE_RATE, BIT_DEPTH, myWorld); AudioComponentDescription desc; desc.componentType = kAudioUnitType_Output; desc.componentSubType = kAudioUnitSubType_RemoteIO; desc.componentFlags = 0; desc.componentFlagsMask = 0; desc.componentManufacturer = kAudioUnitManufacturer_Apple; AudioComponent component = AudioComponentFindNext(NULL, &desc); AudioComponentInstanceNew(component, &audioUnitInstance); UInt32 enableIO; AudioUnitElement inputBus = 1; AudioUnitElement outputBus = 0; //Disabling IO for recording enableIO = 0; AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enableIO, sizeof(enableIO)); //Enabling IO for playback enableIO = 1; AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &enableIO, sizeof(enableIO)); UInt32 bytesPerSample = sizeof(short) ; //sizeof(AudioUnitSampleType); AudioStreamBasicDescription stereoStreamFormat = {0}; stereoStreamFormat.mBitsPerChannel = 8 * bytesPerSample; stereoStreamFormat.mBytesPerFrame = bytesPerSample; stereoStreamFormat.mBytesPerPacket = bytesPerSample; stereoStreamFormat.mChannelsPerFrame = 2; // 2 incdicates stereo stereoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved; stereoStreamFormat.mFormatID = kAudioFormatLinearPCM; stereoStreamFormat.mFramesPerPacket = 1; stereoStreamFormat.mReserved = 0; stereoStreamFormat.mSampleRate = 44100.0; AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription)); AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, outputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription)); //Setting input callback AURenderCallbackStruct callbackStruct; callbackStruct.inputProc = &recordingCallback; //////Should there be an ampersand callbackStruct.inputProcRefCon = audioUnitInstance; AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, inputBus, &callbackStruct, sizeof(callbackStruct)); /////Not sure of scope and bus/element //Setting output callback callbackStruct.inputProc = &playbackCallback; callbackStruct.inputProcRefCon = audioUnitInstance; AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, outputBus, &callbackStruct, sizeof(callbackStruct)); AudioUnitInitialize(audioUnitInstance); } CustomAudioUnit::CustomAudioUnit() { myWorld = new World; init(); std::cout<<"\nConstructor"; } CustomAudioUnit::~CustomAudioUnit() { AudioUnitUninitialize(audioUnitInstance); AudioComponentInstanceDispose(audioUnitInstance); std::cout<<"\nDestructor"; } void CustomAudioUnit::play() { //init(); myWorld->createWriteThread(); AudioOutputUnitStart(audioUnitInstance); std::cout<<"\nPlay"; } void CustomAudioUnit::stop() { AudioOutputUnitStop(audioUnitInstance); //AudioUnitUninitialize(audioUnitInstance); //AudioComponentInstanceDispose(audioUnitInstance); std::cout<<"\nStop"; } AudioObj* CustomAudioUnit::addAudioObjectInWorld(string wavFile, VariableForLocation x, VariableForLocation y, VariableForLocation z) { if(myWorld != nullptr) { Location loc = Location(x, y, z); Velocity vel = Velocity(); return myWorld->addAudioObj(loc,vel,wavFile); } else { throw("World has to be created before adding audio objects"); return nullptr; } } void CustomAudioUnit::setPlayerPosition(VariableForLocation x, VariableForLocation y, VariableForLocation z) { myWorld->setPlayerPosition(x, y, z); } void CustomAudioUnit::setPlayerBearing(float bearing) { myWorld->setPlayerBearing(bearing); }
37.32
203
0.740009
DaCao
759013fd7f21515fac3ea4e693f277b4004598b3
9,994
cpp
C++
common/quote.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
common/quote.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
common/quote.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)1998-2022, WWIV Software Services */ /* */ /* 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 "common/quote.h" #include "common/common_events.h" #include "common/input.h" #include "common/output.h" #include "core/datetime.h" #include "core/eventbus.h" #include "core/strings.h" #include "core/textfile.h" #include "fmt/printf.h" #include "local_io/keycodes.h" #include "sdk/filenames.h" #include "sdk/msgapi/parsed_message.h" #include <memory> #include <string> #include <vector> using namespace wwiv::core; using namespace wwiv::sdk; using namespace wwiv::local::io; using namespace wwiv::strings; namespace wwiv::common { static std::unique_ptr<std::vector<std::string>> quotes_ind; static std::string FirstLettersOfVectorAsString(const std::vector<std::string>& parts) { std::string result; for (const auto& part : parts) { result.push_back(part.front()); } return result; } void set_quotes_ind(std::unique_ptr<std::vector<std::string>>&& u) { quotes_ind = std::move(u); } std::string GetQuoteInitials(const std::string& orig_name) { if (orig_name.empty()) { return {}; } auto name = orig_name; if (starts_with(name, "``")) { name = name.substr(2); } if (const auto paren_start = name.find('('); paren_start != std::string::npos && !isdigit(name.at(paren_start + 1))) { const auto inner = name.substr(paren_start + 1); return GetQuoteInitials(inner); } const auto last = name.find_first_of("#<>()[]`"); const auto parts = last != std::string::npos ? SplitString(name.substr(0, last), " ") : SplitString(name, " "); return FirstLettersOfVectorAsString(parts); } void clear_quotes(wwiv::common::SessionContext& ctx) { File::Remove(FilePath(ctx.dirs().temp_directory(), QUOTES_TXT), true); quotes_ind.reset(); } static std::string to_quote_date_format(time_t t, bool use_24h_format) { const auto dt = DateTime::from_time_t(t); std::ostringstream ss; ss << dt.to_string("%A,%B %d, %Y") << " at "; if (use_24h_format) { ss << dt.to_string("%H:%M"); } else { ss << dt.to_string("%I:%M %p"); } return ss.str(); } static std::string to_quote_date_line(quote_date_format_t type, bool use_24h_format, time_t tt, const std::string& tb) { const auto datetime = to_quote_date_format(tt, use_24h_format); std::string date_line; switch (type) { case quote_date_format_t::generic: date_line = fmt::sprintf("%c3On %c1%s, %c2%s%c3 wrote:%c0", 0x03, 0x03, datetime, 0x03, tb, 0x03, 0x03); break; case quote_date_format_t::email: date_line = fmt::sprintf("%c3In your e-mail of %c2%s%c3, you wrote:%c0", 0x03, 0x03, datetime, 0x03, 0x03); break; case quote_date_format_t::post: date_line = fmt::sprintf("%c3In a message posted %c2%s%c3, you wrote:%c0", 0x03, 0x03, datetime, 0x03, 0x03); break; case quote_date_format_t::forward: date_line = fmt::sprintf("%c3Message forwarded from %c2%s%c3, sent on %s.%c0", 0x03, 0x03, tb, 0x03, datetime, 0x03); break; case quote_date_format_t::no_quote: default: return {}; } date_line.append("\r\n"); return date_line; } std::vector<std::string> create_quoted_text_from_message(std::string& raw_text, const std::string& to_name, quote_date_format_t type, bool use_24h_format, time_t tt) { const msgapi::WWIVParsedMessageText pmt(raw_text); msgapi::parsed_message_lines_style_t style{}; style.line_length = 72; style.ctrl_lines = msgapi::control_lines_t::no_control_lines; style.add_wrapping_marker = false; // experimental style.reattribute_quotes = true; auto lines = pmt.to_lines(style); auto it = std::begin(lines); const auto end = std::end(lines); if (lines.size() < 2) { return {}; } const auto to_node = *it++; ++it; const auto quote_initials = GetQuoteInitials(to_name); std::vector<std::string> out; if (type != quote_date_format_t::no_quote) { out.emplace_back( to_quote_date_line(type, use_24h_format, tt, properize(strip_to_node(to_node)))); } for (; it != end; ++it) { auto line = *it; StringReplace(&line, "\x03" "0", "\x03" "5"); out.emplace_back(fmt::sprintf("%c%c%s%c%c> %c%c%s%c0", 0x03, '1', quote_initials, 0x03, '7', 0x03, '5', line, 0x03)); } return out; } void auto_quote(std::string& raw_text, const std::string& to_name, quote_date_format_t type, time_t tt, wwiv::common::Context& ctx) { const auto fn = FilePath(ctx.session_context().dirs().temp_directory(), INPUT_MSG); File::Remove(fn); TextFile f(fn, "w"); if (!f) { return; } const auto use_24h_format = ctx.u().twentyfour_clock(); auto lines = create_quoted_text_from_message(raw_text, to_name, type, use_24h_format, tt); for (const auto& l : lines) { f.WriteLine(l); } if (ctx.u().messages_posted() < 10) { bout.printfile(QUOTE_NOEXT); } } void grab_quotes(std::string& raw_text, const std::string& to_name, wwiv::common::Context& ctx) { if (raw_text.back() == CZ) { // Since CZ isn't special on Win32/Linux. Don't write it out // to the quotes file. raw_text.pop_back(); } clear_quotes(ctx.session_context()); File f(FilePath(ctx.session_context().dirs().temp_directory(), QUOTES_TXT)); if (f.Open(File::modeDefault | File::modeCreateFile | File::modeTruncate, File::shareDenyNone)) { f.Write(raw_text); } const auto use_24h_format = ctx.u().twentyfour_clock(); quotes_ind = std::make_unique<std::vector<std::string>>(create_quoted_text_from_message( raw_text, to_name, quote_date_format_t::no_quote, use_24h_format, 0)); } std::vector<std::string> query_quote_lines(wwiv::common::SessionContext& ctx) { std::vector<std::string> lines; if (!quotes_ind || quotes_ind->empty()) { return {}; } int start_line; int end_line; auto num_lines = 0; do { start_line = 0; end_line = 0; auto iter = std::begin(*quotes_ind); auto end = std::end(*quotes_ind); num_lines = 1; auto abort = false; for (; iter != end; ++iter) { // Skip control line (^D) auto& line = *iter; if (!line.empty() && line.front() == 0x04) { continue; } StringTrimCRLF(&line); bout.bpla(fmt::format("{:>3} {}", num_lines++, line), &abort); if (abort) { break; } // Add line s to the list of lines. lines.emplace_back(line); } --num_lines; bout.nl(); // If the user has hungup, this will throw an exception. bus().invoke<CheckForHangupEvent>(); if (lines.empty() || ctx.hangup()) { return {}; } bout.format("|#2Quote from line 1-{}? (?=relist, Q=quit) ", num_lines); auto k = bin.input_number_hotkey(1, {'Q', '?'}, 1, num_lines); if (k.key == 'Q') { return {}; } if (k.key == '?') { bout.nl(); continue; } start_line = k.num; if (start_line == num_lines) { end_line = start_line; } else { bout.format("|#2through line {} - {} ? (Q=quit) ", start_line, num_lines); k = bin.input_number_hotkey(start_line, {'Q', '?'}, start_line, num_lines); if (k.key == 'Q') { return {}; } if (k.key == '?') { bout.nl(); continue; } end_line = k.num; } if (start_line == end_line) { bout << "|#5Quote line " << start_line << "? "; } else { bout << "|#5Quote lines " << start_line << "-" << end_line << "? "; } if (!bin.noyes()) { return {}; } break; } while (!ctx.hangup()); return std::vector<std::string>(std::begin(lines) + start_line - 1, std::begin(lines) + end_line); } std::string strip_to_node(const std::string& txt) { std::ostringstream os; if (txt.find('@') != std::string::npos) { bool ok = true; for (auto i = txt.begin(); i != txt.end(); i++) { if (ok) { os << *i; } if ((i + 1) != txt.end() && (i + 2) != txt.end() && *(i + 2) == '#') { ok = false; } } return os.str(); } else if (txt.find("AT") != std::string::npos) { bool ok = true; for (std::string::const_iterator i = txt.begin() + 2; i != txt.end(); ++i) { if (ok) { os << *i; } if (*(i + 1) == '`') { ok = false; } } return os.str(); } return txt; } } // namespace wwiv::common
32.553746
100
0.555033
chwash
759518dc8b02f8bb90fc9519b95b32ce60120ca1
3,433
cpp
C++
pod/DekrispatorDroneBox/drifter.cpp
MrBlueXav/DaisyExamples
41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400
[ "MIT" ]
1
2021-11-05T19:04:32.000Z
2021-11-05T19:04:32.000Z
pod/DekrispatorDroneBox/drifter.cpp
MrBlueXav/DaisyExamples
41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400
[ "MIT" ]
null
null
null
pod/DekrispatorDroneBox/drifter.cpp
MrBlueXav/DaisyExamples
41f5e3a646c24b2bab8bcbc9bbe5b36efd7f6400
[ "MIT" ]
1
2020-08-16T07:36:34.000Z
2020-08-16T07:36:34.000Z
/** ****************************************************************************** * File Name : drifter.c * Author : Xavier Halgand * Date : * Description : random segment waveform generator ****************************************************************************** */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "drifter.h" /*-------------------------------------------------------------------------------------------*/ Drifter_t d1 _CCM_; Drifter_t d2 _CCM_; Drifter_t d3 _CCM_; /*-------------------------------------------------------------------------------------------*/ void Drifter_amp_set(uint8_t val) { d1.gain = d2.gain = d3.gain = (val / MIDI_MAX) * (val / MIDI_MAX); } /*-------------------------------------------------------------------------------------------*/ void Drifter_minFreq_set(uint8_t val) { d1.fmin = d2.fmin = d3.fmin = .1f + 50 * val / MIDI_MAX; } /*-------------------------------------------------------------------------------------------*/ void Drifter_maxFreq_set(uint8_t val) { float x; x = (1 + 19 * val / MIDI_MAX) * d1.fmin; if (x > 10000) d1.fmax = d2.fmax = d3.fmax = 10000; else { d1.fmax = d2.fmax = d3.fmax = x; } } /*-------------------------------------------------------------------------------------------*/ void drifter_newSegment(Drifter_t *d) // { d->n = 0; d->initial = d->final; d->minLength = 0.5f * SAMPLERATE / d->fmax; d->maxLength = 0.5f * SAMPLERATE / d->fmin; d->length = frand_a_b(d->minLength, d->maxLength); d->final = frand_a_b(-1, 1); d->slope = (d->final - d->initial) / d->length; } /*-------------------------------------------------------------------------------------------*/ float drifter_nextSample(Drifter_t *d) // { d->out = d->gain * (d->slope * d->n + d->initial); (d->n)++; if (d->n >= d->length) { drifter_newSegment(d); } return d->out; } /*-------------------------------------------------------------------------------------------*/ float d1_drifter_nextSample(void) // { return drifter_nextSample(&d1); } /*-------------------------------------------------------------------------------------------*/ float d2_drifter_nextSample(void) // { return drifter_nextSample(&d2); } /*---------------------------------------------------------------------------------------------*/ void drifter_prepare(Drifter_t *d) { d->final = 0; d->fmax = 4; d->fmin = 2; d->gain = .01f; drifter_newSegment(d); } /*---------------------------------------------------------------------------------------------*/ void drifter_init(void) { drifter_prepare(&d1); drifter_prepare(&d2); drifter_prepare(&d3); } /*------------------------------------------END--------------------------------------------*/
33.009615
97
0.429945
MrBlueXav
759765b242750efa9faffcc463984dd4281bf6a8
1,923
cxx
C++
src/CallContext.cxx
ToolFramework/CPyCppyy
55df2786e7bb839b0550e3cd34332f0d241412ee
[ "BSD-3-Clause-LBNL" ]
13
2021-07-31T01:21:29.000Z
2022-03-16T16:54:48.000Z
src/CallContext.cxx
ToolFramework/CPyCppyy
55df2786e7bb839b0550e3cd34332f0d241412ee
[ "BSD-3-Clause-LBNL" ]
3
2021-09-21T20:16:45.000Z
2022-03-16T16:53:24.000Z
src/CallContext.cxx
ToolFramework/CPyCppyy
55df2786e7bb839b0550e3cd34332f0d241412ee
[ "BSD-3-Clause-LBNL" ]
2
2021-09-21T13:37:31.000Z
2022-02-10T10:38:14.000Z
// Bindings #include "CPyCppyy.h" #include "CallContext.h" //- data _____________________________________________________________________ namespace CPyCppyy { CallContext::ECallFlags CallContext::sMemoryPolicy = CallContext::kUseStrict; // this is just a data holder for linking; actual value is set in CPyCppyyModule.cxx CallContext::ECallFlags CallContext::sSignalPolicy = CallContext::kNone; } // namespace CPyCppyy //----------------------------------------------------------------------------- void CPyCppyy::CallContext::AddTemporary(PyObject* pyobj) { if (pyobj) { if (!fTemps) fTemps = new Temporary{pyobj, nullptr}; else { Temporary* tmp = fTemps; while (tmp->fNext) tmp = tmp->fNext; tmp->fNext = new Temporary{pyobj, nullptr}; } } } //----------------------------------------------------------------------------- void CPyCppyy::CallContext::Cleanup() { Temporary* tmp = fTemps; while (tmp) { Py_DECREF(tmp->fPyObject); Temporary* tmp2 = tmp->fNext; delete tmp; tmp = tmp2; } fTemps = nullptr; } //----------------------------------------------------------------------------- bool CPyCppyy::CallContext::SetMemoryPolicy(ECallFlags e) { // Set the global memory policy, which affects object ownership when objects // are passed as function arguments. if (kUseHeuristics == e || e == kUseStrict) { sMemoryPolicy = e; return true; } return false; } //----------------------------------------------------------------------------- bool CPyCppyy::CallContext::SetGlobalSignalPolicy(bool setProtected) { // Set the global signal policy, which determines whether a jmp address // should be saved to return to after a C++ segfault. bool old = sSignalPolicy == kProtected; sSignalPolicy = setProtected ? kProtected : kNone; return old; }
31.016129
84
0.560062
ToolFramework
75989185cc35048f02733b64c8f4595aaa93b4e1
5,600
cc
C++
src/graphics/lib/compute/tests/common/arc_parameters.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/graphics/lib/compute/tests/common/arc_parameters.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/graphics/lib/compute/tests/common/arc_parameters.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 "tests/common/arc_parameters.h" #include <math.h> // All computations taken from http://www.w3.org/TR/SVG/implnote.html arc_endpoint_parameters_t arc_endpoint_parameters_from_center(arc_center_parameters_t params) { // Section B.2.3. Conversion from center to endpoint parameterization const double cos_phi = cos(params.phi); const double sin_phi = sin(params.phi); const double org_x1 = params.rx * cos(params.theta); const double org_y1 = params.ry * sin(params.theta); const double org_x2 = params.rx * cos(params.theta + params.theta_delta); const double org_y2 = params.ry * sin(params.theta + params.theta_delta); return { .x1 = params.cx + cos_phi * org_x1 - sin_phi * org_y1, .y1 = params.cy + sin_phi * org_x1 + cos_phi * org_y1, .x2 = params.cx + cos_phi * org_x2 - sin_phi * org_y2, .y2 = params.cy + sin_phi * org_x2 + cos_phi * org_y2, .large_arc_flag = fabs(params.theta_delta) > M_PI, .sweep_flag = params.theta_delta > 0, .rx = params.rx, .ry = params.ry, .phi = params.phi, }; } static double angle_from(double dx, double dy) { double len = hypot(dx, dy); if (!isnormal(len)) return 0.; double angle = acos(dx / len); return dy < 0 ? -angle : angle; } // Compute the endpoint parameterization of a given arc from its center one. arc_center_parameters_t arc_center_parameters_from_endpoint(arc_endpoint_parameters_t params) { // Section C.4.2. Out-of-range parameters // "If the endpoints [...] are identical, then this is equivalent to omitting // the elliptic arc segment entirely." if (params.x2 == params.x1 && params.y2 == params.y1) return {}; // B.2.5 step2 (Ensure radii are positive). double rx = fabs(params.rx); double ry = fabs(params.ry); // B.2.5 step 1 (Ensure radii are non zero). if (rx == 0. || ry == 0.) return {}; // B.2.4 step1 (Equation 5.1) const double cos_phi = cos(params.phi); const double sin_phi = sin(params.phi); #if 1 // NOTE: The following computations are equivalent to the one specified // by the SVG implementation note (and found below in the #else .. #endif // block). Experimentation / debugging shows that they give the same result // up to the 14th decimal, and that this version seems to have slightly less // rounding errors overall. // Undo axis rotation and radii scaling first. const double x1 = (+params.x1 * cos_phi + params.y1 * sin_phi) / rx; const double y1 = (-params.x1 * sin_phi + params.y1 * cos_phi) / ry; const double x2 = (+params.x2 * cos_phi + params.y2 * sin_phi) / rx; const double y2 = (-params.x2 * sin_phi + params.y2 * cos_phi) / ry; // Points are now on a unit circle, find its center in transformed space. const double lx = (x1 - x2) * 0.5; const double ly = (y1 - y2) * 0.5; double cx = (x1 + x2) * 0.5; double cy = (y1 + y2) * 0.5; const double llen2 = lx * lx + ly * ly; if (llen2 < 1) { double radicand = sqrt((1 - llen2) / llen2); if (params.large_arc_flag != params.sweep_flag) radicand = -radicand; cx += -ly * radicand; cy += +lx * radicand; } // Get angle and angle sweep. double theta = angle_from(x1 - cx, y1 - cy); double theta_delta = angle_from(x2 - cx, y2 - cy) - theta; // convert center coordinates back to original space. const double cxs = cx * rx; const double cys = cy * ry; cx = cxs * cos_phi - cys * sin_phi; cy = cxs * sin_phi + cys * cos_phi; #else // !1 const double mx = (params.x1 - params.x2) * 0.5; const double my = (params.y1 - params.y2) * 0.5; const double x1p = cos_phi * mx + sin_phi * my; const double y1p = cos_phi * my - sin_phi * mx; // B.5.2. step 3 (Ensure radii are large enough). double rxrx = rx * rx; double ryry = ry * ry; const double x1px1p = x1p * x1p; const double y1py1p = y1p * y1p; // Starting values for cx', cy', cx and cy, corresponding to the case // where |sigma > 1| below. double cxp = 0.; double cyp = 0.; double cx = (params.x1 + params.x2) * 0.5; double cy = (params.y1 + params.y2) * 0.5; const double sigma = x1px1p / rxrx + y1py1p / ryry; if (sigma >= 1.0) { const double sigma_sqrt = sqrt(sigma); rx = sigma_sqrt * rx; ry = sigma_sqrt * ry; } else { // Back to Section B.2.4: Equation 5.2 const double aa = rxrx * y1py1p; const double bb = ryry * x1px1p; double radicand = sqrt((rxrx * ryry - aa - bb) / (aa + bb)); if (params.large_arc_flag == params.sweep_flag) radicand = -radicand; cxp = radicand * rx * y1p / ry; cyp = -radicand * ry * x1p / rx; // B.5.2. step 3 Compute center. cx += cos_phi * cxp - sin_phi * cyp; cy += sin_phi * cxp + cos_phi * cyp; } // B.5.2. step 4 (Compute theta1 and Dtheta) double theta = angle_from((x1p - cxp) / rx, (y1p - cyp) / ry); double theta_delta = angle_from(-(x1p + cxp) / rx, -(y1p + cyp) / ry) - theta; #endif // !1 if (params.sweep_flag) { if (theta_delta < 0.) theta_delta += M_PI * 2.; } else { if (theta_delta > 0.) theta_delta -= M_PI * 2; } return { .cx = cx, .cy = cy, .rx = rx, .ry = ry, .phi = params.phi, .theta = theta, .theta_delta = theta_delta, }; }
29.473684
80
0.613036
allansrc
7598a31d36c90da882a8847f2526c9b2c7c26177
6,073
cc
C++
bindings/ruby/ext/memory.cc
mgallien/typelib
e27ef63564f623c9362d13c6f443c9944c351841
[ "CECILL-B" ]
1
2021-06-03T22:56:53.000Z
2021-06-03T22:56:53.000Z
bindings/ruby/ext/memory.cc
mgallien/typelib
e27ef63564f623c9362d13c6f443c9944c351841
[ "CECILL-B" ]
null
null
null
bindings/ruby/ext/memory.cc
mgallien/typelib
e27ef63564f623c9362d13c6f443c9944c351841
[ "CECILL-B" ]
null
null
null
#include "typelib.hh" #include <typelib/value_ops.hh> #include <ruby.h> #include <ruby/st.h> using namespace Typelib; using namespace std; using namespace typelib_ruby; #undef VERBOSE static VALUE cMemoryZone; static st_table* MemoryTable; /* For those who are wondering, st_data_t is always the size of an void* * (see the first lines of st.h */ static int memory_table_compare(void* a, void* b) { return (a != b); } static int memory_table_hash(void* a) { /* Use the low-order bits as hash value, as they are the most likely to * change */ return (long)a; } static struct st_hash_type memory_table_type = { (int (*)(...))memory_table_compare, (int (*)(...))memory_table_hash }; struct RbMemoryLayout { int refcount; MemoryLayout layout; boost::shared_ptr<Registry> registry; RbMemoryLayout() : refcount(0) {} RbMemoryLayout(MemoryLayout const& layout, boost::shared_ptr<Registry> registry) : layout(layout), registry(registry) {} }; // MemoryTypes actually holds the memory layout of each memory zone. We cannot // simply use the Type object as, at exit, the Ruby GC do not order finalization // and therefore the registry can be deleted before the Type instances. typedef std::map< void const*, void const* > MemoryTypes; typedef std::map< void const*, RbMemoryLayout > TypeLayouts; MemoryTypes memory_types; TypeLayouts memory_layouts; static void memory_unref(void *ptr) { st_delete(MemoryTable, (st_data_t*)&ptr, 0); MemoryTypes::iterator type_it = memory_types.find(ptr); if (type_it != memory_types.end()) { TypeLayouts::iterator layout_it = memory_layouts.find(type_it->second); RbMemoryLayout& layout = layout_it->second; if (0 == --layout.refcount) memory_layouts.erase(layout_it); memory_types.erase(type_it); } } static void memory_delete(void *ptr) { MemoryTypes::iterator it = memory_types.find(ptr); if (it != memory_types.end()) { TypeLayouts::iterator layout_it = memory_layouts.find(it->second); if (layout_it != memory_layouts.end()) { RbMemoryLayout& layout = layout_it->second; Typelib::ValueOps::destroy( static_cast<uint8_t*>(ptr), layout.layout.begin(), layout.layout.end()); } } free(ptr); memory_unref(ptr); } static VALUE memory_aref(void *ptr) { VALUE val; if (!st_lookup(MemoryTable, (st_data_t)ptr, &val)) { return Qnil; } if (val == Qundef) rb_bug("found undef in memory table"); return val; } static void memory_aset(void *ptr, VALUE obj) { if (! NIL_P(memory_aref(ptr))) rb_raise(rb_eArgError, "there is already a wrapper for %x", ptr); st_insert(MemoryTable, (st_data_t)ptr, obj); } VALUE typelib_ruby::memory_allocate(size_t size) { void* ptr = malloc(size); VALUE zone = Data_Wrap_Struct(cMemoryZone, 0, &memory_delete, ptr); # ifdef VERBOSE fprintf(stderr, "%x: new allocated zone of size %i\n", ptr, size); # endif memory_aset(ptr, zone); return zone; } void typelib_ruby::memory_init(VALUE ptr, VALUE type) { try { void* cptr = memory_cptr(ptr); MemoryTypes::iterator it = memory_types.find(cptr); if (it != memory_types.end()) rb_raise(rb_eArgError, "memory zone already initialized"); // For deinitialization later, get or register the type's layout Type const& t(rb2cxx::object<Type>(type)); TypeLayouts::iterator layout_it = memory_layouts.find(&t); if (layout_it == memory_layouts.end()) { cxx2rb::RbRegistry& registry = rb2cxx::object<cxx2rb::RbRegistry>(type_get_registry(type)); layout_it = memory_layouts.insert( make_pair( &t, RbMemoryLayout(layout_of(t, true), registry.registry) ) ).first; } RbMemoryLayout& layout = layout_it->second; ++layout.refcount; memory_types.insert( make_pair(cptr, &t) ); Typelib::ValueOps::init(static_cast<uint8_t*>(cptr), layout.layout.begin(), layout.layout.end()); } catch(std::runtime_error const& e) { rb_raise(rb_eArgError, "internal error: %s", e.what()); } } VALUE typelib_ruby::memory_wrap(void* ptr) { VALUE zone = memory_aref(ptr); if (NIL_P(zone)) { # ifdef VERBOSE fprintf(stderr, "%x: wrapping new memory zone\n", ptr); # endif zone = Data_Wrap_Struct(cMemoryZone, 0, &memory_unref, ptr); memory_aset(ptr, zone); } else { # ifdef VERBOSE fprintf(stderr, "%x: already known memory zone\n", ptr); # endif } return zone; } void* typelib_ruby::memory_cptr(VALUE ptr) { void* cptr; Data_Get_Struct(ptr, void, cptr); return cptr; } static VALUE memory_zone_address(VALUE self) { void* ptr = memory_cptr(self); return LONG2NUM((long)ptr); } static VALUE memory_zone_to_ptr(VALUE self) { VALUE result = memory_allocate(sizeof(void*)); void* newptr = memory_cptr(result); void* ptr = memory_cptr(self); *reinterpret_cast<void**>(newptr) = ptr; rb_iv_set(result, "@pointed_to_memory", self); return result; } static VALUE string_to_memory_ptr(VALUE self) { rb_str_modify(self); VALUE ptr = memory_wrap(StringValuePtr(self)); rb_iv_set(ptr, "@buffer_string", self); return ptr; } void memory_table_mark(void* ptr) { } void typelib_ruby::Typelib_init_memory() { VALUE mTypelib = rb_define_module("Typelib"); MemoryTable = st_init_table(&memory_table_type); VALUE table = Data_Wrap_Struct(rb_cObject, &memory_table_mark, 0, MemoryTable); rb_iv_set(mTypelib, "@__memory_table__", table); cMemoryZone = rb_define_class_under(mTypelib, "MemoryZone", rb_cObject); rb_define_method(cMemoryZone, "zone_address", RUBY_METHOD_FUNC(memory_zone_address), 0); rb_define_method(cMemoryZone, "to_ptr", RUBY_METHOD_FUNC(memory_zone_to_ptr), 0); rb_define_method(rb_cString, "to_memory_ptr", RUBY_METHOD_FUNC(string_to_memory_ptr), 0); }
26.290043
105
0.671497
mgallien
759bbd0bdc623a447a4cbbd4b64d262ee35ec4ac
3,317
cpp
C++
remote_core/remote_core/src/Controllers/HardwareController.cpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
remote_core/remote_core/src/Controllers/HardwareController.cpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
remote_core/remote_core/src/Controllers/HardwareController.cpp
DaveAMoore/remote_core
a46280a7cee5d52ca08d11ea2de518a7d5e12ca5
[ "MIT" ]
null
null
null
// // HardwareController.cpp // remote_core // // Created by David Moore on 11/5/18. // Copyright © 2018 David Moore. All rights reserved. // #include <algorithm> #include <thread> #include <sys/stat.h> #include "HardwareController.hpp" #include "CommandLine.hpp" #define REMOTE_CONFIGURATION_FILE_DIRECTORY "." using namespace RemoteCore; HardwareController::HardwareController() { } bool HardwareController::doesRemoteExist(Remote &remote) { auto relativePath = (REMOTE_CONFIGURATION_FILE_DIRECTORY + remote.getRemoteID() + ".lircd.conf").c_str(); struct stat buffer; return (stat (relativePath, &buffer) == 0); } void HardwareController::sendCommandForRemoteWithCompletionHandler(Command command, Remote remote, CompletionHandler completionHandler) { /* ***************** Send the command. ***************** */ auto commandString = "irsend SEND_ONCE " + remote.getRemoteID() + " " + command.getCommandID(); CommandLine::sharedCommandLine()->executeCommandWithResultHandler(commandString.c_str(), [=](std::string result, bool isComplete) { if (isComplete) { completionHandler(Error::None); } }); // // Create a lirc thread that handles the sending. // auto lircThread = std::thread([completionHandler]() { // // initialize lirc socket and store file descriptor // int fd = lirc_init("remote_core", 0); // if (fd == -1) { // // Handle init fail // } // // // Check for remote existence // /* // if (!checkRemoteConfig(remote.getRemoteID)) { // // Handle remote not found // } // */ // // // Send command // if (lirc_send_one(lirc_get_local_socket(NULL, 1), remote.getRemoteID().c_str(), command.getCommandID().c_str()) == -1) { // // Handle fail send // } // // // Deinitialize lirc socket // lirc_deinit(); // // completionHandler(Error::None); // }); // Detach the thread. // lircThread.detach(); } std::shared_ptr<TrainingSession> HardwareController::newTrainingSessionForRemote(Remote remote) { // Create a new training session. auto trainingSession = std::make_shared<TrainingSession>(remote); // Keep the session identifier stored. sessionIDs.push_back(trainingSession->getSessionID()); return trainingSession; } void HardwareController::startTrainingSession(std::shared_ptr<TrainingSession> trainingSession) { // It is an error to start a new training session when there is currently an active session. if (currentTrainingSession != nullptr) { throw std::logic_error("Expected 'currentTrainingSession' to be nullptr."); } // Retain the training session. currentTrainingSession = trainingSession; // Start the training session. currentTrainingSession->start(); } void HardwareController::suspendTrainingSession(std::shared_ptr<TrainingSession> trainingSession) { if (currentTrainingSession != trainingSession) { return; } // Suspend the training session. currentTrainingSession->suspend(); // Nullify our reference to the training session. currentTrainingSession = nullptr; }
31.590476
135
0.644558
DaveAMoore
759c382ca4554b7ae1d4feae680b6589035ad5de
58,082
cpp
C++
source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_Point_RV2FP.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
#include "source_code\Hyd_Headers_Precompiled.h" //#include "Hyd_Coupling_Point_RV2FP.h" //constructor Hyd_Coupling_Point_RV2FP::Hyd_Coupling_Point_RV2FP(void){ this->river_profile_index_up=-1; this->river_profile_up=NULL; this->river_profile_index_down=-1; this->river_profile_down=NULL; this->floodplain_elem_index=-1; this->floodplain_elem=NULL; this->floodplain_index=-1; this->fpl_section_id=-1; this->first_found_elem_index=-1; this->mid_height=0.0; this->mid_basepoint=0.0; this->mid_basepoint_profile=0.0; this->mid_fac_up=0.0; this->mid_fac_down=0.0; this->mid_waterlevel=0.0; this->overflow_flag=true; this->overflow_flag_fixed=false; this->horizontal_backwater_flag=false; this->horizontal_backwater_flag_upstream=false; this->current_q_break=0.0; this->old_q_break = 0.0; this->coupling_v_break=0.0; this->break_flag=false; this->index_break=-1; this->stop_break_flag=false; this->break_height=0.0; this->break_width=0.0; this->total_flow_width=0.0; this->overflow_width=0.0; this->delta_h_rv2fp_break=0.0; this->max_h_2break.maximum=0.0; this->max_h_2break.time_point=0.0; this->max_h.maximum=0.0; this->max_h.time_point=0.0; this->max_deltah2break=0.0; this->grad_q_current=0.0; this->grad_q_before=0.0; this->oscilation_smoother=1.0; this->number_osci_counter=2.0; this->no_osci_counter=0.0; this->grad_q_break_current=0.0; this->grad_q_break_before=0.0; this->oscilation_smoother_break=1.0; this->number_osci_counter_break=2.0; this->no_osci_counter_break=0.0; this->predicted_h_two=0.0; this->corrected_h_two=0.0; this->gradient_list_h_two.clear(); for(int i=0; i< constant::no_stored_grad; i++){ this->gradient_list_h_two.append(0.0); } this->gradient_h_two=0.0; this->calc_h_two=0.0; this->old_calc_h_two=0.0; this->store_grad_q_before=0.0; this->store_oscilation_smoother=1.0; this->store_number_osci_counter=2.0; this->store_no_osci_counter=0.0; this->store_grad_q_break_before=0.0; this->store_oscilation_smoother_break=1.0; this->store_number_osci_counter_break=2.0; this->store_no_osci_counter_break=0.0; this->store_old_q_break=0.0; //count the memory Sys_Memory_Count::self()->add_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS); } //Copy constructor Hyd_Coupling_Point_RV2FP::Hyd_Coupling_Point_RV2FP(const Hyd_Coupling_Point_RV2FP& object){ _Hyd_Coupling_Point::operator =(object); this->river_profile_index_up=object.river_profile_index_up; this->river_profile_up=object.river_profile_up; this->river_profile_index_down=object.river_profile_index_down; this->river_profile_down=object.river_profile_down; this->floodplain_index=object.floodplain_index; this->floodplain_elem_index=object.floodplain_elem_index; this->first_found_elem_index=object.first_found_elem_index; this->floodplain_elem=object.floodplain_elem; this->fpl_section_id=object.fpl_section_id; this->mid_basepoint=object.mid_basepoint; this->mid_basepoint_profile=object.mid_basepoint_profile; this->mid_height=object.mid_height; this->mid_fac_up=object.mid_fac_up; this->mid_fac_down=object.mid_fac_down; this->mid_waterlevel=object.mid_waterlevel; this->overflow_flag=object.overflow_flag; this->overflow_flag_fixed=object.overflow_flag_fixed; this->horizontal_backwater_flag=object.horizontal_backwater_flag; this->horizontal_backwater_flag_upstream=object.horizontal_backwater_flag_upstream; this->current_q_break = object.current_q_break; this->old_q_break = object.old_q_break; this->coupling_v_break = object.coupling_v_break; this->break_flag=object.break_flag; this->index_break=object.index_break; this->stop_break_flag=object.stop_break_flag; this->break_height=object.break_height; this->break_width=object.break_width; this->total_flow_width=object.total_flow_width; this->overflow_width=object.overflow_width; this->delta_h_rv2fp_break=object.delta_h_rv2fp_break; this->max_h_2break=object.max_h_2break; this->max_h=object.max_h; this->max_deltah2break=object.max_deltah2break; this->grad_q_current=object.grad_q_current; this->grad_q_before=object.grad_q_before; this->oscilation_smoother=object.oscilation_smoother; this->number_osci_counter=object.number_osci_counter; this->no_osci_counter=object.no_osci_counter; this->grad_q_break_current=object.grad_q_break_current; this->grad_q_break_before=object.grad_q_break_before; this->oscilation_smoother_break=object.oscilation_smoother_break; this->no_osci_counter_break=object.no_osci_counter_break; this->number_osci_counter_break=object.number_osci_counter_break; this->corrected_h_two=object.corrected_h_two; this->predicted_h_two=object.predicted_h_two; this->gradient_h_two=object.gradient_h_two; this->calc_h_two=object.calc_h_two; this->old_calc_h_two=object.old_calc_h_two; this->gradient_list_h_two.clear(); for(int i=0; i< constant::no_stored_grad; i++){ this->gradient_list_h_two.append(0.0); } this->store_grad_q_before=object.store_grad_q_before; this->store_oscilation_smoother=object.store_oscilation_smoother; this->store_number_osci_counter=object.store_number_osci_counter; this->store_no_osci_counter=object.store_no_osci_counter; this->store_grad_q_break_before=object.store_grad_q_break_before; this->store_oscilation_smoother_break=object.store_oscilation_smoother_break; this->store_no_osci_counter_break=object.store_no_osci_counter_break; this->store_number_osci_counter_break=object.store_number_osci_counter_break; this->store_old_q_break=object.store_old_q_break; //count the memory Sys_Memory_Count::self()->add_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS); } //destructor Hyd_Coupling_Point_RV2FP::~Hyd_Coupling_Point_RV2FP(void){ //count the memory Sys_Memory_Count::self()->minus_mem(sizeof(Hyd_Coupling_Point_RV2FP), _sys_system_modules::HYD_SYS); } //_________ //public //Set the pointer/index members (without the geometrical members) from the given point void Hyd_Coupling_Point_RV2FP::set_couplingpoint_members(Hyd_Coupling_Point_RV2FP *object){ //from this class this->river_profile_index_up=object->river_profile_index_up; this->river_profile_up=object->river_profile_up; this->river_profile_index_down=object->river_profile_index_down; this->river_profile_down=object->river_profile_down; this->floodplain_index=object->floodplain_index; this->floodplain_elem_index=object->floodplain_elem_index; this->set_pointer_floodplain_element(object->floodplain_elem); this->first_found_elem_index=object->first_found_elem_index; this->fpl_section_id=object->fpl_section_id; } //Output the header for the setted member (static)) void Hyd_Coupling_Point_RV2FP::output_header_setted_member(ostringstream *cout){ *cout <<W(10) << "Id_rv_up," << W(10) << "Id_rv_down," << W(7) << "Id_fp," << W(11) << "Id_fp_elem,"; *cout <<W(15) << "Coupling,"<< W(15) << "Overflow," << W(15) <<"Dist_upstr" << label::m<<"," <<W(15)<< "Dist_downstr" << label::m << ","; *cout << W(15)<< "abs_Height" <<label::m << ","; *cout << W(10)<< "Break," << W(16) << "Stop_break,"; *cout << W(15)<< "Dist_inflow" <<label::m << ","; *cout << W(15)<< "x" << label::m << "," << W(17) << "y" <<label::m << ","; *cout << W(17)<<"Id_fpl_sec" << "," << W(7) << "mid_fac_down" << "," << W(7) << "mid_fac_up"; *cout<< endl; Sys_Common_Output::output_hyd->output_txt(cout,true); } //Output the setted members void Hyd_Coupling_Point_RV2FP::output_setted_members(ostringstream *cout){ *cout <<W(8) << this->river_profile_index_up << "," << W(10) << this->river_profile_index_down << ","; *cout <<W(10) << this->floodplain_index << W(10)<<"," << this->floodplain_elem_index << ","; *cout <<W(15) << functions::convert_boolean2string(this->coupling_flag) << ","; *cout <<W(15) << functions::convert_boolean2string(this->overflow_flag) << ","; *cout <<W(15) <<P(2)<< FORMAT_FIXED_REAL << this->distance_down << ","; *cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->distance_up << ","; *cout <<W(17) <<P(2)<< FORMAT_FIXED_REAL << this->mid_height << ","; *cout <<W(17) << functions::convert_boolean2string(this->break_flag) << ","; *cout <<W(15) << functions::convert_boolean2string(this->stop_break_flag) << ","; *cout <<W(17) << this->distance_along_polysegment << ","; *cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->x_coordinate << ","; *cout <<W(21) <<P(2)<< FORMAT_FIXED_REAL << this->y_coordinate << ","; *cout <<W(21) <<P(0)<< FORMAT_FIXED_REAL << this->fpl_section_id << ","; *cout << W(21) << P(10) << FORMAT_FIXED_REAL << this->mid_fac_down << ","; *cout << W(21) << P(10) << FORMAT_FIXED_REAL << this->mid_fac_up; *cout<< endl; Sys_Common_Output::output_hyd->output_txt(cout, true); } //Set the indices for the upwards river profile (corresponding to the index of the polysegment of the river bank line) and the element index of the Hyd_Floodplain_Element, which is used for calculation void Hyd_Coupling_Point_RV2FP::set_indices(const int up_river_profile, const int floodplain_model_elem){ this->river_profile_index_up=up_river_profile; this->river_profile_index_down=this->river_profile_index_up+1; this->floodplain_elem_index=floodplain_model_elem; } //Set the pointers to the river profiles with help of the indices void Hyd_Coupling_Point_RV2FP::set_pointer_river_profiles(Hyd_Model_River *river_model){ if(this->river_profile_index_up<0 || this->river_profile_index_up>river_model->Param_RV.get_number_profiles()){ this->river_profile_up=NULL; this->river_profile_down=NULL; } //inflow profile upwards else if(this->river_profile_index_up==0){ this->river_profile_up=&(river_model->inflow_river_profile); this->river_profile_down=&(river_model->river_profiles[this->river_profile_index_down-1]); } //outflow profile downwards else if(this->river_profile_index_up==river_model->Param_RV.get_number_profiles()-2){ this->river_profile_up=&(river_model->river_profiles[this->river_profile_index_up-1]); this->river_profile_down=&(river_model->outflow_river_profile); } //just inbetween profiles else{ this->river_profile_up=&(river_model->river_profiles[this->river_profile_index_up-1]); this->river_profile_down=&(river_model->river_profiles[this->river_profile_index_down-1]); } } //Set the indexof the first found Hyd_Floodplain_Element; it is not necessarily used for calculation (e.g. river elements) void Hyd_Coupling_Point_RV2FP::set_first_found_elem_index(const int index){ this->first_found_elem_index=index; } //Set the pointers to the floodplain elements void Hyd_Coupling_Point_RV2FP::set_pointer_floodplain_element(Hyd_Element_Floodplain *floodplain){ this->floodplain_elem=floodplain; if(this->floodplain_elem!=NULL && this->floodplain_elem_index>=0){ this->floodplain_elem->element_type->set_coupling_data(); } } //Set the index of the floodplain element void Hyd_Coupling_Point_RV2FP::set_index_floodplain_element(const int index){ this->floodplain_elem_index=index; } //Get the index of the floodplain element int Hyd_Coupling_Point_RV2FP::get_index_floodplain_element(void){ return this->floodplain_elem_index; } //Set the index of the coupled floodplain void Hyd_Coupling_Point_RV2FP::set_floodplain_index(const int index){ this->floodplain_index=index; } //Get the index of the coupled floodplain int Hyd_Coupling_Point_RV2FP::get_floodplain_index(void){ return this->floodplain_index; } //Get the index of the coupled fpl-section int Hyd_Coupling_Point_RV2FP::get_fpl_section_index(void){ return this->fpl_section_id; } //Get the mid of waterlevel of the two profiles in the river double Hyd_Coupling_Point_RV2FP::get_mid_waterlevel(void){ return this->mid_waterlevel; } //Calculate the current mid-waterlevel via the factors in the river void Hyd_Coupling_Point_RV2FP::calculate_mid_waterlevel(void){ if(this->coupling_flag==true){ this->horizontal_backwater_flag=false; this->horizontal_backwater_flag_upstream=false; //set the mid_waterlevel via the factors if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon && this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon){ this->mid_waterlevel=this->mid_fac_down*this->river_profile_down->get_actual_global_waterlevel()+this->mid_fac_up*this->river_profile_up->get_actual_global_waterlevel(); } else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon&& this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon){ this->mid_waterlevel=this->river_profile_up->get_actual_global_waterlevel(); this->horizontal_backwater_flag_upstream=true; } else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()>constant::dry_hyd_epsilon&& this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){ this->mid_waterlevel=this->river_profile_down->get_actual_global_waterlevel(); this->horizontal_backwater_flag=true; } else if(this->river_profile_down->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon && this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){ this->mid_waterlevel=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min(); } } } //Calculate the current delta h between river and floodplain in case of an break void Hyd_Coupling_Point_RV2FP::calculate_delta_h_break(void){ if(this->coupling_flag==true && this->break_flag==true){ double delta_fp=this->floodplain_elem->element_type->get_s_value()-this->break_height; double delta_rv=this->mid_waterlevel-this->break_height; if(delta_fp <= 0.0 && delta_rv<=0.0){ this->delta_h_rv2fp_break=0.0; } else if(delta_fp > 0.0 && delta_rv<=0.0){ this->delta_h_rv2fp_break=-1.0*delta_fp; } else if(delta_fp <= 0.0 && delta_rv>0.0){ this->delta_h_rv2fp_break=delta_rv; } else if(delta_fp > 0.0 && delta_rv>0.0){ this->delta_h_rv2fp_break=delta_rv-delta_fp; } //set boundary if(abs(this->delta_h_rv2fp_break)<=constant::flow_epsilon){ this->delta_h_rv2fp_break=0.0; } } else{ this->delta_h_rv2fp_break=0.0; } } //Get a pointer to the current delta h between river and floodplain in case of an break double *Hyd_Coupling_Point_RV2FP::get_delta_h_break(void){ return &this->delta_h_rv2fp_break; } //Get the mid height for the overflow-coupling (global) double Hyd_Coupling_Point_RV2FP::get_mid_height(void){ return this->mid_height; } //Get the mid basepoint height for a break coupling (global) double Hyd_Coupling_Point_RV2FP::get_mid_basepoint_height(void){ return this->mid_basepoint; } //Get the mid basepoint height (just profile) for a break coupling (global) double Hyd_Coupling_Point_RV2FP::get_mid_basepoint_height_profile(void){ return this->mid_basepoint_profile; } //Get the pointer to the downstream river profile _Hyd_River_Profile* Hyd_Coupling_Point_RV2FP::get_downstream_rvprofile(void){ return this->river_profile_down; } //Get the pointer to the upstream river profile _Hyd_River_Profile* Hyd_Coupling_Point_RV2FP::get_upstream_rvprofile(void){ return this->river_profile_up; } //Get the index of the downstream river profile int Hyd_Coupling_Point_RV2FP::get_index_downstream_rvprofile(void){ if(this->river_profile_down==NULL){ return -1; } else{ return this->river_profile_down->get_profile_number(); } } //Get the index to the upstream river profile int Hyd_Coupling_Point_RV2FP::get_index_upstream_rvprofile(void){ if(this->river_profile_up==NULL){ return -1; } else{ return this->river_profile_up->get_profile_number(); } } //Get the pointer to the floodplain element Hyd_Element_Floodplain* Hyd_Coupling_Point_RV2FP::get_floodplain_element(void){ return this->floodplain_elem; } //Get the upwards factor for the mid-value calculation of the mid_height and the mid_waterlevel depending on the distances double Hyd_Coupling_Point_RV2FP::get_upwards_mid_factor(void){ return this->mid_fac_up; } //Get the downwards factor for the mid-value calculation of the mid_height and the mid_waterlevel depending on the distances double Hyd_Coupling_Point_RV2FP::get_downwards_mid_factor(void){ return this->mid_fac_down; } //Get the distance from the coupling point to the element mid point double Hyd_Coupling_Point_RV2FP::get_distancecoupling2elem_mid(void){ double distance=-1.0; if(this->coupling_flag==false || this->floodplain_elem==NULL){ return distance; } else{ distance=this->distance(this->floodplain_elem->get_mid_point()); } return distance; } //Transfer the coupling characteristics of the coupled elements void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics(const bool left_river_flag){ if(this->river_profile_index_up<0 || this->floodplain_elem_index<0 || this->river_profile_index_down<0){ this->coupling_flag=false; return; } if(this->floodplain_elem->get_elem_type()==_hyd_elem_type::STANDARD_ELEM || this->floodplain_elem->get_elem_type()==_hyd_elem_type::DIKELINE_ELEM){ this->coupling_flag=true; //left river bank if(left_river_flag==true){ this->transfer_coupling_characteristics_leftbank(); } //right river bank else{ this->transfer_coupling_characteristics_rightbank(); } //Daniel ok? If this is used no direct in coupling is possible //if(abs(this->distance_down)<=constant::meter_epsilon){ //this->coupling_flag=false; //} } else{ this->coupling_flag=false; return; } } //Reset the current coupling discharge of the points and the coupled element void Hyd_Coupling_Point_RV2FP::reset_coupling_discharge(const bool left_river_flag){ _Hyd_Coupling_Point::reset_coupling_discharge(); if(this->coupling_flag==true){ if(this->overflow_flag==true){ this->floodplain_elem->element_type->reset_coupling_discharge_rv_overflow(); if(left_river_flag==true){ this->river_profile_up->reset_coupling_discharge_left_bank(); this->river_profile_down->reset_coupling_discharge_left_bank(); } else{ this->river_profile_up->reset_coupling_discharge_right_bank(); this->river_profile_down->reset_coupling_discharge_right_bank(); } } if(this->break_flag==true){ this->floodplain_elem->element_type->reset_coupling_discharge_rv_dikebreak(); if(left_river_flag==true){ this->river_profile_up->reset_dikebreak_coupling_discharge_left_bank(); this->river_profile_down->reset_dikebreak_coupling_discharge_left_bank(); } else{ this->river_profile_up->reset_dikebreak_coupling_discharge_right_bank(); this->river_profile_down->reset_dikebreak_coupling_discharge_right_bank(); } } } } //Syncronisation of the coupled models with the couplingspoint void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models(const double timepoint, const double delta_t, const bool left_river_flag, const bool time_check, const int internal_counter){ _Hyd_Coupling_Point::syncronisation_coupled_models(); this->delta_t=delta_t; this->time_check=time_check; if(this->coupling_flag==false){ return; } else{ //calculate the current midwaterlevel in the river this->calculate_mid_waterlevel(); double h_one_buff=0.0; double h_two_buff=0.0; this->predict_values(internal_counter); h_one_buff=0.5*(this->predicted_h_one+this->calc_h_one); h_two_buff=0.5*(this->predicted_h_two+this->calc_h_two); if(this->time_check==true){ this->store_grad_q_before=this->grad_q_before; this->store_oscilation_smoother=this->oscilation_smoother; this->store_number_osci_counter=this->number_osci_counter; this->store_no_osci_counter=this->no_osci_counter; this->store_grad_q_break_before=this->grad_q_break_before; this->store_oscilation_smoother_break=this->oscilation_smoother_break; this->store_number_osci_counter_break=this->number_osci_counter_break; this->store_no_osci_counter_break=this->no_osci_counter_break; this->store_old_q_break=this->old_q_break; this->store_old_q=this->old_q; } else{ this->grad_q_before=this->store_grad_q_before; this->oscilation_smoother=this->store_oscilation_smoother; this->number_osci_counter=this->store_number_osci_counter; this->no_osci_counter=this->store_no_osci_counter; this->grad_q_break_before=this->store_grad_q_break_before; this->oscilation_smoother_break=this->store_oscilation_smoother_break; this->number_osci_counter_break=this->store_number_osci_counter_break; this->no_osci_counter_break=this->store_no_osci_counter_break; this->old_q_break=this->store_old_q_break; this->old_q=this->store_old_q; //left river bank if(left_river_flag==true){ if(this->overflow_flag==true){ this->syncronisation_coupled_models_overflow(timepoint, this->river_profile_up->get_overflow_poleni_left(), h_one_buff, h_two_buff); if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){ //discharge to river profile segment: division to the profiles weighted with the factors this->river_profile_up->add_coupling_discharge_left_bank(this->current_q*this->mid_fac_up); this->river_profile_down->add_coupling_discharge_left_bank(this->current_q*this->mid_fac_down); } else if(this->horizontal_backwater_flag==true){ //discharge to river profile segment: just to/out of the downstream profile this->river_profile_down->add_coupling_discharge_left_bank(this->current_q); } else if(this->horizontal_backwater_flag_upstream==true){ //discharge to river profile segment: just to/out of the upstream profile this->river_profile_up->add_coupling_discharge_left_bank(this->current_q); } } if(this->break_flag==true && this->index_break>=0){ this->syncronisation_coupled_models_break(timepoint, h_one_buff, h_two_buff); //discharge to river profile segment: division to the profiles weighted with the factors if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){ this->river_profile_up->add_dikebreak_coupling_discharge_left_bank(this->current_q_break*this->mid_fac_up); this->river_profile_down->add_dikebreak_coupling_discharge_left_bank(this->current_q_break*this->mid_fac_down); } else if(this->horizontal_backwater_flag==true){ //discharge to river profile segment: just to/out of the downstream profile this->river_profile_down->add_dikebreak_coupling_discharge_left_bank(this->current_q_break); } else if(this->horizontal_backwater_flag_upstream==true){ //discharge to river profile segment: just to/out of the upstream profile this->river_profile_up->add_dikebreak_coupling_discharge_left_bank(this->current_q_break); } } if(this->time_check==false){ //calculate maximum waterlevel for a break this->calculate_max_h2break(true, timepoint); } } //right river bank else{ if(this->overflow_flag==true){ this->syncronisation_coupled_models_overflow(timepoint, this->river_profile_up->get_overflow_poleni_right(), h_one_buff, h_two_buff); //discharge to river profile segment: division to the profiles weighted with the factors if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){ this->river_profile_up->add_coupling_discharge_right_bank(this->current_q*this->mid_fac_up); this->river_profile_down->add_coupling_discharge_right_bank(this->current_q*this->mid_fac_down); } else if(this->horizontal_backwater_flag==true){ //discharge to river profile segment: just to/out of the downstream profile this->river_profile_down->add_coupling_discharge_right_bank(this->current_q); } else if(this->horizontal_backwater_flag_upstream==true){ //discharge to river profile segment: just to/out of the upstream profile this->river_profile_up->add_coupling_discharge_right_bank(this->current_q); } } if(this->break_flag==true && this->index_break>=0){ this->syncronisation_coupled_models_break(timepoint, h_one_buff, h_two_buff); //discharge to river profile segment: division to the profiles weighted with the factors if(this->horizontal_backwater_flag==false && this->horizontal_backwater_flag_upstream==false){ this->river_profile_up->add_dikebreak_coupling_discharge_right_bank(this->current_q_break*this->mid_fac_up); this->river_profile_down->add_dikebreak_coupling_discharge_right_bank(this->current_q_break*this->mid_fac_down); } else if(this->horizontal_backwater_flag==true){ //discharge to river profile segment: just to/out of the downstream profile this->river_profile_down->add_dikebreak_coupling_discharge_right_bank(this->current_q_break); } else if(this->horizontal_backwater_flag_upstream==true){ //discharge to river profile segment: just to/out of the upstream profile this->river_profile_up->add_dikebreak_coupling_discharge_right_bank(this->current_q_break); } } } } if(this->time_check==false){ //calculate maximum waterlevel for a break this->calculate_max_h2break(false, timepoint); } } } //Set the flag if a coupling due to a overflow is applicable void Hyd_Coupling_Point_RV2FP::set_overflow_flag(const bool flag){ this->overflow_flag=flag; } //Set the fixed overflow flag to true; it is not more dependent of the profiles void Hyd_Coupling_Point_RV2FP::set_fixed_overflow_flag(void){ this->overflow_flag_fixed=true; } //Get the flag if a coupling due to a break is applicable bool Hyd_Coupling_Point_RV2FP::get_break_flag(void){ return this->break_flag; } //Get a flag if the break width is as same as the total overflow width => break is total bool Hyd_Coupling_Point_RV2FP::get_break_is_total(void){ if(this->break_width==this->total_flow_width){ return true; } else{ return false; } } //Set the flag if a coupling due to a break is applicable void Hyd_Coupling_Point_RV2FP::set_break_flag(const bool flag){ this->break_flag=flag; } //Set the break width; the break height is related to the base points bool Hyd_Coupling_Point_RV2FP::add_break_width(const double delta_break_width){ bool is_full_flag=true; if(this->break_flag==true){ if(abs(this->break_width-this->total_flow_width)<constant::meter_epsilon){ is_full_flag=true; } else{ is_full_flag=false; this->break_width=this->break_width+delta_break_width; if(this->break_width>=this->total_flow_width){ this->break_width=this->total_flow_width; this->overflow_width=this->total_flow_width-this->break_width; } else{ this->overflow_width=this->total_flow_width-this->break_width; } } } else{ is_full_flag=true; } return is_full_flag; } //Set the starting break width void Hyd_Coupling_Point_RV2FP::set_begin_break_width(const double begin_break_width){ if(this->break_flag==true){ this->break_height=this->mid_height; this->break_width=begin_break_width; this->overflow_width=this->total_flow_width-this->break_width; } } //Set a reduction of the overflow height in the starting breach (slow reduction of the height due to numerical reasons) bool Hyd_Coupling_Point_RV2FP::set_overflow_height_reduction(const double height_reduction){ if(this->break_flag==true){ bool break_init_finished=false; this->break_height=this->break_height-height_reduction; if(this->break_height<=this->mid_basepoint){ this->break_height=this->mid_basepoint; break_init_finished=true; return break_init_finished; } else{ break_init_finished=false; return break_init_finished; } } else{ return false; } } //Set the mid basepoint height as the break height void Hyd_Coupling_Point_RV2FP::set_mid_basepoint2breakheight(void){ if(this->break_flag==true){ this->break_height=this->mid_basepoint; } } //Set the flag, that a breach is stopped here to true void Hyd_Coupling_Point_RV2FP::set_stop_break_flag(void){ this->stop_break_flag=true; } //Get the flag, that a breach is stopped here bool Hyd_Coupling_Point_RV2FP::get_stop_break_flag(void){ return this->stop_break_flag; } //Set the index of the break class void Hyd_Coupling_Point_RV2FP::set_index_break_class(const int index){ this->index_break=index; } //Get the index of the break class int Hyd_Coupling_Point_RV2FP::get_index_break_class(void){ return this->index_break; } //Get the current discharge through a break double Hyd_Coupling_Point_RV2FP::get_q_break(void){ return this->current_q_break; } //Get the current velocity through a break double Hyd_Coupling_Point_RV2FP::get_v_break(void){ return this->coupling_v_break; } //Get the maximum waterlevel at this coupling point by the maximum delta waterlevel relevant for a break _hyd_max_values Hyd_Coupling_Point_RV2FP::get_max_h_2break(void){ return this->max_h_2break; } //Get the delta waterlevel between river and floodplain at this coupling point double Hyd_Coupling_Point_RV2FP::get_max_deltah_2break(void){ return this->max_deltah2break; } //Get maximum waterlevel at this coupling point related to the mid base points of the profiles _hyd_max_values Hyd_Coupling_Point_RV2FP::get_max_h(void){ return this->max_h; } //Reset the break width void Hyd_Coupling_Point_RV2FP::reset_break_width(void){ this->break_width=0.0; this->overflow_width=this->total_flow_width-this->break_width; this->index_break=-1; } //Reset the hydrological balance values and the maximum calculated values void Hyd_Coupling_Point_RV2FP::reset_hydro_balance_max_values(void){ _Hyd_Coupling_Point::reset_hydro_balance_max_values(); this->max_coupling_v_break.maximum=0.0; this->max_coupling_v_break.time_point=0.0; this->max_h_2break.maximum=0.0; this->max_h_2break.time_point=0.0; this->max_deltah2break=0.0; this->max_h.maximum=0.0; this->max_h.time_point=0.0; this->reset_break_width(); this->coupling_volume_break.volume_in=0.0; this->coupling_volume_break.volume_out=0.0; this->coupling_volume_break.volume_total=0.0; } //Reset the smoothing calculation members void Hyd_Coupling_Point_RV2FP::reset_smoothing(void){ _Hyd_Coupling_Point::reset_smoothing(); this->grad_q_current=0.0; this->grad_q_before=0.0; this->oscilation_smoother=1.0; this->number_osci_counter=2.0; this->no_osci_counter=0.0; this->grad_q_break_current=0.0; this->grad_q_break_before=0.0; this->oscilation_smoother_break=1.0; this->number_osci_counter_break=2.0; this->no_osci_counter_break=0.0; this->predicted_h_two=0.0; this->corrected_h_two=0.0; this->gradient_list_h_two.clear(); for(int i=0; i< constant::no_stored_grad; i++){ this->gradient_list_h_two.append(0.0); } this->gradient_h_two=0.0; this->calc_h_two=0.0; this->old_calc_h_two=0.0; this->store_grad_q_before=0.0; this->store_oscilation_smoother=1.0; this->store_number_osci_counter=2.0; this->store_no_osci_counter=0.0; this->store_grad_q_break_before=0.0; this->store_oscilation_smoother_break=1.0; this->store_number_osci_counter_break=2.0; this->store_no_osci_counter_break=0.0; this->store_old_q_break=0.0; } //Get the maximum waterlevel gradient double Hyd_Coupling_Point_RV2FP::get_maximum_h_grad(void){ double buffer=0.0; double buffer_max=0.0; buffer=abs(this->grad_q_break_current/this->min_area); if(buffer_max<buffer){ buffer_max=buffer; } buffer=abs(this->grad_q_current/this->min_area); if(buffer_max<buffer){ buffer_max=buffer; } return buffer_max; } //Copy operator Hyd_Coupling_Point_RV2FP& Hyd_Coupling_Point_RV2FP::operator=(const Hyd_Coupling_Point_RV2FP& object){ _Hyd_Coupling_Point::operator =(object); this->river_profile_index_up=object.river_profile_index_up; this->river_profile_up=object.river_profile_up; this->river_profile_index_down=object.river_profile_index_down; this->river_profile_down=object.river_profile_down; this->floodplain_index=object.floodplain_index; this->fpl_section_id=object.fpl_section_id; this->floodplain_elem_index=object.floodplain_elem_index; this->first_found_elem_index=object.first_found_elem_index; this->floodplain_elem=object.floodplain_elem; this->mid_height=object.mid_height; this->mid_basepoint=object.mid_basepoint; this->mid_basepoint_profile=object.mid_basepoint_profile; this->mid_fac_up=object.mid_fac_up; this->mid_fac_down=object.mid_fac_down; this->mid_waterlevel=object.mid_waterlevel; this->overflow_flag=object.overflow_flag; this->overflow_flag_fixed=object.overflow_flag_fixed; this->break_flag=object.break_flag; this->index_break=object.index_break; this->stop_break_flag=object.stop_break_flag; this->break_height=object.break_height; this->break_width=object.break_width; this->total_flow_width=object.total_flow_width; this->overflow_width=object.overflow_width; this->delta_h_rv2fp_break=object.delta_h_rv2fp_break; this->max_h_2break=object.max_h_2break; this->max_deltah2break=object.max_deltah2break; this->max_h=object.max_h; this->horizontal_backwater_flag=object.horizontal_backwater_flag; this->horizontal_backwater_flag_upstream=object.horizontal_backwater_flag_upstream; this->current_q_break = object.current_q_break; this->coupling_v_break = object.coupling_v_break; this->grad_q_current=object.grad_q_current; this->old_q_break = object.old_q_break; this->grad_q_before=object.grad_q_before; this->oscilation_smoother=object.oscilation_smoother; this->number_osci_counter=object.number_osci_counter; this->no_osci_counter=object.no_osci_counter; this->grad_q_break_current=object.grad_q_break_current; this->grad_q_break_before=object.grad_q_break_before; this->oscilation_smoother_break=object.oscilation_smoother_break; this->no_osci_counter_break=object.no_osci_counter_break; this->number_osci_counter_break=object.number_osci_counter_break; this->corrected_h_two=object.corrected_h_two; this->predicted_h_two=object.predicted_h_two; this->gradient_h_two=object.gradient_h_two; this->calc_h_two=object.calc_h_two; this->old_calc_h_two=object.old_calc_h_two; this->store_grad_q_before=object.store_grad_q_before; this->store_oscilation_smoother=object.store_oscilation_smoother; this->store_number_osci_counter=object.store_number_osci_counter; this->store_no_osci_counter=object.store_no_osci_counter; this->store_grad_q_break_before=object.store_grad_q_break_before; this->store_oscilation_smoother_break=object.store_oscilation_smoother_break; this->store_no_osci_counter_break=object.store_no_osci_counter_break; this->store_number_osci_counter_break=object.store_number_osci_counter_break; this->store_old_q_break=object.store_old_q_break; return *this; } //______________ //private //Transfer the coupling characteristics of the coupled elements for a left river bank (in flow direction) void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics_leftbank(void){ //check if a overflow coupling is given by the profiles if(this->overflow_flag_fixed==false){ if(this->river_profile_up->get_overflow_flag_left()==false ){ this->overflow_flag=false; } else{ this->overflow_flag=true; } } //check if a break is applied if(this->river_profile_down->get_break_flag_left()==true && this->river_profile_up->get_break_flag_left()==true){ this->break_flag=true; } else{ this->break_flag=false; } //set the fpl index, if available this->fpl_section_id=this->river_profile_up->get_fpl_section_id_left(); //this->coupling_flag=true; //set the factors for the mid-value calculation depending on the distances double total_prof_distance=0.0; double distance_prof_up=0.0; double distance_prof_down=0.0; //calculate the distances to the profiles for a point between the coupling points => hmid total_prof_distance=abs(this->river_profile_down->typ_of_profile->get_first_point()->get_global_x_y_coordinates().distance(&(this->river_profile_up->typ_of_profile->get_first_point()->get_global_x_y_coordinates()))); distance_prof_up=abs(this->distance(&(this->river_profile_up->typ_of_profile->get_first_point()->get_global_x_y_coordinates()))); distance_prof_up=distance_prof_up-this->distance_down*0.5; distance_prof_down=abs(this->distance(&(this->river_profile_down->typ_of_profile->get_first_point()->get_global_x_y_coordinates()))); //check for stop flags by special types and coupling points, which are caused by a riverprofile if(abs(distance_prof_down)<=constant::meter_epsilon && (this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_down->get_connection_type()==_hyd_connection_types::INFLOW_CONN || this->river_profile_down->get_connection_type()==_hyd_connection_types::OUTFLOW_CONN)){ this->set_stop_break_flag(); } distance_prof_down=distance_prof_down+this->distance_down*0.5; //set the factors via the distances this->mid_fac_down=(1.0-distance_prof_down/total_prof_distance); this->mid_fac_up=(1.0-distance_prof_up/total_prof_distance); //check for a weir profile if(this->river_profile_up->get_profile_type()==_hyd_profile_types::WEIR_TYPE){ //full weight to the downstream profile this->mid_fac_down=1.0; this->mid_fac_up=0.0; } if(this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE){ //full weight to the upstream profile this->mid_fac_down=0.0; this->mid_fac_up=1.0; } //set the mid_height via the factors //this->mid_height=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_first_point()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_first_point()->get_global_z_coordinate(); this->mid_height=this->mid_fac_down*this->river_profile_down->get_height_left_bank_abs()+this->mid_fac_up*this->river_profile_up->get_height_left_bank_abs(); //if the height of the element is above the river bank line set the element height this->mid_height=max(this->mid_height, this->floodplain_elem->get_z_value()); //set the width this->total_flow_width=this->distance_down; this->overflow_width=this->total_flow_width; //set minimal area this->min_area=this->floodplain_elem->element_type->get_relevant_area(); //special settings for a breaking if(this->break_flag==true){ this->mid_basepoint_profile=this->mid_fac_down*this->river_profile_down->get_left_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_left_basepoint()->get_global_z_coordinate(); this->mid_basepoint=this->mid_fac_down*this->river_profile_down->get_left_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_left_basepoint()->get_global_z_coordinate(); this->mid_basepoint=max(this->mid_basepoint, this->floodplain_elem->get_z_value()); //check if the mid_base point is equal to the mid of the global z_min values; than increase the height by 0.05 m double mid_zmin=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min(); if(this->mid_basepoint<=mid_zmin+0.05){ //increase the mid_basepoint, otherwise the riversgements gets numerical problems with to much outflow before getting dry this->mid_basepoint=this->mid_basepoint+0.05; } //there is no break, if floodplain is heigher than floodprotection line if(this->mid_basepoint>=this->mid_height){ this->break_flag=false; } } } //Transfer the coupling characteristics of the coupled elements for a right river bank (in flow direction) void Hyd_Coupling_Point_RV2FP::transfer_coupling_characteristics_rightbank(void){ //check if a overflow coupling is given by the profiles if(this->overflow_flag_fixed==false){ if(this->river_profile_up->get_overflow_flag_right()==false){ this->overflow_flag=false; } else{ this->overflow_flag=true; } } //check if a break is applied if(this->river_profile_down->get_break_flag_right()==true && this->river_profile_up->get_break_flag_right()==true){ this->break_flag=true; } else{ this->break_flag=false; } //set the fpl index, if available this->fpl_section_id=this->river_profile_up->get_fpl_section_id_right(); //this->coupling_flag=true; //set the factors for the mid-value calculation depending on the distances double total_prof_distance=0.0; double distance_prof_up=0.0; double distance_prof_down=0.0; //calculate the distances to the profiles total_prof_distance=abs(this->river_profile_down->typ_of_profile->get_last_point()->get_global_x_y_coordinates().distance(&(this->river_profile_up->typ_of_profile->get_last_point()->get_global_x_y_coordinates()))); distance_prof_up=abs(this->distance(&(this->river_profile_up->typ_of_profile->get_last_point()->get_global_x_y_coordinates()))); distance_prof_up=distance_prof_up-0.5*this->distance_down; distance_prof_down=abs(this->distance(&(this->river_profile_down->typ_of_profile->get_last_point()->get_global_x_y_coordinates()))); //check for stop flags by special types and coupling points, which are caused by a riverprofile if(abs(distance_prof_down)<=constant::meter_epsilon && (this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_down->get_connection_type()==_hyd_connection_types::INFLOW_CONN || this->river_profile_down->get_connection_type()==_hyd_connection_types::OUTFLOW_CONN)){ this->set_stop_break_flag(); } distance_prof_down=distance_prof_down+0.5*this->distance_down; //set the factors via the distances this->mid_fac_down=(1.0-distance_prof_down/total_prof_distance); this->mid_fac_up=(1.0-distance_prof_up/total_prof_distance); //set the mid_height via the factors //this->mid_height=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_last_point()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_last_point()->get_global_z_coordinate(); this->mid_height=this->mid_fac_down*this->river_profile_down->get_height_right_bank_abs()+this->mid_fac_up*this->river_profile_up->get_height_right_bank_abs(); //if the height of the element is above the river bank line set the element height this->mid_height=max(this->mid_height, this->floodplain_elem->get_z_value()); //check for a weir profile if(this->river_profile_up->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_up->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE){ //full weight to the downstream profile this->mid_fac_down=1.0; this->mid_fac_up=0.0; } if(this->river_profile_down->get_profile_type()==_hyd_profile_types::WEIR_TYPE || this->river_profile_down->get_profile_type()==_hyd_profile_types::BRIDGE_TYPE){ //full weight to the upstream profile this->mid_fac_down=0.0; this->mid_fac_up=1.0; } //set the width this->total_flow_width=this->distance_down; this->overflow_width=this->total_flow_width; //set minimal area this->min_area=this->floodplain_elem->element_type->get_relevant_area(); //special settings for a breaking if(this->break_flag==true){ this->mid_basepoint_profile=this->mid_fac_down*this->river_profile_down->get_right_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_right_basepoint()->get_global_z_coordinate(); this->mid_basepoint=this->mid_fac_down*this->river_profile_down->get_right_basepoint()->get_global_z_coordinate()+this->mid_fac_up*this->river_profile_up->get_right_basepoint()->get_global_z_coordinate(); this->mid_basepoint=max(this->mid_basepoint, this->floodplain_elem->get_z_value()); //check if the mid_base point is equal to the mid of the global z_min values; than increase the height by 0.05 m double mid_zmin=this->mid_fac_down*this->river_profile_down->typ_of_profile->get_global_z_min()+this->mid_fac_up*this->river_profile_up->typ_of_profile->get_global_z_min(); if(this->mid_basepoint<=mid_zmin+0.05){ //increase the mid_basepoint, otherwise the riversgements gets numerical problems with to much outflow before getting dry this->mid_basepoint=this->mid_basepoint+0.05; } //there is no break, if floodplain is heigher than floodprotection line if(this->mid_basepoint>=this->mid_height){ this->break_flag=false; } } } //Syncronisation of the coupled models with the couplingspoint for overflow void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models_overflow(const double timepoint, const double poleni, const double h_one, const double h_two){ double delta_h_river=0.0; double delta_h_elem=0.0; double q_buff=0.0; delta_h_river=h_two-this->mid_height; //if(delta_h_river>0.0){ // cout <<"Test"<<endl; //} delta_h_elem=(this->floodplain_elem->get_z_value()+h_one)-this->mid_height; //no width if(abs(this->overflow_width)<constant::flow_epsilon){ this->coupling_v=0.0; q_buff=0.0; } //same waterlevels=> no flow else if(abs(delta_h_river-delta_h_elem)<constant::dry_hyd_epsilon){ this->coupling_v=0.0; q_buff=0.0; } //both waterlevel are under the weirsill=> no flow else if(delta_h_river<=0.0 && delta_h_elem<=0.0){ this->coupling_v=0.0; q_buff=0.0; } //flow out of the river model into the floodplain without submerged reduction else if(delta_h_river> 0.0 && delta_h_elem <= 0.0){ q_buff=-1.0*constant::Cfacweir*poleni*pow(delta_h_river,(3.0/2.0))*this->overflow_width; //factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000]) q_buff=constant::side_weir_reduction*q_buff; //calculate the velocity this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_river); } //flow out of the floodplain element into the river model without submerged reduction else if(delta_h_river<= 0.0 && delta_h_elem > 0.0){ q_buff=constant::Cfacweir*poleni*pow(delta_h_elem,(3.0/2.0))*this->overflow_width; //calculate the velocity this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_elem); } //flow without submerged reduction else if(delta_h_river > 0.0 && delta_h_elem > 0.0){ //flow out of the river model into the floodplain with sideweir reduction if(delta_h_river>delta_h_elem){ q_buff=constant::Cfacweir*poleni*pow(delta_h_river,(3.0/2.0))*this->overflow_width; //reduction of the discharge (submerged weirflow) double reduction_term=(1.0-delta_h_elem/delta_h_river); //replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values if(reduction_term<=0.000463529){ q_buff=-1.0*q_buff*0.057965266895*atan(8984.365582471040*reduction_term); } else{ q_buff=-1.0*q_buff*pow(reduction_term,(1.0/3.0)); } //factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000]) q_buff=constant::side_weir_reduction*q_buff; //calculate the velocity this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_river); } //flow out of the floodplain element into the river model without sideweir reduction else{ q_buff=constant::Cfacweir*poleni*pow(delta_h_elem,(3.0/2.0))*this->overflow_width; //reduction of the discharge (submerged weirflow) double reduction_term=(1.0-delta_h_river/delta_h_elem); //replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values if(reduction_term<=0.000463529){ q_buff=q_buff*0.057965266895*atan(8984.365582471040*reduction_term); } else{ q_buff=q_buff*pow(reduction_term,(1.0/3.0)); } //calculate the velocity this->coupling_v=-1.0*q_buff/(this->overflow_width*delta_h_elem); } } //set a boundary to the discharge if(abs(q_buff)<=this->discharge_boundary){ q_buff=0.0; this->coupling_v=0.0; } //smooth it for numerical reasons q_buff=this->smooth_coupling_discharge(q_buff, &this->old_q); this->current_q=q_buff; this->calculate_maximum_values(timepoint, this->current_q, &this->max_coupling_v); this->calculate_hydrological_balance(this->current_q, &this->coupling_volume); //discharge to element this->floodplain_elem->element_type->add_coupling_discharge_rv_overflow((-1.0)*this->current_q); } //Syncronisation of the coupled models with the couplingspoint for the discharge throught the break void Hyd_Coupling_Point_RV2FP::syncronisation_coupled_models_break(const double timepoint, const double h_one, const double h_two){ double delta_h_river=0.0; double delta_h_elem=0.0; double q_buff=0.0; this->current_q_break=0.0; this->coupling_v_break=0.0; delta_h_river=h_two-this->break_height; delta_h_elem=(this->floodplain_elem->get_z_value()+h_one)-this->break_height; //no width if(abs(this->break_width)<constant::flow_epsilon){ this->coupling_v_break=0.0; q_buff=0.0; } //same waterlevels=> no flow else if(abs(delta_h_river-delta_h_elem)<constant::flow_epsilon){ this->coupling_v_break=0.0; q_buff=0.0; } //both waterlevel are under the weirsill=> no flow else if(delta_h_river<=0.0 && delta_h_elem<=0.0){ this->coupling_v_break=0.0; q_buff=0.0; } //flow out of the river model into the floodplain without submerged reduction, with sideweir reduction else if(delta_h_river> 0.0 && delta_h_elem <= 0.0){ q_buff=-1.0*constant::Cfacweir*constant::poleni_const*pow(delta_h_river,(3.0/2.0))*this->break_width; //factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000]) q_buff=constant::side_weir_reduction*q_buff; //calculate the velocity this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_river); } //flow out of the floodplain element into the river model without submerged reduction, withtout sideweir reduction else if(delta_h_river<= 0.0 && delta_h_elem > 0.0){ q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_elem,(3.0/2.0))*this->break_width; //calculate the velocity this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_elem); } //weir flow with submerged reduction else if(delta_h_river > 0.0 && delta_h_elem > 0.0){ //flow out of the river model into the floodplain with sideweir reduction if(delta_h_river>delta_h_elem){ q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_river,(3.0/2.0))*this->break_width; //reduction of the discharge (submerged weirflow) double reduction_term=(1.0-delta_h_elem/delta_h_river); //replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values if(reduction_term<=0.000463529){ q_buff=-1.0*q_buff*0.057965266895*atan(8984.365582471040*reduction_term); } else{ q_buff=-1.0*q_buff*pow(reduction_term,(1.0/3.0)); } //factor for a side weir overflow (after "Technische Hydromechanik I", Bollrich [2000]) q_buff=constant::side_weir_reduction*q_buff; //calculate the velocity this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_river); } //flow out of the floodplain element into the river model without sideweir reduction else{ q_buff=constant::Cfacweir*constant::poleni_const*pow(delta_h_elem,(3.0/2.0))*this->break_width; //reduction of the discharge (submerged weirflow) double reduction_term=(1.0-delta_h_river/delta_h_elem); //replace the ^(1/3) by a fitted arctan-function; at the boundary they have the same values if(reduction_term<=0.000463529){ q_buff=q_buff*0.057965266895*atan(8984.365582471040*reduction_term); } else{ q_buff=q_buff*pow(reduction_term,(1.0/3.0)); } //calculate the velocity this->coupling_v_break=-1.0*q_buff/(this->break_width*delta_h_elem); } } //set a boundary to the discharge if(abs(q_buff)<=this->discharge_boundary){ q_buff=0.0; this->coupling_v_break=0.0; } //smooth it for numerical reasons q_buff=this->smooth_coupling_dikebreak_discharge(q_buff, &this->old_q_break); this->current_q_break=q_buff; this->calculate_maximum_values(timepoint, this->current_q_break, &this->max_coupling_v_break); this->calculate_hydrological_balance(this->current_q_break, &this->coupling_volume_break); //discharge to element this->floodplain_elem->element_type->add_coupling_discharge_rv_dikebreak((-1.0)*this->current_q_break); } //Smooth the coupling discharge with the coupling discharge calculated one internal timestep before double Hyd_Coupling_Point_RV2FP::smooth_coupling_discharge(const double q_current, double *old_q){ double smooth_q=0.0; if(this->delta_t>0.0){ this->grad_q_current=(q_current-*old_q)/(this->delta_t); if((this->grad_q_before>=0.0 && this->grad_q_current<0.0)|| (this->grad_q_before<=0.0 && this->grad_q_current>0.0)){ this->oscilation_smoother=this->oscilation_smoother+this->number_osci_counter; //this->oscilation_smoother=this->oscilation_smoother+1.0; this->no_osci_counter=0.0; this->number_osci_counter=2.0; if(this->oscilation_smoother>=100.0){ this->oscilation_smoother=100.0; } } else{ this->oscilation_smoother=this->oscilation_smoother-pow(this->no_osci_counter,0.75); //this->oscilation_smoother=this->oscilation_smoother-pow(this->no_osci_counter,1.5); this->no_osci_counter++; this->number_osci_counter=2.0; if(this->oscilation_smoother<1.0){ this->oscilation_smoother=1.0; } } this->grad_q_before=this->grad_q_current; } smooth_q=q_current*(1.0/this->oscilation_smoother)+(*old_q)*(1.0-(1.0/this->oscilation_smoother)); if(this->delta_t>0.0){ this->grad_q_current=(smooth_q-*old_q)/(this->delta_t); this->grad_q_before=this->grad_q_current; } *old_q=smooth_q; return smooth_q; } //Smooth the coupling discharge with the coupling dikebreak discharge calculated one internal timestep before double Hyd_Coupling_Point_RV2FP::smooth_coupling_dikebreak_discharge(const double q_current, double *old_q){ double smooth_q=0.0; if(this->delta_t>0.0){ this->grad_q_break_current=(q_current-*old_q)/(this->delta_t); if((this->grad_q_break_before>=0.0 && this->grad_q_break_current<0.0)|| (this->grad_q_break_before<=0.0 && this->grad_q_break_current>0.0)){ this->oscilation_smoother_break=this->oscilation_smoother_break+this->number_osci_counter_break; this->number_osci_counter_break=2.0; this->no_osci_counter_break=0.0; if(this->oscilation_smoother_break>=100.0){ this->oscilation_smoother_break=100.0; } } else{ this->oscilation_smoother_break=this->oscilation_smoother_break-pow(this->no_osci_counter_break,0.75); this->no_osci_counter_break++; this->number_osci_counter_break=2.0; if(this->oscilation_smoother_break<1.0){ this->oscilation_smoother_break=1.0; } } this->grad_q_break_before=this->grad_q_break_current; } smooth_q=q_current*(1.0/this->oscilation_smoother_break)+(*old_q)*(1.0-(1.0/this->oscilation_smoother_break)); if(this->delta_t>0.0){ this->grad_q_break_current=(smooth_q-*old_q)/(this->delta_t); this->grad_q_break_before=this->grad_q_break_current; } *old_q=smooth_q; return smooth_q; } //Calculate the maximum waterlevel at the maximim waterlevel difference between river and floodplain void Hyd_Coupling_Point_RV2FP::calculate_max_h2break(const bool left_flag, const double timepoint){ double buffer=0.0; if(this->river_profile_up==NULL || this->floodplain_elem ==NULL || this->river_profile_up->typ_of_profile->get_actual_local_waterlevel_h()<=constant::dry_hyd_epsilon){ return; } if(this->break_width>0.0){ return; } if(this->break_flag==false){ return; } buffer=this->mid_waterlevel-this->mid_basepoint; if(buffer>0.0){ this->river_profile_up->set_delta_waterlevel_rv2fp2break(this->mid_waterlevel, buffer, left_flag); if(this->mid_waterlevel-this->mid_basepoint>this->max_deltah2break){ this->max_deltah2break=this->mid_waterlevel-this->mid_basepoint; this->max_h_2break.maximum=this->mid_waterlevel-this->mid_basepoint_profile; this->max_h_2break.time_point=timepoint; } if(this->mid_waterlevel-this->mid_basepoint_profile>this->max_h.maximum){ this->max_h.maximum=this->mid_waterlevel-this->mid_basepoint_profile; this->max_h.time_point=timepoint; } } } //Predict the values void Hyd_Coupling_Point_RV2FP::predict_values(const int int_counter){ if(this->delta_t>0.0){ //one this->calc_h_one=this->floodplain_elem->element_type->get_h_value(); this->gradient_h_one=(this->calc_h_one-this->old_calc_h_one)/this->delta_t; if(this->time_check==false){ this->old_calc_h_one=this->calc_h_one; this->replace_first_grad_list(&this->gradient_list_h_one, this->gradient_h_one); } else{ this->swap_grad_list(&this->gradient_list_h_one, this->gradient_h_one); } //this->predicted_h_one=this->calc_h_one+(1.0/12.0)*(23.0*this->gradient_list_h_one.at(0)-16.0*this->gradient_list_h_one.at(1)+5.0*this->gradient_list_h_one.at(2))*this->delta_t; //this->predicted_h_one=this->calc_h_one+(0.5)*(3.0*this->gradient_list_h_one.at(0)-1.0*this->gradient_list_h_one.at(1))*this->delta_t; this->predicted_h_one=this->calc_h_one+(this->gradient_list_h_one.at(0))*this->delta_t; //two this->calc_h_two=this->mid_waterlevel; this->gradient_h_two=(this->calc_h_two-this->old_calc_h_two)/this->delta_t; if(this->time_check==false){ this->old_calc_h_two=this->calc_h_two; this->replace_first_grad_list(&this->gradient_list_h_two, this->gradient_h_two); } else{ this->swap_grad_list(&this->gradient_list_h_two, this->gradient_h_two); } if(int_counter>3){ //this->predicted_h_two=this->calc_h_two+(1.0/12.0)*(23.0*this->gradient_list_h_two.at(0)-16.0*this->gradient_list_h_two.at(1)+5.0*this->gradient_list_h_two.at(2))*this->delta_t; //this->predicted_h_two=this->calc_h_two+(0.5)*(3.0*this->gradient_list_h_two.at(0)-1.0*this->gradient_list_h_two.at(1))*this->delta_t; this->predicted_h_two=this->calc_h_two+(this->gradient_list_h_two.at(0))*this->delta_t; this->predicted_h_one=this->calc_h_one+(this->gradient_list_h_one.at(0))*this->delta_t; } else{ this->predicted_h_two=this->calc_h_two; this->predicted_h_one=this->calc_h_one; } } }
42.180102
229
0.779088
dabachma
75a164d4007883829cd61f5607ef3becd3d494d6
724
cc
C++
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
22
2019-01-15T12:18:25.000Z
2022-03-24T03:39:59.000Z
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
3
2019-07-13T16:16:16.000Z
2020-07-30T10:07:30.000Z
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
2
2019-06-19T10:09:32.000Z
2020-06-29T15:16:58.000Z
#include <precompiled.hh> #include "asyncjob.hh" namespace Steam { static std::vector<AsyncJob> jobs; AsyncJob NewAsyncJob(AsyncJob::Callback callback) { auto jobId = JobManager::GetNextNonCallJobId(); auto r = AsyncJob{jobId, callback}; jobs.push_back(r); return r; } void RunAsyncJobs() { std::vector<decltype(jobs.begin())> toRemove; for (auto it = jobs.begin(); it != jobs.end(); ++it) { const auto j = *it; auto result = j.RunJob(); if (result == AsyncJob::Result::finish) { toRemove.push_back(it); } } // Now remove them from the jobs for (auto it : toRemove) { jobs.erase(it); } } } // namespace Steam
21.294118
58
0.589779
TBK
75a4cf4f88bead27d7ad6c09dcf664a02bf5e92c
1,459
hxx
C++
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:43.000Z
2022-02-19T21:37:43.000Z
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
null
null
null
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:46.000Z
2022-02-19T21:37:46.000Z
#pragma once #include "../player.hpp" #include "../../../memory/operations.hpp" #include "../../../offsets.hpp" #include "../../../error/game_error.hpp" namespace distant::wow::entities::detail { template <> inline memory::address get_name_ptr<player>(wow::guid guid) { const auto mask = memory::read<wow::dword>(wow::offsets::name_cache::cache_base + wow::offsets::name_cache::player_name_mask); const auto base = memory::read<wow::dword>(wow::offsets::name_cache::cache_base + wow::offsets::name_cache::player_name_base); const auto short_guid = memory::address(guid.low & 0xFFFFFFFF); auto offset = 12 * (mask & short_guid); auto current = memory::read<memory::address>(base + offset + 8); offset = memory::read<wow::dword>(base + offset); if ((current & 0x1) == 0x1) throw error::memory_disparity("[entities::player::get_name_ptr()] Invalid name cache offset"); auto test_guid = memory::read<wow::dword>(current); while (test_guid != short_guid) { current = memory::read<memory::address>(current + offset + 4); if ((current & 0x1) == 0x1) throw error::memory_disparity("[entities::player::get_name_ptr()] Invalid name cache offset"); test_guid = memory::read<wow::dword>(current); } return current + wow::offsets::name_cache::player_name_string; } template <> inline std::string load_name<player>(const wow::guid guid) { return memory::read<std::string>(detail::get_name_ptr<player>(guid)); } }
32.422222
128
0.690199
Ostoic
b5a8a1ac3a4b8386793567fb5f5c8e3df08810e2
2,898
cpp
C++
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.GetNotifyName // () // Parameters: // class FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) class FString UAnimNotify_PlayParticleEffect_C::GetNotifyName() { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.GetNotifyName"); UAnimNotify_PlayParticleEffect_C_GetNotifyName_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.Received_Notify // (NetRequest, Exec, Native, NetResponse, MulticastDelegate, Public, HasOutParms, HasDefaults, DLLImport, BlueprintPure) // Parameters: // class USkeletalMeshComponent** MeshComp (Parm, ZeroConstructor, IsPlainOldData) // class UAnimSequenceBase** Animation (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UAnimNotify_PlayParticleEffect_C::Received_Notify(class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation) { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.Received_Notify"); UAnimNotify_PlayParticleEffect_C_Received_Notify_Params params; params.MeshComp = MeshComp; params.Animation = Animation; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.ExecuteUbergraph_AnimNotify_PlayParticleEffect // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UAnimNotify_PlayParticleEffect_C::ExecuteUbergraph_AnimNotify_PlayParticleEffect(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.ExecuteUbergraph_AnimNotify_PlayParticleEffect"); UAnimNotify_PlayParticleEffect_C_ExecuteUbergraph_AnimNotify_PlayParticleEffect_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
33.310345
170
0.729124
2bite
b5ad7767f42f8083858b5b5fa003472aee4f61df
58,630
hpp
C++
lib/timewhoop/include/pure-abstract-syntax.hpp
NVlabs/data-orchestration
ad86e65fbd99bb7670700cab7c7031bf232c831f
[ "BSD-3-Clause" ]
5
2019-04-13T02:00:35.000Z
2019-07-22T18:23:25.000Z
lib/timewhoop/include/pure-abstract-syntax.hpp
NVlabs/data-orchestration
ad86e65fbd99bb7670700cab7c7031bf232c831f
[ "BSD-3-Clause" ]
null
null
null
lib/timewhoop/include/pure-abstract-syntax.hpp
NVlabs/data-orchestration
ad86e65fbd99bb7670700cab7c7031bf232c831f
[ "BSD-3-Clause" ]
2
2019-06-23T18:14:21.000Z
2019-12-29T02:34:33.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TIMEWHOOP_PURE_ABSTRACT_SYNTAX_HPP_ #define TIMEWHOOP_PURE_ABSTRACT_SYNTAX_HPP_ #include <iostream> #include <list> #include <vector> #include <map> #include <stack> #include <algorithm> #include <memory> #include <boost/format.hpp> #include "maybe-type.hpp" #include "pure-abstract-syntax-types.hpp" #include "pure-abstract-primitive-syntax.hpp" #include "analysis-structure.hpp" /**** Primitive pure abstract syntax **** - Description - This file includes syntax classes for whoop EDSL for pure AST. - Unlike whoop's AST, timewhoop's AST does not include actual data and execution context, and include actual labels of operations (whoop's AST has them as function pointers so it is hard to be processed) - The AST constructed using timewhoop's syntax classes allow various walk-through for further information extraction and analysis - Each class contains virtual APIs designed for some specific walk-throughs for various analysis - Defined classes (:: represents inheritance) Expression::Integer Expression::Float (currently not supported; whoop does not have float data type yet) Expression::Container::Variable Expression::Container::Tensor Expression::Container::Tensor::TensorAccess Expression::UnaryOp Expression::BinaryOp Statement::Declaration::VariableDeclaration Statement::Declaration::TensorDeclaration Statement::PrimAssignment::VariableAssignement Statement::PrimAssignment::TensorAssignement Statement::PrimFor::TemporalFor Statement::PrimFor::SpatialFor Statement::ConditionalStatement::If Statement::ConditionalStatement::Else */ namespace timewhoop { class Integer : public Expression { protected: const int val_; public: Integer(const int& v) : val_(v) {} //No setter; because an integer is constant int getValue() { return val_; } virtual ExpressionClass GetClass() { return ExpressionClass::INTEGER; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { } virtual std::string GetName() { std::string ret = ""; return ret; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Integer, val: %d)") % val_); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("Integer, %d") % val_); return ret; } virtual Maybe<int> FirstOrderEval() { Maybe<int> ret(val_); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; } virtual void SetNumAccess(int num_access) { num_access_ = num_access; } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; } virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret(std::make_tuple(val_, val_+1)); return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { } }; class Float : public Expression { protected: const float val_; public: Float(const float& v) : val_(v) {} //No setter; because an integer is constant int getValue() { return val_; } virtual ExpressionClass GetClass() { return ExpressionClass::FLOAT; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { } virtual std::string GetName() { std::string ret = ""; return ret; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual std::string ToString() { std::string ret = boost::str(boost::format("Float, val: %f") % val_); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("Integer, %d") % val_); return ret; } virtual Maybe<int> FirstOrderEval() { Maybe<int> ret(static_cast<int>(val_)); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; } virtual void SetNumAccess(int num_access) { num_access_ = num_access; } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; } virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret(std::make_tuple(val_, val_+1)); return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { } }; class Variable : public Container //class Container : public Expression { public: Variable(Type tp, const std::string& nm) : Container(tp, nm) {} virtual ExpressionClass GetClass() { return ExpressionClass::VARIABLE; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { } virtual std::string GetName() { return name_; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Variable, name: %s)") % name_); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("Variable, %s") % name_); return ret; } virtual int GetNumDims() { return 1; } virtual int GetDimSize(int dim) { if(dim == 0) { return 1; } else { return -1; } } virtual Maybe<int> FirstOrderEval() { Maybe<int> ret(false); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; } virtual void SetNumAccess(int num_access) { num_access_ = num_access; } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; } //FIXME virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret; auto loop_info = loop_info_table->SearchTable(this, loop_block_id); if(loop_info.IsValid()) { auto loop_info_contents = loop_info.GetValue(); ret.SetValue(std::make_tuple(loop_info_contents->GetIterBase(), loop_info_contents->GetIterBound())); } return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { } }; class Tensor : public Container // class Container : public Expression { protected: std::vector<int> dim_sizes_; public: //Partial initialization; missing dimension sizes Tensor(Type tp, const std::string& nm) : Container(tp, nm) { } //Full initialization Tensor(Type tp, const std::string& nm, const std::vector<int>& dim_sizes) : Container(tp, nm), dim_sizes_(dim_sizes) { } virtual ExpressionClass GetClass() { return ExpressionClass::TENSOR; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { } virtual std::string GetName() { return name_; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Tensor, name: %s)") % name_); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("Tensor, %s") % name_); return ret; } virtual int GetNumDims() { return dim_sizes_.size(); } virtual int GetDimSize(int dim) { return dim_sizes_.at(dim); } virtual Maybe<int> FirstOrderEval() { Maybe<int> ret(false); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; } virtual void SetNumAccess(int num_access) { num_access_ = num_access; } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; } virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret; return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { } }; class TensorAccess : public Tensor { protected: std::shared_ptr<std::list<std::shared_ptr<Expression>>> idx_exprs_; public: TensorAccess(Type tp, const std::string& nm) : Tensor(tp, nm) { } TensorAccess(Type tp, const std::string& nm, const std::shared_ptr<std::list<std::shared_ptr<Expression>>>& idx_exprs) : Tensor(tp, nm), idx_exprs_(idx_exprs) { } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Tensor access, loop_block_id = %d\n target tensor: %s") % loop_block_id_ % name_); std::string idx_expr_string = "\n---index expressions---\n"; for(auto& idx_e : *idx_exprs_) { idx_expr_string += idx_e->ToString(); idx_expr_string += "\n"; } idx_expr_string += "------------------"; ret += idx_expr_string; return ret; } virtual std::string ToCSV() { std::string idx_expr_string; std::string ret = boost::str(boost::format("Tensor access, %s") % name_); for(auto& idx_e : *idx_exprs_) { idx_expr_string += ", ("; idx_expr_string += idx_e->ToCSV(); idx_expr_string += ")"; } ret += idx_expr_string; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { if(targ_tensor->GetName() == this->GetName()) { access_expr_list->push_back(idx_exprs_); } } virtual ExpressionClass GetClass() { return ExpressionClass::TENSOR_ACCESS; } virtual std::string GetName() { return name_; } virtual Maybe<int> FirstOrderEval() { Maybe<int> ret(false); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; for(auto& idx_expr : *idx_exprs_) { idx_expr->SetLoopBlockID(blk_id); } } virtual void SetNumAccess(int num_access) { num_access_ = num_access; for(auto& idx_expr : *idx_exprs_) { idx_expr->SetNumAccess(num_access); } } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; for(auto& idx_expr : *idx_exprs_) { idx_expr->SetAccessProb(access_prob); } } //TODO: Support multi-level indirections virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret; return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(deep_search) { for(auto& idx_e : *idx_exprs_) { if(idx_e->GetClass() == search_class) { search_res->push_back(idx_e); } idx_e->SearchExpressions(search_res, search_class, deep_search); } } } void SetIdxExpr(std::shared_ptr<std::list<std::shared_ptr<Expression>>>& idx_expr) { idx_exprs_ = idx_expr; } std::shared_ptr<std::list<std::shared_ptr<Expression>>>& GetIdxExpr() { return idx_exprs_; } }; // End of class TensorAccess class UnaryOp : public Expression { protected: std::shared_ptr<Expression> src1_; UnaryOperator op_; public: UnaryOp(UnaryOperator op, std::shared_ptr<Expression> src1) : src1_(src1), op_(op) { } virtual ExpressionClass GetClass() { return ExpressionClass::UNARYOP; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { if(src1_->GetClass() == ExpressionClass::VARIABLE) { leaf_list->push_back(src1_); } else { src1_->GetLeaves(leaf_list); } } virtual std::string GetName() { std::string ret = ""; return ret; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { src1_->GetTensorIndexExpressions(targ_tensor, access_expr_list); } virtual std::string ToString() { std::string ret; ret = boost::str(boost::format("(UnaryOp, op: %s, \n operand: %s) ") % timewhoop::ToString(op_) % src1_->ToString()); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("UnaryOp, %s, (%s)") % timewhoop::ToString(op_) % src1_->ToCSV() ); return ret; } virtual Maybe<int> FirstOrderEval() { auto ret = src1_->FirstOrderEval(); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; src1_->SetLoopBlockID(blk_id); } virtual void SetNumAccess(int num_access) { num_access_ = num_access; src1_->SetNumAccess(num_access); } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; src1_->SetAccessProb(access_prob); } virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret; auto src1_range = src1_->MinMaxEval(loop_info_table, loop_block_id); if(src1_range.IsValid()) { auto src1_range_contents = src1_range.GetValue(); int src1_min = std::get<0>(src1_range_contents); int src1_max = std::get<1>(src1_range_contents); switch(op_) { case(UnaryOperator::PRE_INCREMENT): { ret.SetValue(std::make_tuple(src1_min+1, src1_max+1)); break; } case(UnaryOperator::PRE_DECREMENT): { ret.SetValue(std::make_tuple(src1_min-1, src1_max-1)); break; } case(UnaryOperator::POST_INCREMENT): case(UnaryOperator::POST_DECREMENT): { ret.SetValue(std::make_tuple(src1_min, src1_max)); break; } default: break; } } return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(src1_->GetClass() == search_class) { search_res->push_back(src1_); } src1_->SearchExpressions(search_res, search_class, deep_search); } std::shared_ptr<Expression> getSrc1() { return src1_; } UnaryOperator getOp() { return op_; } }; // End of class UnaryOp class BinaryOp : public Expression { protected: std::shared_ptr<Expression> src1_; std::shared_ptr<Expression> src2_; BinaryOperator op_; public: BinaryOp(BinaryOperator op, std::shared_ptr<Expression> s1, std::shared_ptr<Expression> s2) : src1_(s1), src2_(s2), op_(op) { } virtual ExpressionClass GetClass() { return ExpressionClass::BINARYOP; } virtual void GetLeaves(std::shared_ptr<std::list<std::shared_ptr<Expression>>> leaf_list) { if(src1_->GetClass() == ExpressionClass::VARIABLE) { leaf_list->push_back(src1_); } else { src1_->GetLeaves(leaf_list); } if(src2_->GetClass() == ExpressionClass::VARIABLE) { leaf_list->push_back(src2_); } else { src2_->GetLeaves(leaf_list); } } virtual std::string GetName() { std::string ret = ""; return ret; } virtual void GetTensorIndexExpressions (std::shared_ptr<Expression> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { src1_->GetTensorIndexExpressions(targ_tensor, access_expr_list); src2_->GetTensorIndexExpressions(targ_tensor, access_expr_list); } virtual std::string ToString() { std::string ret; ret = boost::str(boost::format("BinaryOp op:%s, \n operand1: %s, \n operand2: %s ") % timewhoop::ToString(op_) % src1_->ToString() % src2_->ToString() ); return ret; } virtual std::string ToCSV() { std::string ret = boost::str(boost::format("BinaryOp, %s, (%s), (%s)") % timewhoop::ToString(op_) % src1_->ToCSV() % src2_->ToCSV() ); return ret; } virtual Maybe<int> FirstOrderEval() { auto ret = src2_->FirstOrderEval(); return ret; } virtual void SetLoopBlockID(int blk_id) { loop_block_id_ = blk_id; src1_->SetLoopBlockID(blk_id); src2_->SetLoopBlockID(blk_id); } virtual void SetNumAccess(int num_access) { num_access_ = num_access; src1_->SetNumAccess(num_access); src2_->SetNumAccess(num_access); } virtual void SetAccessProb(double access_prob) { access_probability_ *= access_prob; src1_->SetAccessProb(access_prob); src2_->SetAccessProb(access_prob); } virtual Maybe<std::tuple<int, int>> MinMaxEval(std::shared_ptr<LoopInformationTable> loop_info_table, int loop_block_id) { Maybe<std::tuple<int, int>> ret; auto src1_range = src1_->MinMaxEval(loop_info_table, loop_block_id); auto src2_range = src2_->MinMaxEval(loop_info_table, loop_block_id); if(src1_range.IsValid() && src2_range.IsValid()) //Evaluation is possible only if src1/src2 eval results are available { auto src1_range_contents = src1_range.GetValue(); auto src2_range_contents = src2_range.GetValue(); int src1_min = std::get<0>(src1_range_contents); int src1_max = std::get<1>(src1_range_contents); int src2_min = std::get<0>(src2_range_contents); int src2_max = std::get<1>(src2_range_contents); //Caution: Double-bound problem // if a is in [0, 3) and b is in [0, 5), the range of a+b is [0+0, 3+5 "-1") switch(op_) { case(BinaryOperator::PLUS): { ret.SetValue(std::make_tuple(src1_min + src2_min, src1_max + src2_max-1)); break; } case(BinaryOperator::MINUS): { int resMin1 = src1_min - src2_min; int resMin2 = src1_max - src2_max; int resMax1 = src1_max - src2_max; int resMax2 = src1_min - src2_min; ret.SetValue(std::make_tuple(std::min(resMin1, resMin2), std::max(resMax1, resMax2) +1 )); break; } case(BinaryOperator::MULT): { ret.SetValue(std::make_tuple(src1_min * src2_min, (src1_max-1) * (src2_max-1) +1 )); break; } case(BinaryOperator::DIV): { //TODO: Apply better error handler assert(src2_min != 0 && src2_max != 0); int resMin1 = src1_min / src2_min; int resMin2 = src1_max / src2_max; int resMax1 = src1_max / src2_max; int resMax2 = src1_min / src2_min; ret.SetValue(std::make_tuple(std::min(resMin1, resMin2), std::max(resMax1, resMax2))); break; } default: break; } //End of switch (op_) } //End of if (ranges->isValid) return ret; } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(src1_->GetClass() == search_class) { search_res->push_back(src1_); } src1_->SearchExpressions(search_res, search_class, deep_search); if(src2_->GetClass() == search_class) { search_res->push_back(src2_); } src2_->SearchExpressions(search_res, search_class, deep_search); } std::shared_ptr<Expression> getSrc1() { return src1_; } std::shared_ptr<Expression> getSrc2() { return src2_; } BinaryOperator getOp() { return op_; } }; // End of class BinaryOp class VariableDeclaration : public Declaration { public: VariableDeclaration(std::shared_ptr<Variable> target) : Declaration(target) { } VariableDeclaration(std::shared_ptr<Variable> target, double exec_prob) : Declaration(target, exec_prob) { } std::shared_ptr<Expression> GetTarget() { return target_; } virtual StatementClass GetClass() { return StatementClass::VARIABLE_DECLARATION; } virtual std::shared_ptr<Container> GetOwner() { return target_; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Variable Declaration, loop_block_id: %d, num_exec: %d \n target_container: %s)") % loop_block_id_ % num_executions_ % target_->ToString() ); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(target_->GetClass() == search_class) { search_res->push_back(target_); } target_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; target_->SetNumAccess(num_executions_); } virtual int AnalyzeLoopBlockID(int current_id) { target_->SetLoopBlockID(current_id); loop_block_id_ = current_id; return current_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; } }; // End of class VariableDeclaration class TensorDeclaration : public Declaration { public: TensorDeclaration(std::shared_ptr<Tensor> target) : Declaration(target) { } TensorDeclaration(std::shared_ptr<Tensor> target, double exec_prob) : Declaration(target, exec_prob) { } std::shared_ptr<Expression> GetTarget() { return target_; } virtual StatementClass GetClass() { return StatementClass::TENSOR_DECLARATION; } virtual std::shared_ptr<Container> GetOwner() { return target_; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Tensor Declaration, loop_block_id: %d, num_exec %d, \n target container: %s )") % loop_block_id_ % num_executions_ % target_->ToString() ); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(target_->GetClass() == search_class) { search_res->push_back(target_); } target_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; target_->SetNumAccess(num_executions_); } virtual int AnalyzeLoopBlockID(int current_id) { target_->SetLoopBlockID(current_id); loop_block_id_ = current_id; return current_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; } }; // End of class TensorDeclaration class TemporalFor : public PrimFor { protected: std::shared_ptr<std::list<std::string>> buffered_tensors_; public: TemporalFor(std::shared_ptr<Statement> init_s, std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> incr_s, std::shared_ptr<Statement> body_s) : PrimFor(init_s, test_e, incr_s, body_s) { } TemporalFor(std::shared_ptr<Statement> init_s, std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> incr_s, std::shared_ptr<Statement> body_s, std::shared_ptr<std::list<std::string>> buffered_tensors) : buffered_tensors_(buffered_tensors), PrimFor(init_s, test_e, incr_s, body_s) { } TemporalFor(std::shared_ptr<Statement> init_s, std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> incr_s, std::shared_ptr<Statement> body_s, double exec_prob) : PrimFor(init_s, test_e, incr_s, body_s, exec_prob) { } virtual StatementClass GetClass() { return StatementClass::TEMPORAL_FOR; } virtual std::shared_ptr<Container> GetOwner() { return init_stmt_->GetOwner(); } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Temporal For, loop_block_id: %d, loop_block_id_base: %d, loop_block_id_bound: %d, num_exec: %d, \n init_statement: %s\n, \n test_expression: %s\n, \n incr_statement: %s\n, \n body_statement: %s\n)") % loop_block_id_ % loop_block_id_base_ % loop_block_id_bound_ % num_executions_ % init_stmt_->ToString() % test_expr_->ToString() % incr_stmt_->ToString() % body_stmt_->ToString() ); std::shared_ptr<Statement> curr_body = body_stmt_->GetNextStmt(); while(curr_body != nullptr) { ret += curr_body->ToString(); curr_body = curr_body->GetNextStmt(); } return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { test_expr_->GetTensorIndexExpressions(targ_tensor, access_expr_list); init_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); incr_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); body_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); std::shared_ptr<Statement> curr_body = body_stmt_->GetNextStmt(); while(curr_body != nullptr) { curr_body->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); curr_body = curr_body->GetNextStmt(); } } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { if(deep_search) { init_stmt_->SearchStatements(search_res, search_class, deep_search); incr_stmt_->SearchStatements(search_res, search_class, deep_search); } body_stmt_->SearchStatements(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(deep_search) { if(test_expr_->GetClass() == search_class) { search_res->push_back(test_expr_); } init_stmt_->SearchExpressions(search_res, search_class, deep_search); test_expr_->SearchExpressions(search_res, search_class, deep_search); incr_stmt_->SearchExpressions(search_res, search_class, deep_search); } body_stmt_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { auto base_query = init_stmt_->FirstOrderEvalBody(); auto bound_query = test_expr_->FirstOrderEval(); //TODO: Add error handling in case of invalid values int base = (base_query.IsValid())? base_query.GetValue() : 0; int bound = (bound_query.IsValid())? bound_query.GetValue() : 0; auto loop_var = init_stmt_->GetOwner(); auto new_loop_info = std::make_shared<LoopInformation>(this, loop_var, loop_block_id_base_, loop_block_id_bound_, base, bound); loop_info_table->AddLoopInfo(new_loop_info); auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->ExtractLoopInfo(loop_info_table); stmt = stmt->GetNextStmt(); } } virtual void EvaluateNumExecs(int mult = 1) { num_executions_ *= mult; init_stmt_->EvaluateNumExecs(mult); incr_stmt_->EvaluateNumExecs(mult); test_expr_->SetNumAccess(num_executions_); int body_mult = mult * GetNumIterations(init_stmt_, test_expr_); auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->EvaluateNumExecs(body_mult); stmt = stmt->GetNextStmt(); } } virtual int AnalyzeLoopBlockID(int current_id) { loop_block_id_ = current_id; loop_block_id_base_ = current_id; test_expr_->SetLoopBlockID(current_id); int last_id = current_id; init_stmt_->AnalyzeLoopBlockID(last_id); last_id = incr_stmt_->AnalyzeLoopBlockID(last_id); last_id = body_stmt_->AnalyzeLoopBlockID(last_id); auto stmt = body_stmt_->GetNextStmt(); while(stmt != nullptr && stmt != NULL) { if(stmt->GetClass() != StatementClass::STATEMENT) //EndLoop { last_id++; } last_id = stmt->AnalyzeLoopBlockID(last_id); stmt = stmt->GetNextStmt(); } loop_block_id_bound_ = last_id; return last_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; init_stmt_->SetExecProb(exec_prob); test_expr_->SetAccessProb(exec_prob); incr_stmt_->SetExecProb(exec_prob); std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->SetExecProb(exec_prob); stmt = stmt->GetNextStmt(); } } }; // End of class TemporalFor class SpatialFor : public PrimFor { protected: int num_partitions_; public: SpatialFor(const int& num_parts, std::shared_ptr<Statement> init_s, std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> incr_s, std::shared_ptr<Statement> body_s) : num_partitions_(num_parts), PrimFor(init_s, test_e, incr_s, body_s) { } SpatialFor(const int& num_parts, std::shared_ptr<Statement> init_s, std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> incr_s, std::shared_ptr<Statement> body_s, double exec_prob) : num_partitions_(num_parts), PrimFor(init_s, test_e, incr_s, body_s, exec_prob) { } virtual StatementClass GetClass() { return StatementClass::SPATIAL_FOR; } virtual std::shared_ptr<Container> GetOwner() { return init_stmt_->GetOwner(); } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Spatial For, loop_block_id: %d, loop_block_id_base: %d, loop_block_id_bound: %d, num_exec: %d, \n init_statement: %s\n, \n test_expression: %s\n, \n incr_statement: %s\n, \n body_statement: %s\n)") % loop_block_id_ % loop_block_id_base_ % loop_block_id_bound_ % num_executions_ % init_stmt_->ToString() % test_expr_->ToString() % incr_stmt_->ToString() % body_stmt_->ToString() ); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { test_expr_->GetTensorIndexExpressions(targ_tensor, access_expr_list); init_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); incr_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); body_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); std::shared_ptr<Statement> curr_body = body_stmt_->GetNextStmt(); while(curr_body != nullptr) { curr_body->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); curr_body = curr_body->GetNextStmt(); } } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { if(deep_search) { init_stmt_->SearchStatements(search_res, search_class, deep_search); incr_stmt_->SearchStatements(search_res, search_class, deep_search); } body_stmt_->SearchStatements(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(deep_search) { if(test_expr_->GetClass() == search_class) { search_res->push_back(test_expr_); } init_stmt_->SearchExpressions(search_res, search_class, deep_search); test_expr_->SearchExpressions(search_res, search_class, deep_search); incr_stmt_->SearchExpressions(search_res, search_class, deep_search); } body_stmt_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { auto base_query = init_stmt_->FirstOrderEvalBody(); auto bound_query = test_expr_->FirstOrderEval(); //TODO: Add error handling in case of invalid values int base = (base_query.IsValid())? base_query.GetValue() : 0; int bound = (bound_query.IsValid())? bound_query.GetValue() : 0; auto loop_var = init_stmt_->GetOwner(); auto new_loop_info = std::make_shared<LoopInformation>(this, loop_var, loop_block_id_base_, loop_block_id_bound_, base, bound); loop_info_table->AddLoopInfo(new_loop_info); auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->ExtractLoopInfo(loop_info_table); stmt = stmt->GetNextStmt(); } } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; init_stmt_->EvaluateNumExecs(mult); incr_stmt_->EvaluateNumExecs(mult); test_expr_->SetNumAccess(num_executions_); int body_mult = mult * GetNumIterations(init_stmt_, test_expr_); auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->EvaluateNumExecs(body_mult); stmt = stmt->GetNextStmt(); } } virtual int AnalyzeLoopBlockID(int current_id) { loop_block_id_ = current_id; loop_block_id_base_ = current_id; test_expr_->SetLoopBlockID(current_id); int last_id = current_id; init_stmt_->AnalyzeLoopBlockID(last_id); last_id = body_stmt_->AnalyzeLoopBlockID(last_id); auto stmt = body_stmt_->GetNextStmt(); while(stmt != nullptr && stmt != NULL) { if(stmt->GetClass() != StatementClass::STATEMENT) //EndLoop { last_id++; } last_id = stmt->AnalyzeLoopBlockID(last_id); stmt = stmt->GetNextStmt(); } loop_block_id_bound_ = last_id; return last_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; init_stmt_->SetExecProb(exec_prob); test_expr_->SetAccessProb(exec_prob); incr_stmt_->SetExecProb(exec_prob); std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->SetExecProb(exec_prob); stmt = stmt->GetNextStmt(); } } }; //End of class SpatialFor class VariableAssignment : public PrimAssignment { public: VariableAssignment(std::shared_ptr<Container> target, std::shared_ptr<Expression> body) : PrimAssignment(target, body) { } VariableAssignment(std::shared_ptr<Container> target, std::shared_ptr<Expression> body, double exec_prob) : PrimAssignment(target, body, exec_prob) { } virtual StatementClass GetClass() { return StatementClass::VAR_ASSIGNMENT; } virtual std::shared_ptr<Container> GetOwner() { return target_; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = body_expr_->FirstOrderEval(); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Variable Assignment, loop_block_id: %d, num_exec: %d, \n target_container: %s, \n assignment_expression: %s") % loop_block_id_ % num_executions_ % target_->ToString() % body_expr_->ToString() ); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { body_expr_->GetTensorIndexExpressions(targ_tensor, access_expr_list); } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(target_->GetClass() == search_class) { search_res->push_back(target_); } if(body_expr_->GetClass() == search_class) { search_res->push_back(body_expr_); } target_->SearchExpressions(search_res, search_class, deep_search); body_expr_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; target_->SetNumAccess(num_executions_); body_expr_->SetNumAccess(num_executions_); } virtual int AnalyzeLoopBlockID(int current_id) { target_->SetLoopBlockID(current_id); body_expr_->SetLoopBlockID(current_id); loop_block_id_ = current_id; return current_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; target_->SetAccessProb(exec_prob); body_expr_->SetAccessProb(exec_prob); } }; // End of class VariableAssignment class TensorAssignment : public PrimAssignment { protected: std::shared_ptr<std::list<std::shared_ptr<Expression>>> idx_exprs_; public: TensorAssignment(std::shared_ptr<Container> target, std::shared_ptr<Expression> body, std::shared_ptr<std::list<std::shared_ptr<Expression>>> idx_exprs) : PrimAssignment(target, body), idx_exprs_(idx_exprs) { } TensorAssignment(std::shared_ptr<Container> target, std::shared_ptr<Expression> body, std::shared_ptr<std::list<std::shared_ptr<Expression>>> idx_exprs, double exec_prob) : PrimAssignment(target, body, exec_prob), idx_exprs_(idx_exprs) { } virtual StatementClass GetClass() { return StatementClass::TENSOR_ASSIGNMENT; } virtual std::shared_ptr<Container> GetOwner() { return target_; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = body_expr_->FirstOrderEval(); return ret; } virtual std::string ToString() { std::string idx_expr_string = "\n---"; for(auto& idx_e : *idx_exprs_) { idx_expr_string += idx_e->ToString(); } idx_expr_string += "---"; std::string ret = boost::str(boost::format("(Tensor Assignment, loop_block_id: %d, num_exec:%d, \n target_container: %s, \n index_expressions: %s, \n assignment_expression: %s)") % loop_block_id_ % num_executions_ % target_->ToString() % idx_expr_string % body_expr_->ToString() ); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { if(targ_tensor->GetName() == target_->GetName()) { access_expr_list->push_back(idx_exprs_); } target_->GetTensorIndexExpressions(targ_tensor, access_expr_list); body_expr_->GetTensorIndexExpressions(targ_tensor, access_expr_list); } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(target_->GetClass() == search_class) { search_res->push_back(target_); } if(body_expr_->GetClass() == search_class) { search_res->push_back(body_expr_); } target_->SearchExpressions(search_res, search_class, deep_search); body_expr_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; target_->SetNumAccess(num_executions_); body_expr_->SetNumAccess(num_executions_); } virtual int AnalyzeLoopBlockID(int current_id) { target_->SetLoopBlockID(current_id); body_expr_->SetLoopBlockID(current_id); loop_block_id_ = current_id; return current_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; target_->SetAccessProb(exec_prob); body_expr_->SetAccessProb(exec_prob); } std::shared_ptr<std::list<std::shared_ptr<Expression>>>& getIdxExpr() { return idx_exprs_; } }; // End of class TensorAssignment class If : public CondStatement // class CondStatement : public Statement { public: If(std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> body_s) : CondStatement(test_e, body_s) { } If(std::shared_ptr<Expression> test_e, std::shared_ptr<Statement> body_s, double exec_prob) : CondStatement(test_e, body_s, exec_prob) { } virtual StatementClass GetClass() { return StatementClass::IF; } virtual std::shared_ptr<Container> GetOwner() { return nullptr; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(If, loop_block_id: %d, num_exec: %d, \n test_expression: %s, \n body_statment: %s)") % loop_block_id_ % num_executions_ % test_expr_->ToString() % body_stmt_->ToString()); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { test_expr_->GetTensorIndexExpressions(targ_tensor, access_expr_list); body_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); std::shared_ptr<Statement> curr_body = body_stmt_->GetNextStmt(); while(curr_body != nullptr) { curr_body->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); curr_body = curr_body->GetNextStmt(); } } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { body_stmt_->SearchStatements(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(deep_search) { if(test_expr_->GetClass() == search_class) { search_res->push_back(test_expr_); } test_expr_->SearchExpressions(search_res, search_class, deep_search); } body_stmt_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->ExtractLoopInfo(loop_info_table); stmt = stmt->GetNextStmt(); } } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; test_expr_->SetNumAccess(num_executions_); std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->EvaluateNumExecs(mult); stmt = stmt->GetNextStmt(); } } virtual int AnalyzeLoopBlockID(int current_id) { loop_block_id_ = current_id; int last_id = body_stmt_->AnalyzeLoopBlockID(current_id); return last_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; test_expr_->SetAccessProb(exec_prob); std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->SetExecProb(execution_probability_); stmt = stmt->GetNextStmt(); } } }; // End of class If class Else : public CondStatement // class CondStatement : public Statement { public: Else(std::shared_ptr<Statement> body_s) : CondStatement (nullptr, body_s) { } Else(std::shared_ptr<Statement> body_s, double exec_prob) : CondStatement (nullptr, body_s, exec_prob) { } virtual StatementClass GetClass() { return StatementClass::ELSE; } virtual std::shared_ptr<Container> GetOwner() { return nullptr; } virtual Maybe<int> FirstOrderEvalBody() { auto ret = Maybe<int>(false); return ret; } virtual std::string ToString() { std::string ret = boost::str(boost::format("(Else, loop_block_id: %d, num_exec: %d, \n body_statement: %s)") % loop_block_id_ % num_executions_ % body_stmt_->ToString()); return ret; } virtual void ExtractTensorAccessExpressions(std::shared_ptr<Container> targ_tensor, std::shared_ptr<std::list<std::shared_ptr<std::list<std::shared_ptr<Expression>>>>> access_expr_list) { body_stmt_->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); std::shared_ptr<Statement> curr_body = body_stmt_->GetNextStmt(); while(curr_body != nullptr) { curr_body->ExtractTensorAccessExpressions(targ_tensor, access_expr_list); curr_body = curr_body->GetNextStmt(); } } virtual void SearchStatements(std::shared_ptr<std::list<std::shared_ptr<Statement>>> search_res, StatementClass search_class, bool deep_search) { body_stmt_->SearchStatements(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { if(next_->GetClass() == search_class) { search_res->push_back(next_); } next_->SearchStatements(search_res, search_class, deep_search); } } virtual void SearchExpressions(std::shared_ptr<std::list<std::shared_ptr<Expression>>> search_res, ExpressionClass search_class, bool deep_search) { if(deep_search) { if(test_expr_ != nullptr) { if(test_expr_->GetClass() == search_class) { search_res->push_back(test_expr_); } test_expr_->SearchExpressions(search_res, search_class, deep_search); } } body_stmt_->SearchExpressions(search_res, search_class, deep_search); if(next_ != nullptr && next_ != NULL) { next_->SearchExpressions(search_res, search_class, deep_search); } } virtual void ExtractLoopInfo(std::shared_ptr<LoopInformationTable> loop_info_table) { auto stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->ExtractLoopInfo(loop_info_table); stmt = stmt->GetNextStmt(); } } virtual void EvaluateNumExecs(int mult) { num_executions_ *= mult; if(test_expr_ != nullptr && test_expr_ != NULL) { test_expr_->SetNumAccess(num_executions_); } std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->EvaluateNumExecs(mult); stmt = stmt->GetNextStmt(); } } virtual int AnalyzeLoopBlockID(int current_id) { loop_block_id_ = current_id; int last_id = current_id; std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { last_id = body_stmt_->AnalyzeLoopBlockID(current_id); } return last_id; } virtual void SetExecProb(double exec_prob) { execution_probability_ *= exec_prob; if(test_expr_ != nullptr && test_expr_ != NULL) { test_expr_->SetAccessProb(exec_prob); } std::shared_ptr<Statement> stmt = body_stmt_; while(stmt != nullptr && stmt != NULL) { stmt->SetExecProb(execution_probability_); stmt = stmt->GetNextStmt(); } } }; //End of class Else }; // namespace timewhoop #endif /* TIMEWHOOP_PURE_ABSTRACT_SYNTAX_HPP_ */
30.712415
434
0.616033
NVlabs
b5b49adcc9d6561e7b9c201c5ec67a30dcd2b12f
1,040
cpp
C++
Codeforces/C. Dominant Piranha.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
Codeforces/C. Dominant Piranha.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
Codeforces/C. Dominant Piranha.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int t, n, x; scanf("%d",&t); while(t--){ scanf("%d",&n); //int arr[n+3]; vector<int> vec; for(int i=0;i<n;i++){ scanf("%d",&x); //scanf("%d",&arr[i]); vec.push_back(x); } //sort(vec.begin(), vec.end()); int len = vec.size(); int flag = 0; for(int i=0;i<len-1;i++){ if(vec[i]!=vec[i+1]) { flag = 1; break; } } if(flag==0) { printf("-1\n"); } else { int idx, mx = -1; for(int i=0;i<len-1;i++){ if(vec[i]>vec[i+1]){ //vec[i] = vec[i]+1; if(mx<vec[i]){ mx = vec[i]; idx = i; } } else if(vec[i]<vec[i+1]){ if(mx<vec[i+1]){ mx = vec[i+1]; idx = i+1; } } } // vec.erase(vec.begin() + (i+1)); //len = vec.size(); //} //else if(vec[i]<vec[i+1]){ //idx = i+1; //vec[i+1]+=1; //vec.erase(vec.begin() + i); //len = vec.size(); //} //} cout<<idx+1<<endl; //" "<<vec.size()<<endl; } } return 0; }
15.522388
46
0.411538
Sowmik23
b5b57f2a3fbb08f02ab3de418a54ab1c6d58e0b3
7,026
cpp
C++
src/bat.cpp
beegee-tokyo/MHC-Sunnyboy-RAK13300
f2e2dc240a9fce3d4b85de426c234f3e10c43c66
[ "Unlicense" ]
1
2021-12-09T10:39:27.000Z
2021-12-09T10:39:27.000Z
src/bat.cpp
beegee-tokyo/MHC-Sunnyboy-RAK13300
f2e2dc240a9fce3d4b85de426c234f3e10c43c66
[ "Unlicense" ]
null
null
null
src/bat.cpp
beegee-tokyo/MHC-Sunnyboy-RAK13300
f2e2dc240a9fce3d4b85de426c234f3e10c43c66
[ "Unlicense" ]
null
null
null
/** * @file bat.cpp * @author Bernd Giesecke (bernd.giesecke@rakwireless.com) * @brief Battery reading functions * @version 0.1 * @date 2021-04-24 * * @copyright Copyright (c) 2021 * */ #include "main.h" /** Millivolts per LSB 3.0V ADC range and 12-bit ADC resolution = 3000mV/4096 */ #define VBAT_MV_PER_LSB (0.73242188F) /** 1.5M + 1M voltage divider on VBAT = (1.5M / (1M + 1.5M)) */ #define VBAT_DIVIDER (0.6F) /** Compensation factor for the VBAT divider, depend on the board */ #define VBAT_DIVIDER_COMP (1.45F) /** Real milli Volts per LSB including compensation */ #define REAL_VBAT_MV_PER_LSB (VBAT_DIVIDER_COMP * VBAT_MV_PER_LSB) /** Analog input for battery level */ uint32_t vbat_pin = WB_A0; // Forward declarations uint32_t esp_adc_cal_raw_to_voltage(uint32_t adc_raw); /** * @brief Initialize the battery analog input * */ void init_batt(void) { adcAttachPin(vbat_pin); analogSetAttenuation(ADC_11db); // Set the resolution to 12-bit (0..4095) analogReadResolution(12); // Can be 8, 10, 12 or 14 } /** * @brief Read the analog value from the battery analog pin * and convert it to milli volt * * @return float Battery level in milli volts 0 ... 4200 */ float read_batt(void) { int i; float raw; float mv; raw = 0; for (i = 0; i < 10; i++) { raw += analogRead(vbat_pin); } raw /= 10; mv = esp_adc_cal_raw_to_voltage(raw * REAL_VBAT_MV_PER_LSB); return mv * (1 / VBAT_DIVIDER); } /** * @brief Estimate the battery level in percentage * from milli volts * * @param mvolts Milli volts measured from analog pin * @return uint8_t Battery level as percentage (0 to 100) */ uint8_t mv_to_percent(float mvolts) { if (mvolts < 3300) return 0; if (mvolts < 3600) { mvolts -= 3300; return mvolts / 30; } if (mvolts > 4200) { return 100; } mvolts -= 3600; return 10 + (mvolts * 0.15F); // thats mvolts /6.66666666 } /** * @brief Read the battery level as value * between 0 and 254. This is used in LoRaWan status requests * as the battery level * * @return uint8_t Battery level as value between 0 and 254 */ uint8_t get_lora_batt(void) { uint16_t read_val = 0; for (int i = 0; i < 10; i++) { read_val += read_batt(); } return (mv_to_percent(read_val/10) * 2.54); } // ESP32 low level battery reading #include <soc/soc.h> #include <stdint.h> #define LUT_POINTS 20 #define LUT_VREF_LOW 1000 #define LUT_VREF_HIGH 1200 #define LUT_ADC_STEP_SIZE 64 #define LUT_POINTS 20 #define LUT_LOW_THRESH 2880 #define LUT_HIGH_THRESH (LUT_LOW_THRESH + LUT_ADC_STEP_SIZE) #define VREF_OFFSET 1100 #define DR_REG_EFUSE_BASE 0x3ff5A000 #define EFUSE_BLK0_RDATA4_REG (DR_REG_EFUSE_BASE + 0x010) #define VREF_REG EFUSE_BLK0_RDATA4_REG #define VREF_MASK 0x1F #define VREF_FORMAT 0 #define VREF_STEP_SIZE 7 #define EFUSE_ADC_VREF 0x0000001F #define EFUSE_ADC_VREF_V 0x1F #define EFUSE_ADC_VREF_S 8 #define EFUSE_ADC_VREF_M ((EFUSE_ADC_VREF_V) << (EFUSE_ADC_VREF_S)) //20 Point lookup tables, covering ADC readings from 2880 to 4096, step size of 64 static const uint32_t lut_adc1_low[LUT_POINTS] = {2240, 2297, 2352, 2405, 2457, 2512, 2564, 2616, 2664, 2709, 2754, 2795, 2832, 2868, 2903, 2937, 2969, 3000, 3030, 3060}; static const uint32_t lut_adc1_high[LUT_POINTS] = {2667, 2706, 2745, 2780, 2813, 2844, 2873, 2901, 2928, 2956, 2982, 3006, 3032, 3059, 3084, 3110, 3135, 3160, 3184, 3209}; /** * @brief Only call when ADC reading is above threshold * * @param adc ADC raw data * @param vref Reference voltage * @return uint32_t Calculated voltage */ static uint32_t calculate_voltage_lut(uint32_t adc, uint32_t vref) { //Get index of lower bound points of LUT uint32_t i = (adc - LUT_LOW_THRESH) / LUT_ADC_STEP_SIZE; //Let the X Axis be Vref, Y axis be ADC reading, and Z be voltage int x2dist = LUT_VREF_HIGH - vref; //(x2 - x) int x1dist = vref - LUT_VREF_LOW; //(x - x1) int y2dist = ((i + 1) * LUT_ADC_STEP_SIZE) + LUT_LOW_THRESH - adc; //(y2 - y) int y1dist = adc - ((i * LUT_ADC_STEP_SIZE) + LUT_LOW_THRESH); //(y - y1) //For points for bilinear interpolation int q11 = lut_adc1_low[i]; //Lower bound point of low_vref_curve int q12 = lut_adc1_low[i + 1]; //Upper bound point of low_vref_curve int q21 = lut_adc1_high[i]; //Lower bound point of high_vref_curve int q22 = lut_adc1_high[i + 1]; //Upper bound point of high_vref_curve //Bilinear interpolation //Where z = 1/((x2-x1)*(y2-y1)) * ( (q11*x2dist*y2dist) + (q21*x1dist*y2dist) + (q12*x2dist*y1dist) + (q22*x1dist*y1dist) ) int voltage = (q11 * x2dist * y2dist) + (q21 * x1dist * y2dist) + (q12 * x2dist * y1dist) + (q22 * x1dist * y1dist); voltage += ((LUT_VREF_HIGH - LUT_VREF_LOW) * LUT_ADC_STEP_SIZE) / 2; //Integer division rounding voltage /= ((LUT_VREF_HIGH - LUT_VREF_LOW) * LUT_ADC_STEP_SIZE); //Divide by ((x2-x1)*(y2-y1)) return (uint32_t)voltage; } /** * @brief Decode bits of eFuse value * * @param bits Bits from the eFuse * @param mask Bit Mask * @param is_twos_compl Format * @return int Decoded eFuse bits */ static inline int decode_bits(uint32_t bits, uint32_t mask, bool is_twos_compl) { int ret; if (bits & (~(mask >> 1) & mask)) { //Check sign bit (MSB of mask) //Negative if (is_twos_compl) { ret = -(((~bits) + 1) & (mask >> 1)); //2's complement } else { ret = -(bits & (mask >> 1)); //Sign-magnitude } } else { //Positive ret = bits & (mask >> 1); } return ret; } /** * @brief Read and decode voltage reference deviation from eFuse * * @return uint32_t voltage reference deviation */ static uint32_t read_efuse_vref(void) { //eFuse stores deviation from ideal reference voltage uint32_t ret = VREF_OFFSET; //Ideal vref uint32_t bits = REG_GET_FIELD(VREF_REG, EFUSE_ADC_VREF); ret += decode_bits(bits, VREF_MASK, VREF_FORMAT) * VREF_STEP_SIZE; return ret; //ADC Vref in mV } /** * @brief Interpolation between two points * * @param y1 * @param y2 * @param x_step * @param x * @return uint32_t */ static inline uint32_t interpolate_two_points(uint32_t y1, uint32_t y2, uint32_t x_step, uint32_t x) { //Interpolate between two points (x1,y1) (x2,y2) between 'lower' and 'upper' separated by 'step' return ((y1 * x_step) + (y2 * x) - (y1 * x) + (x_step / 2)) / x_step; } /** * @brief Calculate voltage from raw ADC value * * @param adc_raw Raw ADC value * @return uint32_t voltage */ uint32_t esp_adc_cal_raw_to_voltage(uint32_t adc_raw) { uint32_t vref = read_efuse_vref(); uint32_t lut_voltage = calculate_voltage_lut(adc_raw, vref); if (adc_raw >= LUT_LOW_THRESH) { if (adc_raw <= LUT_HIGH_THRESH) { uint32_t linear_voltage = (((((vref * 196602 / 4096)) * adc_raw) + (65536 / 2)) / 65536) + 142; return interpolate_two_points(linear_voltage, lut_voltage, LUT_ADC_STEP_SIZE, (adc_raw - LUT_LOW_THRESH)); } else { return lut_voltage; } } else if (adc_raw == 0) { return 0; } else { return ((((((vref * 196602 / 4096) * adc_raw) + (65536 / 2))) / 65536) + 142); } }
26.714829
124
0.687447
beegee-tokyo
b5b60c6c501899f1a53093c64571419171ce1db9
7,861
cc
C++
src/tools/callgraph.cc
sbc100/wasp
766c04335f3766da1441b891471e9b762e938056
[ "Apache-2.0" ]
null
null
null
src/tools/callgraph.cc
sbc100/wasp
766c04335f3766da1441b891471e9b762e938056
[ "Apache-2.0" ]
null
null
null
src/tools/callgraph.cc
sbc100/wasp
766c04335f3766da1441b891471e9b762e938056
[ "Apache-2.0" ]
null
null
null
// // Copyright 2019 WebAssembly Community Group participants // // 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 <cassert> #include <fstream> #include <iostream> #include <iterator> #include <map> #include <set> #include <string> #include <vector> #include "fmt/format.h" #include "fmt/ostream.h" #include "src/tools/argparser.h" #include "src/tools/binary_errors.h" #include "wasp/base/enumerate.h" #include "wasp/base/features.h" #include "wasp/base/file.h" #include "wasp/base/formatters.h" #include "wasp/base/optional.h" #include "wasp/base/str_to_u32.h" #include "wasp/base/string_view.h" #include "wasp/binary/lazy_expression.h" #include "wasp/binary/lazy_module.h" #include "wasp/binary/lazy_module_utils.h" #include "wasp/binary/name_section/sections.h" #include "wasp/binary/sections.h" namespace wasp::tools::callgraph { using fmt::print; using namespace ::wasp::binary; enum class Mode { All, Calls, Callers, }; struct Options { Features features; string_view output_filename; optional<string_view> function; optional<Index> function_index; Mode mode = Mode::All; }; struct Tool { explicit Tool(SpanU8 data, Options); int Run(); void DoPrepass(); void GetFunctionIndex(); void CalculateCallGraph(); void WriteDotFile(); optional<string_view> GetFunctionName(Index) const; BinaryErrors errors; Options options; LazyModule module; std::map<Index, string_view> function_names; std::map<string_view, Index> name_to_function; Index imported_function_count = 0; std::set<std::pair<Index, Index>> call_graph; }; int Main(span<string_view> args) { string_view filename; Options options; options.features.EnableAll(); ArgParser parser{"wasp callgraph"}; parser .Add('h', "--help", "print help and exit", [&]() { parser.PrintHelpAndExit(0); }) .Add('o', "--output", "<filename>", "write DOT file output to <filename>", [&](string_view arg) { options.output_filename = arg; }) .Add("--calls", "<func>", "find all functions called by func", [&](string_view arg) { options.function = arg; options.mode = Mode::Calls; }) .Add("--callers", "<func>", "find all functions that call func", [&](string_view arg) { options.function = arg; options.mode = Mode::Callers; }) .Add("<filename>", "input wasm file", [&](string_view arg) { if (filename.empty()) { filename = arg; } else { print(std::cerr, "Filename already given\n"); } }); parser.Parse(args); if (filename.empty()) { print(std::cerr, "No filenames given.\n"); parser.PrintHelpAndExit(1); } auto optbuf = ReadFile(filename); if (!optbuf) { print(std::cerr, "Error reading file {}.\n", filename); return 1; } SpanU8 data{*optbuf}; Tool tool{data, options}; int result = tool.Run(); tool.errors.PrintTo(std::cerr); return result; } Tool::Tool(SpanU8 data, Options options) : errors{data}, options{options}, module{ReadModule(data, options.features, errors)} {} int Tool::Run() { DoPrepass(); GetFunctionIndex(); if (options.mode != Mode::All && !options.function_index) { print(std::cerr, "Unknown function {}.\n", *options.function); return 1; } CalculateCallGraph(); WriteDotFile(); return 0; } void Tool::DoPrepass() { ForEachFunctionName(module, [this](const IndexNamePair& pair) { name_to_function.insert(std::make_pair(pair.second, pair.first)); }); CopyFunctionNames(module, std::inserter(function_names, function_names.end())); imported_function_count = GetImportCount(module, ExternalKind::Function); } void Tool::GetFunctionIndex() { if (!options.function) { options.function_index = nullopt; return; } // Search by name. auto iter = name_to_function.find(*options.function); if (iter != name_to_function.end()) { options.function_index = iter->second; return; } // Try to convert the string to an integer and search by index. options.function_index = StrToU32(*options.function); } void Tool::CalculateCallGraph() { std::multimap<Index, Index> full_graph; for (auto section : module.sections) { if (section->is_known()) { auto known = section->known(); if (known->id == SectionId::Code) { auto section = ReadCodeSection(known, module.context); for (auto code : enumerate(section.sequence, imported_function_count)) { for (const auto& instr : ReadExpression(code.value->body, module.context)) { if (instr->opcode == Opcode::Call) { assert(instr->has_index_immediate()); auto callee_index = instr->index_immediate(); if (options.mode == Mode::Callers) { full_graph.emplace(callee_index, code.index); } else { full_graph.emplace(code.index, callee_index); } } } } } } } // Calculate subgraph that only includes calls/callers. switch (options.mode) { case Mode::All: for (auto pair : full_graph) { call_graph.insert(pair); } break; case Mode::Calls: case Mode::Callers: { std::set<Index> seen; std::set<Index> next = {*options.function_index}; while (!next.empty()) { std::set<Index> new_next; for (auto caller : next) { if (seen.count(caller)) { continue; } seen.insert(caller); auto range = full_graph.equal_range(caller); for (auto iter = range.first; iter != range.second; ++iter) { Index callee = iter->second; new_next.insert(callee); if (options.mode == Mode::Callers) { call_graph.insert(std::make_pair(callee, caller)); } else { call_graph.insert(std::make_pair(caller, callee)); } } } next = std::move(new_next); } break; } } } void Tool::WriteDotFile() { std::ofstream fstream; std::ostream* stream = &std::cout; if (!options.output_filename.empty()) { fstream = std::ofstream{std::string{options.output_filename}}; if (fstream) { stream = &fstream; } } print(*stream, "strict digraph {{\n"); print(*stream, " rankdir = LR;\n"); // Write nodes. std::set<Index> functions; for (auto pair : call_graph) { functions.insert(pair.first); functions.insert(pair.second); } for (auto function : functions) { print(*stream, " {}", function); auto name = GetFunctionName(function); if (name) { print(*stream, " [label = \"{}\"]", *name); } else { print(*stream, " [label = \"f{}\"]", function); } print(*stream, ";\n"); } // Write edges. for (auto pair : call_graph) { Index caller = pair.first; Index callee = pair.second; print(*stream, " {} -> {};\n", caller, callee); } print(*stream, "}}\n"); stream->flush(); } optional<string_view> Tool::GetFunctionName(Index index) const { auto it = function_names.find(index); if (it != function_names.end()) { return it->second; } else { return nullopt; } } } // namespace wasp::tools::callgraph
26.921233
80
0.62244
sbc100
b5b793b32977564b5d59ef6aae49482a58422ddf
641
cpp
C++
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
#include <iostream> #include "Partida.hpp" #include "Jogador.hpp" using namespace std; int main() { int numero_cartas_por_jogador; int numero_jogadores; cin >> numero_jogadores; cin >> numero_cartas_por_jogador; Partida *p = new Partida(numero_jogadores); string nomeJogador; int numero_pontos_carta; int i, j; string naipe; for(int i=0; i<numero_jogadores; i++) { cin >> nomeJogador; for(int j=0; j<numero_cartas_por_jogador; j++){ cin >> numero_pontos_carta; cin >> naipe; p->addJogadorCarta(nomeJogador, numero_pontos_carta, naipe); } } p->imprimeJogadoresOrdenados(); return 0; }
20.677419
66
0.694228
0lilauro
b5b9be3b4ed25510e205e3ddeb9281f1583c1547
95
cpp
C++
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
#include <stdio.h> int main(void) { int i; for(i=0;i<10;i++) printf("%d",i); }
11.875
23
0.473684
LilyOSullivan
b5ba5a5e1c4328c3b399677985032754b2633537
153
cc
C++
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
1
2020-01-16T07:49:03.000Z
2020-01-16T07:49:03.000Z
#include "cmt_circuit_builder.hh" CMTCircuitBuilder:: ~CMTCircuitBuilder() { } void CMTCircuitBuilder:: destroyCircuit(CMTCircuit* c) { delete c; }
11.769231
33
0.751634
hyraxZK
b5bb4cbaceb3b6811cb0a48d68fbf3fec159f2f2
1,441
cpp
C++
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: NumberofIslands_200.cpp > Author: zzy > Mail: 942744575@qq.com > Created Time: Thu 08 Aug 2019 11:22:34 AM CST ********************************************************************** */ #include <stdio.h> #include <vector> #include <string> #include <stdio.h> #include <climits> #include <gtest/gtest.h> using std::vector; using std::string; /* * 200. 岛屿数量 * * 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 * */ /* * 解法1;DFS 顺序遍历二维数组。如果是岛,把他周围的岛都变成水。 ++ * * * */ class Solution { public: void Flood(vector<vector<char>>& grid, int sr, int sc) { if (sr < 0 || sr >= (int)grid.size()) return; if (sc < 0 || sc >= (int)grid[0].size()) return; if (grid[sr][sc] == '0') return; grid[sr][sc] = '0'; Flood(grid, sr - 1, sc); Flood(grid, sr + 1, sc); Flood(grid, sr, sc + 1); Flood(grid, sr, sc - 1); } int numIslands(vector<vector<char>>& grid) { if (grid.empty()) return 0; int sr = grid.size(); int sc = grid[0].size(); int island_num = 0; for (int i = 0; i < sr; ++i) { for (int j = 0; j < sc; ++j) { if (grid[i][j] == '1') { ++ island_num; Flood(grid, i, j); } } } return island_num; } }; TEST(testCase,test0) { } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
19.472973
93
0.521166
obviouskkk
b5bcd2817b54740bef2b5cc8f67613308cb8ae5a
3,607
hpp
C++
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
#ifndef HAZEN_FRICTION_METHODS #define HAZEN_FRICTION_METHODS // HAZEN #include "Hazen/HydraulicShapes.hpp" namespace hazen { /** * @brief An Abstract Friction Method used to calculate head losses in the * Passage Hydraulic Link. */ class FrictionMethod { public: /** * @brief Compute the slope of the Energy Grade Line (EGL) at one point in * a Passage due to irreversible friction losses. * * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the point of interest. * @return The slope of the EGL at the point of interest along the * Passage. */ virtual Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) = 0; }; /** * @brief An implementation of Manning's Equation to compute the slope of the * Energy Grade Line (EGL) in a Passage. * */ class ManningsFriction : public FrictionMethod { public: /** * @brief Construct a new Mannings Friction object. * * @param n Manning's n coefficient. */ ManningsFriction(Dimensionless n); /** * @brief An implementation of Manning's Equation to compute the slope of * the Energy Grade Line (EGL) in a Passage. * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the calculation point. * @return The slope of the EGL at a point along the Passage. */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Dimensionless n; /**< Manning's n coefficient used in Manning's Equation.*/ }; /** * @brief An implementation of the Hazen-Williams Equation to compute the * slope of the Energy Grade Line (EGL) in a Passage. * */ class HazenFriction : public FrictionMethod { public: /** * @brief Construct a new Hazen Friction object. * * @param C Hazen roughness coefficient. */ HazenFriction(Dimensionless C); /** * @brief An implementation of Hazen-Williams Equation to compute the slope * of the Energy Grade Line (EGL) in a Passage. * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the calculation point. * @return double The slope of the EGL at a point along the Passage. */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Dimensionless C; /**< C friction coefficient used in the Hazen-Williams Equation.*/ }; /** * @brief An implementation of the Darcy-Weisbach Equation to compute the * slope of the Energy Grade Line (EGL) in a Passage. * */ class DarcyFriction : public FrictionMethod { public: /** * @brief Construct a new Darcy Friction object * * @param eps Pipe roughness coefficient. * @param rho Fluid density. * @param mu Fluid dynamic viscosity. */ DarcyFriction(Length eps, Density rho, Dynamic_Viscosity mu); /** * @brief An implementation of Darcy-Weisbach Equation to compute the slope * of the Energy Grade Line (EGL) in a Passage. * @return The slope of the EGL at a point along the Passage. * */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Length eps; /**< epsilon, pipe roughness coefficient used in the Darcy-Weisbach Equation. Dimension matches that of the Hydraulic Shape.*/ Density rho; /**< Density of the fluid.*/ Dynamic_Viscosity mu; /**< Dynamic Viscosity of the fluid.*/ }; } // namespace hazen #endif
31.365217
80
0.703077
barne856
b5befa808059182fe6ed1bf1e778c49c09380dcc
11,293
cpp
C++
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
1
2019-02-19T19:33:00.000Z
2019-02-19T19:33:00.000Z
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
5
2019-01-09T06:10:02.000Z
2019-02-02T06:31:31.000Z
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
null
null
null
#include "NodeGraphicsObject.hpp" #include <cstdlib> #include <iostream> #include <QtWidgets/QGraphicsEffect> #include <QtWidgets/QtWidgets> #include "ConnectionGraphicsObject.hpp" #include "ConnectionState.hpp" #include "FlowScene.hpp" #include "NodePainter.hpp" #include "FlowSceneModel.hpp" #include "NodeConnectionInteraction.hpp" #include "NodeIndex.hpp" #include "StyleCollection.hpp" using QtNodes::ConnectionPolicy; using QtNodes::FlowScene; using QtNodes::Node; using QtNodes::NodeDataType; using QtNodes::NodeGeometry; using QtNodes::NodeGraphicsObject; using QtNodes::NodeIndex; using QtNodes::NodeState; using QtNodes::PortDirection; NodeGraphicsObject::NodeGraphicsObject(FlowScene& scene, NodeIndex const& node) : _scene(scene) , _nodeIndex(node) , _geometry(node, *this) , _state(node) , _locked(false) { _scene.addItem(this); setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true); setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setCacheMode(QGraphicsItem::DeviceCoordinateCache); auto const& nodeStyle = flowScene().model()->nodeStyle(index()); { auto effect = new QGraphicsDropShadowEffect; effect->setOffset(4, 4); effect->setBlurRadius(20); effect->setColor(nodeStyle.ShadowColor); setGraphicsEffect(effect); } setOpacity(nodeStyle.Opacity); setAcceptHoverEvents(true); setZValue(0.); embedQWidget(); // connect to the move signals auto onMoveSlot = [this] { // ask the model to move it if (!flowScene().model()->moveNode(index(), pos())) { // set the location back setPos(flowScene().model()->nodeLocation(index())); moveConnections(); } }; connect(this, &QGraphicsObject::xChanged, this, onMoveSlot); connect(this, &QGraphicsObject::yChanged, this, onMoveSlot); } NodeGraphicsObject::~NodeGraphicsObject() { // TODO I think it is dangerous - user have to delete widget if he allocated // it //if (_proxyWidget) { // delete _proxyWidget->widget(); //} // TODO here can be problem, when item have a parent, then parent remove item // when it will be removed _scene.removeItem(this); } NodeIndex NodeGraphicsObject::index() const { return _nodeIndex; } FlowScene& NodeGraphicsObject::flowScene() { return _scene; } FlowScene const& NodeGraphicsObject::flowScene() const { return _scene; } NodeGeometry& NodeGraphicsObject::geometry() { return _geometry; } NodeGeometry const& NodeGraphicsObject::geometry() const { return _geometry; } NodeState& NodeGraphicsObject::nodeState() { return _state; } NodeState const& NodeGraphicsObject::nodeState() const { return _state; } void NodeGraphicsObject::embedQWidget() { if (auto w = flowScene().model()->nodeWidget(index())) { _proxyWidget = new QGraphicsProxyWidget(this); _proxyWidget->setWidget(w); _proxyWidget->setPreferredWidth(5); geometry().recalculateSize(); _proxyWidget->setPos(geometry().widgetPosition()); update(); _proxyWidget->setOpacity(1.0); _proxyWidget->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); } } QRectF NodeGraphicsObject::boundingRect() const { return geometry().boundingRect(); } void NodeGraphicsObject::moveConnections() const { for (PortDirection portType : { PortDirection::In, PortDirection::Out }) { auto const& connectionEntries = nodeState().getEntries(portType); for (auto const& connections : connectionEntries) { for (auto& con : connections) con->move(); } }; } void NodeGraphicsObject::reactToPossibleConnection(PortDirection reactingPortType, NodeDataType reactingDataType, QPointF const& scenePoint) { QTransform const t = sceneTransform(); QPointF p = t.inverted().map(scenePoint); geometry().setDraggingPosition(p); update(); _state.setReaction(NodeState::REACTING, reactingPortType, reactingDataType); } void NodeGraphicsObject::resetReactionToConnection() { _state.setReaction(NodeState::NOT_REACTING); update(); } void NodeGraphicsObject::lock(bool locked) { _locked = locked; setFlag(QGraphicsItem::ItemIsMovable, !locked); setFlag(QGraphicsItem::ItemIsFocusable, !locked); setFlag(QGraphicsItem::ItemIsSelectable, !locked); } void NodeGraphicsObject::paint(QPainter* painter, QStyleOptionGraphicsItem const* option, QWidget*) { painter->setClipRect(option->exposedRect); NodePainter::paint(painter, *this); } QVariant NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVariant& value) { if (change == ItemPositionChange && scene()) { moveConnections(); } return QGraphicsItem::itemChange(change, value); } void NodeGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (_locked) return; // deselect all other items after this one is selected if (!isSelected() && !(event->modifiers() & Qt::ControlModifier)) { _scene.clearSelection(); } // if(isSelected()) // { // qDebug() << "selected"; // emit(selectionUpdated()); // } for (PortDirection portToCheck : { PortDirection::In, PortDirection::Out }) { // TODO do not pass sceneTransform PortIndex portIndex = geometry().checkHitScenePoint( portToCheck, event->scenePos(), sceneTransform()); if (portIndex != INVALID) { std::vector<ConnectionGraphicsObject*> connections = nodeState().connections(portToCheck, portIndex); // start dragging existing connection if (!connections.empty() && flowScene().model()->nodePortConnectionPolicy( index(), portIndex, portToCheck) == ConnectionPolicy::One) { Q_ASSERT(connections.size() == 1); auto con = *connections.begin(); // start connecting anew, except start with the port that this // connection was already connected to Q_ASSERT(_scene._temporaryConn == nullptr); if (portToCheck == PortDirection::In) { _scene._temporaryConn = new ConnectionGraphicsObject(con->node(PortDirection::Out), con->portIndex(PortDirection::Out), NodeIndex{}, INVALID, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::In, event->scenePos()); } else { _scene._temporaryConn = new ConnectionGraphicsObject(NodeIndex{}, INVALID, con->node(PortDirection::In), con->portIndex(PortDirection::In), _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::Out, event->scenePos()); } _scene._temporaryConn->grabMouse(); // remove it flowScene().model()->removeConnection(con->node(PortDirection::Out), con->portIndex(PortDirection::Out), con->node(PortDirection::In), con->portIndex(PortDirection::In)); } else // initialize new Connection { if (portToCheck == PortDirection::In) { Q_ASSERT(_scene._temporaryConn == nullptr); _scene._temporaryConn = new ConnectionGraphicsObject( NodeIndex{}, INVALID, _nodeIndex, portIndex, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::Out, event->scenePos()); } else { Q_ASSERT(_scene._temporaryConn == nullptr); _scene._temporaryConn = new ConnectionGraphicsObject( _nodeIndex, portIndex, NodeIndex{}, INVALID, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::In, event->scenePos()); } _scene._temporaryConn->grabMouse(); } } } auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { nodeState().setResizing(true); } } void NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (nodeState().resizing()) { auto diff = event->pos() - event->lastPos(); if (auto w = flowScene().model()->nodeWidget(index())) { auto oldSize = w->size(); oldSize += QSize(diff.x(), diff.y()); w->setFixedSize(oldSize); // We have to recalculdate size before set widgetPosition in proxyWidget geometry().recalculateSize(); _proxyWidget->setMinimumSize(oldSize); _proxyWidget->setMaximumSize(oldSize); _proxyWidget->setPos(geometry().widgetPosition()); moveConnections(); event->accept(); } } else { QGraphicsObject::mouseMoveEvent(event); if (event->lastPos() != event->pos()) moveConnections(); event->ignore(); } // TODO I think we have to set scene rect not here, but in view // QRectF r = scene()->sceneRect(); // r = r.united(mapToScene(boundingRect()).boundingRect()); // scene()->setSceneRect(r); } void NodeGraphicsObject::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { nodeState().setResizing(false); QGraphicsObject::mouseReleaseEvent(event); // position connections precisely after fast node move moveConnections(); } void NodeGraphicsObject::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { // bring all the colliding nodes to background QList<QGraphicsItem*> overlapItems = collidingItems(); for (QGraphicsItem* item : overlapItems) { if (item->zValue() > 0.0) { item->setZValue(0.0); } } // bring this node forward setZValue(1.0); geometry().setHovered(true); update(); flowScene().model()->nodeHovered(index(), event->screenPos(), true); event->accept(); } void NodeGraphicsObject::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { geometry().setHovered(false); update(); flowScene().model()->nodeHovered(index(), event->screenPos(), false); event->accept(); } void NodeGraphicsObject::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { setCursor(QCursor(Qt::SizeFDiagCursor)); } else { setCursor(QCursor()); } event->accept(); } void NodeGraphicsObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mouseDoubleClickEvent(event); flowScene().model()->nodeDoubleClicked(index(), event->screenPos()); } void NodeGraphicsObject::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { QGraphicsItem::contextMenuEvent(event); flowScene().model()->nodeContextMenu(index(), event->screenPos()); }
26.447307
81
0.647481
Toms42
b5c009d49c579ef5d675ef420b9f3b3af0f3da80
1,002
cpp
C++
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
7
2019-06-07T07:50:59.000Z
2021-12-10T20:38:48.000Z
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
null
null
null
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
3
2019-12-08T11:32:15.000Z
2020-11-26T11:53:25.000Z
#include "CrashRpt.h" #include <stdio.h> #include <tchar.h> #include "CrashRptWrapper.h" int CrashRptWrapper::install() { CR_INSTALL_INFO info; memset(&info, 0, sizeof(CR_INSTALL_INFO)); info.cb = sizeof(CR_INSTALL_INFO); info.pszAppName = _T(CrashRptWrapper::appName); info.pszAppVersion = _T(CrashRptWrapper::appVersion); info.pszEmailSubject = _T(CrashRptWrapper::emailSubject); info.pszEmailTo = _T(CrashRptWrapper::emailTo); info.uPriorities[CR_SMAPI] = 3; // Try send report over Simple MAPI // Install all available exception handlers info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS; // Install crash reporting int nResult = crInstall(&info); if (nResult != 0) { // Something goes wrong. Get error message. TCHAR szErrorMsg[512] = _T(""); crGetLastErrorMsg(szErrorMsg, 512); _tprintf_s(_T("%s\n"), szErrorMsg); return 1; } return 0; } void CrashRptWrapper::uninstall() { crUninstall(); } void CrashRptWrapper::emulateCrash() { crEmulateCrash(CR_SEH_EXCEPTION); }
23.302326
68
0.736527
nCine
b5c50128d72b01b5c812f44e1810634c0199820c
271
cc
C++
hmwk/3/coordinate_manipulation/metric_space/tests/smooth_coordinate_space_test.cc
ForrestHurley/compPhys
34c2d93b77858150a1c099deff812d961ab6378d
[ "MIT" ]
null
null
null
hmwk/3/coordinate_manipulation/metric_space/tests/smooth_coordinate_space_test.cc
ForrestHurley/compPhys
34c2d93b77858150a1c099deff812d961ab6378d
[ "MIT" ]
null
null
null
hmwk/3/coordinate_manipulation/metric_space/tests/smooth_coordinate_space_test.cc
ForrestHurley/compPhys
34c2d93b77858150a1c099deff812d961ab6378d
[ "MIT" ]
null
null
null
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "smooth_coordinate_space.h" TEST(SmoothCoordinateSpaceTest, SmoothCoordinateConstructionTest) { } TEST(SmoothCoordinateSpaceTest, SetCoordinateTest) { } TEST(SmoothCoordinateSpaceTest, GetOriginTest) { }
12.904762
65
0.797048
ForrestHurley
b5c7ff80e1e25b611fb675075f3e9e62c0e53579
9,063
cpp
C++
Source/WebCore/Modules/gamepad/GamepadManager.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/Modules/gamepad/GamepadManager.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/Modules/gamepad/GamepadManager.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE 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 "GamepadManager.h" #if ENABLE(GAMEPAD) #include "DOMWindow.h" #include "Document.h" #include "EventNames.h" #include "Gamepad.h" #include "GamepadEvent.h" #include "GamepadProvider.h" #include "Logging.h" #include "NavigatorGamepad.h" #include "PlatformGamepad.h" #include <wtf/NeverDestroyed.h> namespace WebCore { static NavigatorGamepad* navigatorGamepadFromDOMWindow(DOMWindow* window) { return NavigatorGamepad::from(&window->navigator()); } GamepadManager& GamepadManager::singleton() { static NeverDestroyed<GamepadManager> sharedManager; return sharedManager; } GamepadManager::GamepadManager() : m_isMonitoringGamepads(false) { } void GamepadManager::platformGamepadConnected(PlatformGamepad& platformGamepad, EventMakesGamepadsVisible eventVisibility) { if (eventVisibility == EventMakesGamepadsVisible::No) return; // Notify blind Navigators and Windows about all gamepads except for this one. for (auto* gamepad : GamepadProvider::singleton().platformGamepads()) { if (!gamepad || gamepad == &platformGamepad) continue; makeGamepadVisible(*gamepad, m_gamepadBlindNavigators, m_gamepadBlindDOMWindows); } m_gamepadBlindNavigators.clear(); m_gamepadBlindDOMWindows.clear(); // Notify everyone of this new gamepad. makeGamepadVisible(platformGamepad, m_navigators, m_domWindows); } void GamepadManager::platformGamepadDisconnected(PlatformGamepad& platformGamepad) { Vector<WeakPtr<DOMWindow>> weakWindows; for (auto* domWindow : m_domWindows) weakWindows.append(makeWeakPtr(*domWindow)); HashSet<NavigatorGamepad*> notifiedNavigators; // Handle the disconnect for all DOMWindows with event listeners and their Navigators. for (auto& window : weakWindows) { // Event dispatch might have made this window go away. if (!window) continue; // This DOMWindow's Navigator might not be accessible. e.g. The DOMWindow might be in the back/forward cache. // If this happens the DOMWindow will not get this gamepaddisconnected event. NavigatorGamepad* navigator = navigatorGamepadFromDOMWindow(window.get()); if (!navigator) continue; // If this Navigator hasn't seen gamepads yet then its Window should not get the disconnect event. if (m_gamepadBlindNavigators.contains(navigator)) continue; Ref<Gamepad> gamepad(navigator->gamepadFromPlatformGamepad(platformGamepad)); navigator->gamepadDisconnected(platformGamepad); notifiedNavigators.add(navigator); window->dispatchEvent(GamepadEvent::create(eventNames().gamepaddisconnectedEvent, gamepad.get()), window->document()); } // Notify all the Navigators that haven't already been notified. for (auto* navigator : m_navigators) { if (!notifiedNavigators.contains(navigator)) navigator->gamepadDisconnected(platformGamepad); } } void GamepadManager::platformGamepadInputActivity(EventMakesGamepadsVisible eventVisibility) { if (eventVisibility == EventMakesGamepadsVisible::No) return; if (m_gamepadBlindNavigators.isEmpty() && m_gamepadBlindDOMWindows.isEmpty()) return; for (auto* gamepad : GamepadProvider::singleton().platformGamepads()) { if (gamepad) makeGamepadVisible(*gamepad, m_gamepadBlindNavigators, m_gamepadBlindDOMWindows); } m_gamepadBlindNavigators.clear(); m_gamepadBlindDOMWindows.clear(); } void GamepadManager::makeGamepadVisible(PlatformGamepad& platformGamepad, HashSet<NavigatorGamepad*>& navigatorSet, HashSet<DOMWindow*>& domWindowSet) { LOG(Gamepad, "GamepadManager::makeGamepadVisible - New gamepad '%s' is visible", platformGamepad.id().utf8().data()); if (navigatorSet.isEmpty() && domWindowSet.isEmpty()) return; for (auto* navigator : navigatorSet) navigator->gamepadConnected(platformGamepad); Vector<WeakPtr<DOMWindow>> weakWindows; for (auto* domWindow : m_domWindows) weakWindows.append(makeWeakPtr(*domWindow)); for (auto& window : weakWindows) { // Event dispatch might have made this window go away. if (!window) continue; // This DOMWindow's Navigator might not be accessible. e.g. The DOMWindow might be in the back/forward cache. // If this happens the DOMWindow will not get this gamepadconnected event. // The new gamepad will still be visibile to it once it is restored from the back/forward cache. NavigatorGamepad* navigator = navigatorGamepadFromDOMWindow(window.get()); if (!navigator) continue; Ref<Gamepad> gamepad(navigator->gamepadFromPlatformGamepad(platformGamepad)); LOG(Gamepad, "GamepadManager::makeGamepadVisible - Dispatching gamepadconnected event for gamepad '%s'", platformGamepad.id().utf8().data()); window->dispatchEvent(GamepadEvent::create(eventNames().gamepadconnectedEvent, gamepad.get()), window->document()); } } void GamepadManager::registerNavigator(NavigatorGamepad* navigator) { LOG(Gamepad, "GamepadManager registering NavigatorGamepad %p", navigator); ASSERT(!m_navigators.contains(navigator)); m_navigators.add(navigator); m_gamepadBlindNavigators.add(navigator); maybeStartMonitoringGamepads(); } void GamepadManager::unregisterNavigator(NavigatorGamepad* navigator) { LOG(Gamepad, "GamepadManager unregistering NavigatorGamepad %p", navigator); ASSERT(m_navigators.contains(navigator)); m_navigators.remove(navigator); m_gamepadBlindNavigators.remove(navigator); maybeStopMonitoringGamepads(); } void GamepadManager::registerDOMWindow(DOMWindow* window) { LOG(Gamepad, "GamepadManager registering DOMWindow %p", window); ASSERT(!m_domWindows.contains(window)); m_domWindows.add(window); // Anytime we register a DOMWindow, we should also double check that its NavigatorGamepad is registered. NavigatorGamepad* navigator = navigatorGamepadFromDOMWindow(window); ASSERT(navigator); if (m_navigators.add(navigator).isNewEntry) m_gamepadBlindNavigators.add(navigator); // If this DOMWindow's NavigatorGamepad was already registered but was still blind, // then this DOMWindow should be blind. if (m_gamepadBlindNavigators.contains(navigator)) m_gamepadBlindDOMWindows.add(window); maybeStartMonitoringGamepads(); } void GamepadManager::unregisterDOMWindow(DOMWindow* window) { LOG(Gamepad, "GamepadManager unregistering DOMWindow %p", window); ASSERT(m_domWindows.contains(window)); m_domWindows.remove(window); m_gamepadBlindDOMWindows.remove(window); maybeStopMonitoringGamepads(); } void GamepadManager::maybeStartMonitoringGamepads() { if (m_isMonitoringGamepads) return; if (!m_navigators.isEmpty() || !m_domWindows.isEmpty()) { LOG(Gamepad, "GamepadManager has %i NavigatorGamepads and %i DOMWindows registered, is starting gamepad monitoring", m_navigators.size(), m_domWindows.size()); m_isMonitoringGamepads = true; GamepadProvider::singleton().startMonitoringGamepads(*this); } } void GamepadManager::maybeStopMonitoringGamepads() { if (!m_isMonitoringGamepads) return; if (m_navigators.isEmpty() && m_domWindows.isEmpty()) { LOG(Gamepad, "GamepadManager has no NavigatorGamepads or DOMWindows registered, is stopping gamepad monitoring"); m_isMonitoringGamepads = false; GamepadProvider::singleton().stopMonitoringGamepads(*this); } } } // namespace WebCore #endif // ENABLE(GAMEPAD)
36.10757
167
0.733973
jacadcaps
b5caa80897243259af0a24c9b3ebda65e6e73317
1,024
hpp
C++
src/parser/expression/literal.hpp
rlannon/csin
5e17a7f3c41f5e1709d789d34d708cbb3c245a0a
[ "MIT" ]
null
null
null
src/parser/expression/literal.hpp
rlannon/csin
5e17a7f3c41f5e1709d789d34d708cbb3c245a0a
[ "MIT" ]
null
null
null
src/parser/expression/literal.hpp
rlannon/csin
5e17a7f3c41f5e1709d789d34d708cbb3c245a0a
[ "MIT" ]
null
null
null
#pragma once #include "expression.hpp" #include "../../util/data_type.hpp" #include "../../util/symbol_qualities.hpp" #include <string> #include <memory> namespace expression { class literal : public expression_base { data_type type; std::string value; public: void set_type(data_type t); const data_type& get_data_type() const; const std::string& get_value() const; void override_qualities(symbol_qualities sq) override; bool has_type_information() const override; inline virtual std::unique_ptr<expression_base> clone() const override { return std::make_unique<literal>(type, value); } literal(enumerations::primitive_type primitive_type, const std::string& value, enumerations::primitive_type subtype = enumerations::primitive_type::NONE); literal(const data_type& t, const std::string& value); literal(); virtual ~literal() = default; }; }
27.675676
91
0.638672
rlannon
b5cbf26352660fff17e1cce2a2ddc092f152345d
1,244
cpp
C++
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
17
2018-04-13T00:38:55.000Z
2022-01-21T08:38:36.000Z
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
4
2017-03-16T03:34:38.000Z
2020-05-08T00:05:51.000Z
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
5
2017-09-06T15:56:04.000Z
2021-09-14T07:38:02.000Z
/// @copyright Copyright (c) 2015 Tim Niederhausen (tim@rnc-ag.de) /// Distributed under the Boost Software License, Version 1.0. /// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "asioext/detail/win_path.hpp" #include "asioext/detail/error.hpp" #include <windows.h> ASIOEXT_NS_BEGIN namespace detail { win_path::win_path(const char* s, std::size_t len, error_code& ec) ASIOEXT_NOEXCEPT : heap_memory_(nullptr) { int new_length; if (len >= kMaxPath) { new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); heap_memory_ = new (std::nothrow) wchar_t[new_length + 1]; if (!heap_memory_) { ec = asio::error::no_memory; return; } new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, heap_memory_, new_length); heap_memory_[new_length] = L'\0'; } else { new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, buffer_, kMaxPath); buffer_[new_length] = L'\0'; } if (new_length != 0) { ec = error_code(); } else { ec.assign(::GetLastError(), asio::error::get_system_category()); } } win_path::~win_path() { delete[] heap_memory_; } } ASIOEXT_NS_END
25.387755
91
0.647106
zweistein-frm2