Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add Solution for 454 4Sum II
// 454. 4Sum II /** * Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. * * To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500. All integers are in the range of -2^28 to 2^28 - 1 * and the result is guaranteed to be at most 2^31 - 1. * * Example: * * Input: * A = [ 1, 2] * B = [-2,-1] * C = [-1, 2] * D = [ 0, 2] * * Output: * 2 * * Explanation: * The two tuples are: * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 * * Tags: Binary Search, Hash Table * * Similar Problems: (M) 4Sum * * Author: Kuang Qin */ #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { int n = A.size(); // only count is needed, use a hash map for faster search unordered_map<int, int> map; int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum = -(A[i] + B[j]); map[sum]++; // create hash map using the -sum of A and B } } int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum = C[i] + D[j]; if (map.find(sum) != map.end()) // look up in hash map using the sum of C and D res += map[sum]; } } return res; } }; int main() { vector<int> A = {1, 2}; vector<int> B = {-2, -1}; vector<int> C = {-1, 2}; vector<int> D = {0, 2}; Solution sol; int res = sol.fourSumCount(A, B, C, D); cout << res << endl; cin.get(); return 0; }
Add Printing k digits of 1/n
/* * Copyright 2010, NagaChaitanya Vellanki * * Author NagaChaitanya Vellanki * * Print k digits of decimal representation of 1/n for n > 1 */ #include <inttypes.h> #include <iostream> #include <cstdlib> using namespace std; int main() { int32_t n = 0; int32_t k = 1; cout << "Enter n(n > 1) and number of digits k (k >= 1)" << endl; cin >> n >> k; if((n <= 1) || (k < 1)) { exit(0); } int32_t i = 0; int32_t rem = 1; while(i < k) { cout << (10 * rem) / n; rem = (10 * rem) % n; i++; } return 0; }
Add sample solution to the first problem for the first test
#include <iostream> #include <cstring> using namespace std; class Ticket { int seat; int price; public: Ticket(int _seat) : seat(_seat) { if (seat >= 1 && seat <= 30) price = 70; else if (seat >= 31 && seat <= 70) price = 55; else if (seat >= 71 && seat <= 100) price = 30; else if (seat >= 101 && seat <= 150) price = 15; else price = 0; } int getSeat() { return seat; } int getPrice() { return price; } void print() { cout << "Seat " << seat << " with price " << price << endl; } }; class Guest { char name[32]; Ticket ticket; public: Guest(const char _name[], Ticket _ticket) : ticket(_ticket) { strcpy(name, _name); } bool receivesGift() { return ticket.getSeat() >= 1 && ticket.getSeat() <= 30; } void print() { cout << "Name: " << name << endl; ticket.print(); } }; int main() { Guest guests[5] = { Guest("Ivan", Ticket(2)), Guest("Ivanko", Ticket(29)), Guest("Georgi", Ticket(58)), Guest("Petar", Ticket(102)), Guest("Yordan", Ticket(17)) }; for (int i = 0; i < 5; i++) if (guests[i].receivesGift()) guests[i].print(); return 0; }
Add another windows test case.
/* * This test demonstrates that putting a console into selection mode does not * block the low-level console APIs, even though it blocks WriteFile. */ #define _WIN32_WINNT 0x0501 #include "../Shared/DebugClient.cc" #include <windows.h> #include <stdio.h> const int SC_CONSOLE_MARK = 0xFFF2; CALLBACK DWORD writerThread(void*) { CHAR_INFO xChar, fillChar; memset(&xChar, 0, sizeof(xChar)); xChar.Char.AsciiChar = 'X'; xChar.Attributes = 7; memset(&fillChar, 0, sizeof(fillChar)); fillChar.Char.AsciiChar = ' '; fillChar.Attributes = 7; COORD oneCoord = { 1, 1 }; COORD zeroCoord = { 0, 0 }; while (true) { SMALL_RECT writeRegion = { 5, 5, 5, 5 }; WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE), &xChar, oneCoord, zeroCoord, &writeRegion); Sleep(500); SMALL_RECT scrollRect = { 1, 1, 20, 20 }; COORD destCoord = { 0, 0 }; ScrollConsoleScreenBuffer(GetStdHandle(STD_OUTPUT_HANDLE), &scrollRect, NULL, destCoord, &fillChar); } } int main() { CreateThread(NULL, 0, writerThread, NULL, 0, NULL); Trace("marking console"); HWND hwnd = GetConsoleWindow(); PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0); Sleep(2000); Trace("reading output"); CHAR_INFO buf[1]; COORD bufSize = { 1, 1 }; COORD zeroCoord = { 0, 0 }; SMALL_RECT readRect = { 0, 0, 0, 0 }; ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE), buf, bufSize, zeroCoord, &readRect); Trace("done reading output"); Sleep(2000); PostMessage(hwnd, WM_CHAR, 27, 0x00010001); Sleep(1100); return 0; }
Fix Android RegisterNativeMethods failure logic
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/android/jni_registrar.h" #include "base/logging.h" #include "base/android/jni_android.h" namespace base { namespace android { bool RegisterNativeMethods(JNIEnv* env, const RegistrationMethod* method, size_t count) { const RegistrationMethod* end = method + count; while (method != end) { if (!method->func(env) < 0) { DLOG(ERROR) << method->name << " failed registration!"; return false; } method++; } return true; } } // namespace android } // namespace base
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/android/jni_registrar.h" #include "base/logging.h" #include "base/android/jni_android.h" namespace base { namespace android { bool RegisterNativeMethods(JNIEnv* env, const RegistrationMethod* method, size_t count) { const RegistrationMethod* end = method + count; while (method != end) { if (!method->func(env)) { DLOG(ERROR) << method->name << " failed registration!"; return false; } method++; } return true; } } // namespace android } // namespace base
Implement cell-refinement of triangular cartesian 2D cells.
#include "cell_refine.hpp" #include <viennagrid/algorithm/refine.hpp> /*************** * CELL_REFINE * ***************/ // Triangular tuple TriangularCartesian2D_Domain_cell_refine(TriangularCartesian2D_Domain domain_in, TriangularCartesian2D_Segmentation segmentation_in, bool (*predicate)(const TriangularCartesian2D_Cell &)) { TriangularCartesian2D_Domain domain_out; TriangularCartesian2D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularCartesian2D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularCartesian2D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularCartesian2D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularCartesian2D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularCartesian2D_Domain, TriangularCartesian2D_Segmentation>(domain_out, segmentation_out); }
Add test for autoencoder with RBM pretraining
//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <deque> #include "dll_test.hpp" #include "dll/dense_layer.hpp" #include "dll/scale_layer.hpp" #include "dll/dbn.hpp" #include "dll/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("dbn/ae/1", "[rbm][dbn][mnist][sgd][ae]") { typedef dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>>::rbm_t, dll::rbm_desc<200, 28 * 28, dll::momentum, dll::batch_size<25>>::rbm_t >, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000); REQUIRE(!dataset.training_images.empty()); dll_test::mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 50); dbn->learning_rate = 0.1; auto ft_error = dbn->fine_tune_ae(dataset.training_images, 50); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set_ae(*dbn, dataset.test_images); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); }
Add Solution 006 ZigZag Conversion
// 6. ZigZag Conversion /** * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: * (you may want to display this pattern in a fixed font for better legibility) * * P A H N * A P L S I I G * Y I R * * And then read line by line: "PAHNAPLSIIGYIR" * Write the code that will take a string and make this conversion given a number of rows: * * string convert(string text, int nRows); * * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". * * Tags: String * * Author: Kuang Qin */ #include <iostream> #include <string> using namespace std; class Solution { public: string convert(string s, int numRows) { if (numRows <= 1) { return s; } string res; // P | A | H | N // A P | L S | I I | G // Y | I | R | // each row has 2 elements except the first row and the last row in one period int period = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { // build each row for (int j = i; j < s.size(); j += period) { // build string in each period res += s[j]; // 0 : 0 | // 1 : 1 p - 1 | // . . . | // . . . | // . . . | // i : j p - i | // . . . | // . . . | // . . . | // n - 2 : n - 2 p - (n - 2) | // n - 1 : n - 1 | // calculate the position of the second element int k = j - i + period - i; // if not the first or last row append the second element if (i != 0 && i != numRows - 1 && k < s.size()) { res += s[k]; } } } return res; } }; int main() { string s = "PAYPALISHIRING"; Solution sol; string res = sol.convert(s, 3); cout << res << endl; cin.get(); return 0; }
Add a test for PR14074
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <streambuf> // template <class charT, class traits = char_traits<charT> > // class basic_streambuf; // streamsize xsputn(const char_type* s, streamsize n); // Test https://bugs.llvm.org/show_bug.cgi?id=14074. The bug is really inside // basic_streambuf, but I can't seem to reproduce without going through one // of its derived classes. #include <cassert> #include <cstddef> #include <cstdio> #include <fstream> #include <sstream> #include <string> #include "platform_support.h" // Count the number of bytes in a file -- make sure to use only functionality // provided by the C library to avoid relying on the C++ library, which we're // trying to test. static std::size_t count_bytes(char const* filename) { std::FILE* f = std::fopen(filename, "rb"); std::size_t count = 0; while (std::fgetc(f) != EOF) ++count; return count; } int main(int, char**) { { // with basic_stringbuf std::basic_stringbuf<char> buf; std::streamsize sz = buf.sputn("\xFF", 1); assert(sz == 1); assert(buf.str().size() == 1); } { // with basic_filebuf std::string temp = get_temp_file_name(); { std::basic_filebuf<char> buf; buf.open(temp.c_str(), std::ios_base::out); std::streamsize sz = buf.sputn("\xFF", 1); assert(sz == 1); } assert(count_bytes(temp.c_str()) == 1); std::remove(temp.c_str()); } return 0; }
Test for 'bad_array_length'; got left out of initial commit
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // test bad_array_length #include <new> #include <type_traits> #include <cassert> int main() { #if __LIBCPP_STD_VER > 11 static_assert((std::is_base_of<std::bad_alloc, std::bad_array_length>::value), "std::is_base_of<std::bad_alloc, std::bad_array_length>::value"); static_assert(std::is_polymorphic<std::bad_array_length>::value, "std::is_polymorphic<std::bad_array_length>::value"); std::bad_array_length b; std::bad_array_length b2 = b; b2 = b; const char* w = b2.what(); assert(w); #endif }
Implement useful function to compare double in order to prevent problems with precision.
#include <stdio.h> using namespace std; const double EPS = 1e-15; /* * Return * -1 if x < y * 0 if x == y * 1 if x > y */ int cmp (double x, double y){ return (x <= y + EPS) ? (x + EPS < y) ? -1 : 0 : 1; } int main(){ double d1 = 0.00000000000212; double d2 = 0.00000000000213; int res = cmp(d1,d2); if (res == 0){ printf("Equal \n"); }else if(res == 1){ printf("Greater\n"); }else { printf("Less \n"); } }
Add nested loop example specimen 5
// A nested loop. #include <stdio.h> int main() { int n; scanf("%d", &n); int *A = new int[n]; int *B = new int[n]; for (int i = 0; i < n; ++i) { scanf("%d", &A[i]); } for (int i = 0; i < n; ++i) { scanf("%d", &B[i]); } int sum = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { sum += A[i] * B[j]; } } printf("%d\n", sum); delete[] A; delete[] B; }
Add a list of TODOs
#include "server.h" using namespace SeaSocks; int main(int argc, const char* argv[]) { Server server; server.serve("src/web", 9090); return 0; }
#include "server.h" /* * TODOs: * * Add logging * * Connection class does *everything*. Work out better division of labour; server should do more, connection should just be connection stuff, handlers for data? * * sort out buffers and buffering * * work out what state to hang on to; handle multiple WS endpoints * * work out threading model for asynch message passing. * * Fix bloody SO_REUSEADDR */ using namespace SeaSocks; int main(int argc, const char* argv[]) { Server server; server.serve("src/web", 9090); return 0; }
Add a RNN perf workbench
//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define ETL_COUNTERS #define ETL_GPU_POOL #include "dll/neural/dense/dense_layer.hpp" #include "dll/neural/rnn/rnn_layer.hpp" #include "dll/neural/recurrent/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto dataset = dll::make_mnist_dataset_nc(dll::batch_size<200>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 200; // Build the network using network_t = dll::network_desc< dll::network_layers< dll::rnn_layer<time_steps, sequence_length, hidden_units>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<200> // The mini-batch size , dll::no_batch_display // Disable pretty print of each every batch , dll::no_epoch_error // Disable computation of the error at each epoch >::network_t; auto net = std::make_unique<network_t>(); // Display the network and dataset net->display_pretty(); dataset.display_pretty(); // Train the network for performance sake net->train(dataset.train(), 5); // Test the network on test set net->evaluate(dataset.test()); // Show where the time was spent dll::dump_timers_pretty(); // Show ETL performance counters etl::dump_counters_pretty(); return 0; }
Add lexicographical compare with tie
// Lexicographic-compare // C++11 #include <tuple> class foo { public: foo(int n_, char c_, double d_) : n{n_}, c{c_}, d{d_} {} friend bool operator<(const foo& lh, const foo& rh) { return std::tie(lh.n, lh.c, lh.d) < std::tie(rh.n, rh.c, rh.d); } private: int n; char c; double d; }; // Implement compare of multiple members with std::tie // // Getting an order relation right with 3 elements or more is // tedious and easy to get wrong. Fortunately the standard // library does it with tuples. The function template std::tie() // creates a tuple with references to its arguments. // // The class `foo`, on [6-22] has three member variables `n`, `c` and `d` // declared on [19-21]. // // The less-than operator on [13-17] compares two `foo`s on the member // `n` first, on the member `c` if the `n`s are equal, and finally on // `d` if both the `n`s and `c`s are equal. // // The formatting [14-15] to align the left hand and right hand // arguments straight below each others makes it easier to spot // mistakes as assymetries. // // It is not necessary to declare the less-than operator as a friend // function [13], it can be implemented as a member function as well, // but this is a common idiom. int main() { foo f1(1, 'a', 3.14); foo f2(1, 'b', 2.78); if (f1 < f2) { return 1; } }
Set default value for terrain_data field
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG 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. // // EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "rpg_chipset.h" //////////////////////////////////////////////////////////// /// Constructor //////////////////////////////////////////////////////////// RPG::Chipset::Chipset() { ID = 0; name = ""; chipset_name = ""; animation_type = 0; animation_speed = 0; }
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG 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. // // EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "rpg_chipset.h" //////////////////////////////////////////////////////////// /// Constructor //////////////////////////////////////////////////////////// RPG::Chipset::Chipset() { ID = 0; name = ""; chipset_name = ""; terrain_data.resize(162, 1); animation_type = 0; animation_speed = 0; }
Add a simple example application
#include <cmath> #include <iostream> #include <random> #include <thread> #include "gflags/gflags.h" #include "glog/logging.h" #include "driver/engine.hpp" #include "lib/abstract_data_loader.hpp" #include "lib/labeled_sample.hpp" #include "lib/parser.hpp" using namespace csci5570; using Sample = double; using DataStore = std::vector<Sample>; DEFINE_string(config_file, "", "The config file path"); DEFINE_string(input, "", "The hdfs input url"); int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); FLAGS_stderrthreshold = 0; FLAGS_colorlogtostderr = true; LOG(INFO) << FLAGS_config_file; Node node{0, "localhost", 12353}; Engine engine(node, {node}); // 1. Start system engine.StartEverything(); // 1.1 Create table const auto kTableId = engine.CreateTable<double>(ModelType::SSP, StorageType::Map); // table 0 // 1.2 Load data engine.Barrier(); // 2. Start training task MLTask task; task.SetWorkerAlloc({{0, 3}}); // 3 workers on node 0 task.SetTables({kTableId}); // Use table 0 task.SetLambda([kTableId](const Info& info) { LOG(INFO) << info.DebugString(); KVClientTable<double> table = info.CreateKVClientTable<double>(kTableId); for (int i = 0; i < 1e8; ++i) { std::vector<Key> keys{1}; std::vector<double> ret; table.Get(keys, &ret); LOG(INFO) << ret[0]; std::vector<double> vals{0.5}; table.Add(keys, vals); table.Clock(); } }); engine.Run(task); // 3. Stop engine.StopEverything(); return 0; }
Implement a binary search on a sorted array
// // main.cpp // CPP // // Created by Mgen on 8/27/16. // Copyright © 2016 Mgen. All rights reserved. // #include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; // runs a binary search on a given array, returns the insert position of a given integer int findInsertPosition(vector<int>& nums, int target) { int i = 0, j = nums.size() - 1; while (i < j) { int mid = i + (j - i) / 2; if (target <= nums[mid]) { j = mid; } else { i = mid + 1; } } return i; } // runs a binary search in O(log n) and finds k closest elements in O(k). multiset<int> binarySearch(vector<int> nums, int target, int k) { multiset<int> result; // sort the array sort(nums.begin(), nums.end()); // assume target exists and k <= nums.size() int idx = findInsertPosition(nums, target); // insert the most closest element into the set result.insert(nums[idx]); int i = idx - 1, j = idx + 1; // find the other k - 1 closest elements while (result.size() < k) { if (j >= nums.size() - 1 || target - nums[i] < nums[j] - target) { result.insert(nums[i--]); } else { result.insert(nums[j++]); } } return result; } void printSet(multiset<int>& set) { for (auto n: set) { cout << n << " "; } cout << endl; } int main() { vector<int> sortedNums = {1, 2, 3, 4, 6, 6, 10}; multiset<int> result; // find 4 closest element to 6 result = binarySearch(sortedNums, 6, 4); printSet(result); // find 5 closest element to 5 result = binarySearch(sortedNums, 5, 5); printSet(result); return 0; }
Add a test for PR3733.
struct x { x() : a(4) ; // expected-error {{expected '{'}} }; struct y { int a; y() : a(4) ; // expected-error {{expected '{'}} };
Check if Every Row and Column Contains All Numbers
class Solution { public: bool checkValid(vector<vector<int>>& matrix) { for (int i = 0; i < matrix.size(); ++i) { std::vector<int> check(matrix.size()+1, 0); for (int j = 0; j < matrix[0].size(); ++j) { if (check[matrix[i][j]] == 1) return false; check[matrix[i][j]] = 1; } } for (int j = 0; j < matrix[0].size(); ++j) { std::vector<int> check(matrix.size()+1, 0); for (int i = 0; i < matrix.size(); ++i) { if (check[matrix[i][j]] == 1) return false; check[matrix[i][j]] = 1; } } return true; } };
Add solution for 226. Invert Binary Tree.
/** * [Link:] https://leetcode.com/problems/invert-binary-tree/ */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if(!root) return root; if(!root->left && !root->right) return root; TreeNode* tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; } };
Test implicit declaration of copy assignment operator with non-const argument
// RUN: %clang_cc1 -fsyntax-only -verify %s struct ConstCopy { ConstCopy(); ConstCopy &operator=(const ConstCopy&); }; struct NonConstCopy { NonConstCopy(); NonConstCopy &operator=(NonConstCopy&); }; struct VirtualInheritsNonConstCopy : virtual NonConstCopy { VirtualInheritsNonConstCopy(); VirtualInheritsNonConstCopy &operator=(const VirtualInheritsNonConstCopy&); }; struct ImplicitNonConstCopy1 : NonConstCopy { // expected-note{{the implicit copy assignment operator}} ImplicitNonConstCopy1(); }; struct ImplicitNonConstCopy2 { // expected-note{{the implicit copy assignment operator}} ImplicitNonConstCopy2(); NonConstCopy ncc; }; struct ImplicitNonConstCopy3 { // expected-note{{the implicit copy assignment operator}} ImplicitNonConstCopy3(); NonConstCopy ncc_array[2][3]; }; struct ImplicitNonConstCopy4 : VirtualInheritsNonConstCopy { ImplicitNonConstCopy4(); }; void test_non_const_copy(const ImplicitNonConstCopy1 &cincc1, const ImplicitNonConstCopy2 &cincc2, const ImplicitNonConstCopy3 &cincc3, const ImplicitNonConstCopy4 &cincc4, const VirtualInheritsNonConstCopy &vincc) { (void)sizeof(ImplicitNonConstCopy1() = cincc1); // expected-error{{no viable overloaded '='}} (void)sizeof(ImplicitNonConstCopy2() = cincc2); // expected-error{{no viable overloaded '='}} (void)sizeof(ImplicitNonConstCopy3() = cincc3); // expected-error{{no viable overloaded '='}} (void)sizeof(ImplicitNonConstCopy4() = cincc4); // okay (void)sizeof(VirtualInheritsNonConstCopy() = vincc); }
Add test program for breadth first search
#include<iostream> #include "bfs.h" // My implementation of breadth first search #include<vector> // tests Bfs traversal, distances and paths void testBfs(){ // edges std::vector<std::vector<int> > edges = { {1,5}, {3,5}, {2,4}, {1,4}, {5,7}, {7,6}, {2,6} }; int n = 8; // no. of vertices int m = 7; // no. of edges int s = 1; // source vertex Bfs bfs(n, m, edges, s); // print traversal std::cout<<"Traversal: "; bfs.traverse(); // print distances of vertices from source std::cout<<"\nDistances:\n"; bfs.printDistances(); // print path from source to all vertices std::cout<<"Paths: \n"; bfs.printAllPaths(); // deallocate vertices bfs.deallocateVertices(); } int main(){ // call testBfs testBfs(); return 0; }
Add algorithm to fing the len of longest common subsequenc..
#include <bits/stdc++.h> #define endl '\n' using namespace std; const int M_MAX = 20; // Máximo size del String 1 const int N_MAX = 20; // Máximo size del String 2 int m, n; // Size de Strings 1 y 2 string X; // String 1 string Y; // String 2 int memo[M_MAX + 1][N_MAX + 1]; int lcs (int m, int n) { for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) memo[i][j] = 0; else if (X[i - 1] == Y[j - 1]) memo[i][j] = memo[i - 1][j - 1] + 1; else memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]); } } return memo[m][n]; } int main(){ X = "XMJYAUZ"; Y = "MZJAWXU"; cout << lcs(X.size(), Y.size()) <<endl; //Sol = MJAU return 0; }
Add Chapter 21, Try This 1
// Chapter 21, Try This 1: test two different definitions of the find algorithm #include "../lib_files/std_lib_facilities.h" //------------------------------------------------------------------------------ template<class In, class T> In find1(In first, In last, const T& val) { while (first!=last && *first!=val) ++first; return first; } //------------------------------------------------------------------------------ template<class In, class T> In find2(In first, In last, const T& val) { for (In p = first; p!=last; ++p) if (*p==val) return p; return last; } //------------------------------------------------------------------------------ int main() try { vector<int> vi; for (int i = 0; i<25; ++i) { vi.push_back(randint(50)); cout << vi[i] << ' '; } cout << "\n"; int idx = randint(vi.size()); cout << "Looking for " << vi[idx] << ":\n"; vector<int>::iterator v_iter1 = find1(vi.begin(),vi.end(),vi[idx]); vector<int>::iterator v_iter2 = find2(vi.begin(),vi.end(),vi[idx]); while (v_iter1!=vi.end()) { cout << *v_iter1 << '/' << *v_iter2 << ' '; ++v_iter1; ++v_iter2; } cout << "\n"; } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
Add a scenario showing a kind of deadlock that is unsupported right now.
/** * This test checks whether we detect a deadlock arising from a parent thread * trying to join a child who requires a lock held by its parent in order to * finish. */ #include <d2mock.hpp> int main(int argc, char const* argv[]) { d2mock::mutex G; d2mock::thread t1([&] { G.lock(); G.unlock(); }); d2mock::thread t0([&] { t1.start(); // if t0 acquires G before t1 does, t1 can never be joined G.lock(); t1.join(); G.unlock(); }); auto test_main = [&] { t0.start(); t0.join(); }; // Right now, we have no way of encoding these kinds of deadlocks, // and we're obviously not detecting them too. For now, we'll always // make the test fail. #if 1 return EXIT_FAILURE; #else return d2mock::check_scenario(test_main, argc, argv, { { // t0 holds G, and waits for t1 to join {t0, G, join(t1)}, // t1 waits for G, and will never be joined {t1, G} } }); #endif }
Test that static_assert is properly visited in liblcang
static_assert(2 + 2 == 4, "Simple maths"); // RUN: c-index-test -test-load-source all -fno-delayed-template-parsing -std=c++11 %s | FileCheck %s // CHECK: load-staticassert.cpp:2:1: StaticAssert=:2:1 (Definition) Extent=[2:1 - 2:42] // CHECK: load-staticassert.cpp:2:15: BinaryOperator= Extent=[2:15 - 2:25] // CHECK: load-staticassert.cpp:2:15: BinaryOperator= Extent=[2:15 - 2:20] // CHECK: load-staticassert.cpp:2:15: IntegerLiteral= Extent=[2:15 - 2:16] // CHECK: load-staticassert.cpp:2:19: IntegerLiteral= Extent=[2:19 - 2:20] // CHECK: load-staticassert.cpp:2:24: IntegerLiteral= Extent=[2:24 - 2:25] // CHECK: load-staticassert.cpp:2:27: StringLiteral="Simple maths" Extent=[2:27 - 2:41]
Remove nth element from the end of list.
/** * Remove Nth Node From End of List * Double pointer. * * cpselvis(cpselvis@gmail.com) * August 18th, 2016 */ #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *fast = head, *slow = head; while (n --) { fast = fast -> next; } while (fast == NULL) { return head -> next; } while (fast -> next != NULL) { fast = fast -> next; slow = slow -> next; } slow -> next = slow -> next -> next; return head; } }; int main(int argc, char **argv) { Solution s; ListNode *p = new ListNode(1); // p -> next = new ListNode(2); // p -> next -> next = new ListNode(3); ListNode *ret = s.removeNthFromEnd(p, 1); cout << ret -> val << endl; }
Add stub exception handler backend for linux
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/exception_handler.h" #include "xenia/base/assert.h" #include "xenia/base/math.h" #include "xenia/base/platform_linux.h" namespace xe { // This can be as large as needed, but isn't often needed. // As we will be sometimes firing many exceptions we want to avoid having to // scan the table too much or invoke many custom handlers. constexpr size_t kMaxHandlerCount = 8; // All custom handlers, left-aligned and null terminated. // Executed in order. std::pair<ExceptionHandler::Handler, void*> handlers_[kMaxHandlerCount]; void ExceptionHandler::Install(Handler fn, void* data) { //TODO(dougvj) stub } void ExceptionHandler::Uninstall(Handler fn, void* data) { //TODO(dougvj) stub } } // namespace xe
Add Chapter 20, Try This 8
// Chapter 20, Try This 8: same as Try This 7, but with an array of int, a // vector<int> and a list<int>, with the value { 1, 2, 3, 4, 5 }. #include "../lib_files/std_lib_facilities.h" // requires size of array as it decays to a pointer void ai_func(const int ai[], int sz) { cout << "Number of elements in ai: " << sz << "\n"; } void vi_func(const vector<int>& vi) { cout << "Number of elements in vi: " << vi.size() << "\n"; } void li_func(const list<int>& li) { cout << "Number of elements in li: " << li.size() << "\n"; } int main() try { int ai[] = { 1, 2, 3, 4, 5 }; ai_func(ai,sizeof(ai)/sizeof(*ai)); vector<int> vi; for (int i = 1; i<6; ++i) vi.push_back(i); vi_func(vi); list<int> li; for (int i = 1; i<6; ++i) li.push_back(i); li_func(li); } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; }
Implement queue using circular array
#include <iostream> using namespace std; struct Queue { int *array; int front, rear; int size; }; Queue* createQueue(int size) { Queue *queue = new Queue(); if (!queue) return NULL; queue->front = queue->rear = -1; queue->size = size; queue->array = new int[queue->size]; if (!queue->array) return NULL; return queue; } bool isFull(Queue* queue) { return (queue && ((queue->rear + 1) % queue->size == queue->front)); } bool isEmpty(Queue* queue) { return (queue && queue->front == -1); } void enqueue(Queue *queue, int data) { if (isFull(queue)) return; queue->rear = (queue->rear + 1) % queue->size; queue->array[queue->rear] = data; if (queue->front == -1) queue->front = queue->rear; } int dequeue(Queue *queue) { if (isEmpty(queue)) return -1; int data = queue->array[queue->front]; if (queue->front == queue->rear) queue->front = queue->rear = -1; else queue->front = (queue->front + 1) % queue->size; return data; } void deleteQueue(Queue *queue) { if (isEmpty(queue)) return; delete [] queue->array; delete queue; } void printQueue(Queue *queue) { if (isEmpty(queue)) return; for (int i = queue->front; i <= queue->rear; i++) { cout<<queue->array[i]<<" "; } cout<<endl; } size_t size(Queue *queue) { return isEmpty(queue) ? 0 : (queue->size - (queue->front + queue->rear+1)) % queue->size; } int main() { Queue *queue = createQueue(10); enqueue(queue, 1); enqueue(queue, 2); enqueue(queue, 3); enqueue(queue, 4); enqueue(queue, 5); enqueue(queue, 6); enqueue(queue, 7); enqueue(queue, 8); enqueue(queue, 9); enqueue(queue, 10); enqueue(queue, 11); printQueue(queue); int del = 5; cout<<"Dequeue 5 elements\n"; while (del--) { cout<<dequeue(queue)<<" "; } cout<<endl; cout<<"Enqueue 12,13,14,15 \n"; enqueue(queue, 12); enqueue(queue, 13); enqueue(queue, 14); enqueue(queue, 15); cout<<"Size of queue: "<<size(queue)<<endl; printQueue(queue); del = 6; cout<<"Dequeue 6 elements\n"; while (del--) { cout<<dequeue(queue)<<" "; } cout<<endl; cout<<"Size of queue: "<<size(queue)<<endl; printQueue(queue); deleteQueue(queue); return 0; }
Add cc file with definition of tensorflow::gtl::nullopt.
/* Copyright 2017 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/lib/gtl/optional.h" namespace tensorflow { namespace gtl { nullopt_t::init_t nullopt_t::init; extern const nullopt_t nullopt{nullopt_t::init}; } // namespace gtl } // namespace tensorflow
Add test case for crash reported in <rdar://problem/8236270> (which has since been fixed in trunk).
// RUN: c-index-test -test-load-source all %s 2>&1 | FileCheck %s // This test case previously just crashed the frontend. struct abc *P; int main( // CHECK: StructDecl=abc:5:8 Extent=[5:1 - 5:11] // CHECK: VarDecl=P:5:13 (Definition) Extent=[5:8 - 5:14] // CHECK: VarDecl=main:6:5 (Definition) Extent=[6:1 - 6:9]
Add unit tests covering operator[] and insert
#include <gtest/gtest.h> #include "LRUCache.hxx" TEST(LRUCache, InsertPair) { LRUCache<int, std::string, 3> cache; auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1")); EXPECT_EQ(std::string("1"), pairResult.first->second); EXPECT_TRUE(pairResult.second); EXPECT_EQ(1, cache.size()); pairResult = cache.insert(std::make_pair<int, std::string>(2, "2")); EXPECT_EQ(std::string("2"), pairResult.first->second); EXPECT_TRUE(pairResult.second); EXPECT_EQ(2, cache.size()); pairResult = cache.insert(std::make_pair<int, std::string>(3, "3")); EXPECT_EQ(std::string("3"), pairResult.first->second); EXPECT_TRUE(pairResult.second); EXPECT_EQ(3, cache.size()); pairResult = cache.insert(std::make_pair<int, std::string>(4, "4")); EXPECT_EQ(std::string("4"), pairResult.first->second); EXPECT_TRUE(pairResult.second); EXPECT_EQ(3, cache.size()); } TEST(LRUCache, BracketOperator) { LRUCache<int, std::string, 5> cache; cache.insert(std::make_pair<int, std::string>(1, "1")); auto& value = cache[1]; EXPECT_EQ(std::string("1"), value); }
Add C++11 solution for Nov. 2013 Bronze Problem 1
#include <istream> #include <fstream> #include <set> #include <vector> #include <array> #include <algorithm> #include <iterator> using namespace std; int main() { ifstream cin("combo.in"); ofstream cout("combo.out"); int size; cin >> size; set<int> options; for (int i = 0; i < 2; i++) { int a, b, c; cin >> a >> b >> c; // creates permutations of allowable combinations and turns them into // an integer so that set can compare them and only retain uniques // the indexes here start at -3 and end at +1 because the input starts // at 1 but here we want it to start at 0 for (int i = a - 3; i <= a + 1; i++) { for (int j = b - 3; j <= b + 1; j++) { for (int k = c - 3; k <= c + 1; k++) { options.insert(((((i % size) + size) % size) << 0) + ((((j % size) + size) % size) << 8) + ((((k % size) + size) % size) << 16)); } } } } // the size of the set is the number of unique combinations cout << options.size() << endl; return 0; }
Add unit test for ControlTask
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Utils/TestUtils.hpp> #include "gtest/gtest.h" #include <hspp/Cards/Minion.hpp> #include <hspp/Managers/GameAgent.hpp> #include <hspp/Tasks/SimpleTasks/ControlTask.hpp> using namespace Hearthstonepp; using namespace SimpleTasks; using namespace TestUtils; TEST(ControlTask, GetTaskID) { const ControlTask control(EntityType::TARGET); EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL); }
Add entry file building glsl optimzier for emscripten
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "glsl_optimizer.h" static glslopt_ctx* gContext = 0; #include <emscripten/val.h> #define str(str) std::string(str) static bool compileShader2(const char* originalShader, bool vertexShader) { if( !originalShader ) return false; const glslopt_shader_type type = vertexShader ? kGlslOptShaderVertex : kGlslOptShaderFragment; glslopt_shader* shader = glslopt_optimize(gContext, type, originalShader, 0); if( !glslopt_get_status(shader) ) { const char* failed_log = glslopt_get_log(shader); // printf( "Failed to compile:\n\n%s\n", failed_log); emscripten::val::global("HLSLParser").call<void>("onError", str("Failed to compiled: ") + str(failed_log)); return false; } const char* optimizedShader = glslopt_get_output(shader); // printf("Out: %s\n", optimizedShader); emscripten::val::global("HLSLParser").call<void>("onSuccess", str(optimizedShader)); return true; } extern "C" { int optimize_glsl(char* source, char* type) { bool vertexShader = false; glslopt_target languageTarget = kGlslTargetOpenGL; // fragment shader vertexShader = false; // ES 2 languageTarget = kGlslTargetOpenGLES20; //kGlslTargetOpenGLES20 kGlslTargetOpenGLES30 kGlslTargetOpenGL if( !source ) return printf("Must give a source"); gContext = glslopt_initialize(languageTarget); if( !gContext ) { printf("Failed to initialize glslopt!\n"); return 1; } int result = 0; if( !compileShader2(source, vertexShader) ) result = 1; glslopt_cleanup(gContext); return result; } }
Add fuzzing driver to classads HTCONDOR-814
#include "classad/classad_distribution.h" #include <string> #include <string.h> #include <sys/types.h> /* This is the driver for the classad fuzz tester. * Note this is intentionally not in the cmake file, it should not be built * by default. * * To use, compile all of classads with clang -fsanitize=fuzzer-nolink,address * then recompile this one file with clang -fsanitize=fuzzer * This adds a magic main function here. * Then, just run ./a.out and let it run for a long time. */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *input, size_t len) { classad::ClassAdParser parser; classad::ExprTree *tree; std::string s(input, input + len); tree = parser.ParseExpression(s); delete tree; return 0; }
Add example to read SDP3x using isr
#include <Arduino.h> #include "sdplib.h" #include "Wire.h" #define IRQ_PIN 4 SDPclass sdp; double diff_pressure, temperature; bool sdpFlag = false; // Interrupt routine void SDP_isr(void){ sdpFlag = true; } void setup(){ while(!Serial){ Serial.begin(115200); } pinMode(IRQ_PIN, INPUT_PULLUP); attachInterrupt(IRQ_PIN, SDP_isr, FALLING); // active when low, so we seek for change to low Wire.begin(); sdp.begin(); sdp.getAddress(); sdp.startContinuousMeasurement(SDP_TEMPCOMP_DIFFERENTIAL_PRESSURE, SDP_AVERAGING_TILL_READ); } void loop(){ if(sdpFlag == true){ diff_pressure = sdp.getDiffPressure(); temperature = sdp.getTemperature(); sdpFlag = false; } }
Add tests for 'InputArg' class
// Standard headers #include <memory> #include <iostream> // External headers #include "gmock/gmock.h" // Internal headers #include "InputArgs.hpp" // Alias using ::testing::DoubleNear; const double PI = 3.141592653589793238462643; class ASetOfInputArguments : public testing::Test { }; TEST_F(ASetOfInputArguments, NonZeroNumberOfThreads) { std::unique_ptr<const char *[]> argv ( new const char *[6] { "Cosine", "2", "f", "10", "1", "d" } ); InputArgs args(6, argv.get()); ASSERT_TRUE(args.n_threads == 2 and args.stop_criteria == 'f' and args.precision == 10 and args.cosine == 1 and args.debug_level == 'd'); } TEST_F(ASetOfInputArguments, ZeroNumberOfThreads) { std::unique_ptr<const char *[]> argv ( new const char *[6] { "Cosine", "0", "f", "10", "1", "d" } ); InputArgs args(6, argv.get()); ASSERT_TRUE(args.n_threads == std::thread::hardware_concurrency() and args.stop_criteria == 'f' and args.precision == 10 and args.cosine == 1 and args.debug_level == 'd'); }
Add missed test in r276090.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <functional> // See https://llvm.org/bugs/show_bug.cgi?id=20002 #include <functional> #include <type_traits> using Fn = std::function<void()>; struct S : Fn { using function::function; }; int main() { S f1( Fn{} ); S f2(std::allocator_arg, std::allocator<void>{}, Fn{}); }
Add a test to cover the bug that was fixed recently where bool in memory is a byte, but a bool vector inside llvm is bitpacked so loading 8 bools would load a byte, not 8-bytes, if vectorized.
#include <stdio.h> #include <Halide.h> using namespace Halide; int main(int argc, char **argv) { Var x, y; Func pred("pred"); pred(x, y) = x < y; Func selector("selector"); selector(x, y) = select(pred(x, y), 1, 0); // Load a vector of 8 bools pred.compute_root(); selector.compute_root().vectorize(x, 8); RDom range(0, 100, 0, 100); int32_t result = evaluate<int32_t>(lambda(sum(selector(range.x, range.y)))); assert(result == 4950); printf("Success!\n"); return 0; }
Add new example: external interrupt on pin change
#include "board.h" #include <aery32/gpio.h> #include <aery32/delay.h> #include <aery32/intc.h> using namespace aery; void isrhandler(void) { gpio_toggle_pin(LED); delay_ms(100); /* Reduce glitch */ porta->ifrc = (1 << 0); /* Remember to clear the interrupt */ } int main(void) { init_board(); /* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */ gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE); /* Init interrupt controller */ intc_init(); intc_register_isrhandler( &isrhandler, /* Function pointer to the ISR handler */ 2, /* Interrupt group number */ 0 /* Priority level */ ); /* Enable interrupts globally */ intc_enable_globally(); for(;;) { /* * Now try to connect PA00 to GND and then disconnecting it * to let pull-up make the pin state high again. The LED should * toggle on the pin change. */ } return 0; }
Add executable allowing generation of the keyfile.
#include "condor_auth_passwd.h" #include "classad/classad.h" #include "classad/sink.h" #include "match_prefix.h" #include "CondorError.h" #include "condor_config.h" void print_usage(const char *argv0) { fprintf(stderr, "Usage: %s -identity USER@UID_DOMAIN [-token VALUE]\n\n" "Generates a derived key from the local master password and prints its contents to stdout.\n", argv0); exit(1); } int main(int argc, char *argv[]) { if (argc < 3) { print_usage(argv[0]); } std::string identity; std::string token; for (int i = 1; i < argc; i++) { if (is_dash_arg_prefix(argv[i], "identity", 2)) { i++; if (!argv[i]) { fprintf(stderr, "%s: -identity requires a condor identity as an argument", argv[0]); exit(1); } identity = argv[i]; } else if (is_dash_arg_prefix(argv[i], "token", 1)) { i++; if (!argv[i]) { fprintf(stderr, "%s: -token requires an argument", argv[0]); exit(1); } token = argv[i]; } else if (is_dash_arg_prefix(argv[i], "help", 1)) { print_usage(argv[0]); exit(1); } else { fprintf(stderr, "%s: Invalid command line argument: %s", argv[0], argv[i]); print_usage(argv[0]); exit(1); } } config(); classad::ClassAd result_ad; CondorError err; if (!Condor_Auth_Passwd::generate_derived_key(identity, token, result_ad, &err)) { fprintf(stderr, "Failed to generate a derived key.\n"); fprintf(stderr, "%s\n", err.getFullText(true).c_str()); exit(2); } classad::ClassAdUnParser unp; std::string result; unp.Unparse(result, &result_ad); printf("%s\n", result.c_str()); return 0; }
Add a solution to problem 237: Delete Node in a Linked List.
// https://leetcode.com/problems/delete-node-in-a-linked-list/ // Since node given is not a tail. We could do a trick: copy the contents of // the next node, then connect to the next of next, delete the next node. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { if (node->next != nullptr) { ListNode* tmp = node->next; node->val = tmp->val; node->next = tmp->next; delete tmp; } else { // we are assured node is not the tail. throw std::invalid_argument(to_string(reinterpret_cast<intptr_t>(node)) + " points to a tail."); } } };
Add test for a bad fold.
#include <stdio.h> #include "Halide.h" using namespace Halide; int main(int argc, char **argv) { Var x, y, c; Func f, g; f(x, y) = x; g(x, y) = f(x-1, y+1) + f(x, y-1); f.store_root().compute_at(g, y).fold_storage(y, 2); Image<int> im = g.realize(100, 1000); printf("Should have gotten a bad fold!\n"); return -1; }
Add solution for 128 Longest Consecutive Sequence
//128. Longest Consecutive Sequence /* *Given an unsorted array of integers, find the length of the longest consecutive elements sequence. * *For example, *Given [100, 4, 200, 1, 3, 2], *The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. * *Your algorithm should run in O(n) complexity. * *Tag: Array, Union Find * *Author: Linsen Wu */ #include "stdafx.h" #include <vector> #include <unordered_set> using namespace std; class Solution { public: int longestConsecutive(vector<int> &nums) { if(nums.empty()) return 0; unordered_set<int> ht; for(int i=0; i<nums.size(); i++) ht.insert(nums[i]); int maxLen = 1; for(int i=0; i<nums.size(); i++) { if(ht.empty()) break; int curLen = 0; int curnums = nums[i]; while(ht.count(curnums)) { ht.erase(curnums); curLen++; curnums++; } curnums = nums[i]-1; while(ht.count(curnums)) { ht.erase(curnums); curLen++; curnums--; } maxLen = max(maxLen, curLen); } return maxLen; } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
Add code to delete node in linked list
#include<iostream> #include<cstdlib> using namespace std; class Node{ public: int data; Node *next; Node(){} Node(int d){ data=d; next=NULL; } Node *insertNode(Node *head, int d){ Node *np=new Node(d); Node *tmp=head; if(head==NULL) return np; else while(tmp->next) tmp=tmp->next; tmp->next=np; return head; } Node *deleteNode(Node *head, int pos){ Node *tmp=head; int c=1; if(pos==1){ head=tmp->next; free(tmp); } else{ while(c!=pos-1){ tmp=tmp->next; c++; } Node *tm=tmp->next; tmp->next=tmp->next->next; free(tm); } return head; } void displayList(Node *head){ Node *tmp=head; cout<<"Elements of the list are:\n"; while(tmp!=NULL){ cout<<tmp->data<<"\n"; tmp=tmp->next; } } }; int main() { int n,p,pos,d; Node np; Node *head=NULL; cout<<"Enter the size of linked list: "; cin>>n; for(int i=0;i<n;i++){ cout<<"\nEnter element "<<i+1<<": "; cin>>p; head=np.insertNode(head,p); } cout<<"\nEnter the position where you wish to delete the element: "; cin>>pos; if(pos>n) cout<<"\nSorry! The position you entered is out of bounds.\n"; else head=np.deleteNode(head,pos); np.displayList(head); }
Add missing C++ test bench driver
/* * Copyright 2019 The Project Oak Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include "VmkModule1.h" #include "verilated.h" #include "verilated_vcd_c.h" int main(int argc, char **argv) { Verilated::commandArgs(argc, argv); VmkModule1 *counter4 = new VmkModule1; VerilatedVcdC* vcd_trace = new VerilatedVcdC; Verilated::traceEverOn(true); counter4->trace(vcd_trace, 99); vcd_trace->open("counter4_tb.vcd"); vluint64_t time = 0; counter4->CLK = 0; counter4->RST_N = 0; counter4->EN_count_value = 1; counter4->eval(); vcd_trace->dump(time); counter4->CLK = 1; counter4->eval(); time += 10; vcd_trace->dump(time); counter4->CLK = 0; counter4->RST_N = 1; time += 10; counter4->eval(); vcd_trace->dump(time); for (int i = 1; i < 20; ++ i) { counter4->CLK = 1; counter4->eval(); time += 10; vcd_trace->dump(time); counter4->CLK = 0; counter4->eval(); time += 10; vcd_trace->dump(time); } vcd_trace->close(); exit(EXIT_SUCCESS); }
Add a test for the full round trip through libclang and the plugin.
// RUN: c-index-test -test-load-source-reparse 2 all %s -Xclang -add-plugin -Xclang clang-include-fixer -fspell-checking -Xclang -plugin-arg-clang-include-fixer -Xclang -input=%p/Inputs/fake_yaml_db.yaml 2>&1 | FileCheck %s foo f; // CHECK: yamldb_plugin.cpp:3:1: error: unknown type name 'foo'; did you mean 'foo'? // CHECK: Number FIX-ITs = 1 // CHECK: FIX-IT: Replace [3:1 - 3:4] with "foo" // CHECK: yamldb_plugin.cpp:3:1: note: Add '#include "foo.h"' to provide the missing declaration [clang-include-fixer] // CHECK: Number FIX-ITs = 1 // CHECK: FIX-IT: Replace [3:1 - 3:4] with "#include "foo.h"
Add unit test for symmetry of OperatorChebyshevSmoother
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "catch.hpp" using namespace mfem; TEST_CASE("OperatorChebyshevSmoother", "[Chebyshev symmetry]") { for (int order = 2; order < 5; ++order) { const int cheb_order = 2; Mesh mesh(4, 4, 4, Element::HEXAHEDRON, true); FiniteElementCollection *fec = new H1_FECollection(order, 3); FiniteElementSpace fespace(&mesh, fec); Array<int> ess_bdr(mesh.bdr_attributes.Max()); ess_bdr = 1; Array<int> ess_tdof_list; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); BilinearForm aform(&fespace); aform.SetAssemblyLevel(AssemblyLevel::PARTIAL); aform.AddDomainIntegrator(new DiffusionIntegrator); aform.Assemble(); OperatorPtr opr; opr.SetType(Operator::ANY_TYPE); aform.FormSystemMatrix(ess_tdof_list, opr); Vector diag(fespace.GetTrueVSize()); aform.AssembleDiagonal(diag); Solver* smoother = new OperatorChebyshevSmoother(opr.Ptr(), diag, ess_tdof_list, cheb_order); int n = smoother->Width(); Vector left(n); Vector right(n); int seed = (int) time(0); left.Randomize(seed); right.Randomize(seed + 2); // test that x^T S y = y^T S x Vector out(n); out = 0.0; smoother->Mult(right, out); double forward_val = left * out; smoother->Mult(left, out); double transpose_val = right * out; double error = fabs(forward_val - transpose_val) / fabs(forward_val); std::cout << "Order " << order << " symmetry error: " << error << std::endl; REQUIRE(error < 1.e-13); delete smoother; } }
Add example that uses both gsl lite and span lite
#include "gsl/gsl-lite.hpp" #include "nonstd/span.hpp" int main() { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; { using gsl::span; span<const int> spn( arr ); } { using nonstd::span; span<const int> spn( arr ); } } // cl -nologo -EHsc -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include 03-gsl-span.cpp && 03-gsl-span // g++ -Wall -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include -o 03-gsl-span 03-gsl-span.cpp && 03-gsl-span
Fix timeouts when using keepalive in apache bench.
/* * Part of HTTPP. * * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2013 Thomas Sanchez. All rights reserved. * */ #include "httpp/http/Utils.hpp" #include <boost/algorithm/string.hpp> #include <iostream> namespace HTTPP { namespace HTTP { static const std::string CLOSE = "Close"; static const std::string KEEPALIVE = "Keep-Alive"; void setShouldConnectionBeClosed(const Request& request, Response& response) { auto headers = request.getSortedHeaders(); auto const& connection = headers["Connection"]; if (boost::iequals(connection, CLOSE)) { response.connectionShouldBeClosed(true); return; } if (boost::iequals(connection, KEEPALIVE)) { response.connectionShouldBeClosed(false); return; } if (request.major == 1 && request.minor == 1) { response.connectionShouldBeClosed(false); return; } response.connectionShouldBeClosed(true); return; } } // namespace HTTP } // namespace HTTPP
/* * Part of HTTPP. * * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2013 Thomas Sanchez. All rights reserved. * */ #include "httpp/http/Utils.hpp" #include <boost/algorithm/string.hpp> #include <iostream> namespace HTTPP { namespace HTTP { static const std::string CLOSE = "Close"; static const std::string KEEPALIVE = "Keep-Alive"; void setShouldConnectionBeClosed(const Request& request, Response& response) { auto headers = request.getSortedHeaders(); auto const& connection = headers["Connection"]; if (boost::iequals(connection, CLOSE)) { response.connectionShouldBeClosed(true); return; } if (boost::iequals(connection, KEEPALIVE)) { response.connectionShouldBeClosed(false); response.addHeader("Connection", KEEPALIVE); return; } if (request.major == 1 && request.minor == 1) { response.connectionShouldBeClosed(false); return; } response.connectionShouldBeClosed(true); return; } } // namespace HTTP } // namespace HTTPP
Add unit tests for parsable, but erroneous programs
#include <gtest/gtest.h> #include <platform.h> #include "util.h" /** Pony code that parses, but is erroneous. Typically type check errors and * things used is invalid contexts. * * We build all the way up to and including code gen and check that we do not * assert, segfault, etc but that the build fails and at least one error is * reported. * * There is definite potential for overlap with other tests but this is also a * suitable location for tests which don't obviously belong anywhere else. */ class BadPonyTest : public PassTest { protected: void test(const char* src) { DO(test_error(src, "ir")); ASSERT_NE(0, get_error_count()); } }; // Cases from reported issues TEST_F(BadPonyTest, DontCareInFieldType) { // From issue #207 const char* src = "class Abc\n" " var _test1: (_)"; DO(test(src)); } TEST_F(BadPonyTest, ClassInOtherClassProvidesList) { // From issue #218 const char* src = "class Named\n" "class Dog is Named\n" "actor Main\n" " new create(env: Env) =>\n" " None"; DO(test(src)); } TEST_F(BadPonyTest, TypeParamMissingForTypeInProvidesList) { // From issue #219 const char* src = "trait Bar[A]\n" " fun bar(a: A) =>\n" " None\n" "trait Foo is Bar // here also should be a type argument, like Bar[U8]\n" " fun foo() =>\n" " None\n" "actor Main\n" " new create(env: Env) =>\n" " None"; DO(test(src)); } TEST_F(BadPonyTest, DontCareInIntLiteralType) { // From issue #222 const char* src = "actor Main\n" " new create(env: Env) =>\n" " let crashme: (_, I32) = (4, 4)"; DO(test(src)); }
Solve SRM 150, Div 2, Problem WidgetRepairs
#include <cassert> #include <vector> using namespace std; class WidgetRepairs { public: int days(vector<int> arrs, int numPerDay) { int ans = 0; int stack = 0; for (int d : arrs) { stack += d; if (stack > 0) { ans++; } stack -= numPerDay; if (stack < 0) { stack = 0; } } while (stack > 0) { stack -= numPerDay; ans++; } return ans; } }; int main() { WidgetRepairs wr; vector<int> v1 = { 10, 0, 0, 4, 20 }; assert (wr.days(v1, 8) == 6); return 0; }
Add forgotten to commit file.
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <sploving1@gmail.com> // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/RuntimeExceptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" namespace cling { namespace runtime { cling_null_deref_exception::cling_null_deref_exception( void* Loc, clang::Sema* S) : m_Location(*(unsigned *)Loc), m_Sema(S){} cling_null_deref_exception::~cling_null_deref_exception() {} void cling_null_deref_exception::what() throw() { clang::DiagnosticsEngine& Diag = m_Sema->getDiagnostics(); Diag.Report(clang::SourceLocation::getFromRawEncoding(m_Location), clang::diag::warn_null_arg); } } // end namespace runtime } // end namespace cling
Add useful script for lower and upper bound over an array.
// lower_bound/upper_bound example #include <iostream> // cout #include <algorithm> // lower_bound, upper_bound, sort #include <vector> // vector using namespace std; int main () { int myints[] = {10,20,30,30,20,10,10,20}; vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20 sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30 vector<int>::iterator low,up; low=lower_bound (v.begin(), v.end(), 20); // ^ up= upper_bound (v.begin(), v.end(), 20); // ^ cout << "lower_bound at position " << (low- v.begin()) << '\n'; cout << "upper_bound at position " << (up - v.begin()) << '\n'; /* lower_bound at position 3 upper_bound at position 6 * return 0; }
Test for shared allocations and thread blocks that depend on blockidx
#include <Halide.h> #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Func f, g; Var x; f(x) = x; g(x) = f(x) + f(2*x); g.gpu_tile(x, 16); f.compute_at(g, Var::gpu_blocks()).gpu_threads(x); // The amount of shared memory required varies with x Image<int> out = g.realize(100); for (int x = 0; x < 100; x++) { int correct = 3*x; if (out(x) != correct) { printf("out(%d) = %d instead of %d\n", x, out(x), correct); return -1; } } printf("Success!\n"); return 0; }
Add basic string unit test
//--------------------------------------------------------------------------// /// Copyright (c) 2018 Milos Tosic. All Rights Reserved. /// /// License: http://www.opensource.org/licenses/BSD-2-Clause /// //--------------------------------------------------------------------------// #include <rbase_test_pch.h> #include <rbase/inc/stringview.h> using namespace rtm; SUITE(rbase) { TEST(string) { char buffer[128]; const char* testString = "This is the test string"; CHECK(23 == strLen(testString)); strlCpy(buffer, 128, testString); CHECK(0 == strCmp(buffer, testString)); strToUpper(buffer); CHECK(0 == strCmp(buffer, "THIS IS THE TEST STRING")); CHECK(0 == striCmp(buffer, testString)); strToLower(buffer); CHECK(0 == strCmp(buffer, "this is the test string")); CHECK(0 == striCmp(buffer, testString)); CHECK(0 == striCmp(strStr(buffer, "test"), "test string")); StringTemp<> fs(testString); String ds = fs; StringView vs(ds.data(), ds.length()); CHECK(0 == strCmp(vs, testString)); CHECK(true); } }
Fix Uart in Logger example
#include <xpcc/architecture/platform.hpp> #include <xpcc/debug/logger.hpp> using namespace xpcc::atmega; // Create a new UART object and configure it to a baudrate of 115200 Uart0 uart(115200); xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart); // Set all four logger streams to use the UART xpcc::log::Logger xpcc::log::debug(loggerDevice); xpcc::log::Logger xpcc::log::info(loggerDevice); xpcc::log::Logger xpcc::log::warning(loggerDevice); xpcc::log::Logger xpcc::log::error(loggerDevice); // Set the log level #undef XPCC_LOG_LEVEL #define XPCC_LOG_LEVEL xpcc::log::DEBUG int main() { // Enable interrupts, this is needed for every buffered UART sei(); // Use the logging streams to print some messages. // Change XPCC_LOG_LEVEL above to enable or disable these messages XPCC_LOG_DEBUG << "debug" << xpcc::endl; XPCC_LOG_INFO << "info" << xpcc::endl; XPCC_LOG_WARNING << "warning" << xpcc::endl; XPCC_LOG_ERROR << "error" << xpcc::endl; while (1) { } }
#include <xpcc/architecture/platform.hpp> #include <xpcc/debug/logger.hpp> using namespace xpcc::atmega; typedef xpcc::avr::SystemClock clock; // Create a new UART object and configure it to a baudrate of 115200 Uart0 uart; xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart); // Set all four logger streams to use the UART xpcc::log::Logger xpcc::log::debug(loggerDevice); xpcc::log::Logger xpcc::log::info(loggerDevice); xpcc::log::Logger xpcc::log::warning(loggerDevice); xpcc::log::Logger xpcc::log::error(loggerDevice); // Set the log level #undef XPCC_LOG_LEVEL #define XPCC_LOG_LEVEL xpcc::log::DEBUG int main() { GpioOutputD1::connect(Uart0::Tx); GpioInputD0::connect(Uart0::Rx); Uart0::initialize<clock, 115200>(); // Enable interrupts, this is needed for every buffered UART sei(); // Use the logging streams to print some messages. // Change XPCC_LOG_LEVEL above to enable or disable these messages XPCC_LOG_DEBUG << "debug" << xpcc::endl; XPCC_LOG_INFO << "info" << xpcc::endl; XPCC_LOG_WARNING << "warning" << xpcc::endl; XPCC_LOG_ERROR << "error" << xpcc::endl; while (1) { } }
Add file missed in previous commit.
// Copyright (c) 2015 The Gulden developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifdef __APPLE__ #include <TargetConditionals.h> #import "BRMerkleBlock.h" #endif #include "diff_common.h" #include "diff_delta.h" #include "diff_old.h" #ifdef BUILD_IOS #import "BRMerkleBlock.h" #endif unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit) { static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 1, 250000); static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(500, 500, 260000); if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock) { if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock) { return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock); } else { return 524287999; } } return diff_old(INDEX_HEIGHT(indexLast)+1); }
Add some tests for tasks.
#include <iostream> #include <gtest/gtest.h> #include "ell.hpp" #include "exceptions/cancelled.hpp" TEST(test_task, simple_yield) { using namespace ell; EventLoop loop; int count = 0; bool has_run = false; auto task2 = loop.call_soon([&]() { for (int i = 0; i < 5; ++i) { ASSERT_TRUE(has_run); // make sure that has run first. count--; ASSERT_EQ(0, count); yield(); } }); auto task = loop.call_soon([&]() { for (int i = 0; i < 5; ++i) { has_run = true; ASSERT_EQ(0, count); count++; yield(); } }); loop.run_until_complete(task); ASSERT_EQ(0, count); } TEST(test_task, chained) { using namespace ell; EventLoop loop; int count = 0; auto task = loop.call_soon([&]() { ASSERT_EQ(0, count); yield([&]() { ASSERT_EQ(0, count); count++; yield([&]() { ASSERT_EQ(1, count); count++; yield([&]() { ASSERT_EQ(2, count); count++; yield(); }); }); }); }); loop.run_until_complete(task); ASSERT_EQ(3, count); } int main(int ac, char **av) { ell::initialize_logger(); ::testing::InitGoogleTest(&ac, av); return RUN_ALL_TESTS(); }
Add a test for resizing of a vector with copy-only elements
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // RUN: %build -fno-exceptions // RUN: %run // RUN: %build // RUN: %run // UNSUPPORTED: c++98, c++03 // <vector> // Test that vector won't try to call the move constructor when resizing if // the class has a deleted move constructor (but a working copy constructor). #include <vector> class CopyOnly { public: CopyOnly() { } CopyOnly(CopyOnly&&) = delete; CopyOnly& operator=(CopyOnly&&) = delete; CopyOnly(const CopyOnly&) = default; CopyOnly& operator=(const CopyOnly&) = default; }; int main() { std::vector<CopyOnly> x; x.emplace_back(); CopyOnly c; x.push_back(c); return 0; }
Add empty board::lowLevelInitialization() for NUCLEO-F429ZI
/** * \file * \brief board::lowLevelInitialization() implementation for NUCLEO-F429ZI * * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/board/lowLevelInitialization.hpp" namespace distortos { namespace board { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace board } // namespace distortos
Check if strings are anagram
# include <iostream> # include <algorithm> using namespace std; bool isAnagram(string str1, string str2) { if str1.size() != str2.size() return false; sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); return str1 == str2; } int main() { string str1, str2; cout << "Enter first string" << endl; cin >> str1; cout << "Enter second string" << endl; cin >> str2; cout << "Strings are anagram: " << isAnagram(str1, str2) << endl; return 0; }
Test suite for global fakes from a cpp context
extern "C"{ #include "global_fakes.h" } #include <gtest/gtest.h> DEFINE_FFF_GLOBALS; class FFFTestSuite: public testing::Test { public: void SetUp() { RESET_FAKE(voidfunc1); RESET_FAKE(voidfunc2); RESET_FAKE(longfunc0); RESET_HISTORY(); } }; #include "test_cases.include"
Add dfs implementation in c++
#include <bits/stdc++.h> #define MAX ... vector<int> G[MAX]; /* this array may be initialized with false eg.: memset(visited, false, sizeof visited) */ bool visited[MAX]; void dfs(int at) { if(visited[at]) return; visited[at] = true; for (int i= 0; i< (int)G[at].size(); i++) dfs(G[at][i]); }
Fix wrong renames detected by git.
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #include "test.hh" namespace pegtl { void unit_test() { verify_analyze< not_at< eof > >( __LINE__, __FILE__, false ); verify_analyze< not_at< any > >( __LINE__, __FILE__, false ); verify_rule< not_at< eof > >( __LINE__, __FILE__, "", result_type::LOCAL_FAILURE, 0 ); verify_rule< not_at< eof > >( __LINE__, __FILE__, " ", result_type::SUCCESS, 1 ); verify_rule< not_at< any > >( __LINE__, __FILE__, "", result_type::SUCCESS, 0 ); verify_rule< not_at< any > >( __LINE__, __FILE__, "a", result_type::LOCAL_FAILURE, 1 ); verify_rule< not_at< any > >( __LINE__, __FILE__, "aa", result_type::LOCAL_FAILURE, 2 ); verify_rule< not_at< any > >( __LINE__, __FILE__, "aaaa", result_type::LOCAL_FAILURE, 4 ); } } // pegtl #include "main.hh"
Add algorithm to find Longest Repeated substring withot overlapping.
#include<bits/stdc++.h> using namespace std; // Returns the longest repeating non-overlapping substring string longestRepeatedSubstring(string str){ int n = str.length(); int LCSRe[n+1][n+1]; // Setting all to 0 memset(LCSRe, 0, sizeof(LCSRe)); string res; // To store result int res_length = 0; // To store length of result // building table in bottom-up manner int i, index = 0; for (i=1; i<=n; i++){ for (int j=i+1; j<=n; j++){ // (j-i) > LCSRe[i-1][j-1] to remove if (str[i-1] == str[j-1] && LCSRe[i-1][j-1] < (j - i)){ LCSRe[i][j] = LCSRe[i-1][j-1] + 1; if (LCSRe[i][j] > res_length){ res_length = LCSRe[i][j]; index = max(i, index); } } else LCSRe[i][j] = 0; } } if (res_length > 0){ cout << (index - res_length +1)<<endl; for (i = index - res_length + 1; i <= index; i++) res.push_back(str[i-1]); } return res; } // Driver program to test the above function int main(){ string str = "hello,p23puoeouhello,oues"; cout << longestRepeatedSubstring(str); //hello, return 0; }
Print elements from the end of linked list
#include<iostream> using namespace std; class Node{ public: int data; Node *next; Node(){} Node(int d){ data=d; next=NULL; } Node *insertElement(Node *head,int d){ Node *np=new Node(d); Node *tmp=head; if(head==NULL) return np; else while(tmp->next) tmp=tmp->next; tmp->next=np; return head; } void displayFromEnd(Node *head){ if(!head->next){ cout<<head->data<<"\n"; return; } displayFromEnd(head->next); cout<<head->data<<"\n"; } }; int main() { int n,p,pos,d; Node np; Node *head=NULL; cout<<"Enter the size of linked list: "; cin>>n; for(int i=0;i<n;i++){ cout<<"\nEnter element "<<i+1<<": "; cin>>p; head=np.insertElement(head,p); } if(!head) cout<<"Sorry! No elements in the list. :(\n"; else{ cout<<"The elements accessed from the end are: \n"; np.displayFromEnd(head); } }
Add tests of skip() function.
#include <test.hpp> TEST_CASE("skip") { SECTION("check that skip skips the right amount of bytes") { std::vector<std::string> filenames = { "boolean/data-true", "boolean/data-false", "bytes/data-one", "bytes/data-string", "bytes/data-binary", "double/data-zero", "double/data-pos", "double/data-neg", "float/data-zero", "float/data-pos", "float/data-neg", "fixed32/data-zero", "fixed32/data-max-uint", "fixed32/data-min-uint", "fixed64/data-zero", "fixed64/data-max-uint", "fixed64/data-min-uint", "sfixed32/data-zero", "sfixed32/data-max-int", "sfixed32/data-min-int", "sfixed64/data-zero", "sfixed64/data-max-int", "sfixed64/data-min-int", "message/data-message", "string/data-one", "string/data-string", "int32/data-zero", "int32/data-pos", "int32/data-neg", "int32/data-min", "int32/data-max", "int64/data-zero", "int64/data-pos", "int64/data-neg", "int64/data-min", "int64/data-max", "sint32/data-zero", "sint32/data-pos", "sint32/data-neg", "sint32/data-min", "sint32/data-max", "sint64/data-zero", "sint64/data-pos", "sint64/data-neg", "sint64/data-min", "sint64/data-max", "uint32/data-zero", "uint32/data-pos", "uint32/data-max", "uint64/data-zero", "uint64/data-pos", "repeated/data-one", }; for (const auto& filename : filenames) { std::string buffer = get_file_data(std::string("test/t/") + filename + ".pbf"); mapbox::util::pbf item(buffer.data(), buffer.size()); REQUIRE(item.next()); item.skip(); REQUIRE(!item); } } }
Add test case to check that implicit downcasting when a Func returns float (32 bits) but the buffer has type float16_t (16 bits) is an error.
#include "Halide.h" #include <stdio.h> #include <cmath> using namespace Halide; // FIXME: We should use a proper framework for this. See issue #898 void h_assert(bool condition, const char *msg) { if (!condition) { printf("FAIL: %s\n", msg); abort(); } } int main() { Halide::Func f; Halide::Var x, y; // This should throw an error because downcasting will loose precision which // should only happen if the user explicitly asks for it f(x, y) = 0.1f; // Use JIT for computation Image<float16_t> simple = f.realize(10, 3); // Assert some basic properties of the image h_assert(simple.extent(0) == 10, "invalid width"); h_assert(simple.extent(1) == 3, "invalid height"); h_assert(simple.min(0) == 0, "unexpected non zero min in x"); h_assert(simple.min(1) == 0, "unexpected non zero min in y"); h_assert(simple.channels() == 1, "invalid channels"); h_assert(simple.dimensions() == 2, "invalid number of dimensions"); printf("Should not be reached!\n"); return 0; }
Add cross-call example (case 2)
#include <iostream> using std::cin; using std::cout; int *A; int sum; void f(int i) { A[i] = i * 3; } void g(int i) { sum += A[i]; } int main() { unsigned n; cin >> n; A = new int[n]; sum = 0; for (unsigned i = 0; i < n; ++i) { f(i); g(i); } cout << sum << '\n'; return 0; }
Add test for current AST dump behavior
// RUN: %clang_cc1 %s -chain-include %s -ast-dump | FileCheck -strict-whitespace %s // CHECK: TranslationUnitDecl 0x{{.+}} <<invalid sloc>> <invalid sloc> // CHECK: `-<undeserialized declarations>
Add solution for chapter 18, test 28
#include <iostream> using namespace std; struct Base { void bar(int i) { cout << "Base::bar(int)" << endl; } protected: int ival = 0; }; struct Derived1 : virtual public Base { void bar(char c) { cout << "Derived1::bar(char)" << endl; } void foo(char c) { cout << "Derived1::foo(char)" << endl; } protected: char cval = 'c'; }; struct Derived2 : virtual public Base { void foo(int i) { cout << "Derived2::foo(int)" << endl; } protected: int ival = 1; char cval = 'd'; }; class VMI : public Derived1, public Derived2 { public: void access_ival() { cout << Base::ival << endl;//without Base::, it will be Derived2::ival } void access_cval() { cout << Derived1::cval << endl;//both cval need :: } }; int main() { VMI vmi; vmi.access_ival(); vmi.access_cval(); vmi.Derived1::foo('c');//both need :: vmi.bar(1);//call Derived1::bar() vmi.bar('c');//call Derived1::bar() vmi.Base::bar(1); return 0; }
Fix for crash trying to deference ash::Shell::message_center()
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/message_center_util.h" #include "base/command_line.h" #include "ui/message_center/message_center_switches.h" namespace message_center { bool IsRichNotificationEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableRichNotifications); } } // namespace message_center
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/message_center_util.h" #include "base/command_line.h" #include "ui/message_center/message_center_switches.h" namespace message_center { bool IsRichNotificationEnabled() { #if defined(OS_WIN) && defined(USE_AURA) return false; #else return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableRichNotifications); #endif } } // namespace message_center
Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ struct GrGLInterface; const GrGLInterface* GrGLDefaultInterface() { return NULL; }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLInterface.h" const GrGLInterface* GrGLDefaultInterface() { return NULL; }
Add missing source for DTLS hello verify
/* * DTLS Hello Verify Request * (C) 2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/lookup.h> #include <memory> namespace Botan { namespace TLS { Hello_Verify_Request::Hello_Verify_Request(const MemoryRegion<byte>& buf) { if(buf.size() < 3) throw Decoding_Error("Hello verify request too small"); if(buf[0] != 254 || (buf[1] != 255 && buf[1] != 253)) throw Decoding_Error("Unknown version from server in hello verify request"); m_cookie.resize(buf.size() - 2); copy_mem(&m_cookie[0], &buf[2], buf.size() - 2); } Hello_Verify_Request::Hello_Verify_Request(const MemoryVector<byte>& client_hello_bits, const std::string& client_identity, const SymmetricKey& secret_key) { std::auto_ptr<MessageAuthenticationCode> hmac(get_mac("HMAC(SHA-256)")); hmac->set_key(secret_key); hmac->update_be(client_hello_bits.size()); hmac->update(client_hello_bits); hmac->update_be(client_identity.size()); hmac->update(client_identity); m_cookie = hmac->final(); } MemoryVector<byte> Hello_Verify_Request::serialize() const { /* DTLS 1.2 server implementations SHOULD use DTLS version 1.0 regardless of the version of TLS that is expected to be negotiated (RFC 6347, section 4.2.1) */ Protocol_Version format_version(Protocol_Version::TLS_V11); MemoryVector<byte> bits; bits.push_back(format_version.major_version()); bits.push_back(format_version.minor_version()); bits += m_cookie; return bits; } } }
Add gpio interrupt plus signal wait
extern "C" { #include <wiringPi.h> } #include <signal.h> #include <errno.h> #include <iostream> #include <thread> #include <chrono> void gpio4Callback(void) { std::cout << "Hello" << std::endl; } int main(){ sigset_t set; int sig; int *sigptr = &sig; int ret_val; sigemptyset(&set); sigaddset(&set, SIGQUIT); sigaddset(&set, SIGINT); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR1); sigprocmask( SIG_BLOCK, &set, NULL ); std::cout << "Waiting for a signal or button\n"; wiringPiSetup () ; wiringPiISR (4, INT_EDGE_FALLING, &gpio4Callback) ; ret_val = sigwait(&set,sigptr); if(ret_val == -1) perror("sigwait failed\n"); else { std::cout << "sigwait returned with sig: " << *sigptr << std::endl; } return 0; }
Add solution for chapter 16 test 41
#include <iostream> #include <limits> using namespace std; template <typename T1, typename T2> auto sum(T1 a, T2 b) -> decltype(a + b) { return a + b; } int main() { char c1 = 127; char c2 = 127; long lng = numeric_limits<long>::max() - 200; cout << sum(c1, c2) << endl; cout << sum(c2, lng) << endl; return 0; }
Implement For Loop Using Sizeof Example
#include <iostream> using namespace std; int main(){ string animals[][3] = { {"fox", "dog", "cat"}, {"mouse", "squirrel", "parrot"} }; for(int i = 0; i < sizeof(animals)/sizeof(animals[0]); i++){ for(int j = 0; j < sizeof(animals[0])/sizeof(string); j++){ cout << animals[i][j] << " " << flush; } cout << endl; } return 0; }
Append K Integers With Minimal Sum
class Solution { public: long long minimalKSum(vector<int>& nums, int k) { auto cmp = [](int left, int right){ return left > right; }; std::priority_queue<int, std::vector<int>, decltype(cmp)> q(cmp); for (const auto& num : nums) { q.emplace(std::move(num)); } // while (!q.empty()) { // std::cout << q.top() << std::endl; // q.pop(); // } int64_t ret = 0; int start = 0; while (!q.empty()) { int cur = q.top(); q.pop(); if (cur == start) continue; int count = cur - start - 1; if (count == 0) { start = cur; continue; } if (count >= k) { ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2; return ret; } else { ret += int64_t((start + cur)) * int64_t(count) / 2; k -= count; start = cur; } } if (k > 0) { ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2; } return ret; } };
Use unique_ptr for pwalletMain (CWallet)
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "rpc/server.h" #include "wallet/db.h" #include "wallet/wallet.h" CWallet *pwalletMain; WalletTestingSetup::WalletTestingSetup(const std::string& chainName): TestingSetup(chainName) { bitdb.MakeMock(); bool fFirstRun; std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat")); pwalletMain = new CWallet(std::move(dbw)); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain); RegisterWalletRPCCommands(tableRPC); } WalletTestingSetup::~WalletTestingSetup() { UnregisterValidationInterface(pwalletMain); delete pwalletMain; pwalletMain = nullptr; bitdb.Flush(true); bitdb.Reset(); }
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "rpc/server.h" #include "wallet/db.h" #include "wallet/wallet.h" std::unique_ptr<CWallet> pwalletMain; WalletTestingSetup::WalletTestingSetup(const std::string& chainName): TestingSetup(chainName) { bitdb.MakeMock(); bool fFirstRun; std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat")); pwalletMain = std::unique_ptr<CWallet>(new CWallet(std::move(dbw))); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain.get()); RegisterWalletRPCCommands(tableRPC); } WalletTestingSetup::~WalletTestingSetup() { UnregisterValidationInterface(pwalletMain.get()); pwalletMain.reset(); bitdb.Flush(true); bitdb.Reset(); }
Create dumb test for better coverage
#include <sstream> #include <gtest/gtest.h> #include "portsocket.h" #define TEST_CLASS PortSocketTest class TEST_CLASS : public testing::Test { protected: class DummySocket : PortSocket { public: DummySocket(bool *sentinel) : sentinel(sentinel) { *sentinel = true; } int read(PortType port, SizeType len, void *buffer) { } int write(PortType port, SizeType len, const void *buffer) { } ~DummySocket() { *sentinel = false; } private: bool *sentinel; }; }; TEST_F(TEST_CLASS, TestConstructDestruct) { bool sentinel = false; { DummySocket sock(&sentinel); ASSERT_EQ(sentinel, true) << "Failed to construct instance"; } ASSERT_EQ(sentinel, false) << "Failed to destruct instance"; }
Add a test that we emit copy-ctors for captures in generic lambdas.
// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s -std=c++14 | FileCheck %s template<typename> struct custom_copy_ctor { custom_copy_ctor() = default; custom_copy_ctor(custom_copy_ctor const &) {} }; // CHECK: define {{.*}} @_ZN16custom_copy_ctorIvEC2ERKS0_( void pr22354() { custom_copy_ctor<void> cc; [cc](auto){}(1); }
Add an input file that includes all standard C++ headers
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <complex> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <cwchar> #include <cwctype> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <strstream> #include <typeinfo> #include <utility> #include <valarray> #include <vector>
Add binary tree live implementation
#include <iostream> using namespace std; struct Node { int data; Node* left; Node* right; Node(int data, Node* left = nullptr, Node* right = nullptr) : data(data), left(left), right(right) {} }; class BinaryTree { Node* root; BinaryTree(Node* node) { root = copyNode(node); } Node* copyNode(Node* node) { if (node == nullptr) return node; return new Node(node->data, copyNode(node->left), copyNode(node->right)); } void eraseNode(Node* node) { if (node != nullptr) { eraseNode(node->left); eraseNode(node->right); delete node; } } void assignFrom(Node*& to, Node*& from) { Node* toDel = to; to = from; from = nullptr; eraseNode(toDel); } public: BinaryTree() : root(nullptr) {} BinaryTree(int rootData, BinaryTree&& left = BinaryTree(), BinaryTree&& right = BinaryTree()) { root = new Node(rootData); assignFrom(root->left, left.root); assignFrom(root->right, right.root); } BinaryTree(const BinaryTree& other) { root = copyNode(other.root); } BinaryTree& operator=(const BinaryTree& other) { if (this != &other) { eraseNode(root); root = copyNode(other.root); } } ~BinaryTree() { eraseNode(root); } bool empty() const { return root == nullptr; } BinaryTree leftTree() const { return BinaryTree(root->left); } BinaryTree rightTree() const { return BinaryTree(root->right); } int getRoot() const { return root->data; } friend ostream& operator<<(ostream& os, const BinaryTree& bt) { if (bt.empty()) return os << '.'; return os << '(' << bt.getRoot() << ' ' << bt.leftTree() << ' ' << bt.rightTree() << ')'; } }; int main() { BinaryTree bt(3); BinaryTree bt2(3, 4, 5); BinaryTree bt3(3, 4, BinaryTree(5, 6, 7)); cout << bt3 << endl; return 0; }
Add c++ code for printing the side view of a binary tree
#include <iostream> #include <queue> using namespace std; class Node { public: int data; Node *left; Node *right; Node(int x) { data = x; left = NULL; right = NULL; } }; vector<Node *> rightView(Node *root) { vector<Node *> rightView; if (root == NULL) return rightView; queue<Node *> q; q.push(root); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { Node *elem = q.front(); q.pop(); if (i == n - 1) rightView.push_back(elem); if (elem->left != NULL) q.push(elem->left); if (elem->right != NULL) q.push(elem->right); } } return rightView; } vector<Node *> leftView(Node *root) { vector<Node *> leftView; if (root == NULL) return leftView; queue<Node *> q; q.push(root); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { Node *elem = q.front(); q.pop(); if (i == 0) leftView.push_back(elem); if (elem->left != NULL) q.push(elem->left); if (elem->right != NULL) q.push(elem->right); } } return leftView; } int main() { Node *root = new Node(5); root->left = new Node(9); root->right = new Node(6); root->right->right = new Node(8); root->right->left = new Node(3); root->right->left->left = new Node(16); root->right->left->left->right = new Node(66); root->left->right = new Node(10); vector<Node *> Rview = rightView(root); cout << "Right view:\n"; for (auto node : Rview) { cout << node->data << endl; } cout << "Left view:\n"; vector<Node *> Lview = leftView(root); for (auto node : Lview) { cout << node->data << endl; } return 0; }
Add EH test case checking that handlers in noexcept functions can still unwind
//===---------------------- catch_in_noexcept.cpp--------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <exception> #include <stdlib.h> #include <assert.h> struct A {}; // Despite being marked as noexcept, this function must have an EHT entry that // is not 'cantunwind', so that the unwinder can correctly deal with the throw. void f1() noexcept { try { A a; throw a; assert(false); } catch (...) { assert(true); return; } assert(false); } int main() { f1(); }
Add the solution to "Cached Calculations".
#include <iostream> using namespace std; long long solve(int n) { long long *res = new long long[n + 1]; switch (n) { case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 6; } res[1] = 1; res[2] = 2; res[3] = 3; res[4] = 6; for (int i = 5; i <= n; i++) { res[i] = res[i - 1] + res[i - 2] + res[i - 4]; } long long x = res[n]; delete [] res; return x; } int main() { int T; cin >> T; while (T--) { int x; cin >> x; cout << solve(x) << endl; } return 0; }
Add a test for i64sqrt
/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake 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. Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #include "../utils.hpp" #include <limits> #include <array> //#define BOOST_TEST_DYN_LINK //#define BOOST_TEST_MODULE utils test #include <boost/test/unit_test.hpp> #include <boost/test/parameterized_test.hpp> namespace /* anonymous */ { void i64sqrt_test(uint64_t radicand) { uint64_t sqrt_result = i64sqrt(radicand); //implicit cast the result to 64 bits so we can square it BOOST_CHECK(sqrt_result * sqrt_result <= radicand); if(sqrt_result != std::numeric_limits<uint32_t>::max()) { BOOST_CHECK((sqrt_result+1) * (sqrt_result+1) > radicand); } } BOOST_AUTO_TEST_CASE( my_sqrt ) { std::array<uint64_t, 19> numbers_to_test = {{ 0, 1, 2, 3, 4, 5, 17, 232, 500, 78978978, 8948954789789349789ull, 0xfffffffful, 0x100000000ull, 0x100000001ull, 0xffffffffffffffffull, 0xfffffffffffffffeull, 0xeeeeeeeeeeeeeeeeull, 0xfffffffe00000001ull, 0xfffffffe00000000ull }}; BOOST_PARAM_TEST_CASE(i64sqrt_test, numbers_to_test.begin(), numbers_to_test.end()); } } /* end anonymous namespace */
Add tests for glow implementation
#include <gtest/gtest.h> #include "photoeffects.hpp" using namespace cv; TEST(photoeffects, GlowTest) { Mat image(10, 10, CV_8UC1); EXPECT_EQ(10, glow(image)); }
Test for C++11 [class]p6 (trivial classes).
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x class Trivial { int n; void f(); }; class NonTrivial1 { NonTrivial1(const NonTrivial1 &); }; class NonTrivial2 { NonTrivial2(NonTrivial2 &&); }; class NonTrivial3 { NonTrivial3 operator=(const NonTrivial3 &); }; class NonTrivial4 { NonTrivial4 operator=(NonTrivial4 &&); }; class NonTrivial5 { ~NonTrivial5(); }; static_assert(__is_trivial(Trivial), "Trivial is not trivial"); static_assert(!__is_trivial(NonTrivial1), "NonTrivial1 is trivial"); static_assert(!__is_trivial(NonTrivial2), "NonTrivial2 is trivial"); static_assert(!__is_trivial(NonTrivial3), "NonTrivial3 is trivial"); static_assert(!__is_trivial(NonTrivial4), "NonTrivial4 is trivial"); static_assert(!__is_trivial(NonTrivial5), "NonTrivial5 is trivial");
Add Window Message Class (Continued)
#include "LanguageEasy.h" //Windows WindowMessage::WindowMessage() { MessageName = ""; Message = ""; } WindowMessage::WindowMessage(string NewMessageName, string NewMessage) { MessageName = NewMessageName; Message = NewMessage; } void WindowMessage::OutputWindow() { char MessageBuffer[9999]; char MessageNameBuffer[9999]; sprintf_s(MessageBuffer, Message.c_str()); sprintf_s(MessageNameBuffer, MessageName.c_str()); MessageBoxA(NULL, MessageBuffer, MessageNameBuffer, MB_OK); }
Add basic skeleton for object pool
#include "logic.h" #define ARBITRARY_SIZE 20 block* blockAlloc( void ); void blockFree( block * ); //Object pool: static int mem_size {0}; static int mem_used {0}; static block* mem_array[BOARD_HEIGHT * BOARD_WIDTH / PIECES_PER_BLOCK]; block* blockAlloc( void ) { //check if enough space exists if( mem_used <= mem_size ) { //get more space } return mem_array[ mem_used++ ]; } void blockFree( block *b ) { }
Implement queue using only stack
#include <iostream> #include <stack> using namespace std; struct Queue { stack<int> s1, s2; }; void enqueue(Queue *Q, int data) { Q->s1.push(data); } int dequeue(Queue *Q) { int top; if (!Q->s2.empty()) { top = Q->s2.top(); Q->s2.pop(); } else { while (!Q->s1.empty()) { Q->s2.push(Q->s1.top()); Q->s1.pop(); } top = Q->s2.top(); Q->s2.pop(); } return top; } int main() { Queue *Q = new Queue(); cout<<"enqueue 1,2,3,4\n"; enqueue(Q, 1); enqueue(Q, 2); enqueue(Q, 3); enqueue(Q, 4); cout<<"Dequeuing front 3\n"; int i = 0; while (i < 3) { cout<<dequeue(Q)<<" "; i++; } cout<<endl<<"enqueue 5,6,7,8\n"; enqueue(Q, 5); enqueue(Q, 6); enqueue(Q, 7); enqueue(Q, 8); cout<<"Dequeuing again front 3\n"; i = 0; while (i < 3) { cout<<dequeue(Q)<<" "; i++; } cout<<endl<<"enqueue 9,10\n"; enqueue(Q, 9); enqueue(Q, 10); cout<<"Dequeuing again front 3\n"; i = 0; while (i < 3) { cout<<dequeue(Q)<<" "; i++; } cout<<endl; delete Q; return 0; }
Add test coverage for cc1's trigraph option handling.
// RUN: %clang_cc1 -DSTDCPP11 -std=c++11 -verify -fsyntax-only %s // RUN: %clang_cc1 -DSTDGNU11 -std=gnu++11 -verify -fsyntax-only %s // RUN: %clang_cc1 -DSTDGNU11TRI -trigraphs -std=gnu++11 -verify -fsyntax-only %s // RUN: %clang_cc1 -DSTDCPP17 -std=c++1z -verify -fsyntax-only %s // RUN: %clang_cc1 -DSTDCPP17TRI -trigraphs -std=c++1z -verify -fsyntax-only %s void foo() { #if defined(NOFLAGS) || defined(STDCPP11) || defined(STDGNU11TRI) || defined(STDCPP17TRI) const char c[] = "??/n"; // expected-warning{{trigraph converted to '\' character}} #elif defined(STDGNU11) || defined(STDCPP17) const char c[] = "??/n"; // expected-warning{{trigraph ignored}} #else #error Not handled. #endif }
Make compositor unittests opt into real GL NullDraw contexts.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/compositor/test/test_suite.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "ui/compositor/compositor.h" #include "ui/compositor/compositor_switches.h" #include "ui/gfx/gfx_paths.h" #include "ui/gl/gl_surface.h" #if defined(OS_WIN) #include "ui/gfx/win/dpi.h" #endif namespace ui { namespace test { CompositorTestSuite::CompositorTestSuite(int argc, char** argv) : TestSuite(argc, argv) {} CompositorTestSuite::~CompositorTestSuite() {} void CompositorTestSuite::Initialize() { base::TestSuite::Initialize(); gfx::GLSurface::InitializeOneOffForTests(); gfx::RegisterPathProvider(); #if defined(OS_WIN) gfx::InitDeviceScaleFactor(1.0f); #endif message_loop_.reset(new base::MessageLoopForUI); } void CompositorTestSuite::Shutdown() { message_loop_.reset(); base::TestSuite::Shutdown(); } } // namespace test } // namespace ui
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/compositor/test/test_suite.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "ui/compositor/compositor.h" #include "ui/compositor/compositor_switches.h" #include "ui/gfx/gfx_paths.h" #include "ui/gl/gl_surface.h" #if defined(OS_WIN) #include "ui/gfx/win/dpi.h" #endif namespace ui { namespace test { CompositorTestSuite::CompositorTestSuite(int argc, char** argv) : TestSuite(argc, argv) {} CompositorTestSuite::~CompositorTestSuite() {} void CompositorTestSuite::Initialize() { base::TestSuite::Initialize(); gfx::GLSurface::InitializeOneOffForTests(true); gfx::RegisterPathProvider(); #if defined(OS_WIN) gfx::InitDeviceScaleFactor(1.0f); #endif message_loop_.reset(new base::MessageLoopForUI); } void CompositorTestSuite::Shutdown() { message_loop_.reset(); base::TestSuite::Shutdown(); } } // namespace test } // namespace ui
Add CPP hello world example
#include <cstdio> // Libreria estandar de IO C++ int main( int argc, char *argv[] ) { /* Usamos el operador de resolucion :: para acceder a los elementos dentro de la libreria estandar std */ std::cout << "Hola mundo!" << std::endl; }
Add Solution for Problem 043
// 043. Multiply Strings /** * Given two numbers represented as strings, return multiplication of the numbers as a string. * * Note: The numbers can be arbitrarily large and are non-negative * * Tags: Math, String * * Similar Problems: (M) Add Two Numbers, (E) Plus One, (E) Add Binary * * Author: Kuang Qin */ #include "stdafx.h" #include <string> #include <iostream> using namespace std; class Solution { public: string multiply(string num1, string num2) { if ((num1 == "0") || (num2 == "0")) { return "0"; } // use an integer array to store multiplication products int len1 = num1.size(), len2 = num2.size(), len = len1 + len2; int *product = new int[len](); for (int i = len1 - 1; i >= 0; i--) { for (int j = len2 - 1; j >= 0; j--) { product[i + j + 1] += (num1[i] - '0') * (num2[j] - '0'); } } // gather carry info to make each digit valid for (int i = len - 1; i > 0; i--) { product[i - 1] += product[i] / 10; // add carry to previous digit product[i] = product[i] % 10; // set current digit } // convert int into string string res(""); if (product[0] != 0) // first position could be zero { res += product[0] + '0'; } for (int i = 1; i < len; i++) { res += product[i] + '0'; } return res; } }; int _tmain(int argc, _TCHAR* argv[]) { string num1("8354"), num2("7890"); Solution mySolution; string res = mySolution.multiply(num1, num2); cout << num1 << " x " << num2 << " = " << res << endl; system("pause"); return 0; }