diff --git a/code/train/C++/0000525_main.cpp b/code/train/C++/0000525_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a272f232496d4b992f50f7d70c1c8eec54471da6 --- /dev/null +++ b/code/train/C++/0000525_main.cpp @@ -0,0 +1,176 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +// OpenCV headers +#include +#include + +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include + +using std::cout; +using std::endl; + +PluginManager plugin_manager_; + +bool myfunction (std::map i, std::map j) +{ + if (i["FPR"] == j["FPR"]) { + return (i["TPR"] < j["TPR"]); + } else { + return (i["FPR"] < j["FPR"]); + } +} + +int main(int argc, char *argv[]) +{ + std::string xml_dir = ""; + + int c; + int create_roc_file = 0; + int output_file_set = 0; + std::string output_file = ""; + std::string output_dir = "./"; + while ((c = getopt (argc, argv, "f:o:d:")) != -1) { + switch (c) { + //case 'a': + // aflag = 1; + // break; + //case 'b': + // bflag = 1; + // break; + case 'o': + output_dir = std::string(optarg); + create_roc_file = 1; + break; + case 'f': + output_file = std::string(optarg); + output_file_set = 1; + break; + case 'd': + xml_dir = std::string(optarg); + break; + case '?': + if (optopt == 'd') { + fprintf (stderr, "Option -%c requires an argument.\n", optopt); + } else if (isprint (optopt)) { + fprintf (stderr, "Unknown option `-%c'.\n", optopt); + } else { + fprintf (stderr, + "Unknown option character `\\x%x'.\n", + optopt); + } + return 1; + default: + abort (); + } + } + + // Check existence of xml directory + if ( !boost::filesystem::exists( fs::path(xml_dir) ) ) { + cout << "Error: XML Directory doesn't exist." << endl; + return -1; + } + + // Open each xml file and count metrics + std::vector file_paths; + syllo::get_files_with_ext(fs::path(xml_dir), ".xml", + file_paths,true); + + + std::vector< std::map > metrics_vector; + + int TP = 0, TN = 0, FP = 0, FN = 0; + for (std::vector::iterator it = file_paths.begin(); + it != file_paths.end(); it++) { + cout << "File: " << it->string() << endl; + + AnnotationParser parser; + int retcode = parser.ParseFile(it->string()); + if (retcode != 0) { + cout << "Failed to parse: " << it->string(); + continue; + } + std::map metrics = parser.get_metrics(); + + metrics_vector.push_back(metrics); + } + + std::sort(metrics_vector.begin(), metrics_vector.end(), myfunction); + + std::string roc_fn; + if (output_file_set == 1) { + roc_fn = output_dir + "/" + output_file; + } else { + // time string generation + time_t rawtime; + struct tm * timeinfo; + char buffer [80]; + time (&rawtime); + timeinfo = localtime (&rawtime); + strftime (buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo); + std::string time_str = std::string(buffer); + + roc_fn = output_dir + "/" + time_str + "_ROC.csv"; + } + + std::ofstream roc_stream; + if (create_roc_file) { + cout << "ROC Output file: " << roc_fn << endl; + roc_stream.open (roc_fn.c_str(), std::ofstream::out); + roc_stream << "# FPR,TPR,thresh,FP,FN,TP,TN," << endl; + } + + for(std::vector< std::map >::iterator it = metrics_vector.begin(); + it != metrics_vector.end(); it++) { + + // 0 for threshold place holder for now: TODO + roc_stream << (*it)["FPR"] <<","<< (*it)["TPR"] << ",0," + << (*it)["FP"] <<","<< (*it)["FN"] <<"," + << (*it)["TP"] <<","<< (*it)["TN"] <<"," + << endl; + + TP += (*it)["TP"]; + TN += (*it)["TN"]; + FP += (*it)["FP"]; + FN += (*it)["FN"]; + } + + roc_stream.close(); + + double TPR = 0, FPR = 0; + + TPR = (double)TP / (double)(TP + FN) ; + FPR = (double)FP / (double)(FP + TN) ; + + // Display results + syllo::fill_line("+"); + cout << "Totals... " << endl; + cout << "True Positives: " << TP << endl; + cout << "True Negatives: " << TN << endl; + cout << "False Positives: " << FP << endl; + cout << "False Negatives: " << FN << endl; + cout << "True Positive Rate: " << TPR << endl; + cout << "False Positive Rate: " << FPR << endl; + syllo::fill_line("+"); + + return 0; +} diff --git a/code/train/C++/0000584_main.cpp b/code/train/C++/0000584_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..053ccb54b5d81e2218e8e9fd2b7bb4aa0b1f2d03 --- /dev/null +++ b/code/train/C++/0000584_main.cpp @@ -0,0 +1,170 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "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 The Qt Company Ltd 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 +** 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "rasterwindow.h" + +//! [5] +class AnalogClockWindow : public RasterWindow +{ +public: + AnalogClockWindow(); + +protected: + void timerEvent(QTimerEvent *) override; + void render(QPainter *p) override; + +private: + int m_timerId; +}; +//! [5] + + +//! [6] +AnalogClockWindow::AnalogClockWindow() +{ + setTitle("Analog Clock"); + resize(200, 200); + + m_timerId = startTimer(1000); +} +//! [6] + +//! [7] +void AnalogClockWindow::timerEvent(QTimerEvent *event) +{ + if (event->timerId() == m_timerId) + renderLater(); +} +//! [7] + +//! [1] //! [14] +void AnalogClockWindow::render(QPainter *p) +{ +//! [14] +//! [8] + static const QPoint hourHand[3] = { + QPoint(7, 8), + QPoint(-7, 8), + QPoint(0, -40) + }; + static const QPoint minuteHand[3] = { + QPoint(7, 8), + QPoint(-7, 8), + QPoint(0, -70) + }; + + QColor hourColor(127, 0, 127); + QColor minuteColor(0, 127, 127, 191); +//! [8] + +//! [9] + p->setRenderHint(QPainter::Antialiasing); +//! [9] //! [10] + p->translate(width() / 2, height() / 2); + + int side = qMin(width(), height()); + p->scale(side / 200.0, side / 200.0); +//! [1] //! [10] + +//! [11] + p->setPen(Qt::NoPen); + p->setBrush(hourColor); +//! [11] + +//! [2] + QTime time = QTime::currentTime(); + + p->save(); + p->rotate(30.0 * ((time.hour() + time.minute() / 60.0))); + p->drawConvexPolygon(hourHand, 3); + p->restore(); +//! [2] + +//! [12] + p->setPen(hourColor); + + for (int i = 0; i < 12; ++i) { + p->drawLine(88, 0, 96, 0); + p->rotate(30.0); + } +//! [12] //! [13] + p->setPen(Qt::NoPen); + p->setBrush(minuteColor); +//! [13] + +//! [3] + p->save(); + p->rotate(6.0 * (time.minute() + time.second() / 60.0)); + p->drawConvexPolygon(minuteHand, 3); + p->restore(); +//! [3] + +//! [4] + p->setPen(minuteColor); + + for (int j = 0; j < 60; ++j) { + if ((j % 5) != 0) + p->drawLine(92, 0, 96, 0); + p->rotate(6.0); + } +//! [4] +} + +int main(int argc, char **argv) +{ + QGuiApplication app(argc, argv); + + AnalogClockWindow clock; + clock.show(); + + return app.exec(); +} diff --git a/code/train/C++/0000623_asgn8.cpp b/code/train/C++/0000623_asgn8.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4885054596d91328dc089b8e9d85c61898bebb0 --- /dev/null +++ b/code/train/C++/0000623_asgn8.cpp @@ -0,0 +1,263 @@ +/****************************************************************************** +CSCI 240 - Program 7 - Spring 2008 + +Name: Joe Dan Parker +Z-Number: 158012 +Section: 8 +TA: Kalpana Mangalarapu + +Purpose: Create a program that will analyze three types of household utility + expenses (gas, electricity and water) over 12 months. +******************************************************************************/ + +#include +#include +#include + +using namespace std; + +// I initialized these variables outside of any function, so that they are available to the entire program, not just within any one scope. +string caption; + +int numScores; + +double mean; +int median; +int hi; +int lo; + +int ar[200]; + +/* Function Prototypes */ + +int buildArray( int[] ); + +void showArray( string, int[], int ); + +void sortArray( int[], int ); + +void doStatsRef( int[], int, double&, int&, int&, int& ); + +void meanAndMedianRef( int[], int, double&, int& ); + +void hiAndLoRef( int[], int, int&, int& ); + +double calcAverage( int[], int ); + +int calcMedian( int[], int ); + +int calcLo( int[], int ); + +int calcHi( int[], int); + +void getScores(int[], int, int[]); + +int main() + { + int counts[6] = {0,0,0,0,0}; + + numScores = buildArray( ar ); + + showArray( "*** Scores ***", ar, numScores ); + + doStatsRef( ar, numScores, mean, median, hi, lo ); + + getScores( ar, numScores, counts ); + + cout << "Mean = " << mean << endl; + cout << "Median = " << median << endl; + cout << "Highest Score = " << hi << endl; + cout << "Lowest Score = " << lo << endl; + cout << endl; + cout << "Number of A's = " << counts[0] << endl; + cout << "Number of B's = " << counts[1] << endl; + cout << "Number of C's = " << counts[2] << endl; + cout << "Number of D's = " << counts[3] << endl; + cout << "Number of E's = " << counts[4] << endl; + cout << "Number of F's = " << counts[5] << endl; + } + +/********** Code your Functions below this line **********/ + +int buildArray( int ar[] ) + { + ifstream inFile; + + int i = 0, + num; + + inFile.open("scores.txt"); + if (inFile.fail()) + { + cout << "Unable to open scores.txt file\n"; + exit(1); + } + inFile >> num; + + while ( inFile ) + { + ar[i] = num; + i++; + inFile >> num; + } + + inFile.close(); + return i; + } + +void showArray( string caption, int ar[], int numScores ) + { + int temp_int = 0, + i; + + cout << caption << endl << endl; + + while ( temp_int < numScores ) + { + for (i = 1; i <= 8; i++ ) + { + if ( ar[temp_int] != 0 ) + { + cout << ar[temp_int] << ' '; + temp_int ++; + } + } + cout << endl; + } + cout << endl << temp_int + 1 << " Scores" << endl << endl; + } + +void sortArray(int ar[], int numScores) + { + int i, j; + int max; + int temp; + + for (i = 0; i <= numScores; i++) + { + max = i; + for (j = i+1; j <= numScores; j++) + { + if (ar[j] > ar[max]) + max = j; + } + temp = ar[i]; + ar[i] = ar[max]; + ar[max] = temp; + } + } + +void doStatsRef( int ar[], int numScores, double & mean, int & median, int & hi, int & lo ) + { + int sortedAr[200], + i; + + for (i = 0; i <= 200; i++) + { + sortedAr[i] = ar[i]; + } + sortArray( sortedAr, numScores ); + + meanAndMedianRef( sortedAr, numScores, mean, median ); + + hiAndLoRef( sortedAr, numScores, hi, lo ); + } + +void meanAndMedianRef( int sortedAr[], int numScores, double & mean, int & median ) + { + mean = calcAverage(sortedAr, numScores); + + median = calcMedian(sortedAr, numScores); + } + +void hiAndLoRef( int sortedAr[], int numScores, int& hi, int& lo ) + { + hi = calcHi( sortedAr, numScores ); + + lo = calcLo( sortedAr, numScores ); + } + +double calcAverage( int sortedAr[], int numScores ) + { + int i; + + int temp_int = 0; + + for ( i = 1; i <= numScores; i ++ ) + { + temp_int += sortedAr[i]; + } + return ((double) temp_int / (double) numScores); + } + +int calcMedian( int sortedAr[], int numScores ) + { + return sortedAr[(( numScores / 2 ) + 1)]; + } + +int calcHi( int ar[], int numScores ) + { + int i, + j = 1; + + int temp_int = 0; + + for ( i = 0; i <= numScores; i ++ ) + { + if (ar[j] < ar[i]) + { + ar[j] = ar[i]; + } + } + return ar[j]; + } + +int calcLo( int ar[], int numScores ) + { + int i, + j = 1; + + double temp_int = 0; + + for ( i = 0; i <= numScores; i ++ ) + { + if (ar[j] > ar[i]) + { + ar[j] = ar[i]; + } + } + return ar[j]; + } + +void getScores ( int sortedAr[], int numScores, int counts[] ) + { + int i; + for (i = 0; i <= numScores; i++) + { + if ( sortedAr[i] >= 90 ) + { + counts[0]++; + } + else if ( sortedAr[i] < 90 && sortedAr[i] >= 80 ) + { + counts[1]++; + } + else if ( sortedAr[i] < 80 && sortedAr[i] >= 70 ) + { + counts[2]++; + } + else if ( sortedAr[i] < 70 && sortedAr[i] >= 60 ) + { + counts[3]++; + } + else if ( sortedAr[i] < 60 && sortedAr[i] >= 50 ) + { + counts[4]++; + } + if ( sortedAr[i] < 50 ) + { + counts[5]++; + } + } + } + diff --git a/code/train/C++/0000658_DoAHeuristicPreferredAngle.cpp b/code/train/C++/0000658_DoAHeuristicPreferredAngle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f43692e26d4d562556505329bb8b880e5294510 --- /dev/null +++ b/code/train/C++/0000658_DoAHeuristicPreferredAngle.cpp @@ -0,0 +1,116 @@ +/******************************************************************************* + * This file is part of openWNS (open Wireless Network Simulator) + * _____________________________________________________________________________ + * + * Copyright (C) 2004-2009 + * Chair of Communication Networks (ComNets) + * Kopernikusstr. 5, D-52074 Aachen, Germany + * phone: ++49-241-80-27910, + * fax: ++49-241-80-22242 + * email: info@openwns.org + * www: http://www.openwns.org + * _____________________________________________________________________________ + * + * openWNS is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License version 2 as published by the + * Free Software Foundation; + * + * openWNS 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 Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + ******************************************************************************/ + +#include "DoAHeuristicPreferredAngle.hpp" + +#include +#include + +#include +#include +#include + +using namespace wns::scheduler; +using namespace wns::scheduler::grouper; + + +STATIC_FACTORY_REGISTER_WITH_CREATOR(DoAHeuristicPreferredAngle, GroupingProviderInterface, "DoAHeuristicPreferredAngle", wns::PyConfigViewCreator); + + +DoAHeuristicPreferredAngle::DoAHeuristicPreferredAngle(const wns::pyconfig::View& config) + : DoATreeBasedGrouper(config), + minAngle(config.get("minAngleDegree")*M_PI/180.0), + weight(config.get("weight")) +{ +} + + +float +DoAHeuristicPreferredAngle::groupingCostForAUser(UserSet group, UserID newUser) { + float cost = 0.0; + float threshold = minAngle; +// float threshold = 20.0 / 180.0 * M_PI; + float penalty = 1000.0; + float min = M_PI; + + float newUserDoA = getNormalizedDoA(newUser); + +// if (Debug) +// std::cout << "New user at " << rad2deg(newUserDoA) << " degrees\n"; + + for (UserSet::const_iterator iter = group.begin(); + iter != group.end(); ++iter) { + float userDoA = getNormalizedDoA(*iter); + +// if (Debug) +// std::cout << "Group user at " << rad2deg(userDoA) << " degrees\n"; + + float diff = userDoA - newUserDoA; + // normalize angles to [0.0, M_PI] + if (diff < 0.0) + diff = diff + 2*M_PI; + if (diff > M_PI) + diff = 2*M_PI - diff; + + if (fabs(diff) < min) + min = fabs(diff); + } + +// if (Debug) +// std::cout << "Minimum " << rad2deg(min) << " degrees\n"; + + // calculate cost to add user + if (min < threshold) + cost = penalty; + else + { + // 0..threshold verboten + // threshold .. 2.5X threshold erwuenscht mit minimalen kosten bei 2x + // threshold. von 2.5x threshold bis 180 konstanter langsam wachsender + // wert auf 1+mincost + + float minCost = threshold / M_PI; + if (min < 2.5*threshold) + cost = weight*(fabs(min-2*threshold)/threshold+minCost); + else + // fange bei 2.5*th mit 0.5+minCost an, dann steiger dich auf + // 1+minCost bei M_PI + cost = weight*((min-2.5*threshold)*(0.5/(M_PI-2.5*threshold)) +0.5+minCost ); + + } + +// if (Debug) +// std::cout << "Resulting in cost of " << cost << " \n\n"; + + return cost; +} + + + + + + diff --git a/code/train/C++/0000762_statistic.cpp b/code/train/C++/0000762_statistic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..986b4d60f328f69960bd23f2624fd50c8c7022f5 --- /dev/null +++ b/code/train/C++/0000762_statistic.cpp @@ -0,0 +1,16 @@ +#include +#include +using namespace std; +#define INF 0x3f3f3f3f +int main() { + int n = 0, mmin = INF, mmax = -INF, sum = 0; + int x; + while(scanf("%d", &x) == 1){ + n ++; + sum += x; + if(x > mmax) mmax = x; + if(x < mmin) mmin = x; + } + printf("%d %d %.3f",mmin, mmax, (double)sum / n); + return 0; +} \ No newline at end of file diff --git a/code/train/C++/0000894_7771448.cpp b/code/train/C++/0000894_7771448.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69a911f22f9ec6f9f11198e1509d8605c0a59c9e --- /dev/null +++ b/code/train/C++/0000894_7771448.cpp @@ -0,0 +1,110 @@ +//Language: GNU C++ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +#define LL long long +#define uLL unsigned long long +#define B puts("^_^"); +#define FILEIN freopen("in", "r", stdin); +#define MP make_pair +#define PB push_back +#define fi first +#define se second +#define PI pair +#define VI vector +#define FOR(i, x, y) for(int i=(x); i<(y); ++i) +#define F(x) for(int i=0; i<(x); ++i) +#define F1(x) for(int i=1; i<=(x); ++i) +#define FJ(x) for(int j=0; j<(x); ++j) +#define FJ1(x) for(int j=1; j<=(x); ++j) +#define FK(x) for(int k=0; k<=(x); ++k) +#define lson (u<<1) +#define rson (u<<1|1) +const int N=500005; +const int INF=0x3f3f3f3f; +//const int M=7+1e9; +inline int IN() {int x; scanf("%d", &x); return x;} +#define GET(x) int x=IN() +inline void OUT(int x) {printf("%d\n", x);} + +int fst[N], nxt[N], from[N], to[N], w[N], h; +#define bian for(int i=fst[u]; ~i; i=nxt[i]) +void jiabian(int u, int v, int x){ + nxt[h]=fst[u], from[h]=u, to[h]=v, w[h]=x, fst[u]=h++; +} + +int n, m; +int d[N], t[N][20], _t[N]; +int fa[N][20]; +VI ch[N]; +vector > query; +int zuo[N]; +int _root[N]; + +void dfs(int u, int f){ + if(f==-1) fa[u][0]=u, d[u]=0; + else t[u][0]=_t[u], fa[u][0]=f, d[u]=d[f]+1; + F1(19) fa[u][i]=fa[fa[u][i-1]][i-1], t[u][i]=max(t[fa[u][i-1]][i-1], t[u][i-1]); + int sz=ch[u].size(); + F(sz){ + int v=ch[u][i]; + dfs(v, u); + } +} + +int get(int u, int d){ + F(20) if(d&(1<=query[i].se) + puts("NO"); + else puts("YES"); + } + return 0; +} diff --git a/code/train/C++/0001490_bip32_tests.cpp b/code/train/C++/0001490_bip32_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbec756806253d581d9a6fd9a5b285f8301a09e3 --- /dev/null +++ b/code/train/C++/0001490_bip32_tests.cpp @@ -0,0 +1,154 @@ +// Copyright (c) 2013-2019 TurboCoin +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +struct TestDerivation { + std::string pub; + std::string prv; + unsigned int nChild; +}; + +struct TestVector { + std::string strHexMaster; + std::vector vDerive; + + explicit TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {} + + TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) { + vDerive.push_back(TestDerivation()); + TestDerivation &der = vDerive.back(); + der.pub = pub; + der.prv = prv; + der.nChild = nChild; + return *this; + } +}; + +TestVector test1 = + TestVector("000102030405060708090a0b0c0d0e0f") + ("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", + "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", + 0x80000000) + ("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw", + "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", + 1) + ("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ", + "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", + 0x80000002) + ("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5", + "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", + 2) + ("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV", + "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", + 1000000000) + ("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy", + "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", + 0); + +TestVector test2 = + TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542") + ("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", + "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", + 0) + ("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH", + "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", + 0xFFFFFFFF) + ("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a", + "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", + 1) + ("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon", + "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", + 0xFFFFFFFE) + ("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL", + "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", + 2) + ("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt", + "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", + 0); + +TestVector test3 = + TestVector("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be") + ("xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13", + "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", + 0x80000000) + ("xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y", + "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", + 0); + +static void RunTest(const TestVector &test) { + std::vector seed = ParseHex(test.strHexMaster); + CExtKey key; + CExtPubKey pubkey; + key.SetSeed(seed.data(), seed.size()); + pubkey = key.Neuter(); + for (const TestDerivation &derive : test.vDerive) { + unsigned char data[74]; + key.Encode(data); + pubkey.Encode(data); + + // Test private key + BOOST_CHECK(EncodeExtKey(key) == derive.prv); + BOOST_CHECK(DecodeExtKey(derive.prv) == key); //ensure a base58 decoded key also matches + + // Test public key + BOOST_CHECK(EncodeExtPubKey(pubkey) == derive.pub); + BOOST_CHECK(DecodeExtPubKey(derive.pub) == pubkey); //ensure a base58 decoded pubkey also matches + + // Derive new keys + CExtKey keyNew; + BOOST_CHECK(key.Derive(keyNew, derive.nChild)); + CExtPubKey pubkeyNew = keyNew.Neuter(); + if (!(derive.nChild & 0x80000000)) { + // Compare with public derivation + CExtPubKey pubkeyNew2; + BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild)); + BOOST_CHECK(pubkeyNew == pubkeyNew2); + } + key = keyNew; + pubkey = pubkeyNew; + + CDataStream ssPub(SER_DISK, CLIENT_VERSION); + ssPub << pubkeyNew; + BOOST_CHECK(ssPub.size() == 75); + + CDataStream ssPriv(SER_DISK, CLIENT_VERSION); + ssPriv << keyNew; + BOOST_CHECK(ssPriv.size() == 75); + + CExtPubKey pubCheck; + CExtKey privCheck; + ssPub >> pubCheck; + ssPriv >> privCheck; + + BOOST_CHECK(pubCheck == pubkeyNew); + BOOST_CHECK(privCheck == keyNew); + } +} + +BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup) + +BOOST_AUTO_TEST_CASE(bip32_test1) { + RunTest(test1); +} + +BOOST_AUTO_TEST_CASE(bip32_test2) { + RunTest(test2); +} + +BOOST_AUTO_TEST_CASE(bip32_test3) { + RunTest(test3); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/code/train/C++/0002138_A.cpp b/code/train/C++/0002138_A.cpp new file mode 100644 index 0000000000000000000000000000000000000000..223cf76f7565c6c37b4b433f18f7f3c9cca5dd2d --- /dev/null +++ b/code/train/C++/0002138_A.cpp @@ -0,0 +1,34 @@ +// This is a personal academic project. Dear PVS-Studio, please check it. +// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +// PVS-settings + +// PVS-settings end +#include +#include +#include + +using namespace std; + +int main() +{ + int n, a, m; + cin >> n; + vector > arr(n); + for (int i = 0; i < n; ++i) + { + cin >> a; + arr[i] = make_pair(a, i + 1); + } + sort(arr.begin(), arr.end()); + m = 2000000005; + for (int i = 1; i < n; ++i) + if (arr[i].first - arr[i - 1].first < m) + { + a = i; + m = arr[i].first - arr[i - 1].first; + } + cout << m << endl << + ((arr[a - 1].second > arr[a].second) ? arr[a].second : arr[a - 1].second) << ' ' << + ((arr[a - 1].second > arr[a].second) ? arr[a - 1].second : arr[a].second); + return 0; +} diff --git a/code/train/C++/0002412_authmessagevalidator.cpp b/code/train/C++/0002412_authmessagevalidator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87fdef9719dcdf92c552a39030d3e2218fd9c8ef --- /dev/null +++ b/code/train/C++/0002412_authmessagevalidator.cpp @@ -0,0 +1,117 @@ +/***************************************************************************** + * PokerTH - The open source texas holdem engine * + * Copyright (C) 2006-2012 Felix Hammer, Florian Thauer, Lothar May * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as * + * published by the Free Software Foundation, either version 3 of the * + * License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU Affero General Public License for more details. * + * * + * You should have received a copy of the GNU Affero General Public License * + * along with this program. If not, see . * + * * + * * + * Additional permission under GNU AGPL version 3 section 7 * + * * + * If you modify this program, or any covered work, by linking or * + * combining it with the OpenSSL project's OpenSSL library (or a * + * modified version of that library), containing parts covered by the * + * terms of the OpenSSL or SSLeay licenses, the authors of PokerTH * + * (Felix Hammer, Florian Thauer, Lothar May) grant you additional * + * permission to convey the resulting work. * + * Corresponding Source for a non-source form of such a combination * + * shall include the source code for the parts of OpenSSL used as well * + * as that of the covered work. * + *****************************************************************************/ + +#include +#include + +using namespace std; + + +AuthMessageValidator::AuthMessageValidator() +{ + m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthClientRequestMessage, ValidateAuthClientRequestMessage)); + m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthServerChallengeMessage, ValidateAuthServerChallengeMessage)); + m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthClientResponseMessage, ValidateAuthClientResponseMessage)); + m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthServerVerificationMessage, ValidateAuthServerVerificationMessage)); +} + +bool +AuthMessageValidator::IsValidMessage(const AuthMessage &msg) const +{ + // Default: Invalid packet. + bool retVal = false; + ValidateFunctorMap::const_iterator pos = m_validationMap.find(msg.messagetype()); + if (pos != m_validationMap.end()) { + // Call validation functor. + retVal = pos->second(msg); + } + return retVal; +} + +bool +AuthMessageValidator::ValidateAuthClientRequestMessage(const AuthMessage &msg) +{ + bool retVal = false; + if (msg.has_authclientrequestmessage()) { + const AuthClientRequestMessage &request = msg.authclientrequestmessage(); + if (VALIDATE_IS_UINT16(request.requestedversion().majorversion()) + && VALIDATE_IS_UINT16(request.requestedversion().minorversion()) + && (!request.has_mylastsessionid() || request.mylastsessionid().size() == 16) + && (!request.has_authserverpassword() || VALIDATE_STRING_SIZE(request.authserverpassword(), 1, 64)) + && (!request.has_nickname() || VALIDATE_STRING_SIZE(request.nickname(), 1, 64)) + && (!request.has_clientuserdata() || VALIDATE_STRING_SIZE(request.clientuserdata(), 1, 256)) + && (!request.has_avatarhash() || request.avatarhash().size() == 16)) { + + retVal = true; + } + } + return retVal; +} + +bool +AuthMessageValidator::ValidateAuthServerChallengeMessage(const AuthMessage &msg) +{ + bool retVal = false; + if (msg.has_authserverchallengemessage()) { + const AuthServerChallengeMessage &challenge = msg.authserverchallengemessage(); + if (VALIDATE_STRING_SIZE(challenge.serverchallenge(), 1, 256)) { + retVal = true; + } + } + return retVal; +} + +bool +AuthMessageValidator::ValidateAuthClientResponseMessage(const AuthMessage &msg) +{ + bool retVal = false; + if (msg.has_authclientresponsemessage()) { + const AuthClientResponseMessage &response = msg.authclientresponsemessage(); + if (VALIDATE_STRING_SIZE(response.clientresponse(), 1, 256)) { + retVal = true; + } + } + return retVal; +} + +bool +AuthMessageValidator::ValidateAuthServerVerificationMessage(const AuthMessage &msg) +{ + bool retVal = false; + if (msg.has_authserververificationmessage()) { + const AuthServerVerificationMessage &verification = msg.authserververificationmessage(); + if (VALIDATE_STRING_SIZE(verification.serververification(), 1, 256)) { + retVal = true; + } + } + return retVal; +} + diff --git a/code/train/C++/0002530_AppMoblet.cpp b/code/train/C++/0002530_AppMoblet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e0047fda3fdddd9f463f11c579c4f2039c71dcb --- /dev/null +++ b/code/train/C++/0002530_AppMoblet.cpp @@ -0,0 +1,285 @@ +/* Copyright 2013 David Axmark + +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. +*/ + +/** + * @file AppMoblet.cpp + * @author Bogdan Iusco + * + * AppMoblet class shows how to: + * - open and close contacts list. + * - create contact item. + * - remove contact item from the list. + */ + +// Minimum number of values for drag events. +#define MIN_DRAG_VALUES 5 + +#include +#include +#include + +#include "AppMoblet.h" +#include "Util.h" +#include "PIMContact.h" + +/** + * Constructor. + */ +AppMoblet::AppMoblet() : + Moblet(), + mHandlePointerEvent(false) +{ + this->startPIM(); +} + +/** + * Destructor. + */ +AppMoblet::~AppMoblet() +{ + +} + +/** + * This function is called with a coordinate when a pointer is moved. + */ +void AppMoblet::pointerMoveEvent(MAPoint2d point) +{ + if (mHandlePointerEvent) + { + mDragValues.add(point.x); + } +} + +/** + * This function is called with a coordinate when a pointer is released. + */ +void AppMoblet::pointerReleaseEvent(MAPoint2d point) +{ + // Handle this event only if no PIM action is on progress. + if (mHandlePointerEvent) + { + // Check if there are enough drag events for analysis. + if (MIN_DRAG_VALUES > mDragValues.size()) + { + return; + } + + // Check if drag is from left to right of from right to left. + bool dragFromLeftToRight = true; + bool dragFromRightToLeft = true; + int previousValue = mDragValues[0]; + for (int i = 1; (i < mDragValues.size()) && (dragFromLeftToRight + || dragFromRightToLeft); i++) + { + int currentValue = mDragValues[i]; + if (previousValue > currentValue) + { + dragFromLeftToRight = false; + } + if (previousValue < currentValue) + { + dragFromRightToLeft = false; + } + + previousValue = currentValue; + } + + // If drag is from left to right print the next contact, otherwise + // close the PIM contacts list. + if (dragFromLeftToRight) + { + this->printNextContact(); + } + else if (dragFromRightToLeft) + { + this->closePIMContactsList(); + } + } +} + +/** + * Called when the screen is touched. + */ +void AppMoblet::pointerPressEvent(MAPoint2d point) +{ + if (mHandlePointerEvent) + { + mDragValues.clear(); + } +} + +/** + * Method called when a key is pressed. + */ +void AppMoblet::keyPressEvent(int keyCode, int nativeCode) +{ + // Close the application if the back key is pressed. + if(MAK_BACK == keyCode) + { + close(); + } +} + +/** + * Start working with PIM. + * Add, modify and remove a PIM contact. + */ +void AppMoblet::startPIM() +{ + // Open PIM contacts list. + this->openPIMContactsList(); + + // Create new contact and add data into fields. + PIMContact* newContact = this->createContact(); + if (NULL == newContact) + { + return; + } + newContact->addDataToContact(); + + // Modify the new contact. + this->modifyContact(newContact); + + // Remove the new contact from the list and delete the object. + this->removeContact(newContact); + delete newContact; + + // Print options on the screen and wait for drag events. + this->printInfo(); +} + +/** + * Open PIM contacts list. + */ +void AppMoblet::openPIMContactsList() +{ + printf("\n==============Open contacts list==============="); + + // Get a handle to the list of contacts. + mContactsListHandle = maPimListOpen(MA_PIM_CONTACTS); + checkResultCode(mContactsListHandle); +} + +/** + * Print the next contact from the PIM contacts list. + */ +void AppMoblet::printNextContact() +{ + // Ignore all drag events handled by this moblet. + mHandlePointerEvent = false; + + printf("\n=============Printing next contact=============\n"); + + // Get a hold on a contact item. + MAHandle pimItemHandle = maPimListNext(mContactsListHandle); + + // Check if the new contact handle is valid. + if (0 < pimItemHandle) + { + // Create new contact item and print it on the screen. + PIMContact* item = new PIMContact(pimItemHandle); + item->printContact(); + delete item; + } + else if (pimItemHandle == 0) + { + // Reached at the end of the list. + printf("The contacts list does not contain more items."); + } + else + { + // Print the error on the screen. + printResultCode(pimItemHandle); + } + + // Print options on the screen and wait for drag events. + this->printInfo(); +} + +/** + * Create a new contact. + * @return The new created contact, or NULL in case of error. + * The ownership of the result is passed to the caller. + */ +PIMContact* AppMoblet::createContact() +{ + // Get a handle to the new created contact. + printf("\n==============Create new contact==============\n"); + MAHandle newContantHandle = maPimItemCreate(mContactsListHandle); + + // Check for errors. + if (0 > newContantHandle) + { + printf("Cann't create new contact."); + printResultCode(newContantHandle); + return NULL; + } + + // Create and return the new contact. + PIMContact* newContact = new PIMContact(newContantHandle); + return newContact; +} + +/** + * Modify the address field of a specified contact. + * Remove the first value from the phone field. + * @param contact The given contact item. + */ +void AppMoblet::modifyContact(PIMContact* contact) +{ + contact->modifyAddressField(); + + printf("\n====Remove field value from the new contact====\n"); + contact->removeFieldValue(MA_PIM_FIELD_CONTACT_TEL, 0); +} + +/** + * Remove a specified contact from the list. + * It also closes the item. + * @param contact The given contact item. + */ +void AppMoblet::removeContact(PIMContact* contact) +{ + printf("\n===========Remove the new contact=============\n"); + int resultCode = maPimItemRemove(mContactsListHandle, contact->getHandle()); + printResultCode(resultCode); +} + +/** + * Close the PIM contacts list. + */ +void AppMoblet::closePIMContactsList() +{ + printf("\n ==============Close the contacts list=========\n"); + printResultCode(maPimListClose(mContactsListHandle)); + + // Start again working with PIM> + this->startPIM(); +} + +/** + * Print show next contact / close pim list options on the screen. + */ +void AppMoblet::printInfo() +{ + printf("\n=============================================="); + printf("Drag from left to right to show the next \n contact"); + printf("Drag from right to left to close the contacts \n list"); + printf("==============================================\n\n"); + + // Allow this moblet to handle pointer events. + mHandlePointerEvent = true; +} diff --git a/code/train/C++/0002981_vcardmanager.cpp b/code/train/C++/0002981_vcardmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2845e82a263223460937128f6a29378e1728186e --- /dev/null +++ b/code/train/C++/0002981_vcardmanager.cpp @@ -0,0 +1,127 @@ +/* + Copyright (c) 2006-2009 by Jakob Schroeter + This file is part of the gloox library. http://camaya.net/gloox + + This software is distributed under a license. The full license + agreement can be found in the file LICENSE in this distribution. + This software may not be copied, modified, sold or distributed + other than expressed in the named license agreement. + + This software is distributed without any warranty. +*/ + + +#include "vcardmanager.h" +#include "vcardhandler.h" +#include "vcard.h" +#include "clientbase.h" +#include "disco.h" +#include "error.h" + +namespace gloox +{ + + VCardManager::VCardManager( ClientBase* parent ) + : m_parent( parent ) + { + if( m_parent ) + { + m_parent->registerIqHandler( this, ExtVCard ); + m_parent->disco()->addFeature( XMLNS_VCARD_TEMP ); + m_parent->registerStanzaExtension( new VCard() ); + } + } + + VCardManager::~VCardManager() + { + if( m_parent ) + { + m_parent->disco()->removeFeature( XMLNS_VCARD_TEMP ); + m_parent->removeIqHandler( this, ExtVCard ); + m_parent->removeIDHandler( this ); + } + } + + void VCardManager::fetchVCard( const JID& jid, VCardHandler* vch ) + { + if( !m_parent || !vch ) + return; + + TrackMap::const_iterator it = m_trackMap.find( jid.bare() ); + if( it != m_trackMap.end() ) + return; + + const std::string& id = m_parent->getID(); + IQ iq ( IQ::Get, jid, id ); + iq.addExtension( new VCard() ); + + m_trackMap[id] = vch; + m_parent->send( iq, this,VCardHandler::FetchVCard ); + } + + void VCardManager::cancelVCardOperations( VCardHandler* vch ) + { + TrackMap::iterator t; + TrackMap::iterator it = m_trackMap.begin(); + while( it != m_trackMap.end() ) + { + t = it; + ++it; + if( (*t).second == vch ) + m_trackMap.erase( t ); + } + } + + void VCardManager::storeVCard( VCard* vcard, VCardHandler* vch ) + { + if( !m_parent || !vch ) + return; + + const std::string& id = m_parent->getID(); + IQ iq( IQ::Set, JID(), id ); + iq.addExtension( vcard ); + + m_trackMap[id] = vch; + m_parent->send( iq, this, VCardHandler::StoreVCard ); + } + + void VCardManager::handleIqID( const IQ& iq, int context ) + { + TrackMap::iterator it = m_trackMap.find( iq.id() ); + if( it != m_trackMap.end() ) + { + switch( iq.subtype() ) + { + case IQ::Result: + { + switch( context ) + { + case VCardHandler::FetchVCard: + { + const VCard* v = iq.findExtension( ExtVCard ); + (*it).second->handleVCard( iq.from(), v ); + break; + } + case VCardHandler::StoreVCard: + (*it).second->handleVCardResult( VCardHandler::StoreVCard, iq.from() ); + break; + } + } + break; + case IQ::Error: + { + (*it).second->handleVCardResult( (VCardHandler::VCardContext)context, + iq.from(), + iq.error() ? iq.error()->error() + : StanzaErrorUndefined ); + break; + } + default: + break; + } + + m_trackMap.erase( it ); + } + } + +} diff --git a/code/train/C++/0003712_PEMer_Lite.cpp b/code/train/C++/0003712_PEMer_Lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7782cc5953d2dd03f6d37597369c81bf116c5da0 --- /dev/null +++ b/code/train/C++/0003712_PEMer_Lite.cpp @@ -0,0 +1,267 @@ +/* +Name: saminput +Author: Lars Zerbe +Author: Stephan Peter +Maintainer: Lars Zerbe +License: GPL v3 +Copyright: 2008-2012, FU Berlin +Status: under development +*/ + +#include "PEMer_Lite.h" + + +bool candidateSortFunction(candidate &x, candidate &y) +{ + try{return (x.pos < y.pos);} + catch(std::exception allgemeineException){return false;} +} + +int samSort(candidates &save) +{ + std::cout << "samSort" << std::endl; + std::sort(save.begin(),save.end(),candidateSortFunction); + + return 0; +} + +seqan::ArgumentParser::ParseResult commands(modifier &options, int argc, char const ** argv) +{ + std::cout << "Parser" << std::endl; + seqan::ArgumentParser parser("PEMer_Lite"); + + // Optionen hinzufügen + addOption(parser, seqan::ArgParseOption("i","input-file","Input SAM-file.",seqan::ArgParseArgument::INPUTFILE)); + setValidValues(parser, "input-file", "sam"); + setRequired(parser, "input-file"); + + addOption(parser,seqan::ArgParseOption("x","SD-variable", "Variable to use for multiples of standard degression.",seqan::ArgParseArgument::INTEGER, "INT")); + setMinValue(parser, "SD-variable", "1"); + setDefaultValue(parser,"SD-variable","1"); + + addOption(parser,seqan::ArgParseOption("y","Del_SD-variable", "Variable to spezify multiples of standard degression for deletions.",seqan::ArgParseArgument::INTEGER, "INT")); + setMinValue(parser, "Del_SD-variable", "1"); + setDefaultValue(parser,"Del_SD-variable","1"); + + addOption(parser,seqan::ArgParseOption("s","standard_degression", "Variable to use for standard degression for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT")); + setMinValue(parser, "standard_degression", "1"); + + addOption(parser,seqan::ArgParseOption("e","expected_value", "Variable to use for the expected value for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT")); + setMinValue(parser, "expected_value", "1"); + + addOption(parser, seqan::ArgParseOption("p","Print", "Select to print temporary solutions.")); + + // verarbeitet die Kommandozeile + seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); + + // Überprüfung der richtigen Ausführung von commands() + if (res != seqan::ArgumentParser::PARSE_OK) + return res; + + // extrahiert Werte aus der parser. + getOptionValue(options.x, parser, "SD-variable"); + getOptionValue(options.y, parser, "Del_SD-variable"); + getOptionValue(options.e, parser, "expected_value"); + getOptionValue(options.sd, parser, "standard_degression"); + options.p = isSet(parser, "Print"); + getOptionValue(options.inputFile, parser, "input-file"); + + return seqan::ArgumentParser::PARSE_OK; +} + +unsigned generateStandardDegression(candidates &input,int e_value) //erzeugt die Standartabweichung +{ + std::cout << "SD" << std::endl; + unsigned standardDegression=0; + + unsigned n = input.size(); + for (unsigned i=0;i0) + { + median.add(record.tLen); + std::cout << record.tLen << "\t" << median.getMedian() << std::endl; + tmp.addvalues(record.rID,record.beginPos,record.tLen,candidate::undefine); + save.push_back(tmp); + } + } + std::cout << options.e << std::endl; + if(options.e==0) + { + stats.e_value=median.getMedian(); + } + else + { + stats.e_value=options.e; + } + if(options.sd==0) + { + stats.standardDegression=generateStandardDegression(save,stats.e_value); + } + else + { + stats.standardDegression=options.sd; + } + + return 0; +} + +int devide(candidates &input, candidates &result, modifier &options, statisticals &stats) // sucht nach insertions und deletions +{ + std::cout << "devide\t" << stats.e_value << "\t" << stats.standardDegression << std::endl; + for (unsigned i=0;i(stats.e_value+(options.y * stats.standardDegression))) << (input[i].len<(stats.e_value-(options.x * stats.standardDegression))) << std::endl; + bool second = (input[i].len>(stats.e_value+(options.y * stats.standardDegression))); + bool first = (input[i].len<(stats.e_value-(options.x * stats.standardDegression))); + if(first) + { + std::cout << "d" << std::endl; + + //result.push_back(input[i]); + //result[i].type=candidate::deletion; + } + if(second) + { + std::cout << "i" << std::endl; + //result.push_back(input[i]); + //result[i].type=candidate::insertion; + } + } + std::cout << "devie_end" <> &input,candidates &ref, char *out) +{ + std::cout << "out" << std::endl; + std::fstream outFile(out, std::ios::out); + + if (!outFile) + { + std::cerr << "-ERROR- Could not open output file" << std::endl; + return 1; + } + else + { + outFile << "ID\tPOS\tLEN\tBegin\tEND\tTYPE " << std::endl; + if(!input.empty()) + { + for (unsigned i=0;i maxBegin){maxBegin=ref[*j].pos;} + if((ref[*j].pos+ref[*j].len) < minEnd||minEnd==0){minEnd=(ref[*j].pos+ref[*j].len);} + } + } + if(n!=0) + { + targetSize /= n; + + outFile << ref[0].ref << "\t" << (maxBegin+minEnd)/2<< "\t" << targetSize << "\t" << maxBegin << "\t" << minEnd << "\t" << (candidate::form)ref[0].type << std::endl; + } + } + } + } + + outFile.close(); + + return 0; +} + +int findCluster(candidates &input, std::vector > &dest, candidate::form indel) +{ + std::cout << "findCluster" << std::endl; + std::vector currentCluster; + unsigned currentClusterEndPos; + + // Iterieren über alle Funde + for(unsigned i = 0; i < input.size(); ++i) + { + // Insertionen bzw. Deletionen herausfiltern + if(input[i].type == indel) + { + if(currentCluster.empty()) + { + // ersten Fund zu bisher leerem ersten Cluster hinzufügen + currentCluster.push_back(i); + currentClusterEndPos = input[i].pos + input[i].len - 1; + } + + else + { + // Fall 1: Fund liegt innerhalb der Grenzen eines vorherigen Fundes + if(input[i].pos + input[i].len - 1 <= currentClusterEndPos){ + currentCluster.push_back(i); + } + + else + { + unsigned overlapLen = std::max((int)(currentClusterEndPos - input[i].pos + 1), 0); + + // Fall 2: Fund überlappt ausreichend mit dem Cluster + if(overlapLen / std::min(currentClusterEndPos - input[currentCluster.back()].pos + 1, input[i].pos + input[i].len - 1) > 0.5){ + currentCluster.push_back(i); + } + // Fall 3: Fund überlappt nicht ausreichend mit dem Cluster + else + { + dest.push_back(currentCluster); + currentCluster.clear(); + currentCluster.push_back(i); + } + + currentClusterEndPos = input[i].pos + input[i].len - 1; + } + + } + } + } + + dest.push_back(currentCluster); + + return 0; +} + diff --git a/code/train/C++/0003837_poj1852.cc b/code/train/C++/0003837_poj1852.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab08e984ce0cb6966d622f5d3f4bdda11a14f963 --- /dev/null +++ b/code/train/C++/0003837_poj1852.cc @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int inf=0x7fffffff; +int main() +{ + +#ifdef DEBUG +// freopen("in", "r", stdin); +// freopen("out", "w", stdout); +#endif + int KT; + scanf("%d",&KT); + while(KT--) + { + int n,num; + scanf("%d%d",&n,&num); + int best=0; + int worst=0; + int x; + while(num--) + { + scanf("%d",&x); + best=max(best,min(n-x,x)); + worst=max(worst,max(n-x,x)); + } + printf("%d %d\n",best + ,worst); + } + + + //insert code + return 0; +} diff --git a/code/train/C++/0004781_heapSort.cpp b/code/train/C++/0004781_heapSort.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50c3e6f13ee67903945cb57a4fb39c0effcec78d --- /dev/null +++ b/code/train/C++/0004781_heapSort.cpp @@ -0,0 +1,136 @@ +/* + Algorithm : Heap Sort + Refer : CLRS Chapter on heap sort + Author : manojpandey +*/ + +#include +#include +#include +#include // pair +#include +#include +#include +#include //memset +using namespace std; + +typedef vector vi; +typedef vector vvi; +typedef pair ii; +typedef long long ll; +#define sz(a) int((a).size()) +#define pb push_back +#define all(c) (c).begin(),(c).end() +#define present(c,x) ((c).find(x) != (c).end()) +#define cpresent(c,x) (find(all(c),x) != (c).end()) +#define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++) +#define rep(i,n) for (i=0; i a[i]) + largest = l; + else largest = i; + if(r <= heapSize && a[r] > a[largest]) + largest = r; + if(largest != i) { + swap(a[i], a[largest]); + maxHeapify(a, largest); + } +} + +void buildMaxHeap(int a[]) { + for (int i = N/2 ; i >0 ; i--) + maxHeapify(a, i); +} + +void HeapSort(int a[]) { + buildMaxHeap(a); + for (int i = N ; i > 1 ; i--) { + swap(a[1], a[i]); + heapSize--; + maxHeapify(a, 1); + } +} + +int main() { + + freopen ("in.txt", "r", stdin); + int i; + cin >> N; + heapSize = N; + rep1(i, N) cin >> a[i]; + cout << "INPUT:\n"; + cout << a[1] << "\n"; + PRINT(a,1); + + HeapSort(a); + cout << "OUTPUT:\n"; + cout << a[1] << "\n"; + PRINT(a,1); + return 0; +} + +/* + +10 +4 1 3 2 16 9 10 14 8 7 + + +INPUT: +4 + |1 + | |2 + | | |14 + | | |8 + | |16 + | | |7 + | | |0 + |3 + | |9 + | |10 +OUTPUT: +1 + |2 + | |4 + | | |10 + | | |14 + | |7 + | | |16 + | | |0 + |3 + | |8 + | |9 + + +*/ diff --git a/code/train/C++/0004813_276A.cpp b/code/train/C++/0004813_276A.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a53a23c2da232ebe350c5cb8bf0c5ef7cebe2f13 --- /dev/null +++ b/code/train/C++/0004813_276A.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define ll long long + +using namespace std; + +struct aa { + int x, y; + bool operator < (const aa &b) {return x < b.x;} +}; + +bool cmp(int a, int b) {return a > b;} +int bsearch(int *a, int n, int k); + +int main() { + ll n, k, m = LLONG_MIN; + cin >> n >> k; + for (int i=0;i> f >> t; + if (t > k) m = max(m, f - (t - k)); + else m = max(m, f); + } + cout << m; + return 0; +} + +int bsearch(int *a, int n, int k) { + int l = 0, h = n; + while (l < h) { + int m = (l + h) / 2; + if (a[m] == k) return m; + else if (a[m] > k) h = m; + else l = m + 1; + } + return l; +} diff --git a/code/train/C++/0005979_WorldRunnable.cpp b/code/train/C++/0005979_WorldRunnable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..321e1aa6bffc901c9c1b48b942ab19cf32f35e7c --- /dev/null +++ b/code/train/C++/0005979_WorldRunnable.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2005-2010 MaNGOS + * Copyright (C) 2009-2010 MaNGOSZero + * + * 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 + */ + +/** \file + \ingroup mangosd +*/ + +#include "WorldSocketMgr.h" +#include "Common.h" +#include "World.h" +#include "WorldRunnable.h" +#include "Timer.h" +#include "ObjectAccessor.h" +#include "MapManager.h" +#include "BattleGroundMgr.h" + +#include "Database/DatabaseEnv.h" + +#ifdef WIN32 +#define WORLD_SLEEP_CONST 50 +#else +#define WORLD_SLEEP_CONST 100 //Is this still needed?? [On linux some time ago not working 50ms] +#endif + +#ifdef WIN32 +#include "ServiceWin32.h" +extern int m_ServiceStatus; +#endif + +/// Heartbeat for the World +void WorldRunnable::run() +{ + ///- Init new SQL thread for the world database + WorldDatabase.ThreadStart(); // let thread do safe mySQL requests (one connection call enough) + sWorld.InitResultQueue(); + + uint32 realCurrTime = 0; + uint32 realPrevTime = getMSTime(); + + uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST + + ///- While we have not World::m_stopEvent, update the world + while (!World::IsStopped()) + { + ++World::m_worldLoopCounter; + realCurrTime = getMSTime(); + + uint32 diff = getMSTimeDiff(realPrevTime,realCurrTime); + + sWorld.Update( diff ); + realPrevTime = realCurrTime; + + // diff (D0) include time of previous sleep (d0) + tick time (t0) + // we want that next d1 + t1 == WORLD_SLEEP_CONST + // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement + // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0 + if (diff <= WORLD_SLEEP_CONST+prevSleepTime) + { + prevSleepTime = WORLD_SLEEP_CONST+prevSleepTime-diff; + ACE_Based::Thread::Sleep(prevSleepTime); + } + else + prevSleepTime = 0; + + #ifdef WIN32 + if (m_ServiceStatus == 0) World::StopNow(SHUTDOWN_EXIT_CODE); + while (m_ServiceStatus == 2) Sleep(1000); + #endif + } + + sWorld.KickAll(); // save and kick all players + sWorld.UpdateSessions( 1 ); // real players unload required UpdateSessions call + + // unload battleground templates before different singletons destroyed + sBattleGroundMgr.DeleteAllBattleGrounds(); + + sWorldSocketMgr->StopNetwork(); + + sMapMgr.UnloadAll(); // unload all grids (including locked in memory) + + ///- End the database thread + WorldDatabase.ThreadEnd(); // free mySQL thread resources +} diff --git a/code/train/C++/0006023_SpecificPartialLoudnessGM.cpp b/code/train/C++/0006023_SpecificPartialLoudnessGM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0959efad81dde55debb0c609fb542c6f325b660e --- /dev/null +++ b/code/train/C++/0006023_SpecificPartialLoudnessGM.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2014 Dominic Ward + * + * This file is part of Loudness + * + * Loudness is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Loudness 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 Loudness. If not, see . + */ + +#include "SpecificPartialLoudnessGM.h" +#include "../Support/AuditoryTools.h" + +namespace loudness{ + + SpecificPartialLoudnessGM::SpecificPartialLoudnessGM(bool ansiS3407) : + Module("SpecificPartialLoudnessGM"), + ansiS3407_(ansiS3407) + {} + + SpecificPartialLoudnessGM::~SpecificPartialLoudnessGM() {} + + bool SpecificPartialLoudnessGM::initializeInternal(const TrackBank &input) + { + if (input.getNTracks() % 2 != 0) + { + LOUDNESS_ERROR(name_ << ": TrackBank must have an even number of tracks"); + } + //c value from ANSI 2007 + cParam_ = 0.046871; + c2Param_ = 0.0000459608; // C_2 = C / (1.04 x 10^6)^0.5 + + Real eThrqdB500Hz = IntExc(500); + + //Number of filters below 500Hz + nFiltersLT500_ = 0; + + //fill loudness parameter vectors + Real fcPrev = input.getCentreFreq(0); + for(int i=0; i 1e10) + { + if (eSig >= eThrqParam_[freq]) // equation 19 from Glasberg and Moore 1997 + { + pl = c2Param_ * pow(eSig + eNoise, 0.5) + - c2Param_ * (pow((1 + k_[freq]) * eNoise + eThrqParam_[freq], 0.5) + - pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq]) + + pow(aParam_[freq], alphaParam_[freq])) + * pow(eThrqParam_[freq] / eSig, 0.3); + } + else // equation 20 from Glasberg and Moore 1997 + { + pl = cParam_ + * pow(2 * eSig / (eSig + eThrqParam_[freq]), 1.5) + * ((pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq]) + - pow(aParam_[freq], alphaParam_[freq])) + / (pow(eNoise * (1 + k_[freq]) + eThrqParam_[freq], 0.5) - pow(eNoise, 0.5))) + * (pow(eSig + eNoise, 0.5) - pow(eNoise, 0.5)); + } + } + else // eSig + eNoise <= 1e10 + { + if (eSig >= eThrn) // // equation 17 from Glasberg and Moore 1997 + { + pl = cParam_ * (pow((eSig + eNoise) * gParam_[freq] + aParam_[freq], alphaParam_[freq]) + - pow(aParam_[freq], alphaParam_[freq])) + - cParam_ + * (pow((eNoise * (1 + k_[freq]) + eThrqParam_[freq]) * gParam_[freq] + aParam_[freq], alphaParam_[freq]) + - pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq])) + * pow(eThrn / eSig, 0.3); + } + else // equation 18 from Glasberg and Moore 1997 + { + pl = cParam_ + * pow(2 * eSig / (eSig + eThrqParam_[freq]), 1.5) + * ((pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq]) + - pow(aParam_[freq], alphaParam_[freq])) + / (pow(eNoise * (1 + k_[freq]) + eThrqParam_[freq], 0.5) - pow(eNoise, 0.5))); + } + } + + // set partial loudness at output channel 1 + output_.setSample(target, freq, 1, pl); + //plSum += pl; + + // loudness calculation (the isolated target signal) + //high level + if (eSig > 1e10) + { + if(ansiS3407_) + sl = pow((eSig/1.0707),0.2); + else + sl = pow((eSig/1.04e6),0.5); + } + else if(freqeThrqParam_[freq]) //medium level + { + sl = (pow(gParam_[freq]*eSig+aParam_[freq], alphaParam_[freq])- + pow(aParam_[freq],alphaParam_[freq])); + } + else //low level + { + sl = pow((2*eSig)/(eSig+eThrqParam_[freq]), 1.5)* + (pow(gParam_[freq]*eSig+aParam_[freq],alphaParam_[freq]) + -pow(aParam_[freq],alphaParam_[freq])); + } + } + else //high freqs (variables are constant >= 500 Hz) + { + if(eSig>2.3604782331805771) //medium level + { + sl = pow(eSig+4.72096, 0.2)-1.3639739128330546; + } + else //low level + { + sl = pow((2*eSig)/(eSig+2.3604782331805771), 1.5)* + (pow(eSig+4.72096, 0.2)-1.3639739128330546); + } + } + + // set loudness at output channel 0 + output_.setSample(target, freq, 0, cParam_*sl); + //slSum += sl; + } + //output_.setSample(0, 0, 0, cParam_*slSum); + //output_.setSample(0, 0, 1, plSum); + } + } + + void SpecificPartialLoudnessGM::resetInternal(){}; +} + + + diff --git a/code/train/C++/0006349_XScaleBar.cpp b/code/train/C++/0006349_XScaleBar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed57279c657638874d2aad4742f5e0a9f8099e80 --- /dev/null +++ b/code/train/C++/0006349_XScaleBar.cpp @@ -0,0 +1,165 @@ +/* FTSPlot - fast time series dataset plotter + Copyright (C) 2013 Michael Riss + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ + + +#include +#include "XScaleBar.h" + +#define MAX(a,b) awidth = width; + this->height = height; + glViewport(0, 0, (GLint)width, (GLint)height); + glMatrixMode ( GL_PROJECTION ); + glLoadIdentity (); + gluOrtho2D( 0.0, (double) width, (double) height, 0 ); +} + +void XScaleBar::paintGL() +{ + glClear ( GL_COLOR_BUFFER_BIT ); + + glColor3f ( 0.0, 0.0, 0.0 ); + glLineWidth( 2.0 ); + glBegin ( GL_LINES ); + glVertex2d ( 0, 0 ); + glVertex2d ( width, 0 ); + glEnd(); + glLineWidth( 1.0 ); + + // Draw tick marks + long double XDelta = Xscale * (double) width; + long double XMax = Xcursor + XDelta; + qtlabelbuffer = " " + QString::number( XMax, 'f', 0 ); + int labelWidth = fm->width( qtlabelbuffer ); + long double powerDueToLabel = ceill( log10l( XDelta / ( (long double) width / labelWidth ))) - 1; + long double power = MAX( 0, ceill( log10l( XDelta / ( (long double)width / (long double)qtminDeltaticks ) ) ) ); + power = MAX( power, powerDueToLabel ); + long double XStart = powl( 10, power ) * ceill( Xcursor / powl(10, power) ); + long double XEnd = powl( 10, power ) * floorl( screen2data(width) / powl(10, power) ); + + glBegin ( GL_LINES ); + for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power) ) + { + glVertex2d( data2screen(idx), 0 ); + glVertex2d( data2screen(idx), 5 ); + } + + XStart = powl( 10, power+1 ) * ceill( Xcursor / powl(10, power+1) ) - powl(10, power+1)/2.0 ; + if ( XStart < Xcursor ) + { + XStart += powl(10, power+1); + } + XEnd = powl( 10, power+1 ) * floorl( screen2data(width) / powl(10, power+1) ); + glBegin ( GL_LINES ); + for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) ) + { + glVertex2d( data2screen(idx), 0 ); + glVertex2d( data2screen(idx), 8 ); + } + + XStart = powl( 10, power+1 ) * ceill( Xcursor / powl(10, power+1) ); + XEnd = powl( 10, power+1 ) * floorl( screen2data(width) / powl(10, power+1) ); + for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) ) + { + glVertex2d( data2screen(idx), 0 ); + glVertex2d( data2screen(idx), 10 ); + } + + glEnd(); + + + for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) ) + { + qtlabelbuffer = QString::number( idx, 'f', 0 ); + renderText( data2screen(idx) - fm->width( qtlabelbuffer ) / 2, 20, qtlabelbuffer, fixedFont ); + } + + glFlush(); +} + +void XScaleBar::updateCoords( long double Xcursor, double Xscale ) +{ + this->Xcursor = Xcursor; + this->Xscale = Xscale; + this->makeCurrent(); + update(); +} + +long double XScaleBar::screen2data( int screenCoord) +{ + return Xcursor + (long double) screenCoord * (long double) Xscale; +} + +int XScaleBar::data2screen( long double dataCoord ) +{ + return (int) ( ( (long double) dataCoord - Xcursor) / (long double) Xscale ); +} + +void XScaleBar::setNewXmin(long double Xmin) +{ + this->Xmin = Xmin; +} + +void XScaleBar::setNewXmax( long double Xmax ) +{ + this->Xmax = Xmax; + + // Cached Calculations + stringstream buffer; + buffer << Xmax; + + QString label; + label = QString::number( Xmax, 'f', 0 ); + int qtlabelwidth = fm->width(label); + qtminDeltaticks = MAX( 3, ceill( qtlabelwidth / 10.0 ) ); + + update(); +} + +// kate: indent-mode cstyle; space-indent on; indent-width 0; diff --git a/code/train/C++/0006416_TestStanfordCPPLib.cpp b/code/train/C++/0006416_TestStanfordCPPLib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44595a6b0970d494b514427c2975b003ca26b837 --- /dev/null +++ b/code/train/C++/0006416_TestStanfordCPPLib.cpp @@ -0,0 +1,121 @@ +/* + * File: TestStanfordCPPLib.cpp + * ---------------------------- + * This file tests the C++ library packages used at Stanford. + */ + +/*************************************************************************/ +/* Stanford Portable Library */ +/* Copyright (c) 2014 by Eric Roberts */ +/* */ +/* This program is free software: you can redistribute it and/or modify */ +/* it under the terms of the GNU General Public License as published by */ +/* the Free Software Foundation, either version 3 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ +/* GNU General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program. If not, see . */ +/*************************************************************************/ + +#include +#include +#include "console.h" // JL +#include "strlib.h" +#include "unittest.h" + +using namespace std; + +void testFilelibLibrary(); +void testRandomLibrary(); +void testSimpioLibrary(); +void testStrlibLibrary(); +void testDirectionType(); +void testGraphClass(); +void testGridClass(); +void testHashMapClass(); +void testHashSetClass(); +void testLexiconClass(); +void testMapClass(); +void testPriorityQueueClass(); +void testQueueClass(); +void testSetClass(); +void testStackClass(); +void testTokenScannerClass(); +void testVectorClass(); +void testForeachStatement(); + +/* + * Type: TestEntry + * --------------- + * This structure associates a key with a test function. + */ + +struct TestEntry { + string name; + void (*fn)(); +}; + +const TestEntry TESTS[] = { + { "fileliblibrary", testFilelibLibrary }, + { "randomlibrary", testRandomLibrary }, + { "simpiolibrary", testSimpioLibrary }, + { "strliblibrary", testStrlibLibrary }, + { "directiontype", testDirectionType }, + { "graphclass", testGraphClass }, + { "gridclass", testGridClass }, + { "hashmapclass", testHashMapClass }, + { "hashsetclass", testHashSetClass }, + { "lexiconclass", testLexiconClass }, + { "mapclass", testMapClass }, + { "priorityqueueclass", testPriorityQueueClass }, + { "queueclass", testQueueClass }, + { "setclass", testSetClass }, + { "stackclass", testStackClass }, + { "tokenscannerclass", testTokenScannerClass }, + { "vectorclass", testVectorClass }, + { "foreachstatement", testForeachStatement } +}; +const int N_TESTS = sizeof TESTS / sizeof TESTS[0]; + +int findTest(string key) { + int index = -1; + key = toLowerCase(key); + for (int i = 0; i < N_TESTS; i++) { + if (startsWith(TESTS[i].name, key)) { + if (index != -1) return -1; + index = i; + } + } + return index; +} + +int main() { + setConsolePrintExceptions(true); // JL + int argc = getArgumentCount(); + char **argv = getArguments(); + int base = 1; + if (argc > 1 && startsWith("-verbose", argv[base])) { + setVerboseTestingFlag(true); + base++; + } + if (base == argc) { + for (int i = 0; i < N_TESTS; i++) { + TESTS[i].fn(); + } + } else { + for (int i = base; i < argc; i++) { + int index = findTest(argv[i]); + if (index == -1) { + cout << "Unrecognized test: " << argv[i] << endl; + } else { + TESTS[index].fn(); + } + } + } + return 0; +} diff --git a/code/train/C++/0006687_instprofile.cpp b/code/train/C++/0006687_instprofile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b4ec2710cea451716c8e3b55586a10dcd10e3b3 --- /dev/null +++ b/code/train/C++/0006687_instprofile.cpp @@ -0,0 +1,247 @@ +/************************************************************************** + *Copyright (C) 2003-2006 Intel Corporation + * + *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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +// +// Author: Srilatha Manne +// + +#include "asim/provides/inst_stats.h" + +// +// PERINST_ENTRY +// + +/************************** + * Constructor + **************************/ + + +PERINST_ENTRY_CLASS::PERINST_ENTRY_CLASS(const char* des_str, UINT64 a) : + addr(a), + commHist(LAST_COUNTER), + noncommHist(LAST_COUNTER) +{ + + strncpy (des, des_str, 99); + + // + // Initialize row names. We will register the stats at the end because + // that's the only time we'll have a ASIM_REGISTRY object with which to + // register the stats. + commHist.RowNames(PERINST_COUNTER_STRING); + noncommHist.RowNames(PERINST_COUNTER_STRING); +} + +/************************** + * Stats Registration + **************************/ + +void +PERINST_ENTRY_CLASS::RegisterEntry(ASIM_REGISTRY reg) +{ + // Register stats + // Convert the address to a string. + ostringstream os1, os2; + if (ENABLE_INST_PROFILE == 2) + { + os1 << "Committed_" << hex << addr; + os2 << "NonCommitted_" << hex << addr; + } + else if (ENABLE_INST_PROFILE == 1 || ENABLE_INST_PROFILE == 0) + { + os1 << "Committed_" << des; + os2 << "NonCommitted_" << des; + } + else + { + ASSERTX("Unknown instruction profile type."); + } + +// cout << "Address: " << os.str() << endl; + + reg->RegisterState(&commHist, os1.str().c_str(), des); + reg->RegisterState(&noncommHist, os2.str().c_str(), des); + + // Update the histogram with the correct data. + for (UINT32 i = 0; i < LAST_COUNTER; i++) + { + commHist.AddEvent(i, 0, commInst.Get((PERINST_COUNTER)i)); + noncommHist.AddEvent(i, 0, noncommInst.Get((PERINST_COUNTER)i)); + } +} + +// +// PERINST_PAGE +// + +/************************** + * Destructor + **************************/ +PERINST_PAGE_CLASS::~PERINST_PAGE_CLASS() +{ +/* + for (UINT32 i = 0; i < ENTRIES_PER_PAGE; i++) + { + if (page[i] != NULL) + { + delete page[i]; + } + } +*/ +} + + +/************************** + * Update information for an instruction. + **************************/ + +void +PERINST_PAGE_CLASS::UpdateInst(const UINT64 addr, + const char *inst_name, + const PERINST_STATS_CLASS &ifs, + bool commit) +{ + UINT64 offset = addr - pageAddr; + +// cout << "Updating instruction, Addr: " << addr << ", offset: " << offset << endl; + + ASSERTX(offset < ENTRIES_PER_PAGE); + if (page[offset] == NULL) + { + // + // Null pointer, which means first time inst is seen. + page[offset] = new PERINST_ENTRY_CLASS(inst_name, addr); + UINT32 n = numInst++; + if (n > MAX_NUM_INSTS) + { + VERIFY(false, "Exceeding maximum number of static inst: 100000\n"); + } + } + // + // Update + ASSERTX(page[offset]->GetAddr() == addr); + + page[offset]->UpdateInst(ifs, commit); +} + +/************************** + * Register stats for a page + **************************/ +// +// Register a page of stats. +void +PERINST_PAGE_CLASS::RegisterPage(ASIM_REGISTRY reg) +{ + for (UINT32 i = 0; i < ENTRIES_PER_PAGE; i++) + { + if (page[i] != NULL) + { +// cout << "Registering page" << endl; + page[i]->RegisterEntry(reg); + } + } +} + + + +// +// PERINST_CACHE +// + +/************************** + * Destructor + **************************/ + +PERINST_CACHE_CLASS::~PERINST_CACHE_CLASS() +{ + STAT_CACHE::iterator i = statCache.begin(); + STAT_CACHE::iterator prev; + + while (i != statCache.end()) + { + delete (*i).second; + prev = i; + ++i; + statCache.erase(prev); + } +} + +/************************** + * Update stats + **************************/ + +void +PERINST_CACHE_CLASS::UpdateStats(UINT64 addr, + const char* name, + const PERINST_STATS_CLASS& ifs, + bool commit) +{ + + PERINST_PAGE page; + + // + // Update per-inst stats. + // + if (lastPage && + (addr & (~((1 << LOG2_ENTRIES_PER_PAGE) - 1)))==lastPage->PageAddr()) + { +// cout << "Using lastpage" << endl; + page = lastPage; + } + else + { + STAT_CACHE::iterator i = statCache.find((addr >> LOG2_ENTRIES_PER_PAGE)); + if (i != statCache.end()) { + page = (*i).second; + lastPage = page; +// cout << "Finding page in stat cache" << endl; + } + else + { + // + // Page doesn't currently exist. + // + UINT64 page_addr = addr & (~((1 << LOG2_ENTRIES_PER_PAGE) - 1)); + page = new PERINST_PAGE_CLASS(page_addr); +// cout << "Creating new page" << endl; + // + // Place new page into cache + // + statCache[(addr >> LOG2_ENTRIES_PER_PAGE)] = page; + lastPage = page; + } + } + // Update stats per address + page->UpdateInst(addr, name, ifs, commit); +} + +/************************** + * Register stats + **************************/ +void +PERINST_CACHE_CLASS::RegisterPerinstStats(ASIM_REGISTRY reg) +{ + STAT_CACHE::iterator i = statCache.begin(); + while (i != statCache.end()) + { +// cout << "Registering page: " << i << endl; + (*i).second->RegisterPage(reg); + ++i; + } +} + diff --git a/code/train/C++/0006795_testscore.ex3.cpp b/code/train/C++/0006795_testscore.ex3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaac5934f22c6caf60176012753edfb8bc822bb0 --- /dev/null +++ b/code/train/C++/0006795_testscore.ex3.cpp @@ -0,0 +1,137 @@ +// This program will read in a group of test scores (positive integers +// from 1 to 100) from the keyboard and then calculates and outputs +// the average score as well as the highest and lowest score. +// There will be a maximum of 100 scores. +// +// ** This version is designed to take file input from 'gradfile.txt' +// instead of from stdin ** +// +// Walter B. Vaughan + +#include +#include +#include // for limits +using namespace std; + +typedef int GradeType[100]; // declares a new data type: + // an integer array of 100 elements + +float findAverage( const GradeType, int ); // finds average of all grades +int findHighest( const GradeType, int ); // finds highest of all grades +int findLowest( const GradeType, int ); // finds lowest of all grades + +int main() { + GradeType grades; // the array holding the grades. + int numberOfGrades; // the number of grades read. + int pos; // index to the array. + + float avgOfGrades; // contains the average of the grades. + int highestGrade; // contains the highest grade. + int lowestGrade; // contains the lowest grade. + + ifstream f ("gradfile.txt"); + + // Read in the values into the array + pos = 0; + while ( pos < 100 and f.good() ) { + f >> grades[pos]; + pos++; + } + pos--; // truncate the size to ignore end of array (-99 or bounds error) + + if ( pos == -1 ) { + std::cerr << "**Error Opening 'gradfile.txt'**"; + return 1; // error value returned + } + + numberOfGrades = pos; // Fill blank with appropriate identifier + + // call to the function to find average + avgOfGrades = findAverage( grades, numberOfGrades ); + + cout << endl << "The average of all the grades is " << avgOfGrades << endl; + + // Fill in the call to the function that calculates highest grade + highestGrade = findHighest( grades, numberOfGrades ); + + cout << endl << "The highest grade is " << highestGrade << endl; + + // Fill in the call to the function that calculates lowest grade + lowestGrade = findLowest( grades, numberOfGrades ); + + // Fill in code to write the lowest to the screen + cout << endl << "The lowest grade is " << lowestGrade << endl; + + return 0; +} + + +//****************************************************************************** +// findAverage +// +// task: This function receives an array of integers and its size. +// It finds and returns the average of the numbers in the array +// data in: array of floating point numbers +// data returned: avarage of the numbers in the array +// +//****************************************************************************** +float findAverage( const GradeType array, int size ) { + float sum = 0; // holds the sum of all the numbers + + for (int pos = 0; pos < size; pos++) + sum = sum + array[pos]; + + return (sum / size); //returns the average +} + + +//****************************************************************************** +// findHighest +// +// task: This function receives an array of integers and its size. +// It finds and returns the highest value of the numbers in +// the array +// data in: array of floating point numbers +// data returned: highest value of the numbers in the array +// +//****************************************************************************** +int findHighest( const GradeType array, int size ) { + // Fill in the code for this function + int max = std::numeric_limits::min(); // start with lowest int + + if ( size == 0 ) { + std::cerr << "Note: Empty grade list given, INT_MIN returned"; + } + + for ( int i = 0 ; i < size ; i++ ) + if ( array[i] > max) + max = array[i]; + + return max; +} + + +//****************************************************************************** +// findLowest +// +// task: This function receives an array of integers and its size. +// It finds and returns the lowest value of the numbers in +// the array +// data in: array of floating point numbers +// data returned: lowest value of the numbers in the array +// +//****************************************************************************** +int findLowest( const GradeType array, int size ) { + // Fill in the code for this function + int min = std::numeric_limits::max(); // start with largest int + + if ( size == 0 ) { + std::cerr << "Note: Empty grade list given, INT_MAX returned"; + } + + for ( int i = 0 ; i < size ; i++ ) + if ( array[i] < min) + min = array[i]; + + return min; +} diff --git a/code/train/C++/0006861_sqldb.cpp b/code/train/C++/0006861_sqldb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..597a999cf5de7c12114103e3fa953d6633fd6e6b --- /dev/null +++ b/code/train/C++/0006861_sqldb.cpp @@ -0,0 +1,338 @@ +//////////////////////////////////////////////////////////////////////////// +// SQL Database MMF Extension +// (c) 2004-2005, Jim St. Jean +// +// SQL DB wrapper utilities source file +// +// The file provides wrapper routines to the MMF extension so, for +// example, the underlying SQLite implementation can be swapped or changed +// to be encrypted etc. +// +//////////////////////////////////////////////////////////////////////////// + + +// Database engine wrapper +#include "sqldb.h" +#include "common.h" + +//////////////////////////////////////////////////////////////////////////////// +// Prototypes for SQLite functions not included in SQLite DLL, but copied below +// from SQLite encode.c +//////////////////////////////////////////////////////////////////////////////// +int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out); +int sqlite3_decode_binary(const unsigned char *in, unsigned char *out); + + +/* +** A function to open a new sqlite database. +** +*/ +sqldb *sqldb_open(const char *filename, char **errmsg) +{ + sqldb *db; + if (SQLITE_OK != sqlite3_open(filename, &db)) { + // get error message + strcpy(*errmsg,sqlite3_errmsg(db)); + } + return db; +} + +/* +** A function to close the database. +** +*/ +void sqldb_close(sqldb *db) +{ + sqlite3_close(db); +} + +/* +** The following routine +** returns the integer key of the most recent insert in the database. +*/ +int sqldb_last_insert_rowid(sqldb *db) +{ + return sqlite3_last_insert_rowid(db); +} + +/* +** This function returns the number of database rows that were changed +** (or inserted or deleted) by the most recent called sqlite_exec(). +** +*/ +int sqldb_changes(sqldb *db) +{ + return sqlite3_changes(db); +} + +/* +** This next routine is really just a wrapper around sqlite_exec(). +** Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from malloc(), then returns all of the result after the +** query has finished. +** +*/ +int sqldb_get_table( + sqldb* db, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +) +{ + return sqlite3_get_table( + db, /* An open database */ + sql, /* SQL to be executed */ + resultp, /* Result written to a char *[] that this points to */ + nrow, /* Number of result rows written here */ + ncolumn, /* Number of result columns written here */ + errmsg /* Error msg written here */ + ); +} + +/* +** Call this routine to free the memory that sqlite_get_table() allocated. +*/ +void sqldb_free_table(char **result) +{ + sqlite3_free_table(result); +} + + +/* +** Windows systems should call this routine to free memory that +** is returned in the in the errmsg parameter of sqlite_open() when +** SQLite is a DLL. For some reason, it does not work to call free() +** directly. +** +** As of sqlite3, this is no longer needed! Still provided for backwards compatibility... +*/ +void sqldb_freemem(void *p) +{ + //sqlite_freemem(p); +} + + +/* +** Encode a binary buffer "in" of size n bytes so that it contains +** no instances of characters '\'' or '\000'. The output is +** null-terminated and can be used as a string value in an INSERT +** or UPDATE statement. Use sqlite_decode_binary() to convert the +** string back into its original binary. +** +*/ +int sqldb_encode_binary(const unsigned char *in, int n, unsigned char *out) +{ + return sqlite3_encode_binary(in, n, out); +} + +/* +** Decode the string "in" into binary data and write it into "out". +** This routine reverses the encoding created by sqlite_encode_binary(). +** The output will always be a few bytes less than the input. The number +** of bytes of output is returned. If the input is not a well-formed +** encoding, -1 is returned. +** +*/ +int sqldb_decode_binary(const unsigned char *in, unsigned char *out) +{ + return sqlite3_decode_binary(in, out); +} + +//////////////////////////////////////////////////////////////////////////////// +// SQLite encode.c reproduced here, containing implementation notes and source +// for sqlite3_encode_binary() and sqlite3_decode_binary() +//////////////////////////////////////////////////////////////////////////////// + +/* +** 2002 April 25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains helper routines used to translate binary data into +** a null-terminated string (suitable for use in SQLite) and back again. +** These are convenience routines for use by people who want to store binary +** data in an SQLite database. The code in this file is not used by any other +** part of the SQLite library. +** +** $Id: encode.c,v 1.10 2004/01/14 21:59:23 drh Exp $ +*/ + +/* +** How This Encoder Works +** +** The output is allowed to contain any character except 0x27 (') and +** 0x00. This is accomplished by using an escape character to encode +** 0x27 and 0x00 as a two-byte sequence. The escape character is always +** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The +** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally, +** the escape character itself is encoded as the two-character sequence +** 0x01 0x02. +** +** To summarize, the encoder works by using an escape sequences as follows: +** +** 0x00 -> 0x01 0x01 +** 0x01 -> 0x01 0x02 +** 0x27 -> 0x01 0x03 +** +** If that were all the encoder did, it would work, but in certain cases +** it could double the size of the encoded string. For example, to +** encode a string of 100 0x27 characters would require 100 instances of +** the 0x01 0x03 escape sequence resulting in a 200-character output. +** We would prefer to keep the size of the encoded string smaller than +** this. +** +** To minimize the encoding size, we first add a fixed offset value to each +** byte in the sequence. The addition is modulo 256. (That is to say, if +** the sum of the original character value and the offset exceeds 256, then +** the higher order bits are truncated.) The offset is chosen to minimize +** the number of characters in the string that need to be escaped. For +** example, in the case above where the string was composed of 100 0x27 +** characters, the offset might be 0x01. Each of the 0x27 characters would +** then be converted into an 0x28 character which would not need to be +** escaped at all and so the 100 character input string would be converted +** into just 100 characters of output. Actually 101 characters of output - +** we have to record the offset used as the first byte in the sequence so +** that the string can be decoded. Since the offset value is stored as +** part of the output string and the output string is not allowed to contain +** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27. +** +** Here, then, are the encoding steps: +** +** (1) Choose an offset value and make it the first character of +** output. +** +** (2) Copy each input character into the output buffer, one by +** one, adding the offset value as you copy. +** +** (3) If the value of an input character plus offset is 0x00, replace +** that one character by the two-character sequence 0x01 0x01. +** If the sum is 0x01, replace it with 0x01 0x02. If the sum +** is 0x27, replace it with 0x01 0x03. +** +** (4) Put a 0x00 terminator at the end of the output. +** +** Decoding is obvious: +** +** (5) Copy encoded characters except the first into the decode +** buffer. Set the first encoded character aside for use as +** the offset in step 7 below. +** +** (6) Convert each 0x01 0x01 sequence into a single character 0x00. +** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27. +** +** (7) Subtract the offset value that was the first character of +** the encoded buffer from all characters in the output buffer. +** +** The only tricky part is step (1) - how to compute an offset value to +** minimize the size of the output buffer. This is accomplished by testing +** all offset values and picking the one that results in the fewest number +** of escapes. To do that, we first scan the entire input and count the +** number of occurances of each character value in the input. Suppose +** the number of 0x00 characters is N(0), the number of occurances of 0x01 +** is N(1), and so forth up to the number of occurances of 0xff is N(255). +** An offset of 0 is not allowed so we don't have to test it. The number +** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number +** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth. +** In this way we find the offset that gives the minimum number of escapes, +** and thus minimizes the length of the output string. +*/ + +/* +** Encode a binary buffer "in" of size n bytes so that it contains +** no instances of characters '\'' or '\000'. The output is +** null-terminated and can be used as a string value in an INSERT +** or UPDATE statement. Use sqlite3_decode_binary() to convert the +** string back into its original binary. +** +** The result is written into a preallocated output buffer "out". +** "out" must be able to hold at least 2 +(257*n)/254 bytes. +** In other words, the output will be expanded by as much as 3 +** bytes for every 254 bytes of input plus 2 bytes of fixed overhead. +** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.) +** +** The return value is the number of characters in the encoded +** string, excluding the "\000" terminator. +*/ +int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){ + int i, j, e, m; + int cnt[256]; + if( n<=0 ){ + out[0] = 'x'; + out[1] = 0; + return 1; + } + memset(cnt, 0, sizeof(cnt)); + for(i=n-1; i>=0; i--){ cnt[in[i]]++; } + m = n; + for(i=1; i<256; i++){ + int sum; + if( i=='\'' ) continue; + sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff]; + if( sum &prices) + { + if (prices.size() <= 1) + { + return 0; + } + int result = prices[1] - prices[0]; + int last = result; + for (int i = 2; i < prices.size(); i++) + { + int diff = prices[i] - prices[i - 1]; + last = last > 0 ? last + diff : diff; + result = max(result, last); + } + return result > 0 ? result : 0; + } +}; \ No newline at end of file diff --git a/code/train/C++/0008009_FoxAndDoraemon.cpp b/code/train/C++/0008009_FoxAndDoraemon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5176ae38bdb20599e69c82eba62c4f86676fe33e --- /dev/null +++ b/code/train/C++/0008009_FoxAndDoraemon.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +vector W; +int C; +bool can(int T) { + long long foxes = 1; + int cur = 0; + for (int i=0; i<(int)W.size(); ++i) { + if (foxes==0 || cur+W[i]>T) { + return false; + } + int nsplits = (T-cur-W[i])/C; + while (i+foxes<(int)W.size() && nsplits--) { + foxes <<= 1; + cur += C; + } + assert(cur + W[i] <= T); + --foxes; + } + return true; +} +class FoxAndDoraemon { +public: + int minTime(vector workCost, int splitCost) { + W = workCost; + sort(W.begin(), W.end(), greater()); + C = splitCost; + int lo = 1; + int hi = 2; + while (!can(hi)) { + lo = hi + 1; + hi <<= 1; + } + + while (lo < hi) { + int mid = lo + (hi-lo)/2; + if (can(mid)) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +}; diff --git a/code/train/C++/0008879_IPCWorkerThread.cpp b/code/train/C++/0008879_IPCWorkerThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4660e558531ed8dc69423d71c041dadffb5a32c7 --- /dev/null +++ b/code/train/C++/0008879_IPCWorkerThread.cpp @@ -0,0 +1,119 @@ +/* + * Free RIL implementation for Samsung Android-based smartphones. + * Copyright (C) 2012 Sergey Gridasov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include "IPCWorkerThread.h" +#include "IIPCTransport.h" +#include "IIPCSocket.h" +#include "SocketHandler.h" +#include "Log.h" +#include "IPCSocketHandler.h" + +using namespace SamsungIPC; + +IPCWorkerThread::IPCWorkerThread() { + if(pipe(m_controlPipe) == -1) + Log::panicErrno("pipe"); +} + +IPCWorkerThread::~IPCWorkerThread() { + close(m_controlPipe[0]); + close(m_controlPipe[1]); +} + +int IPCWorkerThread::run() { + dispatchEvents(); + + for(std::list::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) { + delete *it; + } + + return 0; +} + +void IPCWorkerThread::addHandler(SocketHandler *handler) { + m_handlers.push_back(handler); +} + +void IPCWorkerThread::removeHandler(SocketHandler *handler) { + m_handlers.remove(handler); +} + +void IPCWorkerThread::dispatchEvents() { + while(1) { + int maxfd = 0; + fd_set read_set, write_set; + + for(std::list::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) { + SocketHandler *handler = *it; + int fd = handler->fd(); + + maxfd = std::max(maxfd, fd); + + if(handler->wantRead()) + FD_SET(fd, &read_set); + + if(handler->wantWrite()) + FD_SET(fd, &write_set); + } + + FD_SET(m_controlPipe[0], &read_set); + + int ret = select(maxfd + 1, &read_set, &write_set, NULL, NULL); + + if(ret == -1) + Log::panicErrno("select"); + + for(std::list::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) { + SocketHandler *handler = *it; + int fd = handler->fd(); + + if(FD_ISSET(fd, &read_set)) + handler->readable(); + + if(FD_ISSET(fd, &write_set)) + handler->writable(); + } + + if(FD_ISSET(m_controlPipe[0], &read_set)) { + Message *msg; + + int bytes = read(m_controlPipe[0], &msg, sizeof(msg)); + if(bytes == -1) + Log::panicErrno("read(controlPipe)"); + + if(msg == NULL) { + Log::info("Shutdown requested"); + + break; + } else { + static_cast(m_handlers.front())->submit(msg); + } + } + } +} + +void IPCWorkerThread::submit(Message *message) { + int bytes = write(m_controlPipe[1], &message, sizeof(message)); + + if(bytes != sizeof(message)) + Log::panicErrno("write(controlPipe)"); +} + diff --git a/code/train/C++/0009074_cafToggleItemsOnOthersOffFeature.cpp b/code/train/C++/0009074_cafToggleItemsOnOthersOffFeature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c44e94f9e4543a082505d2e238f8f4b63b209b43 --- /dev/null +++ b/code/train/C++/0009074_cafToggleItemsOnOthersOffFeature.cpp @@ -0,0 +1,162 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2019- Ceetron Solutions AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. +// +// See the GNU General Public License at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. +// +// See the GNU Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cafToggleItemsOnOthersOffFeature.h" + +#include "cafToggleItemsFeatureImpl.h" + +#include "cafSelectionManager.h" + +#include "cafPdmObject.h" +#include "cafPdmObjectHandle.h" +#include "cafPdmUiItem.h" +#include + +namespace caf +{ +CAF_CMD_SOURCE_INIT( ToggleItemsOnOthersOffFeature, "cafToggleItemsOnOthersOffFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool ToggleItemsOnOthersOffFeature::isCommandEnabled() +{ + std::vector selectedObjects; + caf::SelectionManager::instance()->objectsByType( &selectedObjects ); + + caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects ); + std::vector children = childObjects( commonParent ); + + return commonParent != nullptr && children.size() > 0 && objectToggleField( children.front() ) && + children.size() > selectedObjects.size(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void ToggleItemsOnOthersOffFeature::onActionTriggered( bool isChecked ) +{ + std::vector selectedObjects; + caf::SelectionManager::instance()->objectsByType( &selectedObjects ); + + // First toggle off all siblings + + caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects ); + + for ( caf::PdmObjectHandle* child : childObjects( commonParent ) ) + { + caf::PdmField* field = objectToggleField( child ); + + if ( field ) + { + field->setValueWithFieldChanged( false ); + } + } + + // Then toggle on the selected item(s) + for ( caf::PdmObject* selectedObject : selectedObjects ) + { + caf::PdmField* field = dynamic_cast*>( selectedObject->objectToggleField() ); + + field->setValueWithFieldChanged( true ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void ToggleItemsOnOthersOffFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "On - Others Off" ); + + actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOnOthersOffL16x16.png" ) ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PdmFieldHandle* + ToggleItemsOnOthersOffFeature::verifySameParentForSelection( const std::vector& selection ) +{ + caf::PdmFieldHandle* sameParent = nullptr; + + for ( caf::PdmObject* obj : selection ) + { + caf::PdmFieldHandle* parent = obj->parentField(); + if ( parent ) + { + if ( !sameParent ) + { + sameParent = parent; + } + else if ( parent != sameParent ) + { + // Different parents detected + + return nullptr; + } + } + } + return sameParent; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector ToggleItemsOnOthersOffFeature::childObjects( caf::PdmFieldHandle* parent ) +{ + std::vector children; + if ( parent ) + { + parent->childObjects( &children ); + } + return children; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PdmField* ToggleItemsOnOthersOffFeature::objectToggleField( caf::PdmObjectHandle* objectHandle ) +{ + caf::PdmUiObjectHandle* childUiObject = uiObj( objectHandle ); + if ( childUiObject && childUiObject->objectToggleField() ) + { + return dynamic_cast*>( childUiObject->objectToggleField() ); + } + return nullptr; +} + +} // namespace caf \ No newline at end of file diff --git a/code/train/C++/0009203_PathTransform.cpp b/code/train/C++/0009203_PathTransform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f7b18fd8b67e217390ec3ac2fbdc4e6ce1b3024 --- /dev/null +++ b/code/train/C++/0009203_PathTransform.cpp @@ -0,0 +1,178 @@ +/* + Copyright (C) 2011 Róbert Vašek + + This file is part of fsync. + + fsync is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + fsync 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 fsync. If not, see . +*/ + +#include +#include +#include +#include "PathTransform.h" +#include "LogManager.h" +#include "defs.h" + +using namespace std; +using namespace boost::filesystem; + +path PathTransform::getPath(PathId id) +{ + for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++) + { + if (i->first == id) + { + if (id >= 0) + return i->second; + else + { + path parentPath = getPath(id * -1); + parentPath /= i->second; + + return parentPath; + } + } + } + + return path(); +} + +PathId PathTransform::getPathId(const path & p) +{ + for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++) + { + if (i->second == p) + return i->first; + } + + return 0; +} + +bool PathTransform::checkPathAndLog(const path & p, PathId pathId) +{ + if (strlen(p.c_str()) == 0) + { + string errMsg = "Path with id "; + errMsg += boost::lexical_cast(pathId); + errMsg += " is not defined, skipping"; + LogManager::getInstancePtr()->log(errMsg, LogManager::L_WARNING); + + return false; + } + + return true; +} + +void PathTransform::cutPath(PathId pathId, const char * pth, char * outPath) +{ + path p = getPath(pathId); + strcpy(outPath, (pth + strlen(p.c_str()) + 1)); // +1 because of the directory separator +} + +path PathTransform::glueCutPath(PathId pathId, const char * p) +{ + return getPath(pathId) / p; +} + +PathList PathTransform::getIncludingPaths() +{ + PathList pl; + + for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++) + { + if (i->first >= 0) + pl.push_back(i->second); + } + + return pl; +} + +PathList PathTransform::getExcludingPaths() +{ + PathList pl; + + for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++) + { + PathId id = i->first; + + if (id < 0) + { + path parentPath = getPath(id * -1); + parentPath /= i->second; + + pl.push_back(parentPath); + } + } + + return pl; +} + +bool PathTransform::isExcluded(const path & currentPath, PathId pathId) +{ + vector absoluteExcldPaths; + path parentPath = getPath(pathId); + PathId excldPathId = pathId * -1; + + for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++) + { + if (i->first == excldPathId) + absoluteExcldPaths.push_back(parentPath / i->second); + } + + if (absoluteExcldPaths.empty()) + return false; + + vector currentPathParts = makeParts(currentPath); + int currentPartsSize = currentPathParts.size(); + + for (vector::const_iterator i = absoluteExcldPaths.begin(); i != absoluteExcldPaths.end(); i++) + { + vector absoluteExcldParts = makeParts(*i); + int excldPartsSize = absoluteExcldParts.size(); + + if (currentPartsSize < excldPartsSize) + continue; + + bool isExcluded = true; + + for (int j = 0; j < excldPartsSize; j++) + { + if (currentPathParts[j] != absoluteExcldParts[j]) + { + isExcluded = false; + break; + } + } + + if (isExcluded) + return true; + } + + return false; +} + +vector PathTransform::makeParts(const path & p) const +{ + vector parts; + + for (path::const_iterator i = p.begin(); i != p.end(); i++) + parts.push_back(i->string()); + + return parts; +} + +path PathTransform::operator[](PathId id) +{ + return getPath(id); +} diff --git a/code/train/C++/0009912_zonedessin.cpp b/code/train/C++/0009912_zonedessin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13777021e045ce6aea95402cf9cb6f03fda85b77 --- /dev/null +++ b/code/train/C++/0009912_zonedessin.cpp @@ -0,0 +1,125 @@ +#include "zonedessin.h" + +zoneDessin::zoneDessin(QRect geometry, QWidget *parent):QWidget(parent) +{ + setGeometry(geometry); + setStyleSheet("background-color: white;"); +} + +void zoneDessin::spectre() +{ + donnees.clear(); + valMax=0; + //int hz=info.retourFrequenceI(); + QFile file(info.retourChemin()); + tailleFichier=file.size()-44; + if(file.open(QFile::ReadOnly)){ + QByteArray data=file.readAll(); + QDataStream analyse(&data,QIODevice::ReadOnly); + + //Passer les metadonnées + if(info.retourExtension()=="wav"){ + analyse.setByteOrder(QDataStream::LittleEndian); + char meta[44]; + analyse.readRawData(meta,44); + } + + if(info.retourExtension()=="aif" || info.retourExtension()=="aiff"){ + analyse.setByteOrder(QDataStream::BigEndian); + char meta[28]; + analyse.readRawData(meta,28); + } + + //int saut=(tailleFichier/width())+info.retourEchantillonageI(); + int saut=info.retourEchantillonageI(); + //char SData[16]; + char sautDonnees[saut]; + qint16 don; + int x=0; + while(!analyse.atEnd()){ + //analyse.readRawData(SData,16); + //donnees[x]=QString::fromLatin1(SData).toInt(); + analyse>>don; + donnees<valMax) + valMax=donnees[x]; + analyse.readRawData(sautDonnees,saut); + x++; + } + /*for(int x=0;x<10000;x++) + donnees.removeLast();*/ + + //Mise à l'échelle + valMax-=10; + for(int x=0;xdrawPrimitive(QStyle::PE_Widget, &opt, &p, this); + + //Créer le painter + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(pen); + pen.setWidth(2); + painter.drawLine(0,height()/2,width(),height()/2); + pen.setWidth(1); + pen.setColor(Qt::black); + //Vidage de la liste + for(int x=0;xhigh) + high=courbe[x]; + if(courbe[x]accept(); +} diff --git a/code/train/C++/0009915_sp-switch.cpp b/code/train/C++/0009915_sp-switch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2dcde15d2ec8e0d6afc0f934ec45f8ad80371aa --- /dev/null +++ b/code/train/C++/0009915_sp-switch.cpp @@ -0,0 +1,159 @@ +/* + * SVG implementation + * + * Authors: + * Andrius R. + * MenTaLguY + * Jon A. Cruz + * Abhishek Sharma + * + * Copyright (C) 2006 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include + +#include "sp-switch.h" +#include "display/drawing-group.h" +#include "conditions.h" + +#include +#include + +SPSwitch::SPSwitch() : SPGroup() { + this->_cached_item = 0; +} + +SPSwitch::~SPSwitch() { + _releaseLastItem(_cached_item); +} + +SPObject *SPSwitch::_evaluateFirst() { + SPObject *first = 0; + + for (SPObject *child = this->firstChild() ; child && !first ; child = child->getNext() ) { + if (SP_IS_ITEM(child) && sp_item_evaluate(SP_ITEM(child))) { + first = child; + } + } + + return first; +} + +std::vector SPSwitch::_childList(bool add_ref, SPObject::Action action) { + if ( action != SPObject::ActionGeneral ) { + return this->childList(add_ref, action); + } + + SPObject *child = _evaluateFirst(); + std::vector x; + if (NULL == child) + return x; + + if (add_ref) { + //g_object_ref (G_OBJECT (child)); + sp_object_ref(child); + } + x.push_back(child); + return x; +} + +const char *SPSwitch::displayName() const { + return _("Conditional Group"); +} + +gchar *SPSwitch::description() const { + gint len = this->getItemCount(); + return g_strdup_printf( + ngettext(_("of %d object"), _("of %d objects"), len), len); +} + +void SPSwitch::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) { + SPGroup::child_added(child, ref); + + this->_reevaluate(true); +} + +void SPSwitch::remove_child(Inkscape::XML::Node *child) { + SPGroup::remove_child(child); + + this->_reevaluate(); +} + +void SPSwitch::order_changed (Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) +{ + SPGroup::order_changed(child, old_ref, new_ref); + + this->_reevaluate(); +} + +void SPSwitch::_reevaluate(bool /*add_to_drawing*/) { + SPObject *evaluated_child = _evaluateFirst(); + if (!evaluated_child || _cached_item == evaluated_child) { + return; + } + + _releaseLastItem(_cached_item); + + std::vector item_list = _childList(false, SPObject::ActionShow); + for ( std::vector::const_reverse_iterator iter=item_list.rbegin();iter!=item_list.rend();++iter) { + SPObject *o = *iter; + if ( !SP_IS_ITEM (o) ) { + continue; + } + + SPItem * child = SP_ITEM(o); + child->setEvaluated(o == evaluated_child); + } + + _cached_item = evaluated_child; + _release_connection = evaluated_child->connectRelease(sigc::bind(sigc::ptr_fun(&SPSwitch::_releaseItem), this)); + + this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); +} + +void SPSwitch::_releaseItem(SPObject *obj, SPSwitch *selection) +{ + selection->_releaseLastItem(obj); +} + +void SPSwitch::_releaseLastItem(SPObject *obj) +{ + if (NULL == this->_cached_item || this->_cached_item != obj) + return; + + this->_release_connection.disconnect(); + this->_cached_item = NULL; +} + +void SPSwitch::_showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) { + SPObject *evaluated_child = this->_evaluateFirst(); + + std::vector l = this->_childList(false, SPObject::ActionShow); + + for ( std::vector::const_reverse_iterator iter=l.rbegin();iter!=l.rend();++iter) { + SPObject *o = *iter; + + if (SP_IS_ITEM (o)) { + SPItem * child = SP_ITEM(o); + child->setEvaluated(o == evaluated_child); + Inkscape::DrawingItem *ac = child->invoke_show (drawing, key, flags); + + if (ac) { + ai->appendChild(ac); + } + } + } +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/code/train/C++/0010000_track.cpp b/code/train/C++/0010000_track.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31b945f001d381a32c74f561a49267fd6e089a2d --- /dev/null +++ b/code/train/C++/0010000_track.cpp @@ -0,0 +1,93 @@ +#include "map/track.hpp" + +#include "map/bookmark_helpers.hpp" +#include "map/user_mark_id_storage.hpp" + +#include "geometry/distance_on_sphere.hpp" +#include "geometry/mercator.hpp" + +#include + +Track::Track(kml::TrackData && data) + : Base(data.m_id == kml::kInvalidTrackId ? UserMarkIdStorage::Instance().GetNextTrackId() : data.m_id) + , m_data(std::move(data)) + , m_groupID(0) +{ + m_data.m_id = GetId(); + ASSERT_GREATER(m_data.m_points.size(), 1, ()); +} + +std::string Track::GetName() const +{ + return GetPreferredBookmarkStr(m_data.m_name); +} + +m2::RectD Track::GetLimitRect() const +{ + m2::RectD rect; + for (auto const & point : m_data.m_points) + rect.Add(point); + return rect; +} + +double Track::GetLengthMeters() const +{ + double res = 0.0; + + auto it = m_data.m_points.begin(); + double lat1 = MercatorBounds::YToLat(it->y); + double lon1 = MercatorBounds::XToLon(it->x); + for (++it; it != m_data.m_points.end(); ++it) + { + double const lat2 = MercatorBounds::YToLat(it->y); + double const lon2 = MercatorBounds::XToLon(it->x); + res += ms::DistanceOnEarth(lat1, lon1, lat2, lon2); + lat1 = lat2; + lon1 = lon2; + } + + return res; +} + +df::DepthLayer Track::GetDepthLayer() const +{ + return df::DepthLayer::UserLineLayer; +} + +size_t Track::GetLayerCount() const +{ + return m_data.m_layers.size(); +} + +dp::Color Track::GetColor(size_t layerIndex) const +{ + CHECK_LESS(layerIndex, m_data.m_layers.size(), ()); + return dp::Color(m_data.m_layers[layerIndex].m_color.m_rgba); +} + +float Track::GetWidth(size_t layerIndex) const +{ + CHECK_LESS(layerIndex, m_data.m_layers.size(), ()); + return static_cast(m_data.m_layers[layerIndex].m_lineWidth); +} + +float Track::GetDepth(size_t layerIndex) const +{ + return layerIndex * 10; +} + +std::vector const & Track::GetPoints() const +{ + return m_data.m_points; +} + +void Track::Attach(kml::MarkGroupId groupId) +{ + ASSERT(!m_groupID, ()); + m_groupID = groupId; +} + +void Track::Detach() +{ + m_groupID = 0; +} diff --git a/code/train/C++/0010267_sgmm-acc-fmllrbasis-ali.cc b/code/train/C++/0010267_sgmm-acc-fmllrbasis-ali.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c33e47dde2997addc57f8b7ede51a15265db961 --- /dev/null +++ b/code/train/C++/0010267_sgmm-acc-fmllrbasis-ali.cc @@ -0,0 +1,216 @@ +// sgmmbin/sgmm-acc-fmllrbasis-ali.cc + +// Copyright 2009-2011 Saarland University +// Author: Arnab Ghoshal + +// See ../../COPYING for clarification regarding multiple authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABLITY OR NON-INFRINGEMENT. +// See the Apache 2 License for the specific language governing permissions and +// limitations under the License. + +#include + +#include "util/common-utils.h" +#include "hmm/transition-model.h" +#include "sgmm/am-sgmm.h" +#include "sgmm/fmllr-sgmm.h" + +int main(int argc, char *argv[]) { + try { + using namespace kaldi; + const char *usage = + "Accumulate stats for FMLLR bases training.\n" + "Usage: sgmm-acc-fmllrbasis-ali [options] " + " \n" + "e.g.: sgmm-acc-fmllrbasis-ali 1.mdl scp:train.scp ark:1.ali 1.acc\n"; + + ParseOptions po(usage); + bool binary_write = true; + std::string gselect_rspecifier, spkvecs_rspecifier, silphones_str; + BaseFloat sil_weight = 0.0; + kaldi::SgmmGselectConfig sgmm_opts; + po.Register("binary", &binary_write, "Write output in binary mode"); + po.Register("gselect", &gselect_rspecifier, + "Precomputed Gaussian indices (rspecifier)"); + po.Register("spk-vecs", &spkvecs_rspecifier, + "Speaker vectors to use during aligment (rspecifier)"); + po.Register("sil-phone-list", &silphones_str, + "Colon-separated list of phones (to weigh differently)"); + po.Register("sil-weight", &sil_weight, "Weight for \"silence\" phones."); + sgmm_opts.Register(&po); + po.Read(argc, argv); + + if (po.NumArgs() != 5) { + po.PrintUsage(); + exit(1); + } + + std::string model_filename = po.GetArg(1), + feature_rspecifier = po.GetArg(2), + alignments_rspecifier = po.GetArg(3), + spk2utt_rspecifier = po.GetArg(4), + accs_wxfilename = po.GetArg(5); + + typedef kaldi::int32 int32; + + AmSgmm am_sgmm; + TransitionModel trans_model; + SgmmFmllrGlobalParams fmllr_globals; + { + bool binary; + Input ki(model_filename, &binary); + trans_model.Read(ki.Stream(), binary); + am_sgmm.Read(ki.Stream(), binary); + fmllr_globals.Read(ki.Stream(), binary); + } + + SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier); + RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier); + RandomAccessInt32VectorReader alignments_reader(alignments_rspecifier); + + RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier); + + RandomAccessBaseFloatVectorReader spkvecs_reader(spkvecs_rspecifier); + + std::vector silence_phones; + if (!SplitStringToIntegers(silphones_str, ":", false, &silence_phones)) { + KALDI_ERR << "Silence-phones string has wrong format " + << silphones_str; + } + ConstIntegerSet silence_set(silence_phones); // faster lookup. + + + kaldi::SgmmPerFrameDerivedVars per_frame_vars; + SpMatrix fmllr_grad_scatter; + int32 dim = am_sgmm.FeatureDim(); + fmllr_grad_scatter.Resize(dim * (dim + 1), kSetZero); + FmllrSgmmAccs spk_stats; + spk_stats.Init(dim, am_sgmm.NumGauss()); + + double tot_like = 0.0, tot_t = 0.0; + int32 num_done = 0, num_no_alignment = 0, num_other_error = 0; + + for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) { + spk_stats.SetZero(); + string spk = spk2utt_reader.Key(); + const std::vector &uttlist = spk2utt_reader.Value(); + + SgmmPerSpkDerivedVars spk_vars; + if (spkvecs_reader.IsOpen()) { + if (spkvecs_reader.HasKey(spk)) { + spk_vars.v_s = spkvecs_reader.Value(spk); + am_sgmm.ComputePerSpkDerivedVars(&spk_vars); + } else { + KALDI_WARN << "Cannot find speaker vector for " << spk; + num_other_error++; + continue; + } + } // else spk_vars is "empty" + + for (size_t i = 0; i < uttlist.size(); i++) { + std::string utt = uttlist[i]; + if (!alignments_reader.HasKey(utt)) { + num_no_alignment++; + continue; + } + const std::vector &alignment = alignments_reader.Value(utt); + + if (!feature_reader.HasKey(utt)) { + KALDI_WARN << "Did not find features for utterance " << utt; + num_other_error++; + continue; + } + const Matrix &feats = feature_reader.Value(utt); + + if (alignment.size() != feats.NumRows()) { + KALDI_WARN << "Alignments has wrong size "<< (alignment.size()) << + " vs. "<< (feats.NumRows()); + num_other_error++; + continue; + } + + bool have_gselect = false; + if (gselect_reader.IsOpen()) { + if (gselect_reader.HasKey(utt)) { + have_gselect = (gselect_reader.Value(utt).size() == feats.NumRows()); + if (!have_gselect) + KALDI_WARN << "Gaussian-selection info available for utterance " + << utt << " has wrong size."; + } else { + KALDI_WARN << "No Gaussian-selection info available for utterance " + << utt; + } + } + + const std::vector > *gselect = + (have_gselect ? &gselect_reader.Value(utt) : NULL); + double file_like = 0.0, file_t = 0.0; + + + for (size_t i = 0; i < alignment.size(); i++) { + int32 tid = alignment[i]; // transition identifier. + int32 pdf_id = trans_model.TransitionIdToPdf(tid), + phone = trans_model.TransitionIdToPhone(tid); + BaseFloat weight = 1.0; + if (silence_set.count(phone) != 0) { // is a silence. + if (sil_weight > 0.0) + weight = sil_weight; + else + continue; + } + + std::vector this_gselect; + if (gselect != NULL) + this_gselect = (*gselect)[i]; + else + am_sgmm.GaussianSelection(sgmm_opts, feats.Row(i), &this_gselect); + am_sgmm.ComputePerFrameVars(feats.Row(i), this_gselect, spk_vars, 0.0, + &per_frame_vars); + file_like += + spk_stats.Accumulate(am_sgmm, spk_vars, feats.Row(i), + per_frame_vars, pdf_id, weight); + file_t += weight; + } // end looping over all the frames in the utterance + KALDI_VLOG(1) << "Average likelihood for utterance " << utt << " is " + << (file_like/file_t) << " over " << file_t << " frames"; + tot_like += file_like; + tot_t += file_t; + num_done++; + if (num_done % 20 == 0) + KALDI_VLOG(1) << "After " << num_done << " utterances: Average " + << "likelihood per frame = " << (tot_like/tot_t) + << ", over " << tot_t << " frames"; + } // end looping over all utterance for a given speaker + spk_stats.AccumulateForFmllrSubspace(am_sgmm, fmllr_globals, &fmllr_grad_scatter); + } // end looping over all speakers + + KALDI_LOG << "Done " << num_done << " files, " << num_no_alignment + << " with no alignments, " << num_other_error + << " with other errors."; + + KALDI_LOG << "Overall likelihood per frame frame = " << (tot_like/tot_t) + << " over " << tot_t << " frames."; + + { + Output ko(accs_wxfilename, binary_write); + fmllr_grad_scatter.Write(ko.Stream(), binary_write); + KALDI_LOG << "Written accs to: " << accs_wxfilename; + } + return (num_done != 0 ? 0 : 1); + } catch(const std::exception &e) { + std::cerr << e.what(); + return -1; + } +} + + diff --git a/code/train/C++/0010531_CCSequence3D.cpp b/code/train/C++/0010531_CCSequence3D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aecb8efff2e3abcb0dd22d7c602c56e730eeb249 --- /dev/null +++ b/code/train/C++/0010531_CCSequence3D.cpp @@ -0,0 +1,232 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCSequence3D.h" + +NS_CC_BEGIN + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +Sequence3D* Sequence3D::variadicCreate(Animate3D *action1, ...) +{ + va_list params; + va_start(params, action1); + + Sequence3D *ret = Sequence3D::createWithVariableList(action1, params); + + va_end(params); + + return ret; +} +#else +Sequence3D* Sequence3D::create(Animate3D *action1, ...) +{ + va_list params; + va_start(params, action1); + + Sequence3D *ret = Sequence3D::createWithVariableList(action1, params); + + va_end(params); + + return ret; +} +#endif + +Sequence3D* Sequence3D::createWithVariableList(Animate3D *action1, va_list args) +{ + Animate3D *now; + + Vector actions; + if (action1) + actions.pushBack(action1); + + while (action1) + { + now = va_arg(args, Animate3D*); + if (now) + { + actions.pushBack(now); + } + else + break; + } + + return create(actions); +} + +Sequence3D* Sequence3D::create(const Vector& arrayOfActions) +{ + Sequence3D* ret = nullptr; + + ret = new (std::nothrow) Sequence3D(); + if (ret->initWithActions(arrayOfActions)) + { + ret->autorelease(); + return ret; + } + + CC_SAFE_RELEASE(ret); + return ret; +} + +bool Sequence3D::initWithActions(const Vector& arrayOfActions) +{ + if (arrayOfActions.size() == 0) + return false; + + _actions.clear(); + _startTime.clear(); + _endTime.clear(); + + Animate3D* preAction = nullptr; + float duration = 0.f, dur = 0.f; + _startTime.push_back(duration); + for (auto& it : arrayOfActions) { + float d1 = 0.f; + if (preAction) + d1 = preAction->getDuration(); + + float d2 = it->getDuration(); + if (d1 < Animate3D::getTransitionTime() || d2 < Animate3D::getTransitionTime()) + dur = d1 > d2 ? d1 : d2; + else + dur = d1 + d2 - Animate3D::getTransitionTime(); + + preAction = it; + _actions.pushBack(it); + _startTime.push_back(dur); + _endTime.push_back(dur); + duration += dur; + } + _startTime.erase(_startTime.end() - 1); + for (ssize_t i = 0; i < _startTime.size(); i++) { + _startTime[i] /= duration; + _endTime[i] /= duration; + } + setDuration(duration); + _curActionIdx = -1; + return true; +} + +Sequence3D* Sequence3D::clone() const +{ + // no copy constructor + auto seq3d = new (std::nothrow) Sequence3D(); + seq3d->initWithActions(_actions); + seq3d->autorelease(); + return seq3d; +} + +Sequence3D::Sequence3D() +: _curActionIdx(-1) +{ + +} + +Sequence3D::~Sequence3D(void) +{ + _actions.clear(); +} + +void Sequence3D::startWithTarget(Node *target) +{ + ActionInterval::startWithTarget(target); + _curActionIdx = -1; +} + +void Sequence3D::stop(void) +{ + for (auto& action : _actions) { + action->stop(); + } + + ActionInterval::stop(); +} + +Sequence3D* Sequence3D::reverse() const +{ + Vector actions; + for (auto it = _actions.rbegin(); it != _actions.rend(); ++it) { + actions.pushBack(*it); + } + + return create(actions); +} + +void Sequence3D::update(float t) +{ + if (_target) + { + int nextIdx = _curActionIdx + 1; + if (nextIdx < _actions.size()) + { + if (t >= _startTime[nextIdx]) + { + _actions.at(nextIdx)->startWithTarget(_target); + } + } + //update action + int preActionIdx = _curActionIdx - 1; + if (preActionIdx >= 0 && _endTime[preActionIdx] > t) + { + float newt = (t - _startTime[preActionIdx]) / (_endTime[preActionIdx] - _startTime[preActionIdx]); + _actions.at(preActionIdx)->update(newt); + } + if (_curActionIdx >= 0 && _curActionIdx < _actions.size()) + { + float newt = (t - _startTime[_curActionIdx]) / (_endTime[_curActionIdx] - _startTime[_curActionIdx]); + _actions.at(_curActionIdx)->update(newt); + } + } +} + void Sequence3D::step(float t) + { + ActionInterval::step(t) ; + if (_target) + { + float newt=MAX(0, MIN(1, _elapsed /MAX(_duration, FLT_EPSILON))); + int nextIdx = _curActionIdx + 1; + if (nextIdx < _actions.size()) + { + if (newt >= _startTime[nextIdx]) + { + _curActionIdx = nextIdx; + } + } + //update action + int preActionIdx = _curActionIdx - 1; + if (preActionIdx >= 0 && _endTime[preActionIdx] >newt) + { + + _actions.at(preActionIdx)->step(t); + + } + if (_curActionIdx >= 0 && _curActionIdx < _actions.size()) + { + _actions.at(_curActionIdx)->step(t); + + } + } + } + +NS_CC_END diff --git a/code/train/C++/0010760_laser.cpp b/code/train/C++/0010760_laser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6df0e38d46551a768f7c145ed6f6671e87a43d4f --- /dev/null +++ b/code/train/C++/0010760_laser.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +using namespace std; + + +#define MAXN 700 + + +typedef unsigned char uch; +typedef unsigned int u32; + + +// +// Hash Map +// +#define HASHB 4096 +const size_t KeySz = sizeof(int) * 2; +struct HM { + struct Key { + int d[2]; + Key(int *D) { memcpy(d, D, KeySz); } + bool operator==(const Key &x) const { + return memcmp(d, x.d, KeySz) == 0; } + }; + struct KV { + Key k; int v; + KV(const Key &K, int V) : k(K), v(V) {} + }; + typedef vector KVV; KVV b[HASHB]; + u32 fnv_hash(const Key &k, int len) const { + uch *p = reinterpret_cast(const_cast(k.d)); + u32 h = 2166136261U; + for (int i = 0; i < len; ++i) h = (h * 16777619U) ^ p[i]; + return h; + } + int add(const Key &k) { + int i = fnv_hash(k, KeySz) % HASHB; + for (int j = 0, J = b[i].size(); j < J; ++j) + if (b[i][j].k == k) + return ++b[i][j].v; + b[i].push_back(KV(k, 2)); + return 2; + return true; + } +}; + + +template +T gcd(T a, T b) { for (T c = a%b; c != 0; a=b,b=c,c=a%b); return b; } + + +int n; +int pts[MAXN][2]; + + +int solve() +{ + if (n <= 2) return n; + int ans = 0; + + int m[2]; // slope, as a rational number + + for (int i = 0; i < n; ++i) { + HM hm; + + for (int j = i + 1; j < n; ++j) { + if (pts[i][0] == pts[j][0]) + m[0] = m[1] = 0; + else { + m[0] = pts[j][1] - pts[i][1]; + m[1] = pts[j][0] - pts[i][0]; + + int g = gcd(m[0], m[1]); + m[0] /= g; + m[1] /= g; + } + + int coll = hm.add(HM::Key(m)); + if (coll > ans) ans = coll; + } + } + + return ans; +} + +int main() +{ + int T; + scanf("%d", &T); + + int ncase = 0; + while (T--) { + scanf("%d", &n); + + for (int i = 0; i < n; ++i) + scanf("%d%d", &pts[i][0], &pts[i][1]); + + printf("Case %d: %d\n", ++ncase, solve()); + } + + return 0; +} diff --git a/code/train/C++/0011798_chapter04_ex16.cpp b/code/train/C++/0011798_chapter04_ex16.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c91d738a951757589057e752ec605e7c4eed84ad --- /dev/null +++ b/code/train/C++/0011798_chapter04_ex16.cpp @@ -0,0 +1,60 @@ +// Chapter 04, exercise 16: find the mode in a vector of integers entered by +// user (only the first, not all of them) + +#include "../lib_files/std_lib_facilities.h" + +int get_mode(vector v) +{ + sort(v.begin(),v.end()); + int mode_cdt = v[0]; + int mode_cdt_ctr = 1; + int mode = 0; + int mode_ctr = 1; + for (int i = 1; imode_ctr) { + mode = mode_cdt; + mode_ctr = mode_cdt_ctr; + } + } + else { + mode_cdt = v[i]; + mode_cdt_ctr = 1; + } + } + cout << "Top value appears " << mode_ctr << " times.\n"; + return mode; +} + +int main() +{ + int n = 0; + int smallest = 0; + int largest = 0; + int mode = 0; + vector vals; + bool is_first = true; + + cout << "Enter sequence of integers:\n"; + + while (cin >> n) { + if (n < smallest || is_first) + smallest = n; + if (n > largest || is_first) + largest = n; + vals.push_back(n); + is_first = false; + } + + mode = get_mode(vals); + cout << "smallest value: " << smallest << endl; + cout << "largest value: " << largest << endl; + cout << "mode: " << mode << endl; + + sort(vals.begin(),vals.end()); + cout << "values:" << endl; + for (int i = 0; i +#include + +int EditDistance(const StringPiece& s1, + const StringPiece& s2, + bool allow_replacements, + int max_edit_distance) { + // The algorithm implemented below is the "classic" + // dynamic-programming algorithm for computing the Levenshtein + // distance, which is described here: + // + // http://en.wikipedia.org/wiki/Levenshtein_distance + // + // Although the algorithm is typically described using an m x n + // array, only two rows are used at a time, so this implementation + // just keeps two separate vectors for those two rows. + int m = s1.len_; + int n = s2.len_; + + vector previous(n + 1); + vector current(n + 1); + + for (int i = 0; i <= n; ++i) + previous[i] = i; + + for (int y = 1; y <= m; ++y) { + current[0] = y; + int best_this_row = current[0]; + + for (int x = 1; x <= n; ++x) { + if (allow_replacements) { + current[x] = min(previous[x-1] + (s1.str_[y-1] == s2.str_[x-1] ? 0 : 1), + min(current[x-1], previous[x])+1); + } + else { + if (s1.str_[y-1] == s2.str_[x-1]) + current[x] = previous[x-1]; + else + current[x] = min(current[x-1], previous[x]) + 1; + } + best_this_row = min(best_this_row, current[x]); + } + + if (max_edit_distance && best_this_row > max_edit_distance) + return max_edit_distance + 1; + + current.swap(previous); + } + + return previous[n]; +} diff --git a/code/train/C++/0024658_MaxPID.cpp b/code/train/C++/0024658_MaxPID.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7631ba99540deaa997e65952aebca9d11211e41e --- /dev/null +++ b/code/train/C++/0024658_MaxPID.cpp @@ -0,0 +1,61 @@ +/* + Copyright (C) 2012,2013 + Max Planck Institute for Polymer Research + Copyright (C) 2008,2009,2010,2011 + Max-Planck-Institute for Polymer Research & Fraunhofer SCAI + + This file is part of ESPResSo++. + + ESPResSo++ is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ESPResSo++ is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "python.hpp" +#include "MaxPID.hpp" +#include "storage/DomainDecomposition.hpp" +#include "iterator/CellListIterator.hpp" + +using namespace espressopp; +using namespace iterator; + +namespace espressopp { + namespace analysis { + real MaxPID::compute() const { + + long myMaxPID, systemMaxPID; + System& system = getSystemRef(); + CellList realCells = system.storage->getRealCells(); + + myMaxPID = 0; + for (CellListIterator cit(realCells); !cit.isDone(); ++cit) { + long pid = cit->id(); + if (pid > myMaxPID) { + myMaxPID = pid; + } + } + + // it was reduce + boost::mpi::all_reduce(*getSystem()->comm, myMaxPID, systemMaxPID, mpi::maximum()); + + return 1.0*systemMaxPID; + + } + + void MaxPID::registerPython() { + using namespace espressopp::python; + class_ > + ("analysis_MaxPID", init< shared_ptr< System > >()) + ; + } + } +} diff --git a/code/train/C++/0024892_ft_send.cpp b/code/train/C++/0024892_ft_send.cpp new file mode 100644 index 0000000000000000000000000000000000000000..679d388eb333f55ae83454ef6399585c26bb72c8 --- /dev/null +++ b/code/train/C++/0024892_ft_send.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2004-2016 by Jakob Schröter + * This file is part of the gloox library. http://camaya.net/gloox + * + * This software is distributed under a license. The full license + * agreement can be found in the file LICENSE in this distribution. + * This software may not be copied, modified, sold or distributed + * other than expressed in the named license agreement. + * + * This software is distributed without any warranty. + */ + +#include "../client.h" +#include "../connectionlistener.h" +#include "../stanza.h" +#include "../gloox.h" +#include "../disco.h" +#include "../loghandler.h" +#include "../logsink.h" +#include "../siprofileft.h" +#include "../siprofilefthandler.h" +#include "../bytestreamdatahandler.h" +#include "../socks5bytestreamserver.h" +using namespace gloox; + +#include +#include +#include +#include +#include +#include +#include + +#include // [s]print[f] + +#if defined( WIN32 ) || defined( _WIN32 ) +# include +#endif + +/** + * Usage: + * ft_send jid@server/full /path/to/file + * + * Sends the given file to the given full JID. + */ +class FTTest : public LogHandler, ConnectionListener, SIProfileFTHandler, BytestreamDataHandler +{ + public: + FTTest( const JID& to, const std::string& file ) : m_bs( 0 ), m_to( to ), m_file( file ), m_quit( false ) {} + + virtual ~FTTest() {} + + void start() + { + + struct stat f_stat; + if( stat( m_file.c_str(), &f_stat ) ) + return; + + m_size = f_stat.st_size; + std::ifstream ifile( m_file.c_str(), std::ios_base::in | std::ios_base::binary ); + if( !ifile ) + return; + + JID jid( "hurkhurk@example.net/glooxsendfile" ); + j = new Client( jid, "hurkhurks" ); + j->registerConnectionListener( this ); + j->disco()->setVersion( "ftsend", GLOOX_VERSION, "Linux" ); + j->disco()->setIdentity( "client", "bot" ); + StringList ca; + ca.push_back( "/path/to/cacert.crt" ); + j->setCACerts( ca ); + + j->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this ); + + + m_server = new SOCKS5BytestreamServer( j->logInstance(), 6666 ); + printf( "about to listen\n" ); + ConnectionError le = ConnNoError; + if( ( le = m_server->listen() ) != ConnNoError ) + printf( "listen returned: %d\n", le ); + printf( "listening\n" ); + + f = new SIProfileFT( j, this ); + f->registerSOCKS5BytestreamServer( m_server ); + f->addStreamHost( j->jid(), "192.168.100.20", 6666 ); + // you should obtain this using disco, really: +// f->addStreamHost( JID( "reflector.amessage.eu" ), "reflector.amessage.eu", 6565 ); +// f->addStreamHost( JID( "proxy.jabber.org" ), "208.245.212.98", 7777 ); + + if( j->connect( false ) ) + { + char input[200024]; + ConnectionError ce = ConnNoError; + ConnectionError se = ConnNoError; + while( ce == ConnNoError ) + { + if( m_quit ) + j->disconnect(); + + ce = j->recv( 1 ); + if( m_server ) + { + se = m_server->recv( 1 ); + if( se != ConnNoError ) + { + printf( "SOCKS5BytestreamServer returned: %d\n", se ); + delete m_server; + m_server = 0; + m_quit = true; + } + } + if( m_bs && !ifile.eof() ) + { + if( m_bs->isOpen() ) + { + ifile.read( input, 200024 ); + std::string t( input, ifile.gcount() ); + if( !m_bs->send( t ) ) + m_quit = true; + } + m_bs->recv( 1 ); + } + else if( m_bs ) + m_bs->close(); + } + printf( "ce: %d\n", ce ); + } + + f->dispose( m_bs ); + delete f; + delete m_server; + delete j; + } + + virtual void onConnect() + { + printf( "connected!!!\n" ); + f->requestFT( m_to, m_file, m_size ); + } + + virtual void onDisconnect( ConnectionError e ) + { + printf( "ft_send: disconnected: %d\n", e ); + if( e == ConnAuthenticationFailed ) + printf( "auth failed. reason: %d\n", j->authError() ); + } + + virtual bool onTLSConnect( const CertInfo& info ) + { + time_t from( info.date_from ); + time_t to( info.date_to ); + + printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n" + "from: %s\nto: %s\n", + info.status, info.issuer.c_str(), info.server.c_str(), + info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(), + info.compression.c_str(), ctime( &from ), ctime( &to ) ); + return true; + } + + virtual void handleLog( LogLevel level, LogArea area, const std::string& message ) + { + printf("log: level: %d, area: %d, %s\n", level, area, message.c_str() ); + } + + virtual void handleFTRequest( const JID& from, const JID& /*to*/, const std::string& sid, + const std::string& name, long size, const std::string& hash, + const std::string& date, const std::string& mimetype, + const std::string& desc, int /*stypes*/ ) + { + printf( "received ft request from %s: %s (%ld bytes, sid: %s). hash: %s, date: %s, mime-type: %s\n" + "desc: %s\n", + from.full().c_str(), name.c_str(), size, sid.c_str(), hash.c_str(), date.c_str(), + mimetype.c_str(), desc.c_str() ); + f->acceptFT( from, sid, SIProfileFT::FTTypeS5B ); + } + +// virtual void handleFTRequestResult( const JID& /*from*/, const std::string& /*sid*/ ) +// { +// } + + virtual void handleFTRequestError( const IQ& /*iq*/, const std::string& /*sid*/ ) + { + printf( "ft request error\n" ); + m_quit = true; + } + + virtual void handleFTBytestream( Bytestream* bs ) + { + printf( "received bytestream of type: %s", bs->type() == Bytestream::S5B ? "s5b" : "ibb" ); + m_bs = bs; + m_bs->registerBytestreamDataHandler( this ); + if( m_bs->connect() ) + { + if( bs->type() == Bytestream::S5B ) + printf( "ok! s5b connected to streamhost\n" ); + else + printf( "ok! ibb sent request to remote entity\n" ); + } + } + + virtual const std::string handleOOBRequestResult( const JID& /*from*/, const JID& /*to*/, const std::string& /*sid*/ ) + { + return std::string(); + }; + + virtual void handleBytestreamData( Bytestream* /*bs*/, const std::string& data ) + { + printf( "received %d bytes of data:\n%s\n", data.length(), data.c_str() ); + } + + virtual void handleBytestreamError( Bytestream* /*bs*/, const IQ& /*iq*/ ) + { + printf( "bytestream error\n" ); + } + + virtual void handleBytestreamOpen( Bytestream* /*bs*/ ) + { + printf( "bytestream opened\n" ); + } + + virtual void handleBytestreamClose( Bytestream* /*bs*/ ) + { + printf( "bytestream closed\n" ); + m_quit = true; + } + + private: + Client *j; + SIProfileFT* f; + Bytestream* m_bs; + SOCKS5BytestreamServer* m_server; + JID m_to; + std::string m_file; + bool m_quit; + int m_size; +}; + +int main( int argc, char** argv ) +{ + if( argc == 3 ) + { + JID j( argv[1] ); + if( j.resource().empty() ) + { + printf( "error: need full jid\n" ); + return 1; + } + FTTest *r = new FTTest( j, argv[2] ); + r->start(); + delete( r ); + } + else + { + printf( "error: need jid + file\n" ); + } + return 0; +} diff --git a/code/train/C++/0025348_sweeperdaemon.cpp b/code/train/C++/0025348_sweeperdaemon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1943d94266baf642f662055cfb830c988aaf7000 --- /dev/null +++ b/code/train/C++/0025348_sweeperdaemon.cpp @@ -0,0 +1,274 @@ +/* + * STaRS, Scalable Task Routing approach to distributed Scheduling + * Copyright (C) 2012 Javier Celaya + * + * This file is part of STaRS. + * + * STaRS is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * STaRS 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 STaRS; if not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +using namespace boost; +namespace fs = boost::filesystem; + + +unsigned long int getAvailableMemory() { + unsigned long int free; + unsigned long int total; + string dummy; + ifstream file("/proc/meminfo"); + file >> dummy >> total; + file.ignore(1000, '\n'); + file >> dummy >> free; + return (free - total / 10) >> 10; // Approx 90% of total memory +} + + +class Simulations { +public: + static Simulations & getInstance() { + static Simulations s; + return s; + } + + void parseCmdLine(int argc, char * argv[]); + int run(int argc, char * argv[]); + void stop(); + void getNewCases(); + void waitProcesses(); + + pid_t spawnProcess(const map & properties); + unsigned long int getMemoryLimit(const map & properties) const { + unsigned long int mem = 0; + auto it = properties.find("max_mem"); + if (it != properties.end()) + istringstream(it->second) >> mem; + return mem; + } + void reschedule(); + +private: + list > caseInstances; + bool end, waitOnPipe; + unsigned int numProcesses; + unsigned long int availableMemory; + list > processes; + string simExec, pipeName; + thread pipeThread, waitThread; + mutex m; ///< Mutex to put and get queue messages. + condition newCasesOrProcesses; ///< Barrier to wait for a message + condition children; ///< Barrier to wait for children + + Simulations() : end(false), waitOnPipe(false), numProcesses(1), availableMemory(getAvailableMemory()), pipeName("sweeperpipe") {} +}; + + +void getPropertiesList(const string & fileName, std::list > & combinations); + + +void finish(int param) { + Simulations::getInstance().stop(); +} + + +int main(int argc, char * argv[]) { + return Simulations::getInstance().run(argc, argv); +} + + +void Simulations::parseCmdLine(int argc, char * argv[]) { + for (int i = 1; i < argc; i++) { + if (argv[i] == string("-f") && ++i < argc) + pipeName = argv[i]; + else if (argv[i] == string("-e") && ++i < argc) + simExec = argv[i]; + else if (argv[i] == string("-p") && ++i < argc) + istringstream(argv[i]) >> numProcesses; + else if (argv[i] == string("-m") && ++i < argc) + istringstream(argv[i]) >> availableMemory; + } +} + + +void Simulations::getNewCases() { + while (true) { + list > newInstances; + getPropertiesList(pipeName, newInstances); + this_thread::interruption_point(); + if (newInstances.empty()) continue; + cout << "Adding " << newInstances.size() << " more cases." << endl; + { + mutex::scoped_lock lock(m); + caseInstances.splice(caseInstances.end(), newInstances); + } + newCasesOrProcesses.notify_all(); + } +} + + +void Simulations::waitProcesses() { + while (true) { + { + mutex::scoped_lock lock(m); + if (processes.empty()) { + if (end) + return; + children.wait(lock); + if (end) + return; + } + } + pid_t pid = wait(NULL); + if (pid != -1) { + cout << "Process " << pid << " ended." << endl; + { + mutex::scoped_lock lock(m); + for (auto it = processes.begin(); it != processes.end(); ++it) { + if (it->first == pid) { + availableMemory += it->second; + processes.erase(it); + break; + } + } + } + newCasesOrProcesses.notify_all(); + } + } +} + + +int Simulations::run(int argc, char * argv[]) { + signal(SIGTERM, finish); + signal(SIGINT, finish); + + parseCmdLine(argc, argv); + if (simExec == "") { + cerr << "Usage: " << argv[0] << " -e sim_program [-f pipe_name] [-p num_processes] [-m max_memory]" << endl; + return 1; + } + cout << "Using " << numProcesses << " processors and " << availableMemory << " megabytes of memory." << endl; + + if (fs::exists(pipeName) && fs::is_regular_file(pipeName)) { + cout << "Reading configuration from " << pipeName << endl; + getPropertiesList(pipeName, caseInstances); + waitOnPipe = false; + } else { + mknod(pipeName.c_str(), S_IFIFO | 0600, 0); + cout << "Listening on " << pipeName << endl; + pipeThread = thread(bind(&Simulations::getNewCases, this)); + waitOnPipe = true; + } + + waitThread = thread(bind(&Simulations::waitProcesses, this)); + + do { + mutex::scoped_lock lock(m); + reschedule(); + if (!waitOnPipe && caseInstances.empty()) { + end = true; + } else { + if (processes.empty() && waitOnPipe) { + cout << "Waiting for tests..." << endl; + } + newCasesOrProcesses.wait(lock); + } + } while (!end); + + pipeThread.join(); + waitThread.join(); + return 0; +} + + +void Simulations::reschedule() { + // Schedule as many cases as possible until memory is full + auto instance = caseInstances.begin(); + while (processes.size() < numProcesses && instance != caseInstances.end()) { + // Try to launch this case + unsigned long int mem = getMemoryLimit(*instance); + if (mem <= availableMemory) { + pid_t pid = spawnProcess(*instance); + availableMemory -= mem; + processes.push_back(make_pair(pid, mem)); + children.notify_all(); + instance = caseInstances.erase(instance); + } + else { + if (processes.empty()) { + cout << "Unable to run simulation, not enough memory." << endl; + instance = caseInstances.erase(instance); + } else ++instance; + } + } +} + + +pid_t Simulations::spawnProcess(const map & properties) { + // Redirect stdio + int fd[2]; + pipe(fd); + pid_t pid; + if ((pid = fork())) { + // Close read end + close(fd[0]); + // Feed configuration through write end + ostringstream oss; + for (auto & i : properties) { + oss << i.first << "=" << i.second << endl; + } + write(fd[1], oss.str().c_str(), oss.tellp()); + close(fd[1]); + return pid; + } else { + // Close write end + close(fd[1]); + // Set read end as standard input + dup2(fd[0], 0); + execl(simExec.c_str(), simExec.c_str(), "-", NULL); + // This function only returns on error + cout << "Error running simulation." << endl; + close(fd[0]); + exit(1); + } +} + + +void Simulations::stop() { + end = true; + pipeThread.interrupt(); + //waitThread.interrupt(); + cout << "Stopping current processes." << endl; + for (list >::iterator it = processes.begin(); it != processes.end(); it++) + kill(it->first, SIGTERM); + children.notify_all(); + // Signal end of file in the pipe + ofstream(pipeName.c_str(), ios::out | ios::app).close(); + newCasesOrProcesses.notify_all(); +} diff --git a/code/train/C++/0025395_part-tld-test.cc b/code/train/C++/0025395_part-tld-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9f81e194b4ff62b6bef8256b94814ed01edea0fc --- /dev/null +++ b/code/train/C++/0025395_part-tld-test.cc @@ -0,0 +1,64 @@ +#include +#include + +#include "common/Arguments.hpp" +#include "core/Sequence.hpp" +#include "parttld/PartTLD.hpp" + +int main(int argc, char** args) { + Arguments arguments = Arguments(argc, args); + + string key = arguments.getString("sequence"); + int limit = arguments.getIntOrDefault("limit", NO_LIMIT); + + printf("Going to run for %s\n", key.c_str()); + Sequence sequence = Sequence(key, 0, limit); + Frame* firstFrame = sequence.next(); + Box* initBox = sequence.initBox; + initBox->isValid = true; + + initBox->x1 -= 1.0; + initBox->y1 -= 1.0; + initBox->x2 -= 1.0; + initBox->y2 -= 1.0; + + PartTLD* tld = new PartTLD(); + + Shape* shape0 = tld->init(firstFrame, initBox); + + Frame* previous = firstFrame; + while (sequence.hasNext()) { + Frame* current = sequence.next(); + printf("Frame(%d) >> Frame(%d)\n", previous->id, current->id); + + Shape* shape1 = tld->track(previous, current, shape0); + + vector currentCorrectedBoxList = shape1->parts; + ImageBuilder* builder = new ImageBuilder(current); + int nrOfModels = (int) currentCorrectedBoxList.size(); + for (int i = 0; i < nrOfModels; i++) { + Box* box = currentCorrectedBoxList[i]; + + if (box != nullptr) { + // string boxString = box->toTLDString(); + builder->withBox(box, Colors::colors[i]); + } else { + printf("Frame(%d) >> Frame(%d) FAILED\n", previous->id, current->id); + } + } + + builder->withCircle(shape1->center, 10); + + builder->display(1); + + shape0 = shape1; + + delete previous; + previous = current; + } + + delete previous; + delete tld; + + return EXIT_SUCCESS; +} diff --git a/code/train/C++/0025424_possibilities.cc b/code/train/C++/0025424_possibilities.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b7ef20298882f7c3fdb7a205ad580b427bab3d2 --- /dev/null +++ b/code/train/C++/0025424_possibilities.cc @@ -0,0 +1,120 @@ +#include "tournament.h" +#include +#include +#include +#include +#include +#include "ez/progress.h" + +struct PossibleScore { + int pickIndex; + int score; + int champ; +} _PossibleScore; + +bool sortScores(const PossibleScore& first, const PossibleScore& second) { + return first.score > second.score; +} + +Tournament::Possibilities::Possibilities(const Tournament::Bracket& b, const Tournament::Scorer& s, int batch, int num_batches) : + bracket_(b), scorer_(s), batch_(batch), number_of_batches_(num_batches), shifts_(NULL) { + reset(); +} + +Tournament::Possibilities::~Possibilities() { + delete shifts_; +} + +void Tournament::Possibilities::reset() { + if (shifts_) { + delete shifts_; + } + games_left_ = bracket_.totalGames() - bracket_.gamesPlayed(); + shifts_ = new std::vector(games_left_ + 1); + uint64_t left = Tournament::flipBits(bracket_.played()); + uint64_t offset = 0ULL; + uint64_t limit = bracket_.numberOfOutcomes(); + if (number_of_batches_ > 1) { + limit = (uint64_t) ((double) limit / number_of_batches_ + 0.5); + offset = limit * batch_; + } + int shift_count = 0; + for (int left_bit = 0; left_bit < bracket_.numberOfTeams(); ++left_bit) { + if (left & (1ULL << left_bit)) { + shifts_->at(shift_count++) = left_bit; + } + } + start_ = bracket_.numberOfOutcomes() - 1ULL - offset; + end_ = batch_ == number_of_batches_ - 1 ? 0ULL : bracket_.numberOfOutcomes() - offset - limit; +} + +std::vector + Tournament::Possibilities::scorePicks(const std::vector& picks, + bool debug) { + uint64_t possibility = start_; + uint64_t played = (1ULL << (bracket_.numberOfTeams() - 1)) - 1; + uint64_t total = start_ - end_ + 1; + if (debug) { + std::cout << "Checking " << total << " outcomes of bracket: " << bracket_ << std::endl; + std::cout << "Number of entries: " << picks.size() << std::endl; + std::cout << "Start: " << start_ << " -> End: " << end_ << std::endl; + std::cout << "Total Outcomes: " << bracket_.numberOfOutcomes() << std::endl; + } + + ez::Progress progress(total); + progress.width = 60; + + std::vector allStats(picks.size()); + std::vector pickScores(picks.size()); + if (debug) { + progress.start(); + } + while (possibility != end_) { + uint64_t real_poss = 0; + for(int i = 0; i < games_left_; ++i) { + real_poss |= (((possibility & (1ULL << i)) ? 1ULL : 0ULL) << shifts_->at(i)); + } + real_poss = bracket_.results() | real_poss; + Tournament::Bracket possible_bracket(bracket_.numberOfTeams(), real_poss, played); + for(int p = 0; p < picks.size(); p++) { + Tournament::Scorer::Score score = scorer_.score(possible_bracket, picks[p]); + pickScores[p].pickIndex = p; + pickScores[p].score = score.score; + pickScores[p].champ = possible_bracket.winner(); + //std::cout << "POSS: " << possibility << ": " << picks[p] << " <-> " << possible_bracket << ": score=" << score.score << " max=" << score.max << std::endl; + } + std::sort(pickScores.begin(), pickScores.end(), sortScores); + int currentScore = pickScores[0].score; + int actualRank = 1; + for(int i = 0; i < picks.size(); ++i) { + PossibleScore& score = pickScores[i]; + Tournament::Stats& stats = allStats[score.pickIndex]; + if (score.score < currentScore) { + actualRank++; + currentScore = score.score; + } + if (score.score > stats.maxScore) { + stats.maxScore = score.score; + } + if (actualRank < stats.maxRank) { + stats.maxRank = actualRank; + } + if (actualRank > stats.minRank) { + stats.minRank = actualRank; + } + if (actualRank == 1) { + stats.champCounts[score.champ]++; + } + } + + if (possibility == end_) { + break; + } + if (debug) { + ++progress; + } + possibility--; + } + if (debug) { std::cout << std::endl << "Done." << std::endl; } + return allStats; +} diff --git a/code/train/C++/0025962_Otsu.cc b/code/train/C++/0025962_Otsu.cc new file mode 100644 index 0000000000000000000000000000000000000000..44e839650a4e716ea293a117c41a52d4ad6b7488 --- /dev/null +++ b/code/train/C++/0025962_Otsu.cc @@ -0,0 +1,78 @@ +/* -*-c++-*- + + This file is part of the IC reverse engineering tool degate. + + Copyright 2013 by Taekgwan Kim + + Degate is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + any later version. + + Degate 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 degate. If not, see . + +*/ + +#include + +using namespace degate; + +Otsu::Otsu() : + otsu_threshold(0) {} + +Otsu::~Otsu() {} + +double Otsu::get_otsu_threshold() { + return otsu_threshold; +} + +void Otsu::run(TileImage_GS_DOUBLE_shptr gray) { + unsigned long histData[256] = {0,}; + + for(unsigned int y = 0; y < gray->get_height(); y++) + for(unsigned int x = 0; x < gray->get_width(); x++) { + gs_byte_pixel_t h = gray->get_pixel_as(x, y); + assert((h >= 0) && (h < 256)); + histData[h]++; + } + + unsigned long total = gray->get_height() * gray->get_width(); + + double sum = 0; + for(int t=0; t < 256; t++) + sum += t * histData[t]; + + double sumB = 0; + unsigned long wB = 0; + unsigned long wF = 0; + + double varMax = 0; + + for(int t=0; t<256; t++) + { + wB += histData[t]; + if(wB == 0) + continue; + + wF = total - wB; + if(wF == 0) + break; + sumB += (double)(t * histData[t]); + + double mB = sumB / wB; + double mF = (sum - sumB) /wF; + double varBetween = (double)wB * (double)wF * (mB-mF) * (mB-mF); + + if(varBetween > varMax) + { + varMax = varBetween; + otsu_threshold = t; + } + } +} diff --git a/code/train/C++/0025967_16.cpp b/code/train/C++/0025967_16.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a39a1999b19e1af4e0a10a0bc4b146fec3ccca7d --- /dev/null +++ b/code/train/C++/0025967_16.cpp @@ -0,0 +1,71 @@ +#include "stdafx.h" +#include +#include +#include +#include +#include +#include +#include +using namespace std; + + +// https://leetcode.com/problems/3sum-closest/ +class Solution { +public: + + int threeSumClosest(vector& nums, int target) { + int result = -1; + int minDiffSoFar = INT32_MAX; + + if (nums.size() < 3) { + return result; + } + else if (nums.size() == 3) { + return (nums[0] + nums[1] + nums[2]); + } + + std::sort(nums.begin(), nums.end()); + + int n = nums.size(); + for (int i = 0; i < n - 2; i++) { + int a = nums[i]; + int start = i + 1; + int end = n - 1; + while (start < end) { + assert(i != start); + assert(i != end); + assert(start != end); + int b = nums[start]; + int c = nums[end]; + int sum = a + b + c; + int diff = sum - target; + int absDiff = abs(diff); + if (absDiff < minDiffSoFar) { + minDiffSoFar = absDiff; + result = sum; + } + + if (diff > 0) { + end--; + } + else if(diff < 0) { + start++; + } + + if (diff == 0) { + return target; + } + } + } + return result; + } +}; + +int _16(int argc, _TCHAR* argv[]) +{ + Solution s; + vector input = { 1,1,1,1 }; + + printf("%d\n", s.threeSumClosest(input, 0)); + return 0; +} \ No newline at end of file diff --git a/code/train/C++/0026485_tst_qscopedvaluerollback.cpp b/code/train/C++/0026485_tst_qscopedvaluerollback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af82897179ff4478067d01f8a900897b37db251c --- /dev/null +++ b/code/train/C++/0026485_tst_qscopedvaluerollback.cpp @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +/*! + \class tst_QScopedValueRollback + \internal + \since 4.8 + \brief Tests class QScopedValueRollback. + + */ +class tst_QScopedValueRollback : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void leavingScope(); + void leavingScopeAfterCommit(); + void rollbackToPreviousCommit(); + void exceptions(); + void earlyExitScope(); +private: + void earlyExitScope_helper(int exitpoint, int &member); +}; + +void tst_QScopedValueRollback::leavingScope() +{ + int i = 0; + bool b = false; + QString s("This is useful"); + + //test rollback on going out of scope + { + QScopedValueRollback ri(i); + QScopedValueRollback rb(b); + QScopedValueRollback rs(s); + QCOMPARE(b, false); + QCOMPARE(i, 0); + QCOMPARE(s, QString("This is useful")); + b = true; + i = 1; + s = "Useless"; + QCOMPARE(b, true); + QCOMPARE(i, 1); + QCOMPARE(s, QString("Useless")); + } + QCOMPARE(b, false); + QCOMPARE(i, 0); + QCOMPARE(s, QString("This is useful")); +} + +void tst_QScopedValueRollback::leavingScopeAfterCommit() +{ + int i = 0; + bool b = false; + QString s("This is useful"); + + //test rollback on going out of scope + { + QScopedValueRollback ri(i); + QScopedValueRollback rb(b); + QScopedValueRollback rs(s); + QCOMPARE(b, false); + QCOMPARE(i, 0); + QCOMPARE(s, QString("This is useful")); + b = true; + i = 1; + s = "Useless"; + QCOMPARE(b, true); + QCOMPARE(i, 1); + QCOMPARE(s, QString("Useless")); + ri.commit(); + rb.commit(); + rs.commit(); + } + QCOMPARE(b, true); + QCOMPARE(i, 1); + QCOMPARE(s, QString("Useless")); +} + +void tst_QScopedValueRollback::rollbackToPreviousCommit() +{ + int i=0; + { + QScopedValueRollback ri(i); + i++; + ri.commit(); + i++; + } + QCOMPARE(i,1); + { + QScopedValueRollback ri1(i); + i++; + ri1.commit(); + i++; + ri1.commit(); + i++; + } + QCOMPARE(i,3); +} + +void tst_QScopedValueRollback::exceptions() +{ + bool b = false; + bool caught = false; + QT_TRY + { + QScopedValueRollback rb(b); + b = true; + QT_THROW(std::bad_alloc()); //if Qt compiled without exceptions this is noop + rb.commit(); //if Qt compiled without exceptions, true is committed + } + QT_CATCH(...) + { + caught = true; + } + QCOMPARE(b, !caught); //expect false if exception was thrown, true otherwise +} + +void tst_QScopedValueRollback::earlyExitScope() +{ + int i=0; + int j=0; + while (true) { + QScopedValueRollback ri(i); + i++; + j=i; + if (i>8) break; + ri.commit(); + } + QCOMPARE(i,8); + QCOMPARE(j,9); + + for (i = 0; i < 5; i++) { + j=1; + earlyExitScope_helper(i,j); + QCOMPARE(j, 1< r(member); + member *= 2; + if (exitpoint == 0) + return; + r.commit(); + member *= 2; + if (exitpoint == 1) + return; + r.commit(); + member *= 2; + if (exitpoint == 2) + return; + r.commit(); + member *= 2; + if (exitpoint == 3) + return; + r.commit(); +} + +QTEST_MAIN(tst_QScopedValueRollback) +#include "tst_qscopedvaluerollback.moc" diff --git a/code/train/C++/0026931_FEEPROM.cpp b/code/train/C++/0026931_FEEPROM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e3ecd33aadf011d52da2d3ca97d6f133a70adb2 --- /dev/null +++ b/code/train/C++/0026931_FEEPROM.cpp @@ -0,0 +1,42 @@ +//all the functions are defined in the header file .cpp file have the constructor the wrapped up class is in the header file + +#include "FEEPROM.h" // access to the definitions of the hmorse header file + +FEEPROM::FEEPROM(word sA, word eA) //constructor when a object of this type is created this constructor is called +{ + startAdd = sA; + endAdd = eA; +} + +void FEEPROM::clearAllFEEPROM(void) //this function clears all the values in the eeprom block +{ + for(word i=0; i<=endAdd; i+=4) + { + EEPROM.put(i,0); + } +} + +void FEEPROM::writeCircularFEEPROM(float f) //this function will write values in a circular buffer way +{ + static word add = startAdd; + EEPROM.put(add,f); + add+=4; + if(add>endAdd) + add=startAdd; +} + +float FEEPROM::readMaxFEEPROM(void) //returns max value of a block +{ + static float maxValue=0.0; + EEPROM.get(startAdd,maxValue); + for(word i=startAdd; i<=endAdd; i+=4) + { + float tmp; + EEPROM.get(i,tmp); + maxValue=max(tmp,maxValue); + } + return maxValue; +} + + + \ No newline at end of file diff --git a/code/train/C++/0027205_main.cpp b/code/train/C++/0027205_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0332d989520c74c553554b38586cfe1983c6ee2 --- /dev/null +++ b/code/train/C++/0027205_main.cpp @@ -0,0 +1,105 @@ +// https://github.com/KubaO/stackoverflown/tree/master/questions/process-fix-binary-crlf-51519654 +#include +#include + +bool appendBinFix(QByteArray &buf, const char *src, int size) { + bool okData = true; + if (!size) return okData; + constexpr char CR = '\x0d'; + constexpr char LF = '\x0a'; + bool hasCR = buf.endsWith(CR); + buf.resize(buf.size() + size); + char *dst = buf.end() - size; + const char *lastSrc = src; + for (const char *const end = src + size; src != end; src++) { + char const c = *src; + if (c == LF) { + if (hasCR) { + std::copy(lastSrc, src, dst); + dst += (src - lastSrc); + dst[-1] = LF; + lastSrc = src + 1; + } else + okData = false; + } + hasCR = (c == CR); + } + dst = std::copy(lastSrc, src, dst); + buf.resize(dst - buf.constData()); + return okData; +} + +bool appendBinFix(QByteArray &buf, const QByteArray &src) { + return appendBinFix(buf, src.data(), src.size()); +} + +#include +#include +#ifdef Q_OS_WIN +#include +#include +#endif + +const auto dataFixed = QByteArrayLiteral("\x00\x11\x0d\x0a\x33"); +const auto data = QByteArrayLiteral("\x00\x11\x0d\x0d\x0a\x33"); + +int writeOutput() { +#ifdef Q_OS_WIN + _setmode(_fileno(stdout), _O_BINARY); +#endif + auto size = fwrite(data.data(), 1, data.size(), stdout); + qDebug() << size << data.size(); + return (size == data.size()) ? 0 : 1; +} + +class AppendTest : public QObject { + Q_OBJECT + struct Result { + QByteArray d; + bool ok; + bool operator==(const Result &o) const { return ok == o.ok && d == o.d; } + }; + static Result getFixed(const QByteArray &src, int split) { + Result f; + f.ok = appendBinFix(f.d, src.data(), split); + f.ok = appendBinFix(f.d, src.data() + split, src.size() - split) && f.ok; + return f; + } + Q_SLOT void worksWithLFCR() { + const auto lf_cr = QByteArrayLiteral("\x00\x11\x0a\x0d\x33"); + for (int i = 0; i < lf_cr.size(); ++i) + QCOMPARE(getFixed(lf_cr, i), (Result{lf_cr, false})); + } + Q_SLOT void worksWithCRLF() { + const auto cr_lf = QByteArrayLiteral("\x00\x11\x0d\x0a\x33"); + const auto cr_lf_fixed = QByteArrayLiteral("\x00\x11\x0a\x33"); + for (int i = 0; i < cr_lf.size(); ++i) + QCOMPARE(getFixed(cr_lf, i), (Result{cr_lf_fixed, true})); + } + Q_SLOT void worksWithCRCRLF() { + for (int i = 0; i < data.size(); ++i) QCOMPARE(getFixed(data, i).d, dataFixed); + } + Q_SLOT void worksWithQProcess() { + QProcess proc; + proc.start(QCoreApplication::applicationFilePath(), {"output"}, + QIODevice::ReadOnly); + proc.waitForFinished(5000); + QCOMPARE(proc.exitCode(), 0); + QCOMPARE(proc.exitStatus(), QProcess::NormalExit); + + QByteArray out = proc.readAllStandardOutput(); + QByteArray fixed; + appendBinFix(fixed, out); + QCOMPARE(out, data); + QCOMPARE(fixed, dataFixed); + } +}; + +int main(int argc, char *argv[]) { + QCoreApplication app(argc, argv); + if (app.arguments().size() > 1) return writeOutput(); + AppendTest test; + QTEST_SET_MAIN_SOURCE_PATH + return QTest::qExec(&test, argc, argv); +} +#include "main.moc" diff --git a/code/train/C++/0027411_Defines.cpp b/code/train/C++/0027411_Defines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53993d109bd5ab577f174af6808b85b0cea462b6 --- /dev/null +++ b/code/train/C++/0027411_Defines.cpp @@ -0,0 +1,300 @@ +#include "Common/Defines.h" +#include "Crypto/Commit.h" +#include "Common/BitVector.h" +//#include "Common/Timer.h" +#include +#include + +namespace bOPRF { + + Timer gTimer; + const block ZeroBlock = _mm_set_epi64x(0, 0); + const block OneBlock = _mm_set_epi64x(0, 1); + const block AllOneBlock = _mm_set_epi64x(u64(-1), u64(-1)); + const block CCBlock = ([]() {block cc; memset(&cc, 0xcc, sizeof(block)); return cc; })(); + + std::ostream& operator<<(std::ostream& out, const block& blk) + { + out << std::hex; + u64* data = (u64*)&blk; + + out << std::setw(16) << std::setfill('0') << data[0] + << std::setw(16) << std::setfill('0') << data[1]; + + out << std::dec << std::setw(0); + + return out; + } + + std::ostream& operator<<(std::ostream& out, const blockBop& blk) + { + out << std::hex; + u64* data = (u64*)&blk; + + out << std::setw(16) << std::setfill('0') << data[0] << "..." + //<< std::setw(16) << std::setfill('0') << data[1] + //<< std::setw(16) << std::setfill('0') << data[2] + //<< std::setw(16) << std::setfill('0') << data[3] + //<< std::setw(16) << std::setfill('0') << data[4] + //<< std::setw(16) << std::setfill('0') << data[5] + << std::setw(16) << std::setfill('0') << data[6]; + + out << std::dec << std::setw(0); + + return out; + } + + + std::ostream* gOut = &std::cout; + + + + std::ostream& operator<<(std::ostream& out, const Commit& comm) + { + out << std::hex; + + u32* data = (u32*)comm.data(); + + out << std::setw(8) << std::setfill('0') << data[0] + << std::setw(8) << std::setfill('0') << data[1] + << std::setw(8) << std::setfill('0') << data[2] + << std::setw(8) << std::setfill('0') << data[3] + << std::setw(8) << std::setfill('0') << data[4]; + + out << std::dec << std::setw(0); + + return out; + } + block PRF(const block& b, u64 i) + { + //TODO("REMOVE THIS!!"); + //return b; + + + + + + block ret, tweak = _mm_set1_epi64x(i), enc; + + ret = b ^ tweak; + + mAesFixedKey.ecbEncBlock(ret, enc); + + ret = ret ^ enc; // H( a0 ) + + return ret; + } + + void split(const std::string &s, char delim, std::vector &elems) { + std::stringstream ss(s); + std::string item; + while (std::getline(ss, item, delim)) { + elems.push_back(item); + } + } + + std::vector split(const std::string &s, char delim) { + std::vector elems; + split(s, delim, elems); + return elems; + } + + const int tab64[64] = { + 63, 0, 58, 1, 59, 47, 53, 2, + 60, 39, 48, 27, 54, 33, 42, 3, + 61, 51, 37, 40, 49, 18, 28, 20, + 55, 30, 34, 11, 43, 14, 22, 4, + 62, 57, 46, 52, 38, 26, 32, 41, + 50, 36, 17, 19, 29, 10, 13, 21, + 56, 45, 25, 31, 35, 16, 9, 12, + 44, 24, 15, 8, 23, 7, 6, 5 }; + + + u64 log2floor(u64 value) + { + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value |= value >> 32; + return tab64[((uint64_t)((value - (value >> 1)) * 0x07EDD5E59A4E28C2)) >> 58]; + } + + u64 log2ceil(u64 value) + { + return u64(std::ceil(std::log2(value))); + } + + u64 get_stash_size(u64 neles) { + if (neles >= (1 << 24)) + return 2; + if (neles >= (1 << 20)) + return 3; + if (neles >= (1 << 16)) + return 4; + if (neles >= (1 << 12)) + return 6; + if (neles >= (1 << 8)) + return 12; + + return 12; //other + + throw std::runtime_error("get_stash_size: rt error at " LOCATION); + + } + + //template + double getBinOverflowProb(u64 numBins, u64 numBalls, u64 binSize, double epsilon = 0.0001) + { + if (numBalls <= binSize) + return std::numeric_limits::max(); + + if (numBalls > unsigned(-1)) + { + auto msg = ("boost::math::binomial_coefficient(...) only supports " + std::to_string(sizeof(unsigned) * 8) + " bit inputs which was exceeded." LOCATION); + std::cout << msg << std::endl; + throw std::runtime_error(msg); + } + + //try + //{ + + //std::cout << numBalls << " " << numBins << " " << binSize << std::endl; + typedef boost::multiprecision::number> T; + T sum = 0.0; + T sec = 0.0;// minSec + 1; + T diff = 1; + u64 i = binSize + 1; + + + while (diff > T(epsilon) && numBalls >= i /*&& sec > minSec*/) + { + sum += numBins * boost::math::binomial_coefficient(numBalls, i) + * boost::multiprecision::pow(T(1.0) / numBins, i) * boost::multiprecision::pow(1 - T(1.0) / numBins, numBalls - i); + + //std::cout << "sum[" << i << "] " << sum << std::endl; + + T sec2 = boost::multiprecision::log2(sum); + diff = boost::multiprecision::abs(sec - sec2); + //std::cout << diff << std::endl; + sec = sec2; + + i++; + } + + return std::max(0, (double)-sec); + //} + //catch (std::exception& e) + //{ + // if (N == 16) + // { + // std::cout << "percision failure at " << LOCATION << "\n tring again with high percision (performance penalty)" << std::endl; + // // try again with higher percition + // return getBinOverflowProb<128>(numBins, numBalls, binSize); + // } + // + // std::cout << "retry percision failure at " << LOCATION << "\n" << e.what() << std::endl; + // throw; + //} + } + + u64 get_bin_size(u64 numBins, u64 numBalls, u64 statSecParam) + { + + auto B = std::max(1, numBalls / numBins); + + double currentProb = 0; + u64 step = 1; + + bool doubling = true; + + while (currentProb < statSecParam || step > 1) + { + if (!step) + throw std::runtime_error(LOCATION); + + + if (statSecParam > currentProb) + { + if (doubling) step = std::max(1, step * 2); + else step = std::max(1, step / 2); + + B += step; + } + else + { + doubling = false; + step = std::max(1, step / 2); + B -= step; + } + currentProb = getBinOverflowProb(numBins, numBalls, B); + } + + + + return B; + //if (simpleSize <= cuckooSize) + //{ + + // if (simpleSize >= (1 << 24)) + // return 28; + // if (simpleSize >= (1 << 20)) + // return 27; + // if (simpleSize >= (1 << 16)) + // return 26; + // if (simpleSize >= (1 << 12)) + // return 25; + // if (simpleSize >= (1 << 8)) + // return 24; + + // //return 30; //other + //} + //else + //{ + // return simpleSize / cuckooSize + 16 + 4 * std::sqrt(simpleSize * std::log2(cuckooSize) / cuckooSize); + //} + + //throw std::runtime_error("get_bin_size: rt error at " LOCATION); + } + + u64 get_codeword_size(u64 neles) { + if (neles >= (1 << 24)) + return 448 / 8; // in byte + if (neles >= (1 << 20)) + return 448 / 8; + if (neles >= (1 << 16)) + return 440 / 8; + if (neles >= (1 << 12)) + return 432 / 8; + if (neles >= (1 << 8)) + return 424 / 8; + + return 424 / 8; + + //throw std::runtime_error("get_codeword_size: rt error at " LOCATION); + } + u64 get_mask_size(u64 neles, u64 othersize, u64 statSecParam) { + + + return (statSecParam + log2(neles * othersize) + 7 ) / 8; + + //if (neles >= (1 << 24)) + // return 88 / 8; // in byte + //if (neles >= (1 << 20)) + // return 80 / 8; + //if (neles >= (1 << 16)) + // return 72 / 8; + //if (neles >= (1 << 12)) + // return 64 / 8; + //if (neles >= (1 << 8)) + // return 56 / 8; + + //return 56 / 8; + ////return (40 + 2 * log(neles)) / 8; + + // throw std::runtime_error("get_codeword_size: rt error at " LOCATION); + } +} + + diff --git a/code/train/C++/0027495_uf.cc b/code/train/C++/0027495_uf.cc new file mode 100644 index 0000000000000000000000000000000000000000..f4cc13e2ffe2636ead35dc32caa1e9d8d85f62b8 --- /dev/null +++ b/code/train/C++/0027495_uf.cc @@ -0,0 +1,210 @@ +// +// libsemigroups - C++ library for semigroups and monoids +// Copyright (C) 2017 Michael Torpey +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// + +// This file defines UF, a class used to make an equivalence relation on +// the integers {1 .. n}, using the UNION-FIND METHOD: new pairs can be added +// and the appropriate classes combined quickly. + +#include "uf.h" + +#include "libsemigroups-debug.h" + +namespace libsemigroups { + + // Copy constructor + UF::UF(const UF& copy) + : _size(copy._size), + _table(new table_t(*copy._table)), + _blocks(nullptr), + _haschanged(copy._haschanged) { + if (copy._blocks != nullptr) { + // Copy the blocks as well + _blocks = new blocks_t(); + _blocks->reserve(copy._blocks->size()); + for (auto const& block : *copy._blocks) { + if (block == nullptr) { + _blocks->push_back(nullptr); + } else { + _blocks->push_back(new table_t(*block)); + } + } + } + } + + // Constructor by table + UF::UF(const table_t& table) + : _size(table.size()), + _table(new table_t(table)), + _blocks(nullptr), + _haschanged(true), + _next_rep(0) {} + + // Constructor by size + UF::UF(size_t size) + : _size(size), + _table(new table_t()), + _blocks(nullptr), + _haschanged(false), + _next_rep(0) { + _table->reserve(size); + for (size_t i = 0; i < size; i++) { + _table->push_back(i); + } + } + + // Destructor + UF::~UF() { + delete _table; + if (_blocks != nullptr) { + for (size_t i = 0; i < _blocks->size(); i++) { + delete _blocks->at(i); + } + delete _blocks; + } + } + + // Getters + size_t UF::get_size() { + return _size; + } + + UF::table_t* UF::get_table() { + return _table; + } + + // get_blocks + UF::blocks_t* UF::get_blocks() { + table_t* block; + // Is _blocks "bound" yet? + if (_blocks == nullptr) { + _blocks = new blocks_t(); + _blocks->reserve(_size); + for (size_t i = 0; i < _size; i++) { + block = new table_t(1, i); + _blocks->push_back(block); + } + } + // Do we need to update the blocks? + if (_haschanged) { + size_t ii; + for (size_t i = 0; i < _size; i++) { + if (_blocks->at(i) != nullptr) { + ii = find(i); + if (ii != i) { + // Combine the two blocks + _blocks->at(ii)->reserve(_blocks->at(ii)->size() + + _blocks->at(i)->size()); + _blocks->at(ii)->insert(_blocks->at(ii)->end(), + _blocks->at(i)->begin(), + _blocks->at(i)->end()); + delete _blocks->at(i); + _blocks->at(i) = nullptr; + } + } + } + _haschanged = false; + } + return _blocks; + } + + // find + size_t UF::find(size_t i) { + size_t ii; + LIBSEMIGROUPS_ASSERT(_size == _table->size()); + do { + ii = i; + LIBSEMIGROUPS_ASSERT(ii < _size); + i = (*_table)[ii]; + } while (ii != i); + return i; + } + + // union + void UF::unite(size_t i, size_t j) { + size_t ii, jj; + LIBSEMIGROUPS_ASSERT(_size == _table->size()); + ii = find(i); + jj = find(j); + if (ii < jj) { + LIBSEMIGROUPS_ASSERT(jj < _size); + (*_table)[jj] = ii; + } else { + LIBSEMIGROUPS_ASSERT(ii < _size); + (*_table)[ii] = jj; + } + _haschanged = true; + } + + // flatten + void UF::flatten() { + LIBSEMIGROUPS_ASSERT(_size == _table->size()); + for (size_t i = 0; i < _size; i++) { + (*_table)[i] = find(i); + } + } + + // add_entry + void UF::add_entry() { + _table->push_back(_size); + if (_blocks != nullptr) { + _blocks->push_back(new table_t(1, _size)); + } + _size++; + } + + // nr_blocks + size_t UF::nr_blocks() { + LIBSEMIGROUPS_ASSERT(_size == _table->size()); + if (_size == 0) { + return 0; + } + size_t count = 1; + size_t max = 0; + flatten(); // So we can use [i] instead of ->find(i) + LIBSEMIGROUPS_ASSERT((*_table)[0] == 0); + for (size_t i = 1; i < _size; i++) { + if ((*_table)[i] > max) { + max = (*_table)[i]; + count++; + } + } + return count; + } + + void UF::reset_next_rep() { + flatten(); + _next_rep = 0; + } + + // Returns the next representative of a block, invalidated by anything that + // changes the partition + size_t UF::next_rep() { + size_t current_rep = _next_rep; + while (_next_rep < _size && (*_table)[_next_rep] <= current_rep) { + _next_rep++; + } + return current_rep; + } + + void UF::join(UF const& uf) { + LIBSEMIGROUPS_ASSERT(this->_size == uf._size); + for (size_t i = 0; i < _size; i++) { + unite((*_table)[i], (*uf._table)[i]); + } + } +} // namespace libsemigroups diff --git a/code/train/C++/0027730_reverse_geocoder.cpp b/code/train/C++/0027730_reverse_geocoder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2796138dcb0400b5b46f08fae813e302155d317 --- /dev/null +++ b/code/train/C++/0027730_reverse_geocoder.cpp @@ -0,0 +1,218 @@ +#include "reverse_geocoder.hpp" + +#include "search/mwm_context.hpp" + +#include "indexer/feature.hpp" +#include "indexer/feature_algo.hpp" +#include "indexer/ftypes_matcher.hpp" +#include "indexer/index.hpp" +#include "indexer/scales.hpp" +#include "indexer/search_string_utils.hpp" + +#include "base/stl_helpers.hpp" + +#include "std/limits.hpp" + +namespace search +{ +namespace +{ +size_t constexpr kSimilarityThresholdPercent = 10; +int constexpr kQueryScale = scales::GetUpperScale(); +/// Max number of tries (nearest houses with housenumber) to check when getting point address. +size_t constexpr kMaxNumTriesToApproxAddress = 10; +} // namespace + +ReverseGeocoder::ReverseGeocoder(Index const & index) : m_index(index) {} + +void ReverseGeocoder::GetNearbyStreets(MwmSet::MwmId const & id, m2::PointD const & center, + vector & streets) const +{ + m2::RectD const rect = GetLookupRect(center, kLookupRadiusM); + + auto const addStreet = [&](FeatureType & ft) + { + if (ft.GetFeatureType() != feature::GEOM_LINE || + !ftypes::IsStreetChecker::Instance()(ft)) + { + return; + } + + string name; + if (!ft.GetName(StringUtf8Multilang::kDefaultCode, name)) + return; + + ASSERT(!name.empty(), ()); + + streets.emplace_back(ft.GetID(), feature::GetMinDistanceMeters(ft, center), name); + }; + + MwmSet::MwmHandle mwmHandle = m_index.GetMwmHandleById(id); + if (mwmHandle.IsAlive()) + { + search::MwmContext(move(mwmHandle)).ForEachFeature(rect, addStreet); + sort(streets.begin(), streets.end(), my::LessBy(&Street::m_distanceMeters)); + } +} + +void ReverseGeocoder::GetNearbyStreets(FeatureType & ft, vector & streets) const +{ + ASSERT(ft.GetID().IsValid(), ()); + GetNearbyStreets(ft.GetID().m_mwmId, feature::GetCenter(ft), streets); +} + +// static +size_t ReverseGeocoder::GetMatchedStreetIndex(strings::UniString const & keyName, + vector const & streets) +{ + // Find the exact match or the best match in kSimilarityTresholdPercent limit. + size_t const count = streets.size(); + size_t result = count; + size_t minPercent = kSimilarityThresholdPercent + 1; + + for (size_t i = 0; i < count; ++i) + { + strings::UniString const actual = GetStreetNameAsKey(streets[i].m_name); + + size_t const editDistance = strings::EditDistance(keyName.begin(), keyName.end(), + actual.begin(), actual.end()); + + if (editDistance == 0) + return i; + + if (actual.empty()) + continue; + + size_t const percent = editDistance * 100 / actual.size(); + if (percent < minPercent) + { + result = i; + minPercent = percent; + } + } + + return result; +} + +pair, uint32_t> +ReverseGeocoder::GetNearbyFeatureStreets(FeatureType & ft) const +{ + pair, uint32_t> result; + + GetNearbyStreets(ft, result.first); + + HouseTable table(m_index); + if (!table.Get(ft.GetID(), result.second)) + result.second = numeric_limits::max(); + + return result; +} + +void ReverseGeocoder::GetNearbyAddress(m2::PointD const & center, Address & addr) const +{ + vector buildings; + GetNearbyBuildings(center, buildings); + + HouseTable table(m_index); + size_t triesCount = 0; + + for (auto const & b : buildings) + { + // It's quite enough to analize nearest kMaxNumTriesToApproxAddress houses for the exact nearby address. + // When we can't guarantee suitable address for the point with distant houses. + if (GetNearbyAddress(table, b, addr) || (++triesCount == kMaxNumTriesToApproxAddress)) + break; + } +} + +bool ReverseGeocoder::GetExactAddress(FeatureType & ft, Address & addr) const +{ + if (ft.GetHouseNumber().empty()) + return false; + HouseTable table(m_index); + return GetNearbyAddress(table, FromFeature(ft, 0.0 /* distMeters */), addr); +} + +bool ReverseGeocoder::GetNearbyAddress(HouseTable & table, Building const & bld, + Address & addr) const +{ + string street; + if (osm::Editor::Instance().GetEditedFeatureStreet(bld.m_id, street)) + { + addr.m_building = bld; + addr.m_street.m_name = street; + return true; + } + + uint32_t ind; + if (!table.Get(bld.m_id, ind)) + return false; + + vector streets; + GetNearbyStreets(bld.m_id.m_mwmId, bld.m_center, streets); + if (ind < streets.size()) + { + addr.m_building = bld; + addr.m_street = streets[ind]; + return true; + } + else + { + LOG(LWARNING, ("Out of bound street index", ind, "for", bld.m_id)); + return false; + } +} + +void ReverseGeocoder::GetNearbyBuildings(m2::PointD const & center, vector & buildings) const +{ + m2::RectD const rect = GetLookupRect(center, kLookupRadiusM); + + auto const addBuilding = [&](FeatureType & ft) + { + if (!ft.GetHouseNumber().empty()) + buildings.push_back(FromFeature(ft, feature::GetMinDistanceMeters(ft, center))); + }; + + m_index.ForEachInRect(addBuilding, rect, kQueryScale); + sort(buildings.begin(), buildings.end(), my::LessBy(&Building::m_distanceMeters)); +} + +// static +ReverseGeocoder::Building ReverseGeocoder::FromFeature(FeatureType & ft, double distMeters) +{ + return { ft.GetID(), distMeters, ft.GetHouseNumber(), feature::GetCenter(ft) }; +} + +// static +m2::RectD ReverseGeocoder::GetLookupRect(m2::PointD const & center, double radiusM) +{ + return MercatorBounds::RectByCenterXYAndSizeInMeters(center, radiusM); +} + +bool ReverseGeocoder::HouseTable::Get(FeatureID const & fid, uint32_t & streetIndex) +{ + if (!m_table || m_handle.GetId() != fid.m_mwmId) + { + m_handle = m_index.GetMwmHandleById(fid.m_mwmId); + if (!m_handle.IsAlive()) + { + LOG(LWARNING, ("MWM", fid, "is dead")); + return false; + } + m_table = search::HouseToStreetTable::Load(*m_handle.GetValue()); + } + + return m_table->Get(fid.m_index, streetIndex); +} + +string DebugPrint(ReverseGeocoder::Object const & obj) +{ + return obj.m_name; +} + +string DebugPrint(ReverseGeocoder::Address const & addr) +{ + return "{ " + DebugPrint(addr.m_building) + ", " + DebugPrint(addr.m_street) + " }"; +} + +} // namespace search diff --git a/code/train/C++/0027996_gain_change_calculator.cc b/code/train/C++/0027996_gain_change_calculator.cc new file mode 100644 index 0000000000000000000000000000000000000000..13017d4220b5b7c41f8f500a198204e4cd0bc879 --- /dev/null +++ b/code/train/C++/0027996_gain_change_calculator.cc @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/modules/audio_mixer/gain_change_calculator.h" + +#include +#include + +namespace webrtc { + +namespace { +constexpr int16_t kReliabilityThreshold = 100; +} // namespace + +float GainChangeCalculator::CalculateGainChange( + rtc::ArrayView in, + rtc::ArrayView out) { + RTC_DCHECK_EQ(in.size(), out.size()); + + std::vector gain(in.size()); + CalculateGain(in, out, gain); + return CalculateDifferences(gain); +} + +void GainChangeCalculator::CalculateGain(rtc::ArrayView in, + rtc::ArrayView out, + rtc::ArrayView gain) { + RTC_DCHECK_EQ(in.size(), out.size()); + RTC_DCHECK_EQ(in.size(), gain.size()); + + for (size_t i = 0; i < in.size(); ++i) { + if (std::abs(in[i]) >= kReliabilityThreshold) { + last_reliable_gain_ = out[i] / static_cast(in[i]); + } + gain[i] = last_reliable_gain_; + } +} + +float GainChangeCalculator::CalculateDifferences( + rtc::ArrayView values) { + float res = 0; + for (float f : values) { + res += fabs(f - last_value_); + last_value_ = f; + } + return res; +} +} // namespace webrtc diff --git a/code/train/C++/0028086_StacksDP.cpp b/code/train/C++/0028086_StacksDP.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71390f268699852c641293595d9c5e7247a98d5f --- /dev/null +++ b/code/train/C++/0028086_StacksDP.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +#include +using std::string; + +#include +using std::cin; +using std::cout; +using std::stringstream; + +#include +#include "StacksAD.cpp" + +using namespace std; + + +class StacksDP +{ +private: + Nodo *FirstNode, *tempNode; +public: + string push(string info){ + if(FirstNode == NULL){ + FirstNode = new Nodo(info); + FirstNode->setNext(NULL); + return "Exitosamente Guardado: "+info; + } + else{ + tempNode = FirstNode; + FirstNode = new Nodo(info); + FirstNode->setNext(tempNode); + return "Exitosamente Guardado: " + info; + } + } + string pop(void){ + + if (FirstNode == NULL) { + return "EMPTY LIST"; + } + + string result = FirstNode->getString(); + FirstNode = FirstNode->getNext(); + return result; + } + string desplegar(void){ + string result =""; + + if (FirstNode == NULL) { + return "NULL LIST"; + } + + Nodo *cursor = FirstNode; + while(cursor!=NULL){ + result += cursor->getString() +"\n"; + cursor = cursor->getNext(); + } + return result; + } + void getData(void); + void saveData(void); + +}; + diff --git a/code/train/C++/0028526_Squirrel_Simulation.cpp b/code/train/C++/0028526_Squirrel_Simulation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e098e15a98e9aeaa76de4c51c390a465d6bb68cf --- /dev/null +++ b/code/train/C++/0028526_Squirrel_Simulation.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +class Solution { +public: + int minDistance(int height, int width, vector& tree, vector& squirrel, vector>& nuts) { + int cnt = 0; + int save = INT_MIN; + for (auto nut : nuts) { + int treeD = calcDis(nut, tree); + int squD = calcDis(nut, squirrel); + save = max(save, treeD - squD); + cnt += treeD * 2; + } + cnt = cnt - save; + return cnt; + } + + int calcDis(vector pos1, vector pos2) { + return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]); + } +}; + + + +int main(int argc, char const *argv[]) { + + Solution s; + vector tree = {3,2}; + vector squ = {0,1}; + vector > nuts = {{2,0},{4,1},{0,4},{1,3},{1,0},{3,4},{3,0},{2,3},{0,2},{0,0},{2,2},{4,2},{3,3},{4,4},{4,0},{4,3},{3,1},{2,1},{1,4},{2,4}}; + + cout << s.minDistance(5,5,tree,squ,nuts) << endl; + return 0; +} diff --git a/code/train/C++/0028563_cblas_d.cpp b/code/train/C++/0028563_cblas_d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39cbc77fd9398dd4b88d5d1d54200b2301d38449 --- /dev/null +++ b/code/train/C++/0028563_cblas_d.cpp @@ -0,0 +1,245 @@ +/* + -- MAGMA (version 2.1.0) -- + Univ. of Tennessee, Knoxville + Univ. of California, Berkeley + Univ. of Colorado, Denver + @date August 2016 + + @author Mark Gates + @generated from src/cblas_z.cpp, normal z -> d, Tue Aug 30 09:38:00 2016 + + Wrappers around a few CBLAS functions. + + Primarily, we use the standard Fortran BLAS interface in MAGMA. However, + functions that return a value (as opposed to subroutines that are void) + are not portable, as they depend on how Fortran returns values. The routines + here provide a portable interface. These are not identical to CBLAS, in + particular, [cz]dot[uc] return real numbers (as in Fortran BLAS) rather + than return values via an argument. + + Only these BLAS-1 functions are provided: + + magma_cblas_dasum / dasum + magma_cblas_dnrm2 / dnrm2 + magma_cblas_ddot / ddot + magma_cblas_ddot / ddot + +*/ +#include "magma_internal.h" + +#define REAL + +/***************************************************************************//** + @return Sum of absolute values of vector x; + \f$ \sum_i | real(x_i) | + | imag(x_i) | \f$. + + To avoid dependence on CBLAS and incompatability issues between BLAS + libraries, MAGMA uses its own implementation, following BLAS reference. + + @param[in] + n Number of elements in vector x. n >= 0. + + @param[in] + x DOUBLE PRECISION array on CPU host. + The n element vector x of dimension (1 + (n-1)*incx). + + @param[in] + incx Stride between consecutive elements of x. incx > 0. + + @ingroup magma_asum +*******************************************************************************/ +extern "C" +double magma_cblas_dasum( + magma_int_t n, + const double *x, magma_int_t incx ) +{ + if ( n <= 0 || incx <= 0 ) { + return 0; + } + double result = 0; + if ( incx == 1 ) { + for( magma_int_t i=0; i < n; ++i ) { + result += MAGMA_D_ABS1( x[i] ); + } + } + else { + magma_int_t nincx = n*incx; + for( magma_int_t i=0; i < nincx; i += incx ) { + result += MAGMA_D_ABS1( x[i] ); + } + } + return result; +} + + +static inline double sqr( double x ) { return x*x; } + +/***************************************************************************//** + Returns 2-norm of vector x. Avoids unnecesary over/underflow. + + To avoid dependence on CBLAS and incompatability issues between BLAS + libraries, MAGMA uses its own implementation, following BLAS reference. + + @param[in] + n Number of elements in vector x. n >= 0. + + @param[in] + x DOUBLE PRECISION array on CPU host. + The n element vector x of dimension (1 + (n-1)*incx). + + @param[in] + incx Stride between consecutive elements of x. incx > 0. + + @ingroup magma_nrm2 +*******************************************************************************/ +extern "C" +double magma_cblas_dnrm2( + magma_int_t n, + const double *x, magma_int_t incx ) +{ + if (n <= 0 || incx <= 0) { + return 0; + } + else { + double scale = 0; + double ssq = 1; + // the following loop is equivalent to this call to the lapack + // auxiliary routine: + // call zlassq( n, x, incx, scale, ssq ) + for( magma_int_t ix=0; ix < 1 + (n-1)*incx; ix += incx ) { + if ( real( x[ix] ) != 0 ) { + double temp = fabs( real( x[ix] )); + if (scale < temp) { + ssq = 1 + ssq * sqr(scale/temp); + scale = temp; + } + else { + ssq += sqr(temp/scale); + } + } + #ifdef COMPLEX + if ( imag( x[ix] ) != 0 ) { + double temp = fabs( imag( x[ix] )); + if (scale < temp) { + ssq = 1 + ssq * sqr(scale/temp); + scale = temp; + } + else { + ssq += sqr(temp/scale); + } + } + #endif + } + return scale*magma_dsqrt(ssq); + } +} + + +#ifdef COMPLEX +/***************************************************************************//** + Returns dot product of vectors x and y; \f$ x^H y \f$. + + To avoid dependence on CBLAS and incompatability issues between BLAS + libraries, MAGMA uses its own implementation, following BLAS reference. + + @param[in] + n Number of elements in vector x and y. n >= 0. + + @param[in] + x DOUBLE PRECISION array on CPU host. + The n element vector x of dimension (1 + (n-1)*incx). + + @param[in] + incx Stride between consecutive elements of x. incx > 0. + + @param[in] + y DOUBLE PRECISION array on CPU host. + The n element vector y of dimension (1 + (n-1)*incy). + + @param[in] + incy Stride between consecutive elements of dy. incy > 0. + + @ingroup magma__dot +*******************************************************************************/ +extern "C" +double magma_cblas_ddot( + magma_int_t n, + const double *x, magma_int_t incx, + const double *y, magma_int_t incy ) +{ + // after too many issues with MKL and other BLAS, just write our own dot product! + double value = MAGMA_D_ZERO; + magma_int_t i; + if ( incx == 1 && incy == 1 ) { + for( i=0; i < n; ++i ) { + value += conj( x[i] ) * y[i]; + } + } + else { + magma_int_t ix=0, iy=0; + if ( incx < 0 ) { ix = (-n + 1)*incx; } + if ( incy < 0 ) { iy = (-n + 1)*incy; } + for( i=0; i < n; ++i ) { + value += conj( x[ix] ) * y[iy]; + ix += incx; + iy += incy; + } + } + return value; +} +#endif // COMPLEX + + +/***************************************************************************//** + @return dot product (unconjugated) of vectors x and y; \f$ x^T y \f$. + + To avoid dependence on CBLAS and incompatability issues between BLAS + libraries, MAGMA uses its own implementation, following BLAS reference. + + @param[in] + n Number of elements in vector x and y. n >= 0. + + @param[in] + x DOUBLE PRECISION array on CPU host. + The n element vector x of dimension (1 + (n-1)*incx). + + @param[in] + incx Stride between consecutive elements of x. incx > 0. + + @param[in] + y DOUBLE PRECISION array on CPU host. + The n element vector y of dimension (1 + (n-1)*incy). + + @param[in] + incy Stride between consecutive elements of dy. incy > 0. + + @ingroup magma__dot +*******************************************************************************/ +extern "C" +double magma_cblas_ddot( + magma_int_t n, + const double *x, magma_int_t incx, + const double *y, magma_int_t incy ) +{ + // after too many issues with MKL and other BLAS, just write our own dot product! + double value = MAGMA_D_ZERO; + magma_int_t i; + if ( incx == 1 && incy == 1 ) { + for( i=0; i < n; ++i ) { + value += x[i] * y[i]; + } + } + else { + magma_int_t ix=0, iy=0; + if ( incx < 0 ) { ix = (-n + 1)*incx; } + if ( incy < 0 ) { iy = (-n + 1)*incy; } + for( i=0; i < n; ++i ) { + value += x[ix] * y[iy]; + ix += incx; + iy += incy; + } + } + return value; +} + +#undef REAL diff --git a/code/train/C++/0028606_largestnum.cpp b/code/train/C++/0028606_largestnum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..656fd30df7d67fbdef8fd48ae83b608a573f7f70 --- /dev/null +++ b/code/train/C++/0028606_largestnum.cpp @@ -0,0 +1,72 @@ +/*Given a list of non negative integers, arrange them such that they form the largest number. + +For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. + +Note: The result may be very large, so you need to return a string instead of an integer.*/ + +#include +#include +#include +using namespace std; + +char *itoa(int num,int radix = 10){ + const int MAX_LEN = 12; + int isNega = 0; + if(num < 0){ + isNega = 1; + num = -num; + } + char* str = new char[MAX_LEN]; + str[MAX_LEN - 1] = '\0'; + int t = MAX_LEN - 2; + while(1){ + int end = num%radix; + str[t--] = end + '0'; + num = (num-end)/radix; + if(num == 0) + break; + } + if(isNega){str[t--] = '-';} + return &str[++t]; +} + +bool cmp(int a, int b) { + char* sa = itoa(a); + char* sb = itoa(b); + for(;*sa && *sb;sa++,sb++){ + if(*sa == *sb) + continue; + else if(*sa > *sb){ + return true; + }else{ + return false; + } + } + return !*sa?true:false; +} + +string largestNumber(vector &num) { + sort(num.begin(), num.end(), cmp); + if (num[0] == 0) { + return "0"; + } + + char strn[11] = { 0 }; // 最大整形为11个数 + string result; + + result.reserve(8 * num.size()); // 开辟保留空间会快点 + for (vector::iterator it = num.begin(); it != num.end(); ++it) { + sprintf(strn, "%d", *it); + result += strn; + } + + return result; +} + + +int main(int argc, char const *argv[]) +{ + vector v = {1,2,3,4,91,89,10,5,6,9}; + cout << largestNumber(v) << endl; + return 0; +} \ No newline at end of file diff --git a/code/train/C++/0028956_2.4.6_K-d_Tree__Nearest_Neighbor_.cpp b/code/train/C++/0028956_2.4.6_K-d_Tree__Nearest_Neighbor_.cpp new file mode 100644 index 0000000000000000000000000000000000000000..382233a2ddf270e2d553d7cd29ee3dae6b20eab6 --- /dev/null +++ b/code/train/C++/0028956_2.4.6_K-d_Tree__Nearest_Neighbor_.cpp @@ -0,0 +1,132 @@ +/* + +Maintain a set of two-dimensional points while supporting queries for the +closest point in the set to a given query point. This implementation uses +std::pair to represent points, requiring operators <, ==, -, and long double +casting to be defined on the numeric template type. + +- kd_tree(lo, hi) constructs a set from two RandomAccessIterators to std::pair + as a range [lo, hi) of points. +- nearest(x, y, can_equal) returns a point in the set that is closest to (x, y) + by Euclidean distance. This may be equal to (x, y) only if can_equal is true. + +Time Complexity: +- O(n log n) per call to the constructor, where n is the number of points. +- O(log n) on average per call to nearest(). + +Space Complexity: +- O(n) for storage of the points. +- O(log n) auxiliary stack space for nearest(). + +*/ + +#include +#include +#include +#include +#include + +template +class kd_tree { + typedef std::pair point; + + static inline bool comp1(const point &a, const point &b) { + return a.first < b.first; + } + + static inline bool comp2(const point &a, const point &b) { + return a.second < b.second; + } + + std::vector tree; + std::vector div_x; + + void build(int lo, int hi) { + if (lo >= hi) { + return; + } + int mid = lo + (hi - lo)/2; + T minx, maxx, miny, maxy; + minx = maxx = tree[lo].first; + miny = maxy = tree[lo].second; + for (int i = lo + 1; i < hi; i++) { + minx = std::min(minx, tree[i].first); + miny = std::min(miny, tree[i].second); + maxx = std::max(maxx, tree[i].first); + maxy = std::max(maxy, tree[i].second); + } + div_x[mid] = !((maxx - minx) < (maxy - miny)); + std::nth_element(tree.begin() + lo, tree.begin() + mid, tree.begin() + hi, + div_x[mid] ? comp1 : comp2); + if (lo + 1 == hi) { + return; + } + build(lo, mid); + build(mid + 1, hi); + } + + // Helper variables for nearest(). + long double min_dist; + int id; + + void nearest(int lo, int hi, const T &x, const T &y, bool can_equal) { + if (lo >= hi) { + return; + } + int mid = lo + (hi - lo)/2; + T dx = x - tree[mid].first, dy = y - tree[mid].second; + long double d = dx*(long double)dx + dy*(long double)dy; + if (d < min_dist && (can_equal || d != 0)) { + min_dist = d; + id = mid; + } + if (lo + 1 == hi) { + return; + } + d = (long double)(div_x[mid] ? dx : dy); + int l1 = lo, r1 = mid, l2 = mid + 1, r2 = hi; + if (d > 0) { + std::swap(l1, l2); + std::swap(r1, r2); + } + nearest(l1, r1, x, y, can_equal); + if (d*(long double)d < min_dist) { + nearest(l2, r2, x, y, can_equal); + } + } + + public: + template + kd_tree(It lo, It hi) : tree(lo, hi) { + int n = std::distance(lo, hi); + if (n <= 1) { + throw std::runtime_error("K-d tree must be have at least 2 points."); + } + div_x.resize(n); + build(0, n); + } + + point nearest(const T &x, const T &y, bool can_equal = true) { + min_dist = std::numeric_limits::max(); + nearest(0, tree.size(), x, y, can_equal); + return tree[id]; + } +}; + +/*** Example Usage ***/ + +#include +using namespace std; + +int main() { + pair p[3]; + p[0] = make_pair(0, 2); + p[1] = make_pair(0, 3); + p[2] = make_pair(-1, 0); + kd_tree t(p, p + 3); + assert(t.nearest(0, 2, true) == make_pair(0, 2)); + assert(t.nearest(0, 2, false) == make_pair(0, 3)); + assert(t.nearest(0, 0) == make_pair(-1, 0)); + assert(t.nearest(-10000, 0) == make_pair(-1, 0)); + return 0; +} diff --git a/code/train/C++/0029412_tree-height.cpp b/code/train/C++/0029412_tree-height.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ce3d3ad27a977594d7a74db8ac0c13eabb2f2c0 --- /dev/null +++ b/code/train/C++/0029412_tree-height.cpp @@ -0,0 +1,121 @@ +#include +#include + +using namespace std; + +class Node{ + public: + int data; + Node *left; + Node *right; + Node(int d){ + data = d; + left = NULL; + right = NULL; + } +}; + +class Solution { + public: + Node* insert(Node* root, int data) { + if(root == NULL) { + return new Node(data); + } + else { + Node* cur; + if(data <= root->data){ + cur = insert(root->left, data); + root->left = cur; + } + else{ + cur = insert(root->right, data); + root->right = cur; + } + + return root; + } + } +/*The tree node has data, left child and right child +class Node { + int data; + Node* left; + Node* right; +}; + +*/ + + // recursive + int height1(Node* root) { + return max(root->left ? (1 + height1(root->left)) : 0, + root->right ? (1 + height1(root->right)) : 0); + } + + // Gosh I need a stack + class stack { + public: + stack() : head(nodes) {} + void push(Node* v) { *head++ = v; } + Node* pop() { return *(--head); } + bool empty() const { return head == nodes; } + private: + Node* nodes[10000]; + Node** head; + }; + + // iterative + int height(Node* root) { + if (!root) return 0; + int depth = 0, max_depth = 0; + + Node* prev = root; + Node* current = root; + stack path; + while (true) { + bool from_left = prev == current->left; + bool from_right = prev == current->right; + bool from_top = !from_left && !from_right; + bool go_left = from_top && current->left; + bool go_right = (!go_left || from_left) && !from_right && current->right; + bool go_up = !go_left && !go_right; + prev = current; + if (go_left) { + path.push(current); + ++depth; + current = current->left; + } + if (go_right) { + path.push(current); + ++depth; + current = current->right; + } + if (go_up) { + if (!current->left && !current->right) { + max_depth = max(depth, max_depth); + } + if (path.empty()) { + return max_depth; + } + current = path.pop(); + --depth; + } + } + } +}; //End of Solution + +int main() { + Solution myTree; + Node* root = NULL; + int t; + int data; + + cin >> t; + + while(t-- > 0){ + cin >> data; + root = myTree.insert(root, data); + } + int height = myTree.height(root); + cout << height; + + return 0; +} diff --git a/code/train/C++/0029708_op_stats_to_pod_stats.cc b/code/train/C++/0029708_op_stats_to_pod_stats.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6a3f15ea6a808c3bcceacccd656bd72e31517ae --- /dev/null +++ b/code/train/C++/0029708_op_stats_to_pod_stats.cc @@ -0,0 +1,96 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/core/profiler/convert/op_stats_to_pod_stats.h" + +#include "google/protobuf/any.pb.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/profiler/protobuf/steps_db.pb.h" +#include "tensorflow/core/profiler/utils/diagnostics.h" +#include "tensorflow/core/profiler/utils/event_span.h" +#include "tensorflow/core/profiler/utils/math_utils.h" + +namespace tensorflow { +namespace profiler { + +namespace { + +PodStatsRecord CreatePodStatsRecord(absl::string_view host_name, + const StepInfoResult& step_info) { + PodStatsRecord record; + GenericStepBreakdown generic; + bool success = step_info.step_breakdown().UnpackTo(&generic); + DCHECK(success); + record.set_host_name(string(host_name)); + record.set_step_num(step_info.step_num()); + record.set_total_duration_us(PicoToMicro(step_info.duration_ps())); + auto& step_breakdown_map = *record.mutable_step_breakdown_us(); + std::vector> metrics; + + auto add_event = [&](GenericEventType type, + std::initializer_list event_list) { + uint64 ps = 0; + for (const auto& event_type : event_list) { + ps += gtl::FindWithDefault(generic.type_ps(), event_type, /*value=*/0); + } + step_breakdown_map[type] = PicoToMicro(ps); + metrics.emplace_back(ps, GetGenericEventTypeStr(type)); + }; + + add_event(kDeviceCompute, {DEVICE_COMPUTE_32, DEVICE_COMPUTE_16}); + add_event(kDeviceToDevice, {DEVICE_TO_DEVICE, DEVICE_WAIT_DEVICE}); + add_event(kDeviceCollectives, {DEVICE_COLLECTIVES}); + add_event(kHostCompute, {HOST_COMPUTE}); + add_event(kHostPrepare, {HOST_PREPARE}); + add_event(kInput, {HOST_WAIT_INPUT, HOST_TO_DEVICE, DEVICE_WAIT_HOST}); + add_event(kOutput, {DEVICE_TO_HOST}); + add_event(kCompile, {HOST_COMPILE}); + add_event(kAllOthers, {UNKNOWN_TIME}); + + std::sort(metrics.begin(), metrics.end()); + record.set_bottleneck(metrics.back().second.data(), + metrics.back().second.size()); + return record; +} + +} // namespace + +PodStatsDatabase ConvertOpStatsToPodStats(const OpStats& op_stats) { + PodStatsDatabase pod_stats_db; + const auto& core_id_map = op_stats.core_id_to_details(); + for (int i = GenericEventType::kFirstGenericEventType; + i <= GenericEventType::kLastGenericEventType; i++) { + auto& event = *pod_stats_db.add_step_breakdown_events(); + event.set_id(i); + absl::string_view type_str = + GetGenericEventTypeStr(static_cast(i)); + event.set_name(type_str.data(), type_str.size()); + } + + for (const auto& step_sequence : op_stats.step_db().step_sequence()) { + for (const auto& entry : step_sequence.step_info_per_core()) { + const CoreDetails& details = core_id_map.at(entry.first); + *pod_stats_db.add_pod_stats_record() = + CreatePodStatsRecord(details.hostname(), entry.second); + } + } + PopulateStepDiagnostics(op_stats, pod_stats_db.mutable_diagnostics()); + return pod_stats_db; +} + +} // namespace profiler +} // namespace tensorflow diff --git a/code/train/C++/0029712_1098.cpp b/code/train/C++/0029712_1098.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6acc4b9440cf6766a8a2f632b49e24defc7d0ba --- /dev/null +++ b/code/train/C++/0029712_1098.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +void AdjustHeap(vector& heap, int heapSize, int adjustIndex) { + // pMaxIndex point to the max node of cur,left,right nodes + int pMaxIndex = adjustIndex; + if (2*adjustIndex+1 < heapSize && heap[2*adjustIndex+1] > heap[pMaxIndex]) + pMaxIndex = 2 * adjustIndex + 1; + if (2*adjustIndex+2 < heapSize && heap[2*adjustIndex+2] > heap[pMaxIndex]) + pMaxIndex = 2 * adjustIndex + 2; + + // the cur node has max value, no need to adjust + if (pMaxIndex == adjustIndex) { + return; + } else { + swap(heap[adjustIndex], heap[pMaxIndex]); + AdjustHeap(heap, heapSize, pMaxIndex); + } +} + +void PrintVector(const vector& v) { + for (size_t i = 0; i < v.size(); ++i) { + if (i == 0) printf("%d", v[i]); + else printf(" %d", v[i]); + } + printf("\n"); +} + +int main() +{ + freopen("input.txt", "r", stdin); + int n; + scanf("%d", &n); + + vector input(n, 0); + vector output(n, 0); + for (int i = 0; i < n; ++i) scanf("%d", &input[i]); + for (int i = 0; i < n; ++i) scanf("%d", &output[i]); + + vector temp(input.begin(), input.end()); + sort(temp.begin(), temp.end()); + + bool isHeapSort = true; + int j = n - 1; + while (j >= 0 && temp[j] == output[j]) j--; + for (int i = 0; i <= j; ++i) { + if (2*i+1 <= j) { + if (output[i] < output[2*i+1]) isHeapSort = false; + } + if (2*i+2 <= j) { + if (output[i] < output[2*i+2]) isHeapSort = false; + } + } + + if (isHeapSort) { + printf("Heap Sort\n"); + int heapSize = j + 1; + swap(output[0], output[heapSize-1]); + heapSize--; + AdjustHeap(output, heapSize, 0); + PrintVector(output); + + } else { + printf("Insertion Sort\n"); + int k = 0; + while (k+1 < n && output[k] <= output[k+1]) k++; + int next = k + 1; + int temp = output[next]; + int start = 0; + while (output[start] <= output[next]) start++; + for (int idx = next - 1; idx >= start; --idx) { + output[idx+1] = output[idx]; + } + output[start] = temp; + PrintVector(output); + } + return 0; +} \ No newline at end of file diff --git a/code/train/C++/0029948_1913.cpp b/code/train/C++/0029948_1913.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2d83174b371bc87db08b0a8bb959de006c7a9aa --- /dev/null +++ b/code/train/C++/0029948_1913.cpp @@ -0,0 +1,80 @@ +//{ +#include +using namespace std; +typedef long long ll; +typedef double lf; +typedef pair ii; +#define REP(i,n) for(ll i=0;i ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} +template ostream& _OUTC(ostream &_s,It _ita,It _itb) +{ + _s<<"{"; + for(It _it=_ita;_it!=_itb;_it++) + { + _s<<(_it==_ita?"":",")<<*_it; + } + _s<<"}"; + return _s; +} +template ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} +template ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} +template ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} +template void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<>T; + while(T--) + { + ll n,ans=0; + cin>>n; + REP(i,n)cin>>d[i]; + REP(i,n-1) + { + FILL(ct,0); + ll mn=d[i],mx=d[i],t=1;ct[d[i]]=1; + for(int j=i+1;j pagePtr; + m_shared_page_pool.getPtr(pagePtr, chunks[0].ptrI); + page8 = (Page8*)pagePtr.p; + + /** + * 1) Build free-list per chunk + * 2) Add chunks to cfreepages-list + */ + cfreepages.init(); + cpagesize = 0; + cpageCount = 0; + LocalPage8List freelist(*this, cfreepages); + for (Int32 i = chunkcnt - 1; i >= 0; i--) + { + Ptr pagePtr; + m_shared_page_pool.getPtr(pagePtr, chunks[i].ptrI); + const Uint32 cnt = 4 * chunks[i].cnt; // 4 8k per 32k + Page8* base = (Page8*)pagePtr.p; + ndbrequire(base >= page8); + const Uint32 ptrI = Uint32(base - page8); + if (ptrI + cnt > cpagesize) + cpagesize = ptrI + cnt; + for (Uint32 j = 0; j < cnt; j++) + { + refresh_watch_dog(); + freelist.addFirst(Page8Ptr::get(&base[j], ptrI + j)); + } + + cpageCount += cnt; + ndbassert(freelist.getCount() + cnoOfAllocatedPages == cpageCount); + } + m_maxAllocPages = cpagesize; + } + + operationrec = (Operationrec*)allocRecord("Operationrec", + sizeof(Operationrec), + coprecsize); + + fragmentrec = (Fragmentrec*)allocRecord("Fragmentrec", + sizeof(Fragmentrec), + cfragmentsize); + + scanRec = (ScanRec*)allocRecord("ScanRec", + sizeof(ScanRec), + cscanRecSize); + + tabrec = (Tabrec*)allocRecord("Tabrec", + sizeof(Tabrec), + ctablesize); +}//Dbacc::initRecords() + +Dbacc::Dbacc(Block_context& ctx, Uint32 instanceNumber): + SimulatedBlock(DBACC, ctx, instanceNumber), + c_tup(0) +{ + BLOCK_CONSTRUCTOR(Dbacc); + + // Transit signals + addRecSignal(GSN_DUMP_STATE_ORD, &Dbacc::execDUMP_STATE_ORD); + addRecSignal(GSN_DEBUG_SIG, &Dbacc::execDEBUG_SIG); + addRecSignal(GSN_CONTINUEB, &Dbacc::execCONTINUEB); + addRecSignal(GSN_ACC_CHECK_SCAN, &Dbacc::execACC_CHECK_SCAN); + addRecSignal(GSN_EXPANDCHECK2, &Dbacc::execEXPANDCHECK2); + addRecSignal(GSN_SHRINKCHECK2, &Dbacc::execSHRINKCHECK2); + addRecSignal(GSN_READ_PSEUDO_REQ, &Dbacc::execREAD_PSEUDO_REQ); + + // Received signals + addRecSignal(GSN_STTOR, &Dbacc::execSTTOR); + addRecSignal(GSN_ACCKEYREQ, &Dbacc::execACCKEYREQ); + addRecSignal(GSN_ACCSEIZEREQ, &Dbacc::execACCSEIZEREQ); + addRecSignal(GSN_ACCFRAGREQ, &Dbacc::execACCFRAGREQ); + addRecSignal(GSN_NEXT_SCANREQ, &Dbacc::execNEXT_SCANREQ); + addRecSignal(GSN_ACC_ABORTREQ, &Dbacc::execACC_ABORTREQ); + addRecSignal(GSN_ACC_SCANREQ, &Dbacc::execACC_SCANREQ); + addRecSignal(GSN_ACCMINUPDATE, &Dbacc::execACCMINUPDATE); + addRecSignal(GSN_ACC_COMMITREQ, &Dbacc::execACC_COMMITREQ); + addRecSignal(GSN_ACC_TO_REQ, &Dbacc::execACC_TO_REQ); + addRecSignal(GSN_ACC_LOCKREQ, &Dbacc::execACC_LOCKREQ); + addRecSignal(GSN_NDB_STTOR, &Dbacc::execNDB_STTOR); + addRecSignal(GSN_DROP_TAB_REQ, &Dbacc::execDROP_TAB_REQ); + addRecSignal(GSN_READ_CONFIG_REQ, &Dbacc::execREAD_CONFIG_REQ, true); + addRecSignal(GSN_DROP_FRAG_REQ, &Dbacc::execDROP_FRAG_REQ); + + addRecSignal(GSN_DBINFO_SCANREQ, &Dbacc::execDBINFO_SCANREQ); + addRecSignal(GSN_NODE_STATE_REP, &Dbacc::execNODE_STATE_REP, true); + + initData(); + +#ifdef VM_TRACE + { + void* tmp[] = { &fragrecptr, + &operationRecPtr, + &queOperPtr, + &expPageptr, + &scanPtr, + &tabptr + }; + init_globals_list(tmp, sizeof(tmp)/sizeof(tmp[0])); + } +#endif +}//Dbacc::Dbacc() + +Dbacc::~Dbacc() +{ + deallocRecord((void **)&fragmentrec, "Fragmentrec", + sizeof(Fragmentrec), + cfragmentsize); + + deallocRecord((void **)&operationrec, "Operationrec", + sizeof(Operationrec), + coprecsize); + + deallocRecord((void **)&scanRec, "ScanRec", + sizeof(ScanRec), + cscanRecSize); + + deallocRecord((void **)&tabrec, "Tabrec", + sizeof(Tabrec), + ctablesize); + }//Dbacc::~Dbacc() + +BLOCK_FUNCTIONS(Dbacc) diff --git a/code/train/C++/0031123_sgu148.cpp b/code/train/C++/0031123_sgu148.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0aa8d3623386c922c212e8da5e50f233c957a3d --- /dev/null +++ b/code/train/C++/0031123_sgu148.cpp @@ -0,0 +1,72 @@ +/* SGU ID: #148 + * Type : Heap + Mathematics + * Author: Hangchen Yu + * Date : 03/06/2015 + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +typedef pair Pair; +#define INF 1000000000 + +int main() { + int n; + scanf("%d", &n); + long W[n+1], L[n+1], P[n+1]; + long SumOfWeight[n+1]; + memset(P, 0, sizeof(P)); + memset(SumOfWeight, 0, sizeof(SumOfWeight)); + for (int i = 1; i <= n; i++) { + scanf("%ld%ld%ld", W+i, L+i, P+i); + SumOfWeight[i] = SumOfWeight[i-1] + W[i]; + } + + priority_queue que, ans; + long best = INF, money = 0; + for (int i = n; i >= 1; i--) { + money += P[i]; + while (!que.empty() && que.top().first > SumOfWeight[i-1]) { + money -= P[que.top().second]; + que.pop(); + } + que.push(make_pair(SumOfWeight[i]-L[i], i)); + if (money < best) { + best = money; + ans = que; + } + } + + while (!ans.empty()) { + printf("%ld\n", ans.top().second); + ans.pop(); + } + + return 0; +} + + +/* + * Suppose the topest level (N is the lowest one) that terrorists + * need to depressurize is p. Then the p-level water must flow to + * the N-level, otherwise it makes no sense. So the levels which + * need to be depressurized are: + * {p} U {i | i>p, SumOfWeight[p~i]<=L[i]} + * Assume SumOfWeight[p] = W[1]+W[2]+...+W[p], then the expressi- + * on becomes + * {p} U {i | i>p, SumOfWeight[i]-SumOfWeight[p-1]<=L[i]} + * {p} U {i | i>p, SumOfWeight[i]-L[i]<=SumOfWeight[p-1]} + * Enumerate p and i, we get an O(N^2) algorithm. + * + * Notice that SumOfWeight[p-1] is increasing. If we enumerate p + * from N downto 1, on each step: + * 1. add p + * 2. delete i that SumOfWeight[i]-L[i] > SumOfWeight[p-1] + * We can use a heap to achieve such expression. + */ diff --git a/code/train/C++/0031570_subsets.cpp b/code/train/C++/0031570_subsets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ef01ce1d4d7cebc223d7b5dcd889700b0935e6e --- /dev/null +++ b/code/train/C++/0031570_subsets.cpp @@ -0,0 +1,70 @@ +#include "basic_includes.hpp" + +using namespace std; + +void print_res(const vector> &res); + +class Solution { + public: + vector> subsets_recur(const vector& nums, int idx) + { + if (idx == 0) + { + // Base case + vector> res; + vector val; + res.push_back(val); + val.push_back(nums[0]); + res.push_back(val); + return res; + } + else + { + auto res = subsets_recur(nums, idx - 1); + size_t original_size = res.size(); + for (size_t i = 0; i < original_size; i++) + { + auto new_val = res[i]; + new_val.push_back(nums[idx]); + res.push_back(new_val); + } + return res; + } + } + vector> subsets(vector& nums) { + sort(nums.begin(), nums.end()); + return subsets_recur(nums, nums.size() - 1); + } +}; + +void print_res(const vector> &res) +{ + for (auto subset: res) + { + cout << "["; + for (auto val: subset) + { + cout << val << ","; + } + cout << "]" << endl; + } +} + +void test(vector input) +{ + Solution sol; + auto res = sol.subsets(input); + cout << "test:\n"; + print_res(res); +} + +int main() +{ + vector input = {4, 2, 3}; + test(input); + vector input2 = {3}; + test(input2); + vector input3 = {1, 2, 3, 4, 5}; + test(input3); + return 0; +} diff --git a/code/train/C++/0031580_ops_dir.cpp b/code/train/C++/0031580_ops_dir.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89975e1c18ce834c7e98b2ad22224d99bfdebfd3 --- /dev/null +++ b/code/train/C++/0031580_ops_dir.cpp @@ -0,0 +1,115 @@ +/* + * Copyright 2009 Michael Stephens + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include + +#include "operations.h" +#include "options.h" +#include "utils.h" + +int gridfs_mkdir(const char* path, mode_t mode) { + path = fuse_to_mongo_path(path); + + auto sdc = make_ScopedDbConnection(); + mongo::DBClientBase &client = sdc->conn(); + + mongo::OID id; + id.init(); + fuse_context *context = fuse_get_context(); + + mongo::BSONObjBuilder file; + file << "_id" << id + << "filename" << path + << "chunkSize" << 0 + << "uploadDate" << mongo::DATENOW + << "md5" << 0 + << "mode" << (mode | S_IFDIR); + { + passwd *pw = getpwuid(context->uid); + if (pw) + file << "owner" << pw->pw_name; + } + { + group *gr = getgrgid(context->gid); + if (gr) + file << "group" << gr->gr_name; + } + + client.insert(db_name() + ".files", + file.obj()); + + return 0; +} + +int gridfs_rmdir(const char* path) { + auto sdc = make_ScopedDbConnection(); + mongo::GridFS gf = get_gridfs(sdc); + + path = fuse_to_mongo_path(path); + gf.removeFile(path); + + return 0; +} + +int gridfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { + path = fuse_to_mongo_path(path); + + filler(buf, ".", NULL, 0); + filler(buf, "..", NULL, 0); + + auto sdc = make_ScopedDbConnection(); + mongo::BSONObj proj = BSON("filename" << 1); + std::string path_start = path; + if (strlen(path) > 0) + path_start += "/"; + std::unique_ptr cursor = sdc->conn().query(db_name() + ".files", + BSON("filename" << + BSON("$regex" << "^" + path_start) + ), + 0, 0, + &proj); + std::string lastFN; + while (cursor->more()) { + std::string filename = cursor->next()["filename"].String(); + std::string rel = filename.substr(path_start.length()); + if (rel.find("/") != std::string::npos) + continue; + + /* If this filename matches the last filename we've seen, *do not* add it to the buffer because it's a duplicate filename */ + if (lastFN != filename) + filler(buf, rel.c_str(), NULL, 0); + + /* Update lastFN with our cursor's current filename */ + lastFN = filename; + fprintf(stderr, "DEBUG: %s\n", lastFN.c_str()); + } + + for (auto i : open_files) + if (i.first.find(path_start) == 0) { + std::string rel = i.first.substr(path_start.length()); + if (rel.find("/") != std::string::npos) + continue; + + filler(buf, i.first.c_str(), NULL, 0); + } + + return 0; +} + diff --git a/code/train/C++/0031772_anim_audio_view.cpp b/code/train/C++/0031772_anim_audio_view.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd4749968f3f115877835f9cb90c04dcbaf32b7b --- /dev/null +++ b/code/train/C++/0031772_anim_audio_view.cpp @@ -0,0 +1,100 @@ +/** + * Mandelbulber v2, a 3D fractal generator ,=#MKNmMMKmmßMNWy, + * ,B" ]L,,p%%%,,,§;, "K + * Copyright (C) 2016-18 Mandelbulber Team §R-==%w["'~5]m%=L.=~5N + * ,=mm=§M ]=4 yJKA"/-Nsaj "Bw,==,, + * This file is part of Mandelbulber. §R.r= jw",M Km .mM FW ",§=ß., ,TN + * ,4R =%["w[N=7]J '"5=],""]]M,w,-; T=]M + * Mandelbulber is free software: §R.ß~-Q/M=,=5"v"]=Qf,'§"M= =,M.§ Rz]M"Kw + * you can redistribute it and/or §w "xDY.J ' -"m=====WeC=\ ""%""y=%"]"" § + * modify it under the terms of the "§M=M =D=4"N #"%==A%p M§ M6 R' #"=~.4M + * GNU General Public License as §W =, ][T"]C § § '§ e===~ U !§[Z ]N + * published by the 4M",,Jm=,"=e~ § § j]]""N BmM"py=ßM + * Free Software Foundation, ]§ T,M=& 'YmMMpM9MMM%=w=,,=MT]M m§;'§, + * either version 3 of the License, TWw [.j"5=~N[=§%=%W,T ]R,"=="Y[LFT ]N + * or (at your option) TW=,-#"%=;[ =Q:["V"" ],,M.m == ]N + * any later version. J§"mr"] ,=,," =="""J]= M"M"]==ß" + * §= "=C=4 §"eM "=B:m|4"]#F,§~ + * Mandelbulber is distributed in "9w=,,]w em%wJ '"~" ,=,,ß" + * the hope that it will be useful, . "K= ,=RMMMßM""" + * 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 Mandelbulber. If not, see . + * + * ########################################################################### + * + * Authors: Krzysztof Marczak (buddhi1980@gmail.com) + * + * cAnimAudioView - promoted QWidget to display the animation curve extracted from + * the audio data and the audio settings + */ + +#include "anim_audio_view.h" + +#include + +#include "src/audio_track.h" + +cAnimAudioView::cAnimAudioView(QWidget *parent) : QWidget(parent) +{ + playbackPositionX = 0; + framesPerSecond = 30.0; +} + +cAnimAudioView::~cAnimAudioView() = default; + +void cAnimAudioView::UpdateChart(const QSharedPointer audioTrack) +{ + if (audioTrack && audioTrack->isLoaded()) + { + const int numberOfFrames = audioTrack->getNumberOfFrames(); + framesPerSecond = audioTrack->getFramesPerSecond(); + setFixedWidth(numberOfFrames); + + animAudioImage = QImage(QSize(numberOfFrames, height()), QImage::Format_RGB32); + animAudioImage.fill(Qt::black); + + QPainter painter(&animAudioImage); + + const int maxY = height() - 1; + QPoint prevPoint(0, maxY); + + painter.setPen(Qt::green); + painter.setRenderHint(QPainter::Antialiasing, true); + + for (int frame = 0; frame < numberOfFrames; frame++) + { + const QPoint point(frame, maxY - audioTrack->getAnimation(frame) * maxY); + painter.drawLine(prevPoint, point); + prevPoint = point; + } + update(); + } + else + { + animAudioImage = QImage(); + update(); + } +} + +void cAnimAudioView::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter painter(this); + painter.drawImage(0, 0, animAudioImage); + const QPen pen(QColor(255, 255, 255, 128)); + + painter.setPen(pen); + painter.drawLine(playbackPositionX, 0, playbackPositionX, height() - 1); +} + +void cAnimAudioView::positionChanged(qint64 position) +{ + const double time = position * 0.001; + playbackPositionX = time * framesPerSecond; + update(); +} diff --git a/code/train/C++/0031969_diamond_manager.cpp b/code/train/C++/0031969_diamond_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba97fa8740ff35d1f626f53811dea3ac958b9b4c --- /dev/null +++ b/code/train/C++/0031969_diamond_manager.cpp @@ -0,0 +1,257 @@ +/* + * (C) 2007-2013 Alibaba Group Holding Limited + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * + * Version: $Id: tair_mc_client_api.hpp 1245 2013-05-13 11:32:45Z huan.wanghuan@alibaba-inc.com $ + * + * Authors: + * yunhen + * + */ + +#include "diamond_manager.hpp" + +#include +#include +#include +#include +#include + +namespace tair{ + + using std::string; + + diamond_manager::diamond_manager(cluster_controller* a_controller) + { + listener = NULL; + config["diamond.invoke.timeout"] = "30"; // timeout,单位秒 + config["diamond.polling.interval"] = "5000000"; // 轮询间隔,单位纳秒,5ms = 5*1000*1000ns +// 容灾目录配置,默认是 ${HOME}/diamond +// config["diamond.localConfigDir"] = ... + diamond_client = new DIAMOND::DiamondClient(&config); + controller = a_controller; + } + + diamond_manager::~diamond_manager() + { + if (diamond_client) { + delete diamond_client; + diamond_client = NULL; + } + } + + void diamond_manager::set_net_device_name(const string& a_net_device_name) { + net_device_name = a_net_device_name; + } + + bool diamond_manager::connect(const string& a_config_id, DIAMOND::SubscriberListener *a_listener) + { + listener = a_listener; + config_id = a_config_id; + rule_group_id = config_id + "-GROUP"; + + string md5; + string rule_group_content; + string error; + string bad_content("config data not exist"); + if((!diamond_client->getConfig(config_id.c_str(), rule_group_id.c_str(), md5 ,rule_group_content, error)) + || (rule_group_content.compare(0, bad_content.size(), bad_content) == 0)) + { + TBSYS_LOG(ERROR, "can't get config info from the diamond dataId=%s, groupId=%s: %s", + config_id.c_str(), rule_group_id.c_str(), error.c_str()); + return false; + } + if (!update_data_group_id(rule_group_content)) + return false; + if (listener) + diamond_client->registerListener(config_id.c_str(), rule_group_id.c_str(), listener, md5); + return true; + } + + void diamond_manager::close() + { + diamond_client->shutdownListen(); + } + + const string& diamond_manager::get_config_id() + { + return config_id; + } + + const string& diamond_manager::get_rule_group_id() + { + return rule_group_id; + } + + const string& diamond_manager::get_data_group_id() + { + return data_group_id; + } + + bool diamond_manager::update_data_group_id(const string& rule_group_content) + { + vector rule_ip, rule_dest; + get_route_rule(rule_group_content, rule_ip, rule_dest); + vector local_ip; + if (!get_local_ip(local_ip)) + { + TBSYS_LOG(ERROR, "get local ip failed"); + return false; + } + string new_data_group_id; + if (!search_data_group(local_ip, rule_ip, rule_dest, new_data_group_id)) + { + TBSYS_LOG(ERROR, "get diamond data group id failed, you ip doesn't match any group rule"); + return false; + } + + if (new_data_group_id.empty()) + { + TBSYS_LOG(ERROR, "get diamond data group id failed, you rule group config is invalid"); + return false; + } + //rule group改变了,本机 对应的data group未变的话,直接返回 + if (!(new_data_group_id != data_group_id)) + { + TBSYS_LOG(INFO, "data group id doesn't change"); + return true; + } + + string md5, data_group_content, error; + string bad_content("config data not exist"); + if ((!diamond_client->getConfig(config_id.c_str(), new_data_group_id.c_str(), md5, data_group_content, error)) + || (data_group_content.compare(0, bad_content.size(), bad_content) == 0)) + { + TBSYS_LOG(ERROR, "can't get config info from the diamond dataId=%s, groupId=%s: %s", + config_id.c_str(), new_data_group_id.c_str(), error.c_str()); + return false; + } + + if (!update_config(data_group_content)) + { + TBSYS_LOG(ERROR, "using config info of diamond dataId=%s, groupId=%s to update tair configserver failed", + config_id.c_str(), new_data_group_id.c_str()); + return false; + } + + if (listener) + { + if(!data_group_id.empty()) + diamond_client->removeListener(config_id.c_str(), data_group_id.c_str()); + diamond_client->registerListener(config_id.c_str(), new_data_group_id.c_str(), listener, md5); + } + + data_group_id = new_data_group_id; + + return true; + } + + bool diamond_manager::update_config(const string& json) + { + if (!controller) + { + TBSYS_LOG(ERROR, "cluster_controller == NULL"); + return false; + } + return controller->update_config(json); + } + + void diamond_manager::get_route_rule(const string& group_rule, vector& rule_ip, vector& rule_dest) + { + istringstream group_rule_in(group_rule); + while(true) + { + string one_line; + if (!getline(group_rule_in, one_line)) + break; + + string::size_type pos = one_line.find_first_of('='); + if (string::npos == pos) + continue; + + string ip(one_line, 0, pos); + string dest(one_line, pos + 1); + + string::size_type begin_ip = ip.find_first_not_of(" \r\t"); + if (string::npos == begin_ip) + continue; + string::size_type end_ip = ip.find_last_not_of(" \r\t"); + + + string::size_type begin_dest = dest.find_first_not_of(" \r\t"); + if (string::npos == begin_dest) + continue; + string::size_type end_dest = dest.find_last_not_of(" \r\t"); + + rule_ip.push_back(ip.substr(begin_ip, end_ip - begin_ip + 1)); + rule_dest.push_back(dest.substr(begin_dest, end_dest - begin_dest + 1)); + } + } + + bool diamond_manager::get_local_ip(vector& ip) + { + struct ifaddrs *ifaddr, *ifa; + int family, s; + char host[NI_MAXHOST]; + + if (getifaddrs(&ifaddr) == -1) + return false; + /* Walk through linked list, maintaining head pointer so we + can free list later */ + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + if (!ifa->ifa_addr) + continue; + family = ifa->ifa_addr->sa_family; + if (family == AF_INET && strcmp(ifa->ifa_name, "lo") != 0) + { + s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); + if (s) + continue; + //若设置了net_device_name, 只取net_device_name对应的ip; 否则取所有ipv4的ip(回环除外) + if (net_device_name.empty()) + ip.push_back(host); + else + { + if(ifa->ifa_name == net_device_name) + { + ip.push_back(host); + break; + } + } + } + } // end of for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + freeifaddrs(ifaddr); + return true; + } + + // 对于多个本地ip,若与分组规则都有匹配,选匹配分组最靠前的。 + // 例如,ipA 匹配了 第1个分组,ipB 匹配了 第4个分组,则选择 第1个分组规则。 + bool diamond_manager::search_data_group(const vector& local_ip, const vector& rule_ip, + const vector& rule_dest, string& data_group_id) + { + vector::size_type min = rule_ip.size(); + for (vector::const_iterator ip_iter = local_ip.begin(); ip_iter != local_ip.end(); ++ip_iter) + { + vector::size_type number = 0; + for(vector::const_iterator rule_ip_iter = rule_ip.begin(); rule_ip_iter != rule_ip.end(); ++rule_ip_iter) + { + if (ip_iter->compare(0, rule_ip_iter->size(), *rule_ip_iter) == 0) + { + if (number < min) + min = number; + break; + } + ++number; + } + }// end of for (vector::const_iterator ip_iter; ip_iter != local_ip.end(); ++ip_iter) + if (rule_ip.size() == min) + return false; + data_group_id = rule_dest[min]; + return true; + } +} diff --git a/code/train/C++/0032568_governancepage.cpp b/code/train/C++/0032568_governancepage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61156f5077b2b5765fd0919a17382da39a4d472c --- /dev/null +++ b/code/train/C++/0032568_governancepage.cpp @@ -0,0 +1,148 @@ +// Copyright (c) 2018-2019 The NPCcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "governancepage.h" +#include "ui_governancepage.h" + +#include "activemasternode.h" +#include "chainparams.h" +#include "clientmodel.h" +#include "masternode-budget.h" +#include "masternode-sync.h" +#include "masternodeconfig.h" +#include "masternodeman.h" +#include "utilmoneystr.h" +#include "walletmodel.h" +#include "askpassphrasedialog.h" +#include "proposalframe.h" + +#include +#include +#include +#include + +GovernancePage::GovernancePage(QWidget* parent) : QWidget(parent), + ui(new Ui::GovernancePage), + clientModel(0), + walletModel(0) +{ + ui->setupUi(this); + + timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(updateProposalList())); + timer->start(100000); + fLockUpdating = false; +} + + +GovernancePage::~GovernancePage() +{ + delete ui; +} + +void GovernancePage::setClientModel(ClientModel* model) +{ + this->clientModel = model; +} + +void GovernancePage::setWalletModel(WalletModel* model) +{ + this->walletModel = model; +} + +void GovernancePage::lockUpdating(bool lock) +{ + fLockUpdating = lock; +} + +struct sortProposalsByVotes +{ + bool operator() (const CBudgetProposal* left, const CBudgetProposal* right) + { + if (left != right) + return (left->GetYeas() - left->GetNays() > right->GetYeas() - right->GetNays()); + return (left->nFeeTXHash > right->nFeeTXHash); + } +}; + +void GovernancePage::updateProposalList() +{ + if (fLockUpdating) return; + + QLayoutItem* child; + while ((child = ui->proposalGrid->takeAt(0)) != 0) { + if (child->widget() != 0) + { + delete child->widget(); + } + delete child; + } + + std::vector allotedProposals = budget.GetBudget(); + CAmount nTotalAllotted = 0; + std::vector proposalsList = budget.GetAllProposals(); + std::sort (proposalsList.begin(), proposalsList.end(), sortProposalsByVotes()); + int nRow = 0; + CBlockIndex* pindexPrev; + { + LOCK(cs_main); + pindexPrev = chainActive.Tip(); + } + if (!pindexPrev) return; + int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % Params().GetBudgetCycleBlocks() + Params().GetBudgetCycleBlocks(); + int nBlocksLeft = nBlockStart - pindexPrev->nHeight; + int nBlockEnd = nBlockStart + Params().GetBudgetCycleBlocks() - 1; + int mnCount = mnodeman.CountEnabled(ActiveProtocol()); + + for (CBudgetProposal* pbudgetProposal : proposalsList) { + if (!pbudgetProposal->fValid) continue; + if (pbudgetProposal->GetRemainingPaymentCount() < 1) continue; + + ProposalFrame* proposalFrame = new ProposalFrame(); + proposalFrame->setWalletModel(walletModel); + proposalFrame->setProposal(pbudgetProposal); + proposalFrame->setGovernancePage(this); + + if (std::find(allotedProposals.begin(), allotedProposals.end(), pbudgetProposal) != allotedProposals.end()) { + nTotalAllotted += pbudgetProposal->GetAllotted(); + proposalFrame->setObjectName(QStringLiteral("proposalFramePassing")); + } else if (!pbudgetProposal->IsEstablished()) { + proposalFrame->setObjectName(QStringLiteral("proposalFrameNotEstablished")); + } else if (pbudgetProposal->IsPassing(pindexPrev, nBlockStart, nBlockEnd, mnCount)) { + proposalFrame->setObjectName(QStringLiteral("proposalFramePassingUnfunded")); + } else { + proposalFrame->setObjectName(QStringLiteral("proposalFrame")); + } + proposalFrame->setFrameShape(QFrame::StyledPanel); + + if (extendedProposal == pbudgetProposal) + proposalFrame->extend(); + proposalFrame->setMaximumHeight(150); + ui->proposalGrid->addWidget(proposalFrame, nRow); + + ++nRow; + } + + ui->next_superblock_value->setText(QString::number(nBlockStart)); + ui->blocks_before_super_value->setText(QString::number(nBlocksLeft)); + ui->time_before_super_value->setText(QString::number(nBlocksLeft/60/24)); + ui->alloted_budget_value->setText(QString::number(nTotalAllotted/COIN)); + ui->unallocated_budget_value->setText(QString::number((budget.GetTotalBudget(pindexPrev->nHeight) - nTotalAllotted)/COIN)); + ui->masternode_count_value->setText(QString::number(mnodeman.CountEnabled(ActiveProtocol()))); +} + +void GovernancePage::setExtendedProposal(CBudgetProposal* proposal) +{ + bool update = false; + if (extendedProposal != proposal) + update = true; + extendedProposal = proposal; + if (update) + updateProposalList(); +} + +void GovernancePage::on_UpdateButton_clicked() +{ + updateProposalList(); +} diff --git a/code/train/C++/0032966_workload-stat.cpp b/code/train/C++/0032966_workload-stat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c20ae1aea05fbfdd8d108b44aeccc127e4dc02f --- /dev/null +++ b/code/train/C++/0032966_workload-stat.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#define SCALE_FACTOR 100 + +#include "workload.h" + +bool histogram = true; + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + fprintf(stderr, "stat file\n"); + exit(1); + } + + char *name = argv[1]; + int fd = open(name, O_RDONLY); + if (fd < 0) { + perror("open"); + exit(1); + } + + /* get the file size */ + struct stat stats; + if (fstat(fd, &stats) < 0) { + perror("fstat"); + exit(1); + } + long file_size = stats.st_size; + + /* the numbers of accesses of each page */ + int num_accesses = (int) (file_size / sizeof(workload_t)); + workload_t *workloads = new workload_t[num_accesses]; + read(fd, (void *) workloads, file_size); + + std::unordered_map page_map; + int num_page_reads = 0; + int num_page_writes = 0; + int num_reads = 0; + int num_writes = 0; + size_t read_size = 0; + size_t write_size = 0; + int max_size = 0; + int min_size = INT_MAX; + long tot_size = 0; + off_t min_off = LONG_MAX; + off_t max_off = 0; + for (int i = 0; i < num_accesses; i++) { + if (min_off > workloads[i].off) + min_off = workloads[i].off; + if (max_off < workloads[i].off) + max_off = workloads[i].off; + off_t page_off = ROUND_PAGE(workloads[i].off); + if (max_size < workloads[i].size) + max_size = workloads[i].size; + if (min_size > workloads[i].size) + min_size = workloads[i].size; + tot_size += workloads[i].size; + off_t last_page = ROUNDUP_PAGE(workloads[i].off + workloads[i].size); + int num_pages = (last_page - page_off) / safs::PAGE_SIZE; + for (; page_off < last_page; page_off += safs::PAGE_SIZE) { + std::unordered_map::iterator it = page_map.find(page_off); + if (it == page_map.end()) { + page_map.insert(std::pair(page_off, 1)); + } + else + it->second++; + } + if (workloads[i].read) { + num_page_reads += num_pages; + num_reads++; + read_size += workloads[i].size; + } + else { + num_page_writes += num_pages; + num_writes++; + write_size += workloads[i].size; + } + } + + if (histogram) { + std::map count_nums; + for (std::unordered_map::iterator it = page_map.begin(); + it != page_map.end(); it++) { + int num_accesses = it->second; + std::map::iterator it1 = count_nums.find(num_accesses); + if (it1 != count_nums.end()) + it1->second++; + else + count_nums.insert(std::pair(num_accesses, 1)); + } + for (std::map::const_iterator it = count_nums.begin(); + it != count_nums.end(); it++) { + printf("%d pages get %d hits\n", it->second, it->first); + } + } + printf("min request size: %d, max req size: %d, avg size: %ld\n", + min_size, max_size, tot_size / num_accesses); + printf("min off: %ld, max off: %ld\n", min_off, max_off); + printf("there are %d accesses\n", num_accesses); + printf("there are %d reads and %d writes\n", num_reads, num_writes); + printf("there are %d reads in pages, %d writes in pages\n", + num_page_reads, num_page_writes); + printf("read %ld in bytes and write %ld in bytes\n", read_size, write_size); + printf("there are %ld accessed pages\n", page_map.size()); +} diff --git a/code/train/C++/0032990_3-longest-substring-without-repeating-characters.cpp b/code/train/C++/0032990_3-longest-substring-without-repeating-characters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3e0de2e51cbe7f27f4da8a182eff08f1cf1ca18 --- /dev/null +++ b/code/train/C++/0032990_3-longest-substring-without-repeating-characters.cpp @@ -0,0 +1,66 @@ +#include +#include + +using namespace std; +/* +class Solution { +public: + int lengthOfLongestSubstring(string s) { + int max_length = 0; + int length = 0; + int pos = 0; + vector set; + set.reserve(256); // note, input source like " " so reserve 2^8 for char + for (int i = 0; i < s.length(); i++) { + int idxInSet = char2int(s[i]); + while (pos < i && set[idxInSet] == 1) { + int delIdx = char2int(s[pos]); + set[delIdx] = 0; + length -= 1; + pos += 1; + } + set[idxInSet] = 1; + length += 1; + if (length > max_length) { + max_length = length; + } + + } + return max_length; + } + + int char2int(char ch) { + return int(ch); + } + +}; + +*/ + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + if (s.size() == 0) return 0; + int res = 0; + int counter[256] = {0}; + int start_idx = 0; + for (int i = 0; i < s.size(); i++) { + while(counter[s[i]] != 0 && start_idx < i) { + counter[s[start_idx]] -= 1; + start_idx += 1; + } + counter[s[i]] += 1; + res = max(res, i - start_idx + 1); + } + return res; + } +}; + +int main() { + Solution s; + cout << s.char2int('a') << endl; + cout << s.lengthOfLongestSubstring("abcabcbb") << endl; + cout << s.lengthOfLongestSubstring("bbbbb") << endl; + cout << s.lengthOfLongestSubstring("pwwkew") << endl; + return 0; +} diff --git a/code/train/C++/0033091_Logger.cpp b/code/train/C++/0033091_Logger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebfd09d56e3424933aaef95f97f992496fbc08ae --- /dev/null +++ b/code/train/C++/0033091_Logger.cpp @@ -0,0 +1,258 @@ +/* + Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2016 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + 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 "Internal.hpp" +#include "NanoLogger.hpp" +#include "Protocol.hpp" +#include "Convert.hpp" +#include "Device/Port/Port.hpp" +#include "Device/RecordedFlight.hpp" +#include "Operation/Operation.hpp" +#include "OS/ByteOrder.hpp" +#include "OS/Path.hpp" +#include "IO/BufferedOutputStream.hxx" +#include "IO/FileOutputStream.hxx" +#include "Util/ScopeExit.hxx" + +#include + +#include +#include + +static bool +ParseDate(BrokenDate &date, const char *p) +{ + char *endptr; + unsigned long l = strtoul(p, &endptr, 10); + if (l < 1 || l > 31 || *endptr != '.') + return false; + + date.day = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l < 1 || l > 12 || *endptr != '.') + return false; + + date.month = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 100 || *endptr != 0) + return false; + + date.year = 2000 + l; // Y2100 problem + return true; +} + +static bool +ParseTime(BrokenTime &time, const char *p) +{ + char *endptr; + unsigned long l = strtoul(p, &endptr, 10); + if (l >= 24 || *endptr != ':') + return false; + + time.hour = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 60 || *endptr != ':') + return false; + + time.minute = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 60 || *endptr != 0) + return false; + + time.second = l; + return true; +} + +static bool +Copy(RecordedFlightInfo &dest, const LX::FlightInfo &src) +{ + if (!ParseDate(dest.date, src.date) || + !ParseTime(dest.start_time, src.start_time) || + !ParseTime(dest.end_time, src.stop_time)) + return false; + + /* not a Nano recording */ + dest.internal.lx.nano_filename[0] = 0; + + dest.internal.lx.start_address[0] = src.start_address.address0; + dest.internal.lx.start_address[1] = src.start_address.address1; + dest.internal.lx.start_address[2] = src.start_address.address2; + dest.internal.lx.end_address[0] = src.end_address.address0; + dest.internal.lx.end_address[1] = src.end_address.address1; + dest.internal.lx.end_address[2] = src.end_address.address2; + + return true; +} + +static bool +ReadFlightListInner(Port &port, RecordedFlightList &flight_list, + OperationEnvironment &env) +{ + if (!LX::CommandMode(port, env)) + return false; + + port.Flush(); + if (!LX::SendCommand(port, LX::READ_FLIGHT_LIST)) + return false; + + bool success = false; + while (!flight_list.full()) { + LX::FlightInfo flight; + if (!LX::ReadCRC(port, &flight, sizeof(flight), env, + std::chrono::seconds(20), + std::chrono::seconds(2), + std::chrono::minutes(3))) + break; + + success = true; + if (!flight.IsValid()) + break; + + RecordedFlightInfo dest; + if (Copy(dest, flight)) + flight_list.append(dest); + } + + return success; +} + +bool +LXDevice::ReadFlightList(RecordedFlightList &flight_list, + OperationEnvironment &env) +{ + if (IsNano()) { + if (!EnableNanoNMEA(env)) + return false; + + assert(!busy); + busy = true; + AtScopeExit(this) { busy = false; }; + + return Nano::ReadFlightList(port, flight_list, env); + } + + if (!EnableCommandMode(env)) + return false; + + assert(!busy); + busy = true; + AtScopeExit(this) { busy = false; }; + + bool success = ReadFlightListInner(port, flight_list, env); + + LX::CommandModeQuick(port, env); + return success; +} + +static bool +DownloadFlightInner(Port &port, const RecordedFlightInfo &flight, + BufferedOutputStream &os, OperationEnvironment &env) +{ + if (!LX::CommandMode(port, env)) + return false; + + port.Flush(); + + LX::SeekMemory seek; + seek.start_address = flight.internal.lx.start_address; + seek.end_address = flight.internal.lx.end_address; + if (!LX::SendPacket(port, LX::SEEK_MEMORY, &seek, sizeof(seek), env) || + !LX::ExpectACK(port, env)) + return false; + + LX::MemorySection memory_section; + if (!LX::ReceivePacketRetry(port, LX::READ_MEMORY_SECTION, + &memory_section, sizeof(memory_section), env, + std::chrono::seconds(5), + std::chrono::seconds(2), + std::chrono::minutes(1), 2)) + return false; + + unsigned lengths[LX::MemorySection::N]; + unsigned total_length = 0; + for (unsigned i = 0; i < LX::MemorySection::N; ++i) { + lengths[i] = FromBE16(memory_section.lengths[i]); + total_length += lengths[i]; + } + + env.SetProgressRange(total_length); + + const auto data = std::make_unique(total_length); + uint8_t *p = data.get(); + for (unsigned i = 0; i < LX::MemorySection::N && lengths[i] > 0; ++i) { + if (!LX::ReceivePacketRetry(port, (LX::Command)(LX::READ_LOGGER_DATA + i), + p, lengths[i], env, + std::chrono::seconds(20), + std::chrono::seconds(2), + std::chrono::minutes(5), 2)) { + return false; + } + + p += lengths[i]; + env.SetProgressPosition(p - data.get()); + } + + return LX::ConvertLXNToIGC(data.get(), total_length, os); +} + +bool +LXDevice::DownloadFlight(const RecordedFlightInfo &flight, + Path path, + OperationEnvironment &env) +{ + if (flight.internal.lx.nano_filename[0] != 0) { + assert(!busy); + busy = true; + AtScopeExit(this) { busy = false; }; + + return Nano::DownloadFlight(port, flight, path, env); + } + + if (!EnableCommandMode(env)) + return false; + + FileOutputStream fos(path); + BufferedOutputStream bos(fos); + + assert(!busy); + busy = true; + AtScopeExit(this) { busy = false; }; + + bool success = DownloadFlightInner(port, flight, bos, env); + + if (success) { + bos.Flush(); + fos.Commit(); + } + + LX::CommandModeQuick(port, env); + return success; +} diff --git a/code/train/C++/0033274_GeometryClamper.cpp b/code/train/C++/0033274_GeometryClamper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..686a434ee040425c7072e09fd4fec8ec90ba39bc --- /dev/null +++ b/code/train/C++/0033274_GeometryClamper.cpp @@ -0,0 +1,198 @@ +/* -*-c++-*- */ +/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph + * Copyright 2016 Pelican Mapping + * http://osgearth.org + * + * osgEarth is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see + */ +#include + +#include + +#include +#include +#include + +#define LC "[GeometryClamper] " + +using namespace osgEarth; + +#define ZOFFSETS_NAME "GeometryClamper::zOffsets" + +//----------------------------------------------------------------------- + +GeometryClamper::GeometryClamper() : +osg::NodeVisitor( osg::NodeVisitor::TRAVERSE_ALL_CHILDREN ), +_preserveZ ( false ), +_scale ( 1.0f ), +_offset ( 0.0f ) +{ + this->setNodeMaskOverride( ~0 ); + _lsi = new osgEarth::DPLineSegmentIntersector(osg::Vec3d(0,0,0), osg::Vec3d(0,0,0)); +} + +void +GeometryClamper::apply(osg::Transform& xform) +{ + osg::Matrixd matrix; + if ( !_matrixStack.empty() ) matrix = _matrixStack.back(); + xform.computeLocalToWorldMatrix( matrix, this ); + _matrixStack.push_back( matrix ); + traverse(xform); + _matrixStack.pop_back(); +} + +void +GeometryClamper::apply(osg::Geode& geode) +{ + if ( !_terrainSRS.valid() ) + return; + + const osg::Matrixd& local2world = _matrixStack.back(); + osg::Matrix world2local; + world2local.invert( local2world ); + + const osg::EllipsoidModel* em = _terrainSRS->getEllipsoid(); + osg::Vec3d n_vector(0,0,1), start, end, msl; + + bool isGeocentric = _terrainSRS->isGeographic(); + + osgUtil::IntersectionVisitor iv( _lsi.get() ); + + double r = std::min( em->getRadiusEquator(), em->getRadiusPolar() ); + + unsigned count = 0; + + for( unsigned i=0; iasGeometry(); + if ( geom ) + { + osg::Vec3Array* verts = static_cast(geom->getVertexArray()); + osg::FloatArray* zOffsets = 0L; + + // if preserve-Z is on, check for our elevations array. Create it if is doesn't + // already exist. + bool buildZOffsets = false; + if ( _preserveZ ) + { + osg::UserDataContainer* udc = geom->getOrCreateUserDataContainer(); + unsigned n = udc->getUserObjectIndex( ZOFFSETS_NAME ); + if ( n < udc->getNumUserObjects() ) + { + zOffsets = dynamic_cast(udc->getUserObject(n)); + } + + else + { + zOffsets = new osg::FloatArray(); + zOffsets->setName( ZOFFSETS_NAME ); + zOffsets->reserve( verts->size() ); + udc->addUserObject( zOffsets ); + buildZOffsets = true; + } + } + + for( unsigned k=0; ksize(); ++k ) + { + osg::Vec3d vw = (*verts)[k]; + vw = vw * local2world; + + if ( isGeocentric ) + { + // normal to the ellipsoid: + n_vector = em->computeLocalUpVector(vw.x(),vw.y(),vw.z()); + + // if we need to build to z-offsets array, calculate the z offset now: + if ( buildZOffsets || _scale != 1.0 ) + { + double lat,lon,hae; + em->convertXYZToLatLongHeight(vw.x(), vw.y(), vw.z(), lat, lon, hae); + + if ( buildZOffsets ) + { + zOffsets->push_back( (*verts)[k].z() ); + } + + if ( _scale != 1.0 ) + { + msl = vw - n_vector*hae; + } + } + } + + else if ( buildZOffsets ) // flat map + { + zOffsets->push_back( float(vw.z()) ); + } + + _lsi->reset(); + _lsi->setStart( vw + n_vector*r*_scale ); + _lsi->setEnd( vw - n_vector*r ); + _lsi->setIntersectionLimit( _lsi->LIMIT_NEAREST ); + + _terrainPatch->accept( iv ); + + if ( _lsi->containsIntersections() ) + { + osg::Vec3d fw = _lsi->getFirstIntersection().getWorldIntersectPoint(); + if ( _scale != 1.0 ) + { + osg::Vec3d delta = fw - msl; + fw += delta*_scale; + } + if ( _offset != 0.0 ) + { + fw += n_vector*_offset; + } + if ( _preserveZ && (zOffsets != 0L) ) + { + fw += n_vector * (*zOffsets)[k]; + } + + (*verts)[k] = (fw * world2local); + geomDirty = true; + ++count; + } + } + + if ( geomDirty ) + { + geom->dirtyBound(); + if ( geom->getUseVertexBufferObjects() ) + { + verts->getVertexBufferObject()->setUsage( GL_DYNAMIC_DRAW_ARB ); + verts->dirty(); + } + else + { + geom->dirtyDisplayList(); + } + } + } + + OE_DEBUG << LC << "clamped " << count << " verts." << std::endl; + } +} + + + +void +GeometryClamperCallback::onTileAdded(const TileKey& key, + osg::Node* tile, + TerrainCallbackContext& context) +{ + tile->accept( _clamper ); +} diff --git a/code/train/C++/0035216_raycast.cpp b/code/train/C++/0035216_raycast.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78d7df683114a01f1274018d21ef54405bcbd5e8 --- /dev/null +++ b/code/train/C++/0035216_raycast.cpp @@ -0,0 +1,200 @@ +/* + This file is part of Warzone 2100. + Copyright (C) 1999-2004 Eidos Interactive + Copyright (C) 2005-2013 Warzone 2100 Project + + Warzone 2100 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. + + Warzone 2100 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 Warzone 2100; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +/** + * @file raycast.cpp + * + * Raycasting routine that gives intersection points with map tiles. + * + */ + +#include "lib/framework/frame.h" + +#include "raycast.h" +#include "map.h" // TILE_UNITS +#include "display3d.h" // clipXY() + +struct HeightCallbackHelp_t +{ + const int height; + uint16_t pitch; +}; + +static void initSteps(int32_t srcM, int32_t dstM, int32_t &tile, int32_t &step, int32_t &cur, int32_t &end) +{ + int increasing = srcM < dstM; + step = -1 + 2*increasing; + tile = srcM - step; + cur = srcM + increasing; + end = dstM + increasing; +} + +// Finds the next intersection of the line with a vertical grid line (or with a horizontal grid line, if called with x and y swapped). +static bool tryStep(int32_t &tile, int32_t step, int32_t &cur, int32_t end, int32_t &px, int32_t &py, int32_t sx, int32_t sy, int32_t dx, int32_t dy) +{ + tile += step; + + if (cur == end) + { + return false; // No more vertical grid lines to cross before reaching the endpoint. + } + + // Find the point on the line with the x coordinate world_coord(cur). + px = world_coord(cur); + py = sy + int64_t(px - sx) * (dy - sy)/(dx - sx); + + cur += step; + return true; +} + +void rayCast(Vector2i src, Vector2i dst, RAY_CALLBACK callback, void *data) +{ + if (!callback(src, 0, data) || src == dst) // Start at src. + { + return; // Callback gave up after the first point, or there are no other points. + } + + Vector2i srcM = map_coord(src); + Vector2i dstM = map_coord(dst); + + Vector2i step, tile, cur, end; + initSteps(srcM.x, dstM.x, tile.x, step.x, cur.x, end.x); + initSteps(srcM.y, dstM.y, tile.y, step.y, cur.y, end.y); + + Vector2i prev(0, 0); // Dummy initialisation. + bool first = true; + Vector2i nextX(0, 0), nextY(0, 0); // Dummy initialisations. + bool canX = tryStep(tile.x, step.x, cur.x, end.x, nextX.x, nextX.y, src.x, src.y, dst.x, dst.y); + bool canY = tryStep(tile.y, step.y, cur.y, end.y, nextY.y, nextY.x, src.y, src.x, dst.y, dst.x); + while (canX || canY) + { + int32_t xDist = abs(nextX.x - src.x) + abs(nextX.y - src.y); + int32_t yDist = abs(nextY.x - src.x) + abs(nextY.y - src.y); + Vector2i sel; + Vector2i selTile; + if (canX && (!canY || xDist < yDist)) // The line crosses a vertical grid line next. + { + sel = nextX; + selTile = tile; + canX = tryStep(tile.x, step.x, cur.x, end.x, nextX.x, nextX.y, src.x, src.y, dst.x, dst.y); + } + else // The line crosses a horizontal grid line next. + { + assert(canY); + sel = nextY; + selTile = tile; + canY = tryStep(tile.y, step.y, cur.y, end.y, nextY.y, nextY.x, src.y, src.x, dst.y, dst.x); + } + if (!first) + { + // Find midpoint. + Vector2i avg = (prev + sel)/2; + // But make sure it's on the right tile, since it could be off-by-one if the line passes exactly through a grid intersection. + avg.x = std::min(std::max(avg.x, world_coord(selTile.x)), world_coord(selTile.x + 1) - 1); + avg.y = std::min(std::max(avg.y, world_coord(selTile.y)), world_coord(selTile.y + 1) - 1); + if (!worldOnMap(avg) || !callback(avg, iHypot(avg), data)) + { + return; // Callback doesn't want any more points, or we reached the edge of the map, so return. + } + } + prev = sel; + first = false; + } + + // Include the endpoint. + if (!worldOnMap(dst)) + { + return; // Stop, since reached the edge of the map. + } + callback(dst, iHypot(dst), data); +} + +//----------------------------------------------------------------------------------- +/* Will return false when we've hit the edge of the grid */ +static bool getTileHeightCallback(Vector2i pos, int32_t dist, void *data) +{ + HeightCallbackHelp_t *help = (HeightCallbackHelp_t *)data; +#ifdef TEST_RAY + Vector3i effect; +#endif + + /* Are we still on the grid? */ + if (clipXY(pos.x, pos.y)) + { + bool HasTallStructure = blockTile(map_coord(pos.x), map_coord(pos.y), AUX_MAP) & AIR_BLOCKED; + + if (dist > TILE_UNITS || HasTallStructure) + { + // Only do it the current tile is > TILE_UNITS away from the starting tile. Or.. + // there is a tall structure on the current tile and the current tile is not the starting tile. + /* Get height at this intersection point */ + int height = map_Height(pos.x, pos.y), heightDiff; + uint16_t newPitch; + + if (HasTallStructure) + { + height += TALLOBJECT_ADJUST; + } + + if (height <= help->height) + { + heightDiff = 0; + } + else + { + heightDiff = height - help->height; + } + + /* Work out the angle to this point from start point */ + newPitch = iAtan2(heightDiff, dist); + + /* Is this the steepest we've found? */ + if (angleDelta(newPitch - help->pitch) > 0) + { + /* Yes, then keep a record of it */ + help->pitch = newPitch; + } + //--- + +#ifdef TEST_RAY + effect.x = pos.x; + effect.y = height; + effect.z = pos.y; + addEffect(&effect, EFFECT_EXPLOSION, EXPLOSION_TYPE_SMALL, false, NULL, 0); +#endif + } + + /* Not at edge yet - so exit */ + return true; + } + + /* We've hit edge of grid - so exit!! */ + return false; +} + +void getBestPitchToEdgeOfGrid(UDWORD x, UDWORD y, uint16_t direction, uint16_t *pitch) +{ + HeightCallbackHelp_t help = {map_Height(x,y), 0}; + + Vector3i src(x, y, 0); + Vector3i delta(iSinCosR(direction, 5430), 0); + rayCast(src, src + delta, getTileHeightCallback, &help); // FIXME Magic value + + *pitch = help.pitch; +} diff --git a/code/train/C++/0035891_stickman.cpp b/code/train/C++/0035891_stickman.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa6838d4364927d4aed578de93c160f19cbdd65b --- /dev/null +++ b/code/train/C++/0035891_stickman.cpp @@ -0,0 +1,337 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Digia Plc and its Subsidiary(-ies) 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 +** 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "stickman.h" +#include "node.h" + +#include +#include + +#define _USE_MATH_DEFINES +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +static const qreal Coords[NodeCount * 2] = { + 0.0, -150.0, // head, #0 + + 0.0, -100.0, // body pentagon, top->bottom, left->right, #1 - 5 + -50.0, -50.0, + 50.0, -50.0, + -25.0, 50.0, + 25.0, 50.0, + + -100.0, 0.0, // right arm, #6 - 7 + -125.0, 50.0, + + 100.0, 0.0, // left arm, #8 - 9 + 125.0, 50.0, + + -35.0, 75.0, // lower body, #10 - 11 + 35.0, 75.0, + + -25.0, 200.0, // right leg, #12 - 13 + -30.0, 300.0, + + 25.0, 200.0, // left leg, #14 - 15 + 30.0, 300.0 + +}; + +static const int Bones[BoneCount * 2] = { + 0, 1, // neck + + 1, 2, // body + 1, 3, + 1, 4, + 1, 5, + 2, 3, + 2, 4, + 2, 5, + 3, 4, + 3, 5, + 4, 5, + + 2, 6, // right arm + 6, 7, + + 3, 8, // left arm + 8, 9, + + 4, 10, // lower body + 4, 11, + 5, 10, + 5, 11, + 10, 11, + + 10, 12, // right leg + 12, 13, + + 11, 14, // left leg + 14, 15 + +}; + +StickMan::StickMan() +{ + m_sticks = true; + m_isDead = false; + m_pixmap = QPixmap("images/head.png"); + m_penColor = Qt::white; + m_fillColor = Qt::black; + + // Set up start position of limbs + for (int i=0; ipos() - node2->pos(); + m_perfectBoneLengths[i] = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); + } + + startTimer(10); +} + +StickMan::~StickMan() +{ +} + +void StickMan::childPositionChanged() +{ + prepareGeometryChange(); +} + +void StickMan::setDrawSticks(bool on) +{ + m_sticks = on; + for (int i=0;isetVisible(on); + } +} + +QRectF StickMan::boundingRect() const +{ + // account for head radius=50.0 plus pen which is 5.0 + return childrenBoundingRect().adjusted(-55.0, -55.0, 55.0, 55.0); +} + +int StickMan::nodeCount() const +{ + return NodeCount; +} + +Node *StickMan::node(int idx) const +{ + if (idx >= 0 && idx < NodeCount) + return m_nodes[idx]; + else + return 0; +} + +void StickMan::timerEvent(QTimerEvent *) +{ + update(); +} + +void StickMan::stabilize() +{ + static const qreal threshold = 0.001; + + for (int i=0; ipos(); + QPointF pos2 = node2->pos(); + + QPointF dist = pos1 - pos2; + qreal length = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); + qreal diff = (length - m_perfectBoneLengths[i]) / length; + + QPointF p = dist * (0.5 * diff); + if (p.x() > threshold && p.y() > threshold) { + pos1 -= p; + pos2 += p; + + node1->setPos(pos1); + node2->setPos(pos2); + } + } +} + +QPointF StickMan::posFor(int idx) const +{ + return m_nodes[idx]->pos(); +} + +//#include +void StickMan::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + /* static int frames = 0; + static QTime time; + if (frames++ % 100 == 0) { + frames = 1; + time.restart(); + } + + if (time.elapsed() > 0) { + painter->setPen(Qt::white); + painter->drawText(0, 0, QString::number(frames / (time.elapsed() / 1000.0))); + }*/ + + stabilize(); + if (m_sticks) { + painter->setPen(Qt::white); + for (int i=0; idrawLine(node1->pos(), node2->pos()); + } + } else { + // first bone is neck and will be used for head + + QPainterPath path; + path.moveTo(posFor(0)); + path.lineTo(posFor(1)); + + // right arm + path.lineTo(posFor(2)); + path.lineTo(posFor(6)); + path.lineTo(posFor(7)); + + // left arm + path.moveTo(posFor(3)); + path.lineTo(posFor(8)); + path.lineTo(posFor(9)); + + // body + path.moveTo(posFor(2)); + path.lineTo(posFor(4)); + path.lineTo(posFor(10)); + path.lineTo(posFor(11)); + path.lineTo(posFor(5)); + path.lineTo(posFor(3)); + path.lineTo(posFor(1)); + + // right leg + path.moveTo(posFor(10)); + path.lineTo(posFor(12)); + path.lineTo(posFor(13)); + + // left leg + path.moveTo(posFor(11)); + path.lineTo(posFor(14)); + path.lineTo(posFor(15)); + + painter->setPen(QPen(m_penColor, 5.0, Qt::SolidLine, Qt::RoundCap)); + painter->drawPath(path); + + { + int n1 = Bones[0]; + int n2 = Bones[1]; + Node *node1 = m_nodes[n1]; + Node *node2 = m_nodes[n2]; + + QPointF dist = node2->pos() - node1->pos(); + + qreal sinAngle = dist.x() / sqrt(pow(dist.x(), 2) + pow(dist.y(), 2)); + qreal angle = asin(sinAngle) * 180.0 / M_PI; + + QPointF headPos = node1->pos(); + painter->translate(headPos); + painter->rotate(-angle); + + painter->setBrush(m_fillColor); + painter->drawEllipse(QPointF(0,0), 50.0, 50.0); + + painter->setBrush(m_penColor); + painter->setPen(QPen(m_penColor, 2.5, Qt::SolidLine, Qt::RoundCap)); + + // eyes + if (m_isDead) { + painter->drawLine(-30.0, -30.0, -20.0, -20.0); + painter->drawLine(-20.0, -30.0, -30.0, -20.0); + + painter->drawLine(20.0, -30.0, 30.0, -20.0); + painter->drawLine(30.0, -30.0, 20.0, -20.0); + } else { + painter->drawChord(QRectF(-30.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); + painter->drawChord(QRectF(5.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); + } + + // mouth + if (m_isDead) { + painter->drawLine(-28.0, 2.0, 29.0, 2.0); + } else { + painter->setBrush(QColor(128, 0, 64 )); + painter->drawChord(QRectF(-28.0, 2.0-55.0/2.0, 57.0, 55.0), 0.0, -180.0*16); + } + + // pupils + if (!m_isDead) { + painter->setPen(QPen(m_fillColor, 1.0, Qt::SolidLine, Qt::RoundCap)); + painter->setBrush(m_fillColor); + painter->drawEllipse(QPointF(-12.0, -25.0), 5.0, 5.0); + painter->drawEllipse(QPointF(22.0, -25.0), 5.0, 5.0); + } + } + } +} + + + diff --git a/code/train/C++/0036012_razorfen_kraul.cpp b/code/train/C++/0036012_razorfen_kraul.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1681ab47aefa355790b0b7f361b8c9bca02107c --- /dev/null +++ b/code/train/C++/0036012_razorfen_kraul.cpp @@ -0,0 +1,272 @@ +/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information + * 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 + */ + +/* ScriptData +SDName: Razorfen_Kraul +SD%Complete: 100 +SDComment: Quest support: 1144, 1221 +SDCategory: Razorfen Kraul +EndScriptData + +*/ + +#include "AI/ScriptDevAI/PreCompiledHeader.h"/* ContentData +quest_willix_the_importer +EndContentData */ + + +#include "AI/ScriptDevAI/base/escort_ai.h" +#include "AI/ScriptDevAI/base/pet_ai.h" + +/*###### +## npc_willix_the_importer +######*/ + +enum +{ + QUEST_WILLIX_THE_IMPORTER = 1144, + + SAY_WILLIX_READY = -1047000, + SAY_WILLIX_1 = -1047001, + SAY_WILLIX_2 = -1047002, + SAY_WILLIX_3 = -1047003, + SAY_WILLIX_4 = -1047004, + SAY_WILLIX_5 = -1047005, + SAY_WILLIX_6 = -1047006, + SAY_WILLIX_7 = -1047007, + SAY_WILLIX_END = -1047008, + + SAY_WILLIX_AGGRO_1 = -1047009, + SAY_WILLIX_AGGRO_2 = -1047010, + SAY_WILLIX_AGGRO_3 = -1047011, + SAY_WILLIX_AGGRO_4 = -1047012, + + NPC_RAGING_AGAMAR = 4514 +}; + +static const float aBoarSpawn[4][3] = +{ + {2151.420f, 1733.18f, 52.10f}, + {2144.463f, 1726.89f, 51.93f}, + {1956.433f, 1597.97f, 81.75f}, + {1958.971f, 1599.01f, 81.44f} +}; + +struct npc_willix_the_importerAI : public npc_escortAI +{ + npc_willix_the_importerAI(Creature* m_creature) : npc_escortAI(m_creature) { Reset(); } + + void Reset() override {} + + // Exact use of these texts remains unknown, it seems that he should only talk when he initiates the attack or he is the first who is attacked by a npc + void Aggro(Unit* pWho) override + { + switch (urand(0, 6)) // Not always said + { + case 0: DoScriptText(SAY_WILLIX_AGGRO_1, m_creature, pWho); break; + case 1: DoScriptText(SAY_WILLIX_AGGRO_2, m_creature, pWho); break; + case 2: DoScriptText(SAY_WILLIX_AGGRO_3, m_creature, pWho); break; + case 3: DoScriptText(SAY_WILLIX_AGGRO_4, m_creature, pWho); break; + } + } + + void JustSummoned(Creature* pSummoned) override + { + pSummoned->AI()->AttackStart(m_creature); + } + + void WaypointReached(uint32 uiPointId) override + { + switch (uiPointId) + { + case 2: + DoScriptText(SAY_WILLIX_1, m_creature); + break; + case 6: + DoScriptText(SAY_WILLIX_2, m_creature); + break; + case 9: + DoScriptText(SAY_WILLIX_3, m_creature); + break; + case 14: + DoScriptText(SAY_WILLIX_4, m_creature); + // Summon 2 boars on the pathway + m_creature->SummonCreature(NPC_RAGING_AGAMAR, aBoarSpawn[0][0], aBoarSpawn[0][1], aBoarSpawn[0][2], 0, TEMPSUMMON_TIMED_OOC_DESPAWN, 25000); + m_creature->SummonCreature(NPC_RAGING_AGAMAR, aBoarSpawn[1][0], aBoarSpawn[1][1], aBoarSpawn[1][2], 0, TEMPSUMMON_TIMED_OOC_DESPAWN, 25000); + break; + case 25: + DoScriptText(SAY_WILLIX_5, m_creature); + break; + case 33: + DoScriptText(SAY_WILLIX_6, m_creature); + break; + case 44: + DoScriptText(SAY_WILLIX_7, m_creature); + // Summon 2 boars at the end + m_creature->SummonCreature(NPC_RAGING_AGAMAR, aBoarSpawn[2][0], aBoarSpawn[2][1], aBoarSpawn[2][2], 0, TEMPSUMMON_TIMED_OOC_DESPAWN, 25000); + m_creature->SummonCreature(NPC_RAGING_AGAMAR, aBoarSpawn[3][0], aBoarSpawn[3][1], aBoarSpawn[3][2], 0, TEMPSUMMON_TIMED_OOC_DESPAWN, 25000); + break; + case 45: + DoScriptText(SAY_WILLIX_END, m_creature); + m_creature->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); + // Complete event + if (Player* pPlayer = GetPlayerForEscort()) + pPlayer->GroupEventHappens(QUEST_WILLIX_THE_IMPORTER, m_creature); + SetEscortPaused(true); + break; + } + } +}; + +CreatureAI* GetAI_npc_willix_the_importer(Creature* pCreature) +{ + return new npc_willix_the_importerAI(pCreature); +} + +bool QuestAccept_npc_willix_the_importer(Player* pPlayer, Creature* pCreature, const Quest* pQuest) +{ + if (pQuest->GetQuestId() == QUEST_WILLIX_THE_IMPORTER) + { + if (npc_willix_the_importerAI* pEscortAI = dynamic_cast(pCreature->AI())) + { + // After 4.0.1 set run = true + pEscortAI->Start(false, pPlayer, pQuest); + DoScriptText(SAY_WILLIX_READY, pCreature, pPlayer); + pCreature->SetFactionTemporary(FACTION_ESCORT_N_NEUTRAL_PASSIVE, TEMPFACTION_RESTORE_RESPAWN); + } + } + + return true; +} + +/*###### +## npc_snufflenose_gopher +######*/ + +enum +{ + SPELL_SNUFFLENOSE_COMMAND = 8283, + NPC_SNUFFLENOSE_GOPHER = 4781, + GO_BLUELEAF_TUBBER = 20920, +}; + +struct npc_snufflenose_gopherAI : public ScriptedPetAI +{ + npc_snufflenose_gopherAI(Creature* pCreature) : ScriptedPetAI(pCreature) { Reset(); } + + bool m_bIsMovementActive; + + ObjectGuid m_targetTubberGuid; + + void Reset() override + { + m_bIsMovementActive = false; + } + + void MovementInform(uint32 uiMoveType, uint32 uiPointId) override + { + if (uiMoveType != POINT_MOTION_TYPE || !uiPointId) + return; + + if (GameObject* pGo = m_creature->GetMap()->GetGameObject(m_targetTubberGuid)) + { + pGo->SetRespawnTime(5 * MINUTE); + pGo->Refresh(); + + pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND); + } + + m_bIsMovementActive = false; + } + + // Function to search for new tubber in range + void DoFindNewTubber() + { + std::list lTubbersInRange; + GetGameObjectListWithEntryInGrid(lTubbersInRange, m_creature, GO_BLUELEAF_TUBBER, 40.0f); + + if (lTubbersInRange.empty()) + return; + + lTubbersInRange.sort(ObjectDistanceOrder(m_creature)); + GameObject* pNearestTubber = nullptr; + + // Always need to find new ones + for (std::list::const_iterator itr = lTubbersInRange.begin(); itr != lTubbersInRange.end(); ++itr) + { + if (!(*itr)->isSpawned() && (*itr)->HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND) && (*itr)->IsWithinLOSInMap(m_creature)) + { + pNearestTubber = *itr; + break; + } + } + + if (!pNearestTubber) + return; + m_targetTubberGuid = pNearestTubber->GetObjectGuid(); + + float fX, fY, fZ; + pNearestTubber->GetContactPoint(m_creature, fX, fY, fZ); + m_creature->GetMotionMaster()->MovePoint(1, fX, fY, fZ); + m_bIsMovementActive = true; + } + + void UpdateAI(const uint32 uiDiff) override + { + if (!m_bIsMovementActive) + ScriptedPetAI::UpdateAI(uiDiff); + } +}; + +CreatureAI* GetAI_npc_snufflenose_gopher(Creature* pCreature) +{ + return new npc_snufflenose_gopherAI(pCreature); +} + +bool EffectDummyCreature_npc_snufflenose_gopher(Unit* pCaster, uint32 uiSpellId, SpellEffectIndex uiEffIndex, Creature* pCreatureTarget, ObjectGuid /*originalCasterGuid*/) +{ + // always check spellid and effectindex + if (uiSpellId == SPELL_SNUFFLENOSE_COMMAND && uiEffIndex == EFFECT_INDEX_0) + { + if (pCreatureTarget->GetEntry() == NPC_SNUFFLENOSE_GOPHER) + { + if (npc_snufflenose_gopherAI* pGopherAI = dynamic_cast(pCreatureTarget->AI())) + pGopherAI->DoFindNewTubber(); + } + + // always return true when we are handling this spell and effect + return true; + } + + return false; +} + +void AddSC_razorfen_kraul() +{ + Script* pNewScript; + + pNewScript = new Script; + pNewScript->Name = "npc_willix_the_importer"; + pNewScript->GetAI = &GetAI_npc_willix_the_importer; + pNewScript->pQuestAcceptNPC = &QuestAccept_npc_willix_the_importer; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "npc_snufflenose_gopher"; + pNewScript->GetAI = &GetAI_npc_snufflenose_gopher; + pNewScript->pEffectDummyNPC = &EffectDummyCreature_npc_snufflenose_gopher; + pNewScript->RegisterSelf(); +} diff --git a/code/train/C++/0036183_BoustrophedonCpp.cpp b/code/train/C++/0036183_BoustrophedonCpp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a371ceefa3c12514491f0e7888f94ee7ac12bb30 --- /dev/null +++ b/code/train/C++/0036183_BoustrophedonCpp.cpp @@ -0,0 +1,129 @@ +/* + * Implementation of dpp::BoustrophdeonCpp class for solving CPP problems + * by generating field tracks that cover a convex field, and decomposing + * the tracks into waypoints by joining the tracks end-to-end. + * + * Copyright (C) 2014-2015 DubinsPathPlanner. + * Created by David Goodman + * Redistribution and use of this file is allowed according to the terms of the MIT license. + * For details see the LICENSE file distributed with DubinsPathPlanner. + */ + +#include +#include + +#include + +namespace dpp { + +/** + * Order field tracks in the track list according to the Boustrophedon CPP + * algorithm. Track direction (reverse or not) will be set. + * @remark This sets the tracks to reversed in an alternating order. + * @param[in] tracks field track list to reorder + * @param[in] startAtLast whether to use the last track as the first + * @param[in] reverseStartTrack whether to start in the reverse direction + * on the first track (or last depending). + */ +void setFieldTrackOrder(FieldTrackList &tracks, bool startAtLast, + bool reverseStartTrack) { + if (startAtLast) { + tracks.reverse(); + } + + bool directionReversed = reverseStartTrack; + FieldTrackListIterator iter; + for (iter = tracks.begin(); iter != tracks.end(); iter++) { + (*iter).reverse(directionReversed); + directionReversed ^= 1; // flip direction + } +} + +/** + * Solves the CPP problem using the Boustrophedon algorithm. + * @param[in] field a coverage field to generate waypoints over + * @param[in] C initial configuration of the vehicle + * @param[in] turnRadius of the vehicle + * @param[in] returnToInitial whether to include return edge and cost + * @param[out] G a graph to populate with nodes for coverage + * @param[out] GA attributes of the graph + * @param[out] Tour an ordered list of nodes representing the path + * @param[out] Edges an ordered list of edges representing the path + * @param[out] Headings headings used along the path at each node + * @param[out] cost overall cost (path length) for covering the field + * @return SUCCESS or FAILURE of the algorithm + */ +int BoustrophedonCpp::run(const Field &field, VehicleConfiguration C, double turnRadius, + bool returnToInitial, Graph &G, GraphAttributes &GA, List &Tour, + List &Edges, NodeArray &Headings, double &cost) { + + // Check arguments + if (Headings.graphOf() != &G) { + throw std::domain_error("Headings should be for G."); + } + + // Generate field tracks + FieldTrackList tracks; + if (field.generateFieldTracks(tracks) < 1) { + throw std::runtime_error("Failed to generate field tracks."); + } + + // Find the closest endpoint among first or last track from initial config + bool startAtLast = false; + bool reverseStartTrack = false; + + FieldTrack firstTrack = tracks.front(); + FieldTrack lastTrack = tracks.back(); + VehicleConfiguration + CfirstStart(firstTrack.start().m_x, firstTrack.start().m_y, firstTrack.angle()), + CfirstEnd(firstTrack.end().m_x, firstTrack.end().m_y, firstTrack.angle(true)), + ClastStart(lastTrack.start().m_x, lastTrack.start().m_y, lastTrack.angle()), + ClastEnd(lastTrack.end().m_x, lastTrack.end().m_y, lastTrack.angle(true)); + + double d_fs = dubinsPathLength(C, CfirstStart, turnRadius), + d_fe = dubinsPathLength(C, CfirstEnd, turnRadius), + d_ls = dubinsPathLength(C, ClastStart, turnRadius), + d_le = dubinsPathLength(C, ClastEnd, turnRadius); + double d_min = d_fs; + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Comparing distances: " << std::endl + << "First track: " << d_fs << " and " << d_fe << std::endl + << "Last track: " << d_ls << " and " << d_le << std::endl; + + if (d_fe < d_min) { + d_min = d_fe; + reverseStartTrack = true; + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Chose first track end: " << firstTrack.end() << std::endl; + } + else if (d_ls < d_min) { + d_min = d_ls; + reverseStartTrack = false; + startAtLast = true; + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Chose last track start: " << lastTrack.start() << std::endl; + } + else if (d_le < d_min) { + d_min = d_le; + reverseStartTrack = true; + startAtLast = true; + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Chose last track end: " << lastTrack.end() << std::endl; + } + else { + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Chose first track start: " << firstTrack.start() << std::endl; + } + + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Decomposing " << tracks.size() + << " field tracks into nodes with coverage width:" << field.coverageWidth() + << std::endl; + + setFieldTrackOrder(tracks, startAtLast, reverseStartTrack); + int n = tracks.addNodesToGraph(G, GA, field.coverageWidth(), Tour, Headings); + + Logger::logDebug(DPP_LOGGER_VERBOSE_2) << "Added " << n + << " nodes to cover entire field." << std::endl; + + // Create edges + cost = createDubinsTourEdges(G, GA, Tour, Headings, turnRadius, Edges, returnToInitial); + + return SUCCESS; +} + +} // namespace dpp \ No newline at end of file diff --git a/code/train/C++/0036385_LongestValidParentheses.cpp b/code/train/C++/0036385_LongestValidParentheses.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8e468e9b017f94dba0e4af566f5b464633b8b7b --- /dev/null +++ b/code/train/C++/0036385_LongestValidParentheses.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +using namespace std; + +class Solution +{ +public: + int longestValidParentheses(string s) + { + stack parenthes; + int val = 0,count = 0; + unsigned int i; + for(i = 0; i < s.size(); i++) + { + if(s[i] == '(') + { + parenthes.push(count); + count = 0; + } + else if(!parenthes.empty()) + { + count = count + 1 + parenthes.top(); + parenthes.pop(); + val = max(val,count); + } + else + { + count = 0; + } + } + return val * 2; + } +}; + +int main() +{ + Solution solution; + cout< + * Christian Schulte + * + * Contributing authors: + * Gabor Szokoli + * + * Copyright: + * Guido Tack, 2004 + * Christian Schulte, 2004 + * Gabor Szokoli, 2004 + * + * Last modified: + * $Date: 2011-05-24 00:48:31 +1000 (Tue, 24 May 2011) $ by $Author: tack $ + * $Revision: 12018 $ + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.org + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { namespace Set { namespace Sequence { + + /* + * "Sequenced union" propagator + * + */ + + Actor* + SeqU::copy(Space& home, bool share) { + return new (home) SeqU(home,share,*this); + } + + ExecStatus + SeqU::propagateSeqUnion(Space& home, + bool& modified, ViewArray& x, + SetView& y) { + Region r(home); + GlbRanges* XLBs = r.alloc >(x.size()); + for (int i=x.size(); i--; ){ + GlbRanges lb(x[i]); + XLBs[i]=lb; + } + Iter::Ranges::NaryAppend > u(XLBs,x.size()); + GECODE_ME_CHECK_MODIFIED(modified, y.includeI(home,u)); + + GLBndSet before(home); + for (int i=0; i xiub(x[i]); + before.includeI(home, xiub); + BndSetRanges beforeR(before); + GlbRanges ylb(y); + Iter::Ranges::Diff, BndSetRanges> diff(ylb, beforeR); + if (diff()) { + GECODE_ME_CHECK_MODIFIED(modified, x[i].exclude(home, diff.min(), + Limits::max)); + } + } + before.dispose(home); + + GLBndSet after(home); + for (int i=x.size(); i--; ) { + LubRanges xiub(x[i]); + after.includeI(home, xiub); + BndSetRanges afterR(after); + GlbRanges ylb(y); + Iter::Ranges::Diff, BndSetRanges> diff(ylb, afterR); + if (diff()) { + int max = diff.max(); + for (; diff(); ++diff) + max = diff.max(); + GECODE_ME_CHECK_MODIFIED(modified, x[i].exclude(home, + Limits::min, + max)); + } + } + after.dispose(home); + + return ES_FIX; + } + + //Enforces sequentiality and ensures y contains union of Xi lower bounds. + ExecStatus + SeqU::propagate(Space& home, const ModEventDelta& med) { + ModEvent me0 = SetView::me(med); + bool ubevent = Rel::testSetEventUB(me0); + bool anybevent = Rel::testSetEventAnyB(me0); + bool cardevent = Rel::testSetEventCard(me0); + + bool modified = false; + bool assigned=false; + bool oldModified = false; + + do { + oldModified = modified; + modified = false; + + if (oldModified || modified || anybevent || cardevent) + GECODE_ES_CHECK(propagateSeq(home,modified,assigned,x)); + if (oldModified || modified || anybevent) + GECODE_ES_CHECK(propagateSeqUnion(home,modified,x,y)); + if (oldModified || modified || ubevent) + GECODE_ES_CHECK(RelOp::unionNXiUB(home,modified,x,y,unionOfDets)); + if (oldModified || modified || ubevent) + GECODE_ES_CHECK(RelOp::partitionNYUB(home,modified,x,y,unionOfDets)); + if (oldModified || modified || anybevent) + GECODE_ES_CHECK(RelOp::partitionNXiLB(home,modified,x,y,unionOfDets)); + if (oldModified || modified || cardevent || ubevent) + GECODE_ES_CHECK(RelOp::partitionNCard(home,modified,x,y,unionOfDets)); + + } while (modified); + + for (int i=x.size(); i--;) + if (!x[i].assigned()) + return ES_FIX; + return home.ES_SUBSUMED(*this); + } + +}}} + +// STATISTICS: set-prop diff --git a/code/train/C++/0038003_system.cpp b/code/train/C++/0038003_system.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db6f1f922de5cc14acc7275661b601a72632f4ea --- /dev/null +++ b/code/train/C++/0038003_system.cpp @@ -0,0 +1,233 @@ +#include "system.h" +#include "Integrators/integrator.h" +#include "Potentials/potential.h" +#include "InitialConditions/initialcondition.h" +#include "particle.h" + +#include "Potentials/newtoniangravity.h" +#include "vec3.h" + +#include +#include +#include +using std::cout; +using std::endl; +using std::setprecision; + + + + + +void System::computeForces() { + resetAllForces(); + m_potential->resetPotentialEnergy(); + + for (int i=0; i < m_numberOfParticles; i++){ + for (int j = i+1; j < m_numberOfParticles; j++){ + m_potential->computeForces(*m_particles.at(i), *m_particles.at(j)); + } + } +} + +void System::resetAllForces() { + for (int i=0; iresetForces(); + } +} + +void System::setPotential(Potential* potential) { + m_potential = potential; +} + +void System::setIntegrator(Integrator* integrator) { + m_integrator = integrator; +} + +void System::setInitialCondition(InitialCondition* initialCondition) { + m_initialCondition = initialCondition; + m_initialCondition->setupParticles(*this); +} + +void System::setDt(double dt) { + m_integrator->setDt(dt); +} + +void System::integrate(int numberOfSteps) { + m_integrateSteps = numberOfSteps; + printIntegrateInfo(0); + for (int i=1; iintegrateOneStep(m_particles); + printIntegrateInfo(i); + writePositionsToFile(); + } + closeOutFile(); +} + +void System::addParticle(Particle* p) { + m_particles.push_back(p); + m_numberOfParticles += 1; +} + +double System::computeKineticEnergy() { + /* + * Here, the kinetic energy of the entire system should be computed. Since + * this is independent of the potential in use, we place this method + * directly in the system class. + * + * Remember that you can access the mass and velocity of particle i by + * + * m_particles.at(i)->getMass() + * m_particles.at(i)->getVelocity() + * + * Remember also that the Particle class has a built in method + * Particle::velocitySquared which can be used here. + */ + + m_kineticEnergy = 0; + for (int i = 0; i < m_numberOfParticles; i++){ + //addParticle(Particle* i); + Particle* p = m_particles.at(i); + double mass = p->getMass(); +// vec3 v = p->getVelocity(); + m_kineticEnergy += 0.5*mass*p->velocitySquared(); + } + + //m_kineticEnergy = 0; + return m_kineticEnergy; +} + +void System::printIntegrateInfo(int stepNumber) { + if (stepNumber == 0) { + cout << endl + << " STARTING INTEGRATION " << endl + << "-------------------------" << endl + << " o Number of steps: " << m_integrateSteps << endl + << " o Time step, dt: " << m_integrator->getDt() << endl + << " o Initial condition: " << m_initialCondition->getName() << endl + << " o Number of particles: " << m_particles.size() << endl + << " o Potential in use: " << m_potential->getName() << endl + << " o Integrator in use: " << m_integrator->getName() << endl + << endl; + } else if (stepNumber % 1000 == 0) { + m_kineticEnergy = computeKineticEnergy(); + m_potentialEnergy = m_potential->getPotentialEnergy(); + m_totalEnergy = m_kineticEnergy + m_potentialEnergy; + printf("Step: %5d E =%10.5f Ek =%10.5f Ep =%10.5f\n", + stepNumber, m_totalEnergy, m_kineticEnergy, m_potentialEnergy); + fflush(stdout); + } +} + +void System::removeLinearMomentum() { + /* + * Here you should remove the total momentum of the entire system, to + * ensure the entire system does not drift away during long integration + * times. + * + * Remember that you can access the mass and velocity of particle i by + * + * m_particles.at(i)->getMass(); + * m_particles.at(i)->getVelocity(); + * + * Remember also that the vec3-vector class supports the += and -= + * operators, so you can do + * + * totalMomentum += p->getVelocity() * p->getMass(); + */ + + vec3 totalMomentum = vec3(0,0,0); +} + +void System::setFileWriting(bool writeToFile) { + m_writeToFile = writeToFile; +} + +void System::writePositionsToFile() { + if (m_outFileOpen == false) { + m_outFile.open(m_filename, std::ios::out); + m_outFileOpen = true; + } + /* + * This is where you should print the positions of each particle to file. + * Note that the file, "positions.dat", is already open; it is opened in + * the above if-test the first time this method is called in + * System::Integrate. + * + * Which format you choose for the data file is up to you. + */ + + for (int i=0; igetPosition(); + double x = position_p.x(); + double y = position_p.y(); + //m_outFile << m_numberOfParticles << endl; + m_outFile << setprecision(15) << x << " " << y << endl; + } +} + +void System::closeOutFile() { + if (m_writeToFile == true) { + m_outFile.close(); + m_outFileOpen = false; + } +} + +void System::perihelion(int numberOfTimeSteps){ +// Set some helper variables before we start the time integration. +double thetaPrevious = 0; // The perihelion angle of the previous time step. +double thetaCurrent = 0; // The perihelion angle of the current time step. + +double rPreviousPrevious = 0; // Mercury-Sun-distance two times steps ago. +double rPrevious = 0; // Mercury-Sun-distance of the previous time step. +double rCurrent = 0; // Mercury-Sun-distance of the current time step. + +m_outFile.open("perihelion_nonrel.dat"); +// This is the integration loop, in which you advance the solution (usually via a integrateOneStep() +// function located in an integrator object, e.g. the Verlet class). + +int year = 0; + +for (int timeStep = 0; timeStep < numberOfTimeSteps; timeStep++) { + + // Integrate the solution one step forward in time, using the GR corrected force calcuation + // and the Verlet algorithm. + m_integrator->integrateOneStep(m_particles); + + // Compute the current perihelion angle, using the inverse tangent function from cmath. + // This assumes there is a vector of planets, called m_particles, available, in which the + // Sun is m_particles[0] and Mercury is m_particles[1]. + double x = m_particles[1]->getPosition().x() - m_particles[0]->getPosition().x(); + double y = m_particles[1]->getPosition().y() - m_particles[0]->getPosition().y(); + thetaCurrent = atan2( y, x ); + + // Compute the current Mercury-Sun distance. + double rCurrent = (m_particles[1]->getPosition() - m_particles[0]->getPosition()).length(); + + // Check if the *previous* time step was a minimum for the Mercury-Sun distance. I.e. check + // if the previous distance is smaller than the current one *and* the previous previous one. + //cout << rCurrent << endl; + //cout << "Calculating angle... " << endl; + + if ( rCurrent > rPrevious && rPrevious < rPreviousPrevious ) { + // If we are perihelion, print angle (in radians) to terminal. + cout << "Year " << year << endl; + m_outFile << thetaPrevious << endl; + year += 1; + //cout << thetaPrevious*3600*180/M_PI << endl; + // Here you should also probably write it to file for later plotting or something. + } + + // Update the helper variables (current, previous, previousPrevious). + rPreviousPrevious = rPrevious; + rPrevious = rCurrent; + thetaPrevious = thetaCurrent; +} +m_outFile.close(); +} + + + + + + diff --git a/code/train/C++/0038061_endgamerule.cpp b/code/train/C++/0038061_endgamerule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b8279fe9c171da2309340f4df7b16efc8b7d159 --- /dev/null +++ b/code/train/C++/0038061_endgamerule.cpp @@ -0,0 +1,156 @@ +/* + Copyright (C) 2014 Marcus Soll + All rights reserved. + + You may use this file under the terms of BSD license as follows: + + 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 the Jolla Ltd 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 HOLDERS 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 "endgamerule.h" +#include "greedyrule.h" +#include "rulehelper.h" + +using RuleHelper::opponent; + +const int EndgameRule::_borderDiscs; + +namespace { +int amountDiscsCanGet(Gameboard board, int player, int x_orig, int y_orig) +{ + int count = 0; + + for(int x = 0; x < 8; ++x) + { + for(int y = 0; y < 8; ++y) + { + if(board.owner(x,y) == player) + { + --count; + } + } + } + + board.play(x_orig,y_orig,player); + for(int x = 0; x < 8; ++x) + { + for(int y = 0; y < 8; ++y) + { + if(board.owner(x,y) == player) + { + ++count; + } + } + } + return count; +} +} + +EndgameRule::EndgameRule(QObject *parent) : + Rule(parent) +{ +} + +bool EndgameRule::applicable(Gameboard board, int player) +{ + return (board.points(player) + board.points(opponent(player))) >= _borderDiscs; +} + +void EndgameRule::doTurn(Gameboard board, int player) +{ + // Find plays where the opponent can't do anything after that + for(int x = 0; x < 8; ++x) + { + for(int y = 0; y < 8; ++y) + { + Gameboard temp = board; + if(temp.play(x,y,player) && !temp.isTurnPossible(opponent(player))) + { + emit turn(x,y); + return; + } + } + } + + //Get the most discs while letting the opponent get few discs + int max = -1000; + int x_turn = -1; + int y_turn = -1; + for(int x = 0; x < 8; ++x) + { + for(int y = 0; y < 8; ++y) + { + if(board.play(x,y,player,true)) + { + int count = amountDiscsCanGet(board,player,x,y); + Gameboard testboard = board; + testboard.play(x,y,player,false); + int countOpponent = -1; + for(int xi = 0; xi < 8; ++xi) + { + for(int yi = 0; yi < 8; ++yi) + { + if(testboard.play(xi,yi,opponent(player),true)) + { + int temp = amountDiscsCanGet(testboard,opponent(player),xi,yi); + if(temp > countOpponent) + { + countOpponent = temp; + } + } + } + } + count -= countOpponent; + if(count > max) + { + max = count; + x_turn = x; + y_turn = y; + } + } + } + } + + if(!(max == -1000 || x_turn == -1 || y_turn == -1)) + { + emit turn(x_turn,y_turn); + return; + } + + //If everything fails do a greedy rule + GreedyRule fallback; + QObject::connect(&fallback,SIGNAL(turn(int,int)),this,SLOT(getTurn(int,int))); + fallback.doTurn(board,player); + QObject::disconnect(&fallback,SIGNAL(turn(int,int)),this,SLOT(getTurn(int,int))); + +} + +QString EndgameRule::name() +{ + return tr("Endgame Rule"); +} + +void EndgameRule::getTurn(int x, int y) +{ + emit turn(x,y); +} diff --git a/code/train/C++/0038247_bestTimeToBuyAndSellStock3.cpp b/code/train/C++/0038247_bestTimeToBuyAndSellStock3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4f40ef86d08922d282a8d62746c99792d1c822f --- /dev/null +++ b/code/train/C++/0038247_bestTimeToBuyAndSellStock3.cpp @@ -0,0 +1,36 @@ +/* + *Say you have an array for which the ith element is the price of a given stock on day i. + +Design an algorithm to find the maximum profit. You may complete at most two transactions. + +Note: +You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). + * */ +#include "header.h" + +class Solution { +public: + int maxProfit(vector& prices) { + int hold1 = INT_MIN; + int hold2 = INT_MIN; + int release1 = 0; + int release2 = 0; + for (int i = 0; i < prices.size(); i++) { + release2 = max(release2, hold2 + prices[i]); + hold2 = max(hold2, release1 - prices[i]); + release1 = max(release1, hold1 + prices[i]); + hold1 = max(hold1, -prices[i]); + } + return release2; + } +}; + +int main(int argc, char **argv) { + vector prices; + for (int i = 1; i < argc; i++) { + prices.push_back(atoi(argv[i])); + } + Solution s; + cout << s.maxProfit(prices) << endl; + return 0; +} diff --git a/code/train/C++/0039567_coverage_tree.cc b/code/train/C++/0039567_coverage_tree.cc new file mode 100644 index 0000000000000000000000000000000000000000..9be1739e32401274b7debfb27f369aa659031fd2 --- /dev/null +++ b/code/train/C++/0039567_coverage_tree.cc @@ -0,0 +1,183 @@ +/* + * fMBT, free Model Based Testing tool + * Copyright (c) 2011, Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, 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 Lesser General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + * + */ +#include "coverage_tree.hh" +#include "model.hh" +#include + +Coverage_Tree::Coverage_Tree(Log& l, std::string params) : + Coverage(l), max_depth(2), push_depth(0) +{ + exec[0] = &root_node; + set_max_depth(params); + push(); +} + +void Coverage_Tree::push() +{ + push_depth++; + std::list > a; + push_restore.push_front(a); + exec_restore.push_front(exec); +} + +void Coverage_Tree::pop() +{ + std::list >::iterator i + = push_restore.front().begin(); + + while(i!=push_restore.front().end()) { + node_count--; + int action=i->second; + struct node* current_node=i->first; + delete current_node->nodes[action]; + current_node->nodes[action]=NULL; + current_node->nodes.erase(action); + i++; + } + push_restore.pop_front(); + + exec=exec_restore.front(); + exec_restore.pop_front(); + push_depth--; +} + +void Coverage_Tree::precalc() +{ + if (model) { + node_count=1; + max_count=0; + int acount=model->getActionNames().size()-1; + long ccount=acount; + for(int i=1;i<=max_depth;i++) { + max_count+=ccount; + ccount*=acount; + } + } +} + +void Coverage_Tree::set_model(Model* _model) +{ + Coverage::set_model(_model); + precalc(); +} + +void Coverage_Tree::history(int action,std::vector& props, + Verdict::Verdict verdict) +{ + if (action) { + execute(action); + } else { + // verdict. And now we should do ?? + exec.clear(); + exec[0] = &root_node; + } +} + +Coverage_Tree::~Coverage_Tree() +{ + if (push_depth) { + pop(); + } else { + abort(); + } +} + +bool Coverage_Tree::execute(int action) +{ + struct node* current_node=&root_node; + struct node* next_node; + int depth=0; + while (current_node && depthnodes[action]==NULL) { + current_node->nodes[action]=new struct node; + current_node->nodes[action]->action=action; + node_count++; + if (push_depth) { + std::pair a(current_node,action); + push_restore.front().push_front(a); + } + } + depth++; + next_node=exec[depth]; + exec[depth]=current_node->nodes[action]; + current_node=next_node; + } + + return true; +} + + +float Coverage_Tree::getCoverage() +{ + return (float)(node_count-1)/max_count; +} + +void Coverage_Tree::print_tree(struct node* node,int depth) +{ + for(int j=0;j<32;j++) { + if (node->nodes[j]) { + for(int i=0;igetActionName(node->nodes[j]->action).c_str()); + print_tree(node->nodes[j],depth+1); + } + } +} + +int Coverage_Tree::fitness(int* action,int n,float* fitness) +{ + int ret=0; + + if (log.is_debug()) { + log.debug("Tree\n"); + print_tree(&root_node,0); + } + + for(int pos=0;posnodes[action[pos]]==NULL) { + f+=1.0/(i+1.0); + } + no=exec[i+1]; + } + fitness[pos]=f; + if (fitness[pos]>fitness[ret]) { + ret=pos; + } + } + + return ret; +} + +void Coverage_Tree::set_max_depth(std::string&s) +{ + if (s!="") { + max_depth=std::atoi(s.c_str()); + if (max_depth<1) { + max_depth=1; + } + } + precalc(); + log.debug("%s(%s) -> %i\n",__PRETTY_FUNCTION__,s.c_str(),max_depth); +} + +FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Tree, "perm") diff --git a/code/train/C++/0039642_stickychan.cpp b/code/train/C++/0039642_stickychan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f57c9edfad03a04defc2d347ad79cb6759ae01d8 --- /dev/null +++ b/code/train/C++/0039642_stickychan.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2004-2011 See the AUTHORS file for details. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation. + */ + +#include "Chan.h" +#include "User.h" + +class CStickyChan : public CModule +{ +public: + MODCONSTRUCTOR(CStickyChan) {} + virtual ~CStickyChan() + { + } + + virtual bool OnLoad(const CString& sArgs, CString& sMessage); + + virtual EModRet OnUserPart(CString& sChannel, CString& sMessage) + { + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) + { + if (sChannel.Equals(it->first)) + { + CChan* pChan = m_pUser->FindChan(sChannel); + + if (pChan) + { + pChan->JoinUser(true, "", m_pClient); + return HALT; + } + } + } + + return CONTINUE; + } + + virtual void OnModCommand(const CString& sCommand) + { + CString sCmdName = sCommand.Token(0); + CString sChannel = sCommand.Token(1); + sChannel.MakeLower(); + if ((sCmdName == "stick") && (!sChannel.empty())) + { + SetNV(sChannel, sCommand.Token(2)); + PutModule("Stuck " + sChannel); + } + else if ((sCmdName == "unstick") && (!sChannel.empty())) + { + MCString::iterator it = FindNV(sChannel); + if (it != EndNV()) + DelNV(it); + + PutModule("UnStuck " + sChannel); + } + else if ((sCmdName == "list") && (sChannel.empty())) + { + int i = 1; + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it, i++) + { + if (it->second.empty()) + PutModule(CString(i) + ": " + it->first); + else + PutModule(CString(i) + ": " + it->first + " (" + it->second + ")"); + } + PutModule(" -- End of List"); + } + else + { + PutModule("USAGE: [un]stick #channel [key], list"); + } + } + + virtual void RunJob() + { + if (!m_pUser->GetIRCSock()) + return; + + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) + { + CChan *pChan = m_pUser->FindChan(it->first); + if (!pChan) { + pChan = new CChan(it->first, m_pUser, true); + if (!it->second.empty()) + pChan->SetKey(it->second); + if (!m_pUser->AddChan(pChan)) { + /* AddChan() deleted that channel */ + PutModule("Could not join [" + it->first + + "] (# prefix missing?)"); + continue; + } + } + if (!pChan->IsOn()) { + PutModule("Joining [" + pChan->GetName() + "]"); + PutIRC("JOIN " + pChan->GetName() + (pChan->GetKey().empty() + ? "" : " " + pChan->GetKey())); + } + } + } + + virtual CString GetWebMenuTitle() { return "Sticky Chans"; } + + virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { + if (sPageName == "index") { + bool bSubmitted = (WebSock.GetParam("submitted").ToInt() != 0); + + const vector& Channels = m_pUser->GetChans(); + for (unsigned int c = 0; c < Channels.size(); c++) { + const CString sChan = Channels[c]->GetName(); + bool bStick = FindNV(sChan) != EndNV(); + + if(bSubmitted) { + bool bNewStick = WebSock.GetParam("stick_" + sChan).ToBool(); + if(bNewStick && !bStick) + SetNV(sChan, ""); // no password support for now unless chansaver is active too + else if(!bNewStick && bStick) { + MCString::iterator it = FindNV(sChan); + if(it != EndNV()) + DelNV(it); + } + bStick = bNewStick; + } + + CTemplate& Row = Tmpl.AddRow("ChannelLoop"); + Row["Name"] = sChan; + Row["Sticky"] = CString(bStick); + } + + if(bSubmitted) { + WebSock.GetSession()->AddSuccess("Changes have been saved!"); + } + + return true; + } + + return false; + } + + virtual bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { + if (sPageName == "webadmin/channel") { + CString sChan = Tmpl["ChanName"]; + bool bStick = FindNV(sChan) != EndNV(); + if (Tmpl["WebadminAction"].Equals("display")) { + Tmpl["Sticky"] = CString(bStick); + } else if (WebSock.GetParam("embed_stickychan_presented").ToBool()) { + bool bNewStick = WebSock.GetParam("embed_stickychan_sticky").ToBool(); + if(bNewStick && !bStick) { + SetNV(sChan, ""); // no password support for now unless chansaver is active too + WebSock.GetSession()->AddSuccess("Channel become sticky!"); + } else if(!bNewStick && bStick) { + DelNV(sChan); + WebSock.GetSession()->AddSuccess("Channel stopped being sticky!"); + } + } + return true; + } + return false; + } + +}; + + +static void RunTimer(CModule * pModule, CFPTimer *pTimer) +{ + ((CStickyChan *)pModule)->RunJob(); +} + +bool CStickyChan::OnLoad(const CString& sArgs, CString& sMessage) +{ + VCString vsChans; + VCString::iterator it; + sArgs.Split(",", vsChans, false); + + for (it = vsChans.begin(); it != vsChans.end(); ++it) { + CString sChan = it->Token(0); + CString sKey = it->Token(1, true); + SetNV(sChan, sKey); + } + + // Since we now have these channels added, clear the argument list + SetArgs(""); + + AddTimer(RunTimer, "StickyChanTimer", 15); + return(true); +} + +MODULEDEFS(CStickyChan, "configless sticky chans, keeps you there very stickily even") diff --git a/code/train/C++/0039868_main.cpp b/code/train/C++/0039868_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e567b1aa9addde98da2ac5d1f830f7ee24ca96d3 --- /dev/null +++ b/code/train/C++/0039868_main.cpp @@ -0,0 +1,54 @@ +/* + Copyright (2016) Michael Baer, Daniel Bonrath, All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include + +#include "TupleFeeder.h" + +#include "boost/asio.hpp" + +int main(int argc, char ** argv) { + argc--; + argv++; + + if (argc != 5) { + std::cerr << "Five parameters expected: config file, rendezvous IP, rendezvous port, own port and node type" << std::endl; + return 1; + } + + struct ifaddrs * ifAddrStruct = nullptr; + struct ifaddrs * ifa = nullptr; + void * tmpAddrPtr = nullptr; + getifaddrs(&ifAddrStruct); + + std::string ownIP; + + for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) { + if (ifa ->ifa_addr->sa_family == AF_INET) { // check it is IP4 + tmpAddrPtr = &(reinterpret_cast(ifa->ifa_addr))->sin_addr; + char addressBuffer[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); + + if (std::strcmp(ifa->ifa_name , "eth0") == 0) { + ownIP = std::string(addressBuffer); + break; + } + } + } + + TupleFeeder tf(argv[0], argv[1], std::atoi(argv[2]), std::atoi(argv[4]), ownIP, std::atoi(argv[3])); + return 0; +} diff --git a/code/train/C++/0040568_Merge_Intervals.cpp b/code/train/C++/0040568_Merge_Intervals.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db7a9e8df3cf9ebe83842568709d30a80a75f0a5 --- /dev/null +++ b/code/train/C++/0040568_Merge_Intervals.cpp @@ -0,0 +1,46 @@ +/** + * Definition of Interval: + * classs Interval { + * int start, end; + * Interval(int start, int end) { + * this->start = start; + * this->end = end; + * } + */ +bool comp(const Interval &i1, const Interval &i2) +{ + if (i1.start != i2.start) + return i1.start < i2.start; + else + return i1.end < i2.end; +} + +class Solution { +public: + /** + * @param intervals: interval list. + * @return: A new interval list. + */ + vector merge(vector &intervals) { + vector &a = intervals; + sort(a.begin(), a.end(), comp); + + int n = a.size(); + if (n == 0) return vector(); + vector ans; + + int j = 0; + ans.push_back(a[0]); + for (int i = 1; i < n; ++i) + { + if (a[i].start > ans[j].end) + { + ++j; + ans.push_back(a[i]); + continue; + } + else ans[j].end = max(ans[j].end, a[i].end); + } + return ans; + } +}; diff --git a/code/train/C++/0040607_StyleElement.cpp b/code/train/C++/0040607_StyleElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7bec24a0f6cd66e2a74ef1b729607c6b3231c396 --- /dev/null +++ b/code/train/C++/0040607_StyleElement.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2006, 2007 Rob Buis + * Copyright (C) 2008 Apple, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "StyleElement.h" + +#include "Document.h" +#include "Element.h" +#include "MappedAttribute.h" +#include "MediaList.h" +#include "MediaQueryEvaluator.h" + +namespace WebCore { + +StyleElement::StyleElement() +{ +} + +StyleSheet* StyleElement::sheet(Element* e) +{ + if (!m_sheet) + createSheet(e); + return m_sheet.get(); +} + +void StyleElement::insertedIntoDocument(Document*, Element* element) +{ + process(element); +} + +void StyleElement::removedFromDocument(Document* document) +{ + // If we're in document teardown, then we don't need to do any notification of our sheet's removal. + if (!document->renderer()) + return; + + // FIXME: It's terrible to do a synchronous update of the style selector just because a