Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add new track to memory | #include <libdariadb/storage/memstorage/memstorage.h>
#include <libdariadb/storage/settings.h>
#include <libdariadb/utils/async/thread_manager.h>
#include <libdariadb/utils/logger.h>
#include <benchmark/benchmark_api.h>
class BenchmarkLogger : public dariadb::utils::ILogger {
public:
BenchmarkLogger() {}
~BenchmarkLogger() {}
void message(dariadb::utils::LOG_MESSAGE_KIND, const std::string &) {}
};
class Memstorage : public benchmark::Fixture {
virtual void SetUp(const ::benchmark::State &) {
auto _raw_ptr = new BenchmarkLogger();
auto _logger = dariadb::utils::ILogger_ptr{_raw_ptr};
dariadb::utils::LogManager::start(_logger);
settings = dariadb::storage::Settings::create();
settings->chunk_size.setValue(10);
auto _engine_env = dariadb::storage::EngineEnvironment::create();
_engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
settings.get());
dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());
ms = dariadb::storage::MemStorage::create(_engine_env, size_t(0));
}
virtual void TearDown(const ::benchmark::State &) {
ms = nullptr;
dariadb::utils::async::ThreadManager::stop();
}
public:
dariadb::storage::Settings_ptr settings;
dariadb::storage::MemStorage_ptr ms;
};
BENCHMARK_DEFINE_F(Memstorage, AddNewTrack)(benchmark::State &state) {
auto meas = dariadb::Meas();
while (state.KeepRunning()) {
benchmark::DoNotOptimize(ms->append(meas));
meas.id++;
}
}
BENCHMARK_REGISTER_F(Memstorage, AddNewTrack)
->Arg(1000)
->Arg(10000)
->Arg(20000)
->Arg(50000);
| |
Add the class 'CMDLINE'. So the user is able to change default setting. | #include <iostream>
#include <cstring>
#include "cmdline.h"
CMDLINE::CMDLINE(int argC, char **argV)
{
argc = argC;
for (int i = 0; i < argc; i++)
argv[i] = argV[i];
}
int CMDLINE::help()
{
std::cout << "Help! (coming soon)" << std::endl;
return 0;
}
int CMDLINE::version()
{
std::cout << "Version: no version numbering yet." << std::endl;
return 0;
}
int CMDLINE::parseCommandLine(cmdoptions_t *CMDoptions)
{
// Set default values for cmd options
CMDoptions->populationSize = 50;
CMDoptions->geneSize = 64;
for (int i = 0; i < argc; i++)
{
char *option = argv[i];
if ((strcmp(option, "--help") == 0)
|| (strcmp(option, "-h") == 0)
|| (strcmp(option, "-?") == 0))
{
help();
}
else if ((strcmp(option, "--version") == 0)
|| (strcmp(option, "-h") == 0))
{
version();
}
else if ((strcmp(option, "--population") == 0)
|| (strcmp(option, "-p") == 0))
{
// give a population size (the number of individuals)
sscanf(argv[++i], "%d", &CMDoptions->populationSize);
}
else if ((strcmp(option, "--genes") == 0)
|| (strcmp(option, "-g") == 0))
{
// Give a gene size of the individual
sscanf(argv[++i], "%d", &CMDoptions->geneSize);
}
}
return 0;
}
| |
Add the solution to "Preorder Perusal". | #include <iostream>
#include <string>
using namespace std;
struct Node
{
string s;
Node *left;
Node *right;
};
Node *new_node(string s)
{
Node *temp = new Node();
temp->s = s;
temp->left = NULL;
temp->right = NULL;
return temp;
}
bool add_edge(Node *root, Node *father, Node *child)
{
if (root == NULL) {
return false;
}
if (root->s == father->s) {
if (root->left == NULL) {
root->left = child;
return true;
}
else {
root->right = child;
return true;
}
}
if (!add_edge(root->left, father, child)) {
return add_edge(root->right, father, child);
}
return true;
}
void pre_order(Node *root)
{
if (root == NULL) {
return;
}
cout << root->s << endl;
pre_order(root->left);
pre_order(root->right);
}
int main()
{
int T;
cin >> T;
while (T--) {
int k;
cin >> k;
string s1, s2;
cin >> s1 >> s2;
Node *tree = new_node(s1);
Node *left = new_node(s2);
tree->left = left;
while (--k) {
cin >> s1 >> s2;
add_edge(tree, new_node(s1), new_node(s2));
}
pre_order(tree);
}
return 0;
}
| |
Fix build. Forgot to explictly add file while patching. BUG=none TEST=none TBR=rsleevi | // Copyright (c) 2011 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 "chrome/test/webdriver/commands/response.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/values.h"
namespace webdriver {
namespace {
// Error message taken from:
// http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes
const char* const kStatusKey = "status";
const char* const kValueKey = "value";
const char* const kMessageKey = "message";
const char* const kScreenKey = "screen";
const char* const kClassKey = "class";
const char* const kStackTraceFileNameKey = "stackTrace.fileName";
const char* const kStackTraceLineNumberKey = "stackTrace.lineNumber";
} // namespace
Response::Response() {
SetStatus(kSuccess);
SetValue(Value::CreateNullValue());
}
Response::~Response() {}
ErrorCode Response::GetStatus() const {
int status;
if (!data_.GetInteger(kStatusKey, &status))
NOTREACHED();
return static_cast<ErrorCode>(status);
}
void Response::SetStatus(ErrorCode status) {
data_.SetInteger(kStatusKey, status);
}
const Value* Response::GetValue() const {
Value* out = NULL;
LOG_IF(WARNING, !data_.Get(kValueKey, &out))
<< "Accessing unset response value."; // Should never happen.
return out;
}
void Response::SetValue(Value* value) {
data_.Set(kValueKey, value);
}
void Response::SetError(ErrorCode error_code, const std::string& message,
const std::string& file, int line) {
DictionaryValue* error = new DictionaryValue;
error->SetString(kMessageKey, message);
error->SetString(kStackTraceFileNameKey, file);
error->SetInteger(kStackTraceLineNumberKey, line);
SetStatus(error_code);
SetValue(error);
}
void Response::SetField(const std::string& key, Value* value) {
data_.Set(key, value);
}
std::string Response::ToJSON() const {
std::string json;
base::JSONWriter::Write(&data_, false, &json);
return json;
}
} // namespace webdriver
| |
Add accidentally forgotten testcase from r262881. | // RUN: %clang_cc1 -std=c++1z -verify %s
void f(int n) {
switch (n) {
case 0:
n += 1;
[[fallthrough]]; // ok
case 1:
if (n) {
[[fallthrough]]; // ok
} else {
return;
}
case 2:
for (int n = 0; n != 10; ++n)
[[fallthrough]]; // expected-error {{does not directly precede switch label}}
case 3:
while (true)
[[fallthrough]]; // expected-error {{does not directly precede switch label}}
case 4:
while (false)
[[fallthrough]]; // expected-error {{does not directly precede switch label}}
case 5:
do [[fallthrough]]; while (true); // expected-error {{does not directly precede switch label}}
case 6:
do [[fallthrough]]; while (false); // expected-error {{does not directly precede switch label}}
case 7:
switch (n) {
case 0:
// FIXME: This should be an error, even though the next thing we do is to
// fall through in an outer switch statement.
[[fallthrough]];
}
case 8:
[[fallthrough]]; // expected-error {{does not directly precede switch label}}
goto label;
label:
case 9:
n += 1;
case 10: // no warning, -Wimplicit-fallthrough is not enabled in this test, and does not need to
// be enabled for these diagnostics to be produced.
break;
}
}
[[fallthrough]] typedef int n; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
typedef int [[fallthrough]] n; // expected-error {{'fallthrough' attribute cannot be applied to types}}
typedef int n [[fallthrough]]; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
enum [[fallthrough]] E {}; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
class [[fallthrough]] C {}; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
[[fallthrough]] // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
void g() {
[[fallthrough]] int n; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
[[fallthrough]] ++n; // expected-error-re {{{{^}}fallthrough attribute is only allowed on empty statements}}
switch (n) {
// FIXME: This should be an error.
[[fallthrough]];
return;
case 0:
[[fallthrough, fallthrough]]; // expected-error {{multiple times}}
case 1:
[[fallthrough(0)]]; // expected-error {{argument list}}
case 2:
break;
}
}
| |
Add Solution for Problem 108 | // 108. Convert Sorted Array to Binary Search Tree
/**
* Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
*
* Tags: Tree, Depth-first Search
*
* Similar Problems: (M) Convert Sorted List to Binary Search Tree
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <vector>
using namespace std;
/**
* 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 {
TreeNode* dfs(vector<int>& nums, int start, int end) {
if (start > end)
{
return NULL;
}
int mid = (start + end) / 2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = dfs(nums, start, mid - 1);
root->right = dfs(nums, mid + 1, end);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int n = nums.size();
if (n == 0)
{
return NULL;
}
return dfs(nums, 0, n - 1);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| |
Add UnitTests for Timer class. | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/Framework/Timer.h"
//#include "MockObjects.h" //NOLINT
using SurgSim::Framework::Timer;
TEST(TimerTest, Constructor)
{
EXPECT_NO_THROW({std::shared_ptr<Timer> timer(new Timer());});
}
TEST(TimerTest, Starting)
{
std::shared_ptr<Timer> timer(new Timer());
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 0);
EXPECT_EQ(timer->getNumberOfClockFails(), 0);
}
TEST(TimerTest, SettingFrames)
{
std::shared_ptr<Timer> timer(new Timer());
timer->endFrame();
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 1);
EXPECT_EQ(timer->getAverageFrameRate(), timer->getLastFrameRate());
EXPECT_EQ(timer->getAverageFramePeriod(), timer->getLastFramePeriod());
timer->start();
timer->setNumberOfFrames(3);
for (auto i = 0; i < 5; ++i)
{
timer->endFrame();
}
EXPECT_EQ(timer->getCurrentNumberOfFrames(), 3);
}
TEST(TimerTest, Comparison)
{
std::shared_ptr<Timer> timer1(new Timer());
std::shared_ptr<Timer> timer2(new Timer());
for (auto i = 0; i < 100; ++i)
{
timer2->beginFrame();
timer2->endFrame();
timer1->endFrame();
}
EXPECT_TRUE(timer1->getAverageFramePeriod() >= timer2->getAverageFramePeriod());
}
| |
Convert a Number to Hexadecimal | class Solution {
public:
string toHex(int num) {
if(num==0) return "0";
string ans;
char hexa[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
int cnt=0;
while(num!=0 && cnt<8){
ans=hexa[(num&15)]+ans;
num=num>>4;
cnt++;
}
return ans;
}
};
| |
Add missing GN test file. | // Copyright 2014 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 "testing/gtest/include/gtest/gtest.h"
#include "tools/gn/value.h"
TEST(Value, ToString) {
Value strval(NULL, "hi\" $me\\you\\$\\\"");
EXPECT_EQ("hi\" $me\\you\\$\\\"", strval.ToString(false));
EXPECT_EQ("\"hi\\\" \\$me\\you\\\\\\$\\\\\\\"\"", strval.ToString(true));
// Test lists, bools, and ints.
Value listval(NULL, Value::LIST);
listval.list_value().push_back(Value(NULL, "hi\"me"));
listval.list_value().push_back(Value(NULL, true));
listval.list_value().push_back(Value(NULL, false));
listval.list_value().push_back(Value(NULL, static_cast<int64>(42)));
// Printing lists always causes embedded strings to be quoted (ignoring the
// quote flag), or else they wouldn't make much sense.
EXPECT_EQ("[\"hi\\\"me\", true, false, 42]", listval.ToString(false));
EXPECT_EQ("[\"hi\\\"me\", true, false, 42]", listval.ToString(true));
// Some weird types, we may want to enhance or change printing of these, but
// here we test the current behavior.
EXPECT_EQ("<void>", Value().ToString(false));
EXPECT_EQ("<scope>", Value(NULL, Value::SCOPE).ToString(false));
}
| |
Add convexity test for polygon | /*
* Copyright (C) 2015-2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <bits/stdc++.h>
typedef std::pair<int, int> IntPair;
typedef std::deque<IntPair> IntPairs;
IntPairs vertices;
// make vector from two points
IntPair makeVector(IntPair p0, IntPair p1) {
IntPair vect(p1.first - p0.first, p1.second - p0.second);
return vect;
}
// [a, b]; where a, b - vectors
int vectorMul(IntPair a, IntPair b) {
return a.first * b.second - b.first * a.second;
}
int lastVectorsMul(int index0, int index1, int index2) {
IntPair v1 = makeVector(vertices[index0], vertices[index1]);
IntPair v2 = makeVector(vertices[index1], vertices[index2]);
return vectorMul(v1, v2);
}
int main() {
int N;
std::cin >> N;
for (int i = 0; i < N; i++) {
int x, y;
std::cin >> x >> y;
vertices.push_back(IntPair(x, y));
}
bool is_convex = true;
bool is_positive = (lastVectorsMul(0, 1, 2) >= 0);
for (int i = 1; i < N; i++) {
bool curr = (lastVectorsMul(i, (i + 1) % N, (i + 2) % N) >= 0);
if (is_positive != curr) {
is_convex = false;
break;
}
is_positive = curr;
}
std::cout << (is_convex ? "YES" : "NO") << std::endl;
return 0;
}
| |
Add a test for the MultipathAlignmentGraph that just explodes | /// \file multipath_alignment_graph.cpp
///
/// unit tests for the multipath mapper's MultipathAlignmentGraph
#include <iostream>
#include "json2pb.h"
#include "vg.pb.h"
#include "../multipath_mapper.hpp"
#include "../build_index.hpp"
#include "catch.hpp"
namespace vg {
namespace unittest {
TEST_CASE( "MultipathAlignmentGraph::align tries multiple traversals of snarls in tails", "[multipath][mapping][multipathalignmentgraph]" ) {
string graph_json = R"({
"node": [
{"id": 1, "sequence": "GATT"},
{"id": 2, "sequence": "A"},
{"id": 3, "sequence": "G"},
{"id": 4, "sequence": "CA"}
],
"edge": [
{"from": 1, "to": 2},
{"from": 1, "to": 3},
{"from": 2, "to": 4},
{"from", 3, "to": 4}
]
})";
// Load the JSON
Graph proto_graph;
json2pb(proto_graph, graph_json.c_str(), graph_json.size());
// Make it into a VG
VG vg;
vg.extend(proto_graph);
// We need a fake read
string read("GATTACA");
// Pack it into an Alignment
Alignment query;
query.set_sequence(read);
// Make up a fake MEM
// GCSA range_type is just a pair of [start, end], so we can fake them.
// This will actually own the MEMs
vector<MaximalExactMatch> mems;
// This will hold our MEMs and their start positions in the imaginary graph.
// Note that this is also a memcluster_t
vector<pair<const MaximalExactMatch*, pos_t>> mem_hits;
// Make a MEM hit
mems.emplace_back(read.begin() + 1, read.begin() + 2, make_pair(5, 5), 1);
// Drop it on node 1 where it should sit
mem_hits.emplace_back(&mems.back(), make_pos_t(1, false, 1));
// Make an Aligner to use for the actual aligning and the scores
Aligner aligner;
// Make an identity projection translation
auto identity = MultipathAlignmentGraph::create_identity_projection_trans(vg);
// Make the MultipathAlignmentGraph to test
MultipathAlignmentGraph mpg(vg, mem_hits, identity);
// Make the output MultipathAlignment
MultipathAlignment out;
// Make it align
mpg.align(query, vg, &aligner, true, 4, false, 5, out);
cerr << pb2json(out) << endl;
// Make sure it worked at all
REQUIRE(out.sequence() == read);
REQUIRE(out.subpath_size() > 0);
}
}
}
| |
Add a test for a crash with unnamed NamedDecls | // Makes sure it doesn't crash.
// XFAIL: linux
// RUN: rm -rf %t
// RUN: not %clang_cc1 %s -index-store-path %t/idx -std=c++14
// RUN: c-index-test core -print-record %t/idx | FileCheck %s
namespace rdar32474406 {
void foo();
typedef void (*Func_t)();
// CHECK: [[@LINE+4]]:1 | type-alias/C | c:record-hash-crash-invalid-name.cpp@N@rdar32474406@T@Func_t | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
// CHECK: [[@LINE+2]]:14 | function/C | c:@N@rdar32474406@F@foo# | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
Func_t[] = { foo }; // invalid decomposition
}
| |
Add solutons that count all permutations. | #include "boost/unordered_map.hpp"
#include <iostream>
#include <vector>
#include "utils/Timer.hpp"
using Bucket = std::vector<int>;
void print(Bucket &buckets) {
std::for_each(buckets.begin(), buckets.end(), [](auto item) { std::cout << item << " "; });
std::cout << "\n";
}
class CountAllPermutations {
public:
size_t count(Bucket &buckets, size_t numsols) {
size_t numberOfSolutions = numsols;
bool isEmpty = std::all_of(buckets.cbegin(), buckets.cend(), [](auto value) { return value == 0; });
if (isEmpty) {
numberOfSolutions++;
return numberOfSolutions;
};
for (size_t idx = 0; idx < buckets.size(); ++idx) {
const int value = buckets[idx];
if (value > 0) {
Bucket newBuckets(buckets);
newBuckets[idx] = value - 1;
numberOfSolutions = count(newBuckets, numberOfSolutions);
}
}
return numberOfSolutions;
}
};
int main() {
{
utils::ElapsedTime<utils::MILLISECOND> t("Run time: ");
Bucket buckets{2, 1};
CountAllPermutations alg;
std::cout << "Number of valid solutions: " << alg.count(buckets, 0) << "\n";
}
{
Bucket buckets{2, 1, 2, 2};
CountAllPermutations alg;
std::cout << "Number of valid solutions: " << alg.count(buckets, 0) << "\n;
}
return 0;
}
| |
Add cpp program which created the LCG64ShiftRandom test data. | #include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
#include <trng/lcg64_shift.hpp>
unsigned long long pow(unsigned long long x, unsigned long long n) {
unsigned long long result=1;
while (n > 0) {
if ((n&1) > 0) {
result=result*x;
}
x = x*x;
n >>= 1;
}
return result;
}
unsigned int log2_floor(unsigned long long x) {
unsigned int y(0);
while (x>0) {
x>>=1;
++y;
};
--y;
return y;
}
int main(void) {
trng::lcg64_shift random_default;
trng::lcg64_shift random_seed_111(111);
trng::lcg64_shift random_split_3_0;
random_split_3_0.split(3, 0);
trng::lcg64_shift random_split_3_1;
random_split_3_1.split(3, 1);
trng::lcg64_shift random_split_3_2;
random_split_3_2.split(3, 2);
trng::lcg64_shift random_jump_6361;
trng::lcg64_shift random_jump2_5667;
std::cout << "# default, seed 111, split 3-0, split 3-1, split 3-2, jump-6361, jump2-5657" << std::endl;
for (int i = 0; i < 1009; ++i) {
std::cout << static_cast<long long>(random_default()) << ',';
std::cout << static_cast<long long>(random_seed_111()) << ',';
std::cout << static_cast<long long>(random_split_3_0()) << ',';
std::cout << static_cast<long long>(random_split_3_1()) << ',';
std::cout << static_cast<long long>(random_split_3_2()) << ',';
random_jump_6361.jump(i);
std::cout << static_cast<long long>(random_jump_6361()) << ',';
random_jump2_5667.jump2(i%64);
std::cout << static_cast<long long>(random_jump2_5667()) << '\n';
}
return 0;
}
| |
Remove Nth Node From End of List | /**
* Definition for singly-linked list.
* 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;
for(int i=0;fast && i < n;i++){
fast = fast->next;
}
if(fast){
while(fast && fast->next){
slow = slow->next;
fast = fast->next;
}
if(slow && slow->next){
slow->next = slow->next->next;
}
}else if(head){
head = head->next;
}
return head;
}
};
| |
Add stub for the starting point | // This is the starting point
//
#include <iostream>
int main() {
std::string testString("This is a sample string");
std::cout << testString << std::endl;
return 0;
}
| |
Add test case verifying PA convection | #include "mfem.hpp"
#include "catch.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
namespace pa_kernels
{
double test_nl_convection_nd(int dim)
{
Mesh *mesh;
if (dim == 2)
{
mesh = new Mesh(2, 2, Element::QUADRILATERAL, 0, 1.0, 1.0);
}
if (dim == 3)
{
mesh = new Mesh(2, 2, 2, Element::HEXAHEDRON, 0, 1.0, 1.0, 1.0);
}
int order = 2;
H1_FECollection fec(order, dim);
FiniteElementSpace fes(mesh, &fec, dim);
GridFunction x(&fes), y_fa(&fes), y_pa(&fes);
x.Randomize(3);
NonlinearForm nlf_fa(&fes);
nlf_fa.AddDomainIntegrator(new VectorConvectionNLFIntegrator);
nlf_fa.Mult(x, y_fa);
NonlinearForm nlf_pa(&fes);
nlf_pa.SetAssemblyLevel(AssemblyLevel::PARTIAL);
nlf_pa.AddDomainIntegrator(new VectorConvectionNLFIntegrator);
nlf_pa.Setup();
nlf_pa.Mult(x, y_pa);
y_fa -= y_pa;
double difference = y_fa.Norml2();
delete mesh;
return difference;
}
TEST_CASE("Nonlinear Convection", "[PartialAssembly], [NonlinearPA]")
{
SECTION("2D")
{
REQUIRE(test_nl_convection_nd(2) == Approx(0.0));
}
SECTION("3D")
{
REQUIRE(test_nl_convection_nd(3) == Approx(0.0));
}
}
}
| |
Add the forgotten file. splice is only a stub. | ////////////////////////////////////////////////////////////////////////////////
/// @brief fundamental types for the optimisation and execution of AQL
///
/// @file arangod/Aql/Types.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/Types.h"
using namespace triagens::aql;
using Json = triagens::basics::Json;
AqlValue::~AqlValue () {
switch (_type) {
case JSON: {
delete _json;
return;
}
case DOCVEC: {
for (auto it = _vector->begin(); it != _vector->end(); ++it) {
delete *it;
}
delete _vector;
return;
}
case RANGE: {
return;
}
default:
return;
}
}
AqlValue* AqlValue::clone () const {
switch (_type) {
case JSON: {
return new AqlValue(new Json(_json->copy()));
}
case DOCVEC: {
auto c = new vector<AqlItemBlock*>;
c->reserve(_vector->size());
for (auto it = _vector->begin(); it != _vector->end(); ++it) {
c->push_back((*it)->slice(0, (*it)->size()));
}
return new AqlValue(c);
}
case RANGE: {
return new AqlValue(_range._low, _range._high);
}
default:
return nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief splice multiple blocks, note that the new block now owns all
/// AqlValue pointers in the old blocks, therefore, the latter are all
/// set to nullptr, just to be sure.
////////////////////////////////////////////////////////////////////////////////
AqlItemBlock* AqlItemBlock::splice(std::vector<AqlItemBlock*>& blocks)
{
return nullptr;
}
| |
Revert "this is my test" | #include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>
INITIALIZE_EASYLOGGINGPP
int main(int argc, char *argv[]) {
START_EASYLOGGINGPP(argc, argv);
std::cout << "Who am I ? where am I ? Lei" << std::endl;
int i = foo();
std::cout << str() + 1 << std::endl << i << std::endl;
LOG(INFO) << "I'm drawing here...";
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
} | #include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>
INITIALIZE_EASYLOGGINGPP
int main(int argc, char *argv[]) {
START_EASYLOGGINGPP(argc, argv);
int i = foo();
std::cout << str() + 1 << std::endl << i << std::endl;
LOG(INFO) << "Drawing...";
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
} |
Add code to insert a node in circular linked list | #include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=this;
}
Node *insertNode(Node *head, int d){
Node *np=new Node(d);
Node *t=head;
if(head==NULL)
return np;
while(t->next!=head)
t=t->next;
t->next=np;
np->next=head;
return head;
}
Node *insertNodePos(Node *head, int d, int pos){
Node *np=new Node(d);
Node *t=head;
if(pos==1){
while(t->next!=head)
t=t->next;
t->next=np;
np->next=head;
head=np;
return head;
}
int c=1;
while(c<pos-1){
t=t->next;
c++;
}
np->next=t->next;
t->next=np;
return head;
}
void displayList(Node *head){
Node *t=head;
cout<<"\nElements of the list are:\n";
while(t->next!=head){
cout<<t->data<<"\n";
t=t->next;
}
cout<<t->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.insertNode(head,p);
}
cout<<"\nEnter the position where you wish to insert the element: ";
cin>>pos;
if(pos>n+1)
cout<<"\nSorry! The position you entered is out of bounds.\n";
else{
cout<<"\nInput the data of the node: ";
cin>>d;
head=np.insertNodePos(head,d,pos);
}
np.displayList(head);
}
| |
Add test for invalid geometry encoding | #include "catch.hpp"
// mapnik vector tile
#include "vector_tile_geometry_feature.hpp"
#include "vector_tile_layer.hpp"
// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/util/variant.hpp>
// protozero
#include <protozero/pbf_writer.hpp>
// libprotobuf
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#include "vector_tile.pb.h"
#pragma GCC diagnostic pop
// std
#include <limits>
//
// Unit tests for encoding of geometries to features
//
TEST_CASE("encode feature pbf of degenerate linestring")
{
mapnik::geometry::line_string<std::int64_t> line;
line.add_coord(10,10);
std::string layer_buffer = "";
mapnik::vector_tile_impl::layer_builder_pbf layer("foo", 4096, layer_buffer);
mapnik::feature_ptr f(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1));
mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor visitor(*f, layer);
visitor(line);
REQUIRE(layer_buffer == "");
}
| |
Add file with comments to be used in the file |
/*
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
-------------------------------------------------------------------------------
CLASS
-------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
*/
/*
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
-------------------------------------------------------------------------------
IMPLEMENTATION
-------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
*/
/*----------------------------------------------------------------------------*/
/* CONSTRUCTORS */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* STATIC METHODS */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* OVERRIDEN METHODS */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* VIRTUAL METHODS */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* CONCRETE METHODS */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* FRIEND FUNCTIONS */
/*----------------------------------------------------------------------------*/
/*================================ TRAINER =================================*/
/*=============================== EVALUATOR ================================*/
/*=============================== GENERATOR ================================*/
/*================================ LABELER =================================*/
/*=============================== SERIALIZER ===============================*/
/*================================= OTHERS =================================*/
/*----------------------------------------------------------------------------*/
// Tags
// Alias
// Type traits
// Inner classes
// Hidden name method inheritance
// Instance variables
// Constructors
// Static methods
// Overriden methods
// Purely Virtual methods
// Virtual methods
// Concrete methods
// Instance variables
| |
Add "class templates SFINAE" sample | // Conditionally instantiate class templates
#include <type_traits>
#include <limits>
template <typename T, typename Enable = void>
class foo;
template <typename T>
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{ };
template <typename T>
class foo<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{ };
int main()
{
foo<int> f1;
foo<float> f2;
}
// Use SFINAE to conditionally instantiate class templates.
//
// We provide two partial specializations of the `foo` class template:
// the first, on [9-11], is instantiated only for integral
// type, such as on [19]; the second, on [13-15], is instantiated
// only for floating point types, such as on [20].
//
// The [Substitution Failure Is Not An
// Error](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error)
// (SFINAE) rule states that
// failing to instantiate a template with some particular
// template arguments does not result in an error and that instantiation
// is simply discarded. On [10] and [14], we use
// [`std::enable_if`](cpp/types/enable_if) to force instantiation to
// succeed only when its first template argument evaluates to `true`
// (in the first case, when `T` is integral, and in the second case,
// when `T` is floating point). If neither case succeeds, the compiler
// will attempt to instantiate the undefined unspecialized template on
// [6-7] and give an error.
//
// If you want to simply prevent a template from being instantiated
// for certain template arguments, consider using `static_assert`
// instead.
| |
Remove duplicates from a sorted array | #include <iostream>
using namespace std;
int removeDuplicates(int A[], int n) {
if (n == 0) {
return 0;
}
int prev = 0;
int length = 1;
for (int i = 1; i < n; ++i) {
if (A[i] == A[prev]) {
continue;
} else {
++length;
++prev;
A[prev] = A[i];
}
}
return length;
}
int main() {
int A[] = {1,1,2};
cout << removeDuplicates(A, 3) << endl;
return 0;
}
| |
Add Matthieu's coroutines test program to the repository. | #include <iostream>
#include <scheduler/coroutine.hh>
Coro* mc;
Coro* c1, *c2;
void start2(void*)
{
int x=1;
int y = 12;
std::cerr <<"c2 start " << std::endl;
std::cerr <<"c2->c1 " << std::endl;
x++;
coroutine_switch_to(c2, c1);
assert(x==2);
x++;
std::cerr <<"c2->main " << std::endl;
assert(x==3);
coroutine_switch_to(c2, mc);
std::cerr <<"END!!" << std::endl;
}
void start(void*)
{
int x=0;
std::cerr <<"c1 start" << std::endl;
c2 = coroutine_new();
std::cerr <<"c1->start c2" << std::endl;
x++;
coroutine_start(c1, c2, &start2, (void*)0);
assert(x==1);x++;
std::cerr <<"c1->main" << std::endl;
coroutine_switch_to(c1, mc);
assert(x==2);x++;
std::cerr <<"c1->main" << std::endl;
coroutine_switch_to(c1, mc);
assert(x==3);x++;
std::cerr <<"END!!" << std::endl;
}
int main(int argc, const char* argv[])
{
mc = coroutine_new();
coroutine_initialize_main(mc);
c1 = coroutine_new();
std::cerr <<"Starting c1 " << std::endl;
coroutine_start(mc, c1, &start, (void*)0);
std::cerr <<"Main->c1" << std::endl;
coroutine_switch_to(mc, c1);
std::cerr <<"Main->c2" << std::endl;
coroutine_switch_to(mc, c2);
std::cerr <<"Main done" << std::endl;
}
| |
Add --brave-new-test-launcher support to remoting_unittests. | // Copyright (c) 2011 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.
// A basic testrunner that supports JavaScript unittests.
// This lives in src/chrome/test/base so that it can include chrome_paths.h
// (required for JS unittests) without updating the DEPS file for each
// subproject.
#include "base/test/test_suite.h"
#include "chrome/common/chrome_paths.h"
#include "media/base/media.h"
#include "net/socket/ssl_server_socket.h"
int main(int argc, char** argv) {
base::TestSuite test_suite(argc, argv);
#if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
// This is required for the JavaScript unittests.
chrome::RegisterPathProvider();
#endif // defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
// Enable support for SSL server sockets, which must be done while
// single-threaded.
net::EnableSSLServerSockets();
// Ensures runtime specific CPU features are initialized.
media::InitializeCPUSpecificMediaFeatures();
return test_suite.Run();
}
| // Copyright (c) 2011 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.
// A basic testrunner that supports JavaScript unittests.
// This lives in src/chrome/test/base so that it can include chrome_paths.h
// (required for JS unittests) without updating the DEPS file for each
// subproject.
#include "base/test/test_suite.h"
#include "base/test/unit_test_launcher.h"
#include "chrome/common/chrome_paths.h"
#include "media/base/media.h"
#include "net/socket/ssl_server_socket.h"
int main(int argc, char** argv) {
base::TestSuite test_suite(argc, argv);
#if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
// This is required for the JavaScript unittests.
chrome::RegisterPathProvider();
#endif // defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
// Enable support for SSL server sockets, which must be done while
// single-threaded.
net::EnableSSLServerSockets();
// Ensures runtime specific CPU features are initialized.
media::InitializeCPUSpecificMediaFeatures();
return base::LaunchUnitTests(
argc, argv, base::Bind(&base::TestSuite::Run,
base::Unretained(&test_suite)));
}
|
Add test for setting coordinates | #include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>
int main(int argc, char** argv)
{
assert(argc==3);
MPI_Init(&argc,&argv);
PCU_Comm_Init();
PCU_Protect();
gmi_register_mesh();
gmi_register_null();
int* conn;
int nelem;
int etype;
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
int dim = m->getDimension();
destruct(m, conn, nelem, etype);
m->destroyNative();
apf::destroyMesh(m);
gmi_model* model = gmi_load(".null");
m = apf::makeEmptyMdsMesh(model, dim, false);
apf::GlobalToVert outMap;
apf::construct(m, conn, nelem, etype, outMap);
outMap.clear();
delete [] conn;
apf::alignMdsRemotes(m);
apf::deriveMdsModel(m);
m->verify();
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
| #include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>
int main(int argc, char** argv)
{
assert(argc==3);
MPI_Init(&argc,&argv);
PCU_Comm_Init();
PCU_Protect();
gmi_register_mesh();
gmi_register_null();
int* conn;
double* coords;
int nelem;
int etype;
int nverts;
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
int dim = m->getDimension();
extractCoords(m, coords, nverts);
destruct(m, conn, nelem, etype);
m->destroyNative();
apf::destroyMesh(m);
gmi_model* model = gmi_load(".null");
m = apf::makeEmptyMdsMesh(model, dim, false);
apf::GlobalToVert outMap;
apf::construct(m, conn, nelem, etype, outMap);
delete [] conn;
apf::alignMdsRemotes(m);
apf::deriveMdsModel(m);
apf::setCoords(m, coords, nverts, outMap);
delete [] coords;
outMap.clear();
m->verify();
//apf::writeVtkFiles("after", m);
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
|
Fix plugin visibility in DRT | // 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 "webkit/support/test_webplugin_page_delegate.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
namespace webkit_support {
webkit::npapi::WebPluginDelegate*
TestWebPluginPageDelegate::CreatePluginDelegate(
const base::FilePath& file_path,
const std::string& mime_type) {
return webkit::npapi::WebPluginDelegateImpl::Create(file_path, mime_type);
}
WebKit::WebPlugin* TestWebPluginPageDelegate::CreatePluginReplacement(
const base::FilePath& file_path) {
return NULL;
}
WebKit::WebCookieJar* TestWebPluginPageDelegate::GetCookieJar() {
return WebKit::Platform::current()->cookieJar();
}
} // namespace webkit_support
| // 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 "webkit/support/test_webplugin_page_delegate.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
namespace webkit_support {
webkit::npapi::WebPluginDelegate*
TestWebPluginPageDelegate::CreatePluginDelegate(
const base::FilePath& file_path,
const std::string& mime_type) {
webkit::npapi::WebPluginDelegateImpl* delegate =
webkit::npapi::WebPluginDelegateImpl::Create(file_path, mime_type);
#if defined(OS_MACOSX) && !defined(USE_AURA)
if (delegate)
delegate->SetContainerVisibility(true);
#endif
return delegate;
}
WebKit::WebPlugin* TestWebPluginPageDelegate::CreatePluginReplacement(
const base::FilePath& file_path) {
return NULL;
}
WebKit::WebCookieJar* TestWebPluginPageDelegate::GetCookieJar() {
return WebKit::Platform::current()->cookieJar();
}
} // namespace webkit_support
|
Add the solution to "Reverse a doubly linked list". | #include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
Node* prev;
};/*
Reverse a doubly linked list, input list may also be empty
Node is defined as
struct Node
{
int data;
Node *next;
Node *prev
}
*/
Node* Reverse(Node *head)
{
if (head == NULL || head->next == NULL) {
return head;
}
Node *prev = NULL;
Node *cur = head;
while (cur->next != NULL) {
Node *next = cur->next;
cur->next = prev;
if (prev != NULL) {
prev->prev = cur;
}
prev = cur;
cur = next;
}
cur->prev = NULL;
cur->next = prev;
prev->prev = cur;
return cur;
}
Node* Insert(Node *head, int data)
{
Node *temp = new Node();
temp->data = data; temp->prev = NULL; temp->next = NULL;
if(head == NULL) return temp;
head->prev = temp;
temp->next = head;
return temp;
}
void Print(Node *head) {
if(head == NULL) return;
while(head->next != NULL){ cout<<head->data<<" "; head = head->next;}
cout<<head->data<<" ";
while(head->prev != NULL) { cout<<head->data<<" "; head = head->prev; }
cout<<head->data<<"\n";
}
int main()
{
int t; cin>>t;
Node *head = NULL;
while(t--) {
int n; cin>>n;
head = NULL;
for(int i = 0;i<n;i++) {
int x; cin>>x;
head = Insert(head,x);
}
head = Reverse(head);
Print(head);
}
} | |
Work on KQUERY on spoj | #include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct query {
int l, r;
int id;
} queries[200000];
int s;
int cmp(const void* a, const void* b) {
struct query* x = (struct query *) a;
struct query* y = (struct query *) b;
if ( (x->l) / s == (y->l) / s) {
return ((x->l)/s - (y->l)/s);
}
return ((x->r) - (y->r))
}
int main(void) {
int n;
scanf("%d", &n);
s = sqrt(n);
int a[n];
for (int i = 0; i < n; i++) {
scanf("%d", a+i);
}
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%d %d", &(q[i].l), &(q[i].r));
q[i].l--;
q[i].r--;
q[i].id = i;
}
qsort(queries, q, sizeof(struct query), cmp);
int ans[q];
for (int i = 0; i < q; i++) {
| |
Add unit test for LayerRegistry::CreateLayer | #include <map>
#include <string>
#include "gtest/gtest.h"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/layer_factory.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
template <typename TypeParam>
class LayerFactoryTest : public MultiDeviceTest<TypeParam> {};
TYPED_TEST_CASE(LayerFactoryTest, TestDtypesAndDevices);
TYPED_TEST(LayerFactoryTest, TestCreateLayer) {
typedef typename TypeParam::Dtype Dtype;
typename LayerRegistry<Dtype>::CreatorRegistry& registry =
LayerRegistry<Dtype>::Registry();
shared_ptr<Layer<Dtype> > layer;
LayerParameter layer_param;
for (typename LayerRegistry<Dtype>::CreatorRegistry::iterator iter =
registry.begin(); iter != registry.end(); ++iter) {
layer_param.set_type(iter->first);
layer.reset(LayerRegistry<Dtype>::CreateLayer(layer_param));
EXPECT_EQ(iter->first, layer->type());
}
}
} // namespace caffe
| |
Test for my last patch. | // RUN: clang-cc %s -emit-llvm -o - | FileCheck %s
struct basic_ios{~basic_ios(); };
template<typename _CharT> struct basic_istream : virtual public basic_ios {
virtual ~basic_istream(){}
};
template<typename _CharT> struct basic_iostream : public basic_istream<_CharT>
{
virtual ~basic_iostream(){}
};
basic_iostream<char> res;
int main() {
}
// CHECK: call void @_ZN9basic_iosD2Ev
| |
Add a simple cert validation example | /*
* Simple example of a certificate validation
* (C) 2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/botan.h>
#include <botan/x509cert.h>
#include <botan/x509stor.h>
#include <stdio.h>
using namespace Botan;
int main()
{
LibraryInitializer init;
X509_Certificate ca_cert("ca_cert.pem");
X509_Certificate subject_cert("http_cert.pem");
X509_Store cert_store;
cert_store.add_cert(ca_cert, /*trusted=*/true);
X509_Code code = cert_store.validate_cert(subject_cert);
if(code == VERIFIED)
printf("Cert validated\n");
else
printf("Cert did not validate, code = %d\n", code);
return 0;
}
| |
Add Solution for Problem 172 | // 172. Factorial Trailing Zeroes
/**
* Given an integer n, return the number of trailing zeroes in n!.
*
* Note: Your solution should be in logarithmic time complexity.
*
* Tags: Math
*
* Similar Problems: (H) Number of Digit One
*/
#include "stdafx.h"
// in the factorial, there are many 2s, so it is enough just to count the number of 5
class Solution {
public:
int trailingZeroes(int n) {
int count = 0;
while (n > 0)
{
n /= 5;
count += n;
}
return count;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| |
Add set of test for geospatial | /*
* Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "test_geospatial.h"
#include "gtest/gtest.h"
TEST(testPoint, GeoPoint) {
EXPECT_EQ(testPoint(), 0);
}
TEST(testMultiPoint, GeoMultiPoint) {
EXPECT_EQ(testMultiPoint(), 0);
}
TEST(testCircle, GeoCircle) {
EXPECT_EQ(testCircle(), 0);
}
TEST(testConvex, GeoConvex) {
EXPECT_EQ(testConvex(), 0);
}
TEST(testPolygon, GeoPolygon) {
EXPECT_EQ(testPolygon(), 0);
}
TEST(testMultiCircle, GeoMultiCircle) {
EXPECT_EQ(testMultiCircle(), 0);
}
TEST(testMultiConvex, GeoMultiConvex) {
EXPECT_EQ(testMultiConvex(), 0);
}
TEST(testMultiPolygon, GeoMultiPolygon) {
EXPECT_EQ(testMultiPolygon(), 0);
}
TEST(testCollection, GeoCollection) {
EXPECT_EQ(testCollection(), 0);
}
TEST(testIntersection, GeoIntersection) {
EXPECT_EQ(testIntersection(), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| |
Check if an input string matches the pattern | #include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <ctime>
#include <set>
#include <utility>
#include <algorithm>
#include <map>
using namespace std;
bool isPatternMatched(string& str, string& pattern) {
if (pattern.size() < 1) {
return true;
}
vector<vector<map<char, string> > > res1(str.size(), vector<map<char, string> >()), res2(str.size(), vector<map<char, string> >());
for (int i = 0; i < res1.size(); i++) {
map<char, string> m;
m[pattern[0]] = str.substr(0, i + 1);
res1[i].push_back(m);
}
for (int i = 1; i < pattern.size(); i++) {
for (int j = 0; j < str.size(); j++) {
res2[j].clear();
for (int k = 1; k <= j; k++) {
string lastWord = str.substr(k, j - k + 1);
for (map<char, string> m : res1[k - 1]) {
if (m.find(pattern[i]) == m.end()) {
map<char, string> m1(m.begin(), m.end());
m1[pattern[i]] = lastWord;
res2[j].push_back(m1);
} else if (m[pattern[i]] == lastWord) {
map<char, string> m1(m.begin(), m.end());
res2[j].push_back(m1);
}
}
}
}
swap(res1, res2);
}
if (res1[str.size() - 1].size() > 0) {
for (map<char, string> m : res1[str.size() - 1]) {
for (auto p : m) {
cout << p.first << ":" << p.second << endl;
}
cout << endl;
}
}
return res1[str.size() - 1].size() > 0;
}
int main(void) {
string str = "asdasdasdasd", pattern = "AAAA";
cout << isPatternMatched(str, pattern) << endl;
str = "bigboyboybig";
pattern = "ABBA";
cout << isPatternMatched(str, pattern) << endl;
}
| |
Check whether given tree is sub tree of other. | #include <stdio.h>
typedef struct _NODE {
int data;
_NODE* left;
_NODE* right;
} NODE;
NODE* newNode(int data) {
NODE* node = new NODE();
node->data = data;
node->left = nullptr;
node->right = nullptr;
return node;
}
bool isIdentical(NODE* T, NODE* S) {
if (T == nullptr && S == nullptr) return true;
if (T == nullptr || S == nullptr) return false;
if (T->data == S->data && isIdentical(T->left, S->left) &&
isIdentical(T->right, S->right))
return true;
return false;
}
bool isSubtree(NODE* T, NODE* S) {
if (S == nullptr) return true;
if (T == nullptr) return false;
if (isIdentical(T, S)) return true;
return isSubtree(T->left, S) || isSubtree(T->right, S);
}
int main(int argc, char const* argv[]) {
NODE* T = newNode(26);
T->right = newNode(3);
T->right->right = newNode(3);
T->left = newNode(10);
T->left->left = newNode(4);
T->left->left->right = newNode(30);
T->left->right = newNode(6);
NODE* S = newNode(10);
S->right = newNode(6);
S->left = newNode(4);
S->left->right = newNode(30);
if (isSubtree(T, S))
printf("Tree 2 is subtree of Tree 1");
else
printf("Tree 2 is not a subtree of Tree 1");
return 0;
} | |
Improve shape function check for `tf.roll` | /* Copyright 2018 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/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
// --------------------------------------------------------------------------
REGISTER_OP("Roll")
.Input("input: T")
.Input("shift: Tshift")
.Input("axis: Taxis")
.Output("output: T")
.Attr("T: type")
.Attr("Tshift: {int32,int64}")
.Attr("Taxis: {int32,int64}")
.SetShapeFn(shape_inference::UnchangedShape);
} // namespace tensorflow
| /* Copyright 2018 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/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
// --------------------------------------------------------------------------
REGISTER_OP("Roll")
.Input("input: T")
.Input("shift: Tshift")
.Input("axis: Taxis")
.Output("output: T")
.Attr("T: type")
.Attr("Tshift: {int32,int64}")
.Attr("Taxis: {int32,int64}")
.SetShapeFn([](shape_inference::InferenceContext* c) {
shape_inference::ShapeHandle unused;
// The `input` must be 1-D or higher
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 1, &unused));
return shape_inference::UnchangedShape(c);
});
} // namespace tensorflow
|
Update branch chapter3 and resolve conflicts. | #include"Game.h"
int main(int argc, char **args)
{
Game *game = new Game();
const char windowTitle[] = "Chapter 1: Setting up SDL";
game->init(windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, false);
while (game->isRunning()) {
game->handleEvents();
game->update();
game->render();
}
game->clean();
return 0;
}
| |
Fix gl error debug print. |
/*
* 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 "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr(const GrGLInterface* gl) {
while (GR_GL_NO_ERROR != gl->fGetError()) {}
}
void GrGLCheckErr(const GrGLInterface* gl,
const char* location,
const char* call) {
uint32_t err = GR_GL_GET_ERROR(gl);
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLResetRowLength(const GrGLInterface* gl) {
if (gl->supportsDesktop()) {
GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
#if GR_GL_LOG_CALLS
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif
#if GR_GL_CHECK_ERROR
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif
|
/*
* 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 "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr(const GrGLInterface* gl) {
while (GR_GL_NO_ERROR != gl->fGetError()) {}
}
void GrGLCheckErr(const GrGLInterface* gl,
const char* location,
const char* call) {
uint32_t err = GR_GL_GET_ERROR(gl);
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", err);
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLResetRowLength(const GrGLInterface* gl) {
if (gl->supportsDesktop()) {
GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
#if GR_GL_LOG_CALLS
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif
#if GR_GL_CHECK_ERROR
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif
|
Add ability to peek registers through USB, beautify code. | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <dpcdecl.h>
#include <dmgr.h>
#include <depp.h>
uint8_t
peek(int reg)
{
HIF deviceHandle;
int status;
char deviceName[32] = "Cr2s2";
uint8_t data;
status = DmgrOpen(&deviceHandle, deviceName);
if (!status) {
printf("Problem opening device, code %d\n", DmgrGetLastError());
return 0;
}
status = DeppEnable(deviceHandle);
if (!status) {
printf("Problem enabling port 0, code %d\n", DmgrGetLastError());
return 0;
}
DeppGetReg(deviceHandle, reg, &data, fFalse);
status = DeppDisable(deviceHandle);
if (!status) {
printf("Problem disabling DEPP, code %d\n", DmgrGetLastError());
return 0;
}
DmgrClose(deviceHandle);
return data;
}
int
main(int argc, char *argv[])
{
int reg;
if (argc != 2) {
printf("usage: %s register\n", argv[0]);
exit(1);
}
reg = atoi(argv[1]);
printf("%x\n", peek(reg));
return 0;
}
| |
Add tiny test for Error::Message(). | // This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Tests for command results.
*/
#include <sstream>
#include "catch.hpp"
#include "../cmd_result.hpp"
#include "dummy_response_sink.hpp"
// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Tests for error classes.
*/
#include "catch.hpp"
#include "../errors.hpp"
SCENARIO("Errors contain a retrievable message", "[error]") {
GIVEN("An Error") {
Error e = NetError("need an RS-232 Interface Lead");
WHEN("Message() is called") {
auto s = e.Message();
THEN("the result is the message given in the Error's ctor") {
REQUIRE(s == "need an RS-232 Interface Lead");
}
}
}
}
| |
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 a very dumb echo repl. | #include <iostream>
namespace
{
class Repl
{
std::istream& in_;
std::ostream& out_;
std::string prompt_ = "mclisp> ";
public:
Repl(std::istream& in=std::cin, std::ostream& out=std::cout) : in_(in), out_(out) {};
int loop();
};
int Repl::loop()
{
std::string val;
while (val != "quit")
{
out_ << prompt_;
in_ >> val;
out_ << val << std::endl;
}
return 0;
}
}; //end namespace
int main(int argc, const char **argv)
{
Repl repl;
return repl.loop();
}
| |
Add example file to create event dump manually | #include <stdio.h>
#include "../include/AliHLTTPCGeometry.h" //We use this to convert from row number to X
struct ClusterData {
int fId;
int fRow;
float fX;
float fY;
float fZ;
float fAmp;
};
int main(int argc, char** argv)
{
for (int iEvent = 0;iEvent < 2;iEvent++) //Multiple events go to multiple files, named event.[NUM].dump
{
char filename[1024];
sprintf(filename, "event.%d.dump", iEvent);
FILE* fp = fopen(filename, "w+b");
int clusterId = 0; //Here we count up the cluster ids we fill (must be unique).
for (int iSector = 0;iSector < 36;iSector++) //HLT Sector numbering, sectors go from 0 to 35, all spanning all rows from 0 to 158.
{
int nNumberOfHits = 100; //For every sector we first have to fill the number of hits in this sector to the file
fwrite(&nNumberOfHits, sizeof(nNumberOfHits), 1, fp);
ClusterData* tempBuffer = new ClusterData[nNumberOfHits]; //As example, we fill 100 clusters per sector
for (int i = 0;i < nNumberOfHits;i++)
{
tempBuffer[i].fId = clusterId++;
tempBuffer[i].fRow = i; //We fill one hit per TPC row
tempBuffer[i].fX = AliHLTTPCGeometry::Row2X(i);
tempBuffer[i].fY = i *iSector * 0.03f;
tempBuffer[i].fZ = i * (1 + iEvent) * (iSector >= 18 ? -1 : 1);
tempBuffer[i].fAmp = 100; //Arbitrary amplitude
}
fwrite(tempBuffer, sizeof(tempBuffer[0]), nNumberOfHits, fp);
delete tempBuffer;
}
fclose(fp);
}
return(0);
}
| |
Add unit test for DamageTask | // 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/DamageTask.hpp>
using namespace Hearthstonepp;
using namespace SimpleTasks;
using namespace TestUtils;
TEST(DamageTask, GetTaskID)
{
const DamageTask damage(EntityType::ENEMIES, 2);
EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);
}
TEST(DamageTask, Run)
{
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& player1 = agent.GetPlayer1();
std::vector<Card> cards;
cards.reserve(5);
const std::string name = "test";
for (size_t i = 0; i < 5; ++i)
{
const auto id = static_cast<char>(i + 0x30);
cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
PlayMinionCard(player1, cards[i]);
}
DamageTask damage(EntityType::FRIENDS, 1);
MetaData result = damage.Run(player1);
EXPECT_EQ(result, MetaData::DAMAGE_SUCCESS);
EXPECT_EQ(player1.GetField().size(), 0u);
}
| |
Add Breadth First Search in Cpp | #include<bits/stdc++.h>
using namespace std;
vector<int> BreadthFirstSearch(int vertex,vector<int> adjacent[],int start_vertex,int destination){
queue<int> que;
//bfsPath will store the path
vector<int> bfsPath;
//this array will take care of duplicate traversing
bool visited[vertex];
vector<int>::iterator it;
que.push(start_vertex);
bfsPath.push_back(start_vertex);
visited[start_vertex]=true;
int flag=0;
while(!que.empty()){
int tem = que.front();
que.pop();
for(it = adjacent[tem].begin();it<adjacent[tem].end();it++){
if(!visited[*it]){
bfsPath.push_back(*it);
//if destination is found
if(*it==destination){
flag=1;
break;
}
visited[*it] = true;
que.push(*it);
}
}
if(flag==1){
break;
}
}
//if we will not find the destination
if(flag==0){
bfsPath.clear();
}
return bfsPath;
}
//this fn will print the path
void printTraversal(vector<int>bfsPath){
vector<int>::iterator it;
for(it = bfsPath.begin();it<bfsPath.end();it++){
cout<<*it<<endl;
}
}
int main() {
//number of vertex
int vertex = 4;
vector<int> adjacent[vertex];
adjacent[0].push_back(1);
adjacent[0].push_back(3);
adjacent[1].push_back(2);
adjacent[2].push_back(3);
//starting vertex
int start_vertex = 0;
//destination
int destination = 3;
vector<int> bfsPath = BreadthFirstSearch(vertex,adjacent,start_vertex,destination);
if(!bfsPath.empty()){
printTraversal(bfsPath);
}else{
cout<<"path not found";
}
return 0;
} | |
Add a test case for r251476. | // RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -stack-protector 2 -emit-llvm -o - %s | FileCheck %s
// Check that function attributes are added to the OpenMP runtime functions.
template <class T>
struct S {
T f;
S(T a) : f(a) {}
S() : f() {}
operator T() { return T(); }
~S() {}
};
// CHECK: define internal void @.omp.copyprivate.copy_func(i8*, i8*) [[ATTR0:#[0-9]+]] {
void foo0();
int foo1() {
char a;
#pragma omp parallel
a = 2;
#pragma omp single copyprivate(a)
foo0();
return 0;
}
// CHECK: define internal void @.omp_task_privates_map.({{.*}}) [[ATTR3:#[0-9]+]] {
// CHECK: define internal i32 @.omp_task_entry.({{.*}}) [[ATTR0]] {
// CHECK: define internal i32 @.omp_task_destructor.({{.*}}) [[ATTR0]] {
int foo2() {
S<double> s_arr[] = {1, 2};
S<double> var(3);
#pragma omp task private(s_arr, var)
s_arr[0] = var;
return 0;
}
// CHECK: define internal void @.omp.reduction.reduction_func(i8*, i8*) [[ATTR0]] {
float foo3(int n, float *a, float *b) {
int i;
float result;
#pragma omp parallel for private(i) reduction(+:result)
for (i=0; i < n; i++)
result = result + (a[i] * b[i]);
return result;
}
// CHECK: attributes [[ATTR0]] = {{{.*}} sspstrong {{.*}}}
// CHECK: attributes [[ATTR3]] = {{{.*}} sspstrong {{.*}}}
| |
Add basic unit test for StreamingDenseFeatures reading | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Viktor Gal
*/
#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/io/CSVFile.h>
#include <shogun/io/streaming/StreamingAsciiFile.h>
#include <unistd.h>
#include <gtest/gtest.h>
using namespace shogun;
TEST(StreamingDenseFeatures, example_reading)
{
index_t n=20;
index_t dim=2;
std::string tmp_name = "/tmp/StreamingDenseFeatures_reading.XXXXXX";
char* fname = mktemp(const_cast<char*>(tmp_name.c_str()));
SGMatrix<float64_t> data(dim,n);
for (index_t i=0; i<dim*n; ++i)
data.matrix[i] = sg_rand->std_normal_distrib();
CDenseFeatures<float64_t>* orig_feats=new CDenseFeatures<float64_t>(data);
//CCSVFile* saved_features = new CCSVFile(fname, 'w');
CAsciiFile* saved_features = new CAsciiFile(fname, 'w');
orig_feats->save(saved_features);
saved_features->close();
SG_UNREF(saved_features);
CStreamingAsciiFile* input = new CStreamingAsciiFile(fname);
CStreamingDenseFeatures<float64_t>* feats = new CStreamingDenseFeatures<float64_t>(input, false, 5);
index_t i = 0;
feats->start_parser();
while (feats->get_next_example())
{
SGVector<float64_t> example = feats->get_vector();
SGVector<float64_t> expected = orig_feats->get_feature_vector(i);
ASSERT_EQ(dim, example.vlen);
for (index_t j = 0; j < dim; j++)
EXPECT_NEAR(expected.vector[j], example.vector[j], 1E-6);
feats->release_example();
i++;
}
feats->end_parser();
SG_UNREF(orig_feats);
SG_UNREF(feats);
}
| |
Merge point of two lists | /*
* Problem: Find Merge Point of Two Lists
* Author: Anirudha Bose <ani07nov@gmail.com>
Find merge point of two linked lists
Node is defined as
struct Node
{
int data;
Node* next;
}
*/
int lengthOfList(Node* head)
{
int l=0;
while(head != NULL)
{
head = head->next;
l++;
}
return l+1;
}
int FindMergeNode(Node *headA, Node *headB)
{
int A = lengthOfList(headA), B = lengthOfList(headB);
int c = 0;
if(A>B)
{
while(c != A-B)
{
headA = headA->next;
c++;
}
}
else
{
while(c != B-A)
{
headB = headB->next;
c++;
}
}
while(headA != NULL && headB != NULL)
{
if(headA == headB)
return headA->data;
headA = headA->next;
headB = headB->next;
}
return -1;
}
| |
Create tests for base cpu | #include <cassert>
#include <gtest/gtest.h>
#include <system.h>
#include <basecpu.h>
#define TEST_CLASS BaseCPUTest
class BaseTestCPU : public BaseCPU {
public:
BaseTestCPU(int maxTicks, const System &sys) : maxTicks(maxTicks), ticks(0), resets(0), BaseCPU(sys) { }
void reset() { resets++; }
void tick() {
assert(isRunning());
ticks++;
if(ticks>= maxTicks) {
stop();
}
}
int ticks;
int resets;
int maxTicks;
};
const int TEST_TICK_COUNT = 3;
class TEST_CLASS : public testing::Test {
protected:
TEST_CLASS() : cpu(TEST_TICK_COUNT, dummySystem) { }
BaseTestCPU cpu;
System dummySystem;
};
TEST_F(TEST_CLASS, TestRunLoop) {
ASSERT_FALSE(cpu.isRunning()) << "Incorrect initial CPU running state";
ASSERT_EQ(cpu.ticks, 0) << "Incorrect initial CPU tick count";
ASSERT_EQ(cpu.resets, 0) << "Incorrect initial CPU reset count";
cpu.startup();
ASSERT_FALSE(cpu.isRunning()) << "Incorrect final CPU running state";
ASSERT_EQ(cpu.ticks, TEST_TICK_COUNT) << "Incorrect final CPU tick count";
ASSERT_EQ(cpu.resets, 1) << "Incorrect initial CPU reset count";
} | |
Fix CodeForKeyboardEvent to properly calculate the scancode. | // 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 "content/renderer/pepper/usb_key_code_conversion.h"
#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"
using blink::WebKeyboardEvent;
namespace content {
uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
// Extract the scancode and extended bit from the native key event's lParam.
int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
if ((key_event.nativeKeyCode & (1 << 24)) != 0)
scancode |= 0xe000;
ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
return key_converter->NativeKeycodeToUsbKeycode(scancode);
}
const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
return key_converter->NativeKeycodeToCode(key_event.nativeKeyCode);
}
} // namespace content
| // 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 "content/renderer/pepper/usb_key_code_conversion.h"
#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"
using blink::WebKeyboardEvent;
namespace content {
uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
// Extract the scancode and extended bit from the native key event's lParam.
int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
if ((key_event.nativeKeyCode & (1 << 24)) != 0)
scancode |= 0xe000;
ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
return key_converter->NativeKeycodeToUsbKeycode(scancode);
}
const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
// Extract the scancode and extended bit from the native key event's lParam.
int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
if ((key_event.nativeKeyCode & (1 << 24)) != 0)
scancode |= 0xe000;
ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
return key_converter->NativeKeycodeToCode(scancode);
}
} // namespace content
|
Add Solution for 083 Remove Duplicates from Sorted List | // 83. Remove Duplicates from Sorted List
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
*
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
*
* Tags: Linked List
*
* Author: Kuang Qin
*/
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *p) : val(x), next(p) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *curr = head;
while (curr != NULL) {
// search and delete duplicates
while (curr->next != NULL && curr->next->val == curr->val) {
curr->next = curr->next->next;
}
// move forward
curr = curr->next;
}
return head;
}
};
// recursive
class Solution_Recursive {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
head->next = deleteDuplicates(head->next);
// duplicates
if (head->val == head->next->val) {
return head->next;
}
return head;
}
};
int main() {
ListNode node5(3), node4(2, &node5), node3(2, &node4), node2(1, &node3), node1(1, &node2);
Solution sol;
ListNode *newhead = sol.deleteDuplicates(&node1);
for (ListNode *p = newhead; p != NULL; p = p->next) {
cout << p->val << " ";
}
cout << endl;
cin.get();
return 0;
} | |
Add capture stack trace benchmark | //
// Created by Ivan Shynkarenka on 15.02.2016.
//
#include "cppbenchmark.h"
#include "debug/stack_trace.h"
const uint64_t iterations = 1000000;
BENCHMARK("Stack trace")
{
uint64_t crc = 0;
for (uint64_t i = 0; i < iterations; ++i)
crc += CppCommon::StackTrace().frames().size();
// Update benchmark metrics
context.metrics().AddIterations(iterations - 1);
context.metrics().SetCustom("CRC", crc);
}
BENCHMARK_MAIN()
| |
Add error test for memoizing a Func with compute and storage at different levels. | #include <Halide.h>
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Param<float> val;
Func f, g;
Var x, y;
f(x, y) = val + cast<uint8_t>(x);
g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);
g.split(y, y, _, 16);
f.store_root();
f.compute_at(g, y).memoize();
val.set(23.0f);
Image<uint8_t> out = g.realize(128, 128);
for (int32_t i = 0; i < 128; i++) {
for (int32_t j = 0; j < 128; j++) {
assert(out(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
}
}
}
| |
Patch for HARMONY-3677 "[classlib][awt] Results of running checker tool" | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/**
* @author Igor V. Stolyarov
* @version $Revision$
*/
#include "LUTTables.h"
#include <string.h>
unsigned char mulLUT[256][256]; /* Multiply Luckup table */
unsigned char divLUT[256][256]; /* Divide Luckup table */
bool mulLUT_inited = false;
bool divLUT_inited = false;
void init_mulLUT(){
int i, j;
if(mulLUT_inited) return;
for(i = 0; i < 256; i++){
for(j = 0; j < 256; j++){
mulLUT[i][j] = (int)(((float)i * j) / 255 + 0.5);
}
}
mulLUT_inited = true;
}
void init_divLUT(){
int i, j;
if(divLUT_inited) return;
memset(divLUT[0], 0, 256);
for(i = 1; i < 256; i++){
for(j = 0; j <= i; j++){
divLUT[i][j] = (int)(((float)j) / i * 255 + 0.5);
}
for(; j < 256; j++){
divLUT[i][j] = 0;
}
}
divLUT_inited = true;
}
| |
Add simplest exception example from lesson | /**
Очень простой вводный пример на демонстрацию исключений
*/
#include <iostream>
#include <exception>
#include <string>
struct MyError
{
std::string msg;
};
class Test
{
public:
~Test()
{
std::cout << "Вызван деструктор\n";
}
};
double sin_by_sharnin(double x)
{
const size_t fakt_3 = 6,
fakt_5 = 120;
Test t1, t2;
if (x == 1.0) {
throw MyError{"Неправильный аргумент"};
}
if (x == 2.0) {
/// ради теста, выбрасываем исключение типа double
/// не стоит так делать в рабочих программах
throw 5.78;
}
if (x == 3.0) {
/// выбрасываем базовый тип исключений для всей стандартной библиотеки
throw std::exception{};
}
t2 = t1; /// демонстрация работы деструкторов, даже при выбросе исключения
return x - (x*x*x)/fakt_3 + (x*x*x*x*x)/fakt_5;
}
void find_sins(int code)
{
std::cout << "sin(1.57) = "
<< sin_by_sharnin(1.57) << "\n";
std::cout << "sin(0.87) = "
<< sin_by_sharnin(0.87) << "\n";
if (code == 1) {
std::cout << "sin(1.0) = "
<< sin_by_sharnin(1.0) << "\n";
} else if (code == 2) {
std::cout << "sin(2.0) = "
<< sin_by_sharnin(2.0) << "\n";
} else {
std::cout << "sin(3.0) = "
<< sin_by_sharnin(3.0) << "\n";
}
}
int main()
{
using namespace std;
int code;
cout << "Введите целое число: ";
cin >> code;
Test t1, t2;
t2 = t1;
try {
find_sins(code);
}
catch (const MyError& err) {
cout << "Исключение перехвачено c сообщением: ";
cout << err.msg << "\n";
}
catch (const double&) {
cout << "Исключение типа double перехвачено\n";
}
catch (const std::exception& exc) {
cout << "Исключение типа exception перехвачено\n";
cout << exc.what() << "\n";
}
}
| |
Add a bench for measuring drawBitmap anti-aliasing overhead | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkString.h"
/**
* This bench measures the rendering time of SkCanvas::drawBitmap with different anti-aliasing /
* matrix combinations.
*/
class DrawBitmapAABench : public Benchmark {
public:
DrawBitmapAABench(bool doAA, const SkMatrix& matrix, const char name[])
: fMatrix(matrix)
, fName("draw_bitmap_") {
fPaint.setAntiAlias(doAA);
fName.appendf("%s_%s", doAA ? "aa" : "noaa", name);
}
protected:
const char* onGetName() override {
return fName.c_str();
}
void onPreDraw() override {
fBitmap.allocN32Pixels(200, 200);
fBitmap.eraseARGB(255, 0, 255, 0);
}
void onDraw(const int loops, SkCanvas* canvas) override {
canvas->concat(fMatrix);
for (int i = 0; i < loops; i++) {
canvas->drawBitmap(fBitmap, 0, 0, &fPaint);
}
}
private:
SkPaint fPaint;
SkMatrix fMatrix;
SkString fName;
SkBitmap fBitmap;
typedef Benchmark INHERITED;
};
DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1), "ident"); )
DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1.17f), "scale"); )
DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )
DEF_BENCH(
SkMatrix m;
m.reset();
m.preRotate(15);
return new DrawBitmapAABench(false, m, "rotate");
)
DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1), "ident"); )
DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1.17f), "scale"); )
DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )
DEF_BENCH(
SkMatrix m;
m.reset();
m.preRotate(15);
return new DrawBitmapAABench(true, m, "rotate");
)
| |
Add file missing from r313583 | //===-- ubsan_init_standalone_preinit.cc
//------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//
#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
#error "UBSan is not supported on this platform!"
#endif
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"
#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used)) void (*__local_ubsan_preinit)(
void) = __ubsan::InitAsStandalone;
#endif // SANITIZER_CAN_USE_PREINIT_ARRAY
| |
Add solution to the dictionary task | #include <iostream>
#include <cstring>
using namespace std;
struct WordTranslation {
char word[100], translation[100];
WordTranslation(const char _word[] = "", const char _translation[] = "") {
strcpy(word, _word);
strcpy(translation, _translation);
}
};
class Dictionary {
int size;
WordTranslation words[1000];
void removeWordAt(int index) {
size--;
for (int i = index; i < size; i++) {
words[i] = words[i+1];
}
}
public:
Dictionary() {
size = 0;
}
void addWord(WordTranslation wordTranslation) {
words[size++] = wordTranslation;
}
void removeWord(const char word[]) {
for (int i = 0; i < size; i++) {
if (strcmp(word, words[i].word) == 0) {
removeWordAt(i);
break;
}
}
}
WordTranslation findWord(const char word[]) {
for (int i = 0; i < size; i++) {
if (strcmp(word, words[i].word) == 0) {
return words[i];
}
}
return WordTranslation(word, word);
}
void translate(const char text[]) {
const char *lastWhiteSpace = text, *currentWhiteSpace = strstr(text, " ");
while (currentWhiteSpace != NULL) {
char word[100] = {'\0'};
strncpy(word, lastWhiteSpace, currentWhiteSpace - lastWhiteSpace);
cout << findWord(word).translation << " ";
lastWhiteSpace = currentWhiteSpace + 1;
currentWhiteSpace = strstr(lastWhiteSpace, " ");
}
char word[100] = {'\0'};
strcpy(word, lastWhiteSpace);
cout << findWord(word).translation;
cout << endl;
}
};
int main() {
Dictionary dictionary;
dictionary.addWord(WordTranslation("tazi", "this"));
dictionary.addWord(WordTranslation("zadacha", "task"));
dictionary.addWord(WordTranslation("e", "is"));
dictionary.addWord(WordTranslation("trudna", "hard"));
dictionary.translate("tazi zadacha e trudna");
dictionary.removeWord("zadacha");
dictionary.translate("tazi zadacha e trudna");
return 0;
} | |
Add rule of zero sample | // The rule of zero
#include <memory>
class shallow
{
private:
std::shared_ptr<int> p = std::make_shared<int>(5);
};
class deep
{
public:
deep() = default;
deep(deep const& other)
: p{std::make_unique<int>(*other.p)}
{ }
private:
std::unique_ptr<int> p = std::make_unique<int>(5);
};
// Use existing RAII types to encapsulate and safely manage
// dynamically allocated resources.
//
// The class `shallow` ([5-9]) manages a dynamically allocated `int`
// object. Rather than manage this object manually, we use a
// [`std::shared_ptr`](cpp/memory/shared_ptr) on [15] to take
// ownership of the object. The lifetime of this object is now
// tied to the lifetime of the `foo` object that contains it
// without having to implement any constructors or destructors. If
// a `shallow` object is copied, the copy will share ownership of
// this resource.
//
// If we want to perform a deep copy, we can instead use a
// [`std::unique_ptr`](cpp/memory/unique_ptr) and implement a
// copy constructor to copy the resource, as shown with the `deep`
// class on [11-22].
int main()
{
shallow s1;
shallow s2 = s1;
deep d1;
deep d2 = d1;
}
| |
Add a trivially simple pass to delete unreachable blocks from the CFG. This pass is required to paper over problems in the code generator (primarily live variables and its clients) which doesn't really have any well defined semantics for unreachable code. | //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is an extremely simple version of the SimplifyCFG pass. Its sole
// job is to delete LLVM basic blocks that are not reachable from the entry
// node. To do this, it performs a simple depth first traversal of the CFG,
// then deletes any unvisited nodes.
//
// Note that this pass is really a hack. In particular, the instruction
// selectors for various targets should just not generate code for unreachable
// blocks. Until LLVM has a more systematic way of defining instruction
// selectors, however, we cannot really expect them to handle additional
// complexity.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/CFG.h"
#include "Support/DepthFirstIterator.h"
using namespace llvm;
namespace {
class UnreachableBlockElim : public FunctionPass {
virtual bool runOnFunction(Function &F);
};
RegisterOpt<UnreachableBlockElim>
X("unreachableblockelim", "Remove unreachable blocks from the CFG");
}
FunctionPass *llvm::createUnreachableBlockEliminationPass() {
return new UnreachableBlockElim();
}
bool UnreachableBlockElim::runOnFunction(Function &F) {
std::set<BasicBlock*> Reachable;
// Mark all reachable blocks.
for (df_ext_iterator<Function*> I = df_ext_begin(&F, Reachable),
E = df_ext_end(&F, Reachable); I != E; ++I)
/* Mark all reachable blocks */;
// Loop over all dead blocks, remembering them and deleting all instructions
// in them.
std::vector<BasicBlock*> DeadBlocks;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (!Reachable.count(I)) {
DeadBlocks.push_back(I);
for (succ_iterator SI = succ_begin(&*I), E = succ_end(&*I); SI != E; ++SI)
(*SI)->removePredecessor(I);
I->dropAllReferences();
}
if (DeadBlocks.empty()) return false;
// Actually remove the blocks now.
for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
F.getBasicBlockList().erase(DeadBlocks[i]);
return true;
}
| |
Add missing file to fix the build. | /*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <gtest/gtest.h>
#include <osre/Assets/AssimpWrapper.h>
namespace OSRE {
namespace UnitTest {
using namespace ::OSRE::Assets;
class AssimpWrapperTest : public ::testing::Test {
// empty
};
TEST_F( AssimpWrapperTest, createTest ) {
bool ok( true );
try {
AssimpWrapper assimpWrapper;
} catch (...) {
ok = false;
}
EXPECT_TRUE( ok );
}
}
}
| |
Add Chapter 20, exercise 5 | // Chapter 20, Exercise 05: Define an input and an output operator (>> and <<)
// for vector.
#include "../lib_files/std_lib_facilities.h"
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
os << "{ ";
for (int i = 0; i<v.size(); ++i) {
os << v[i];
if (i+1<v.size()) os << ',';
os << ' ';
}
os << '}';
return os;
}
template<class T>
istream& operator>>(istream& is, vector<T>& v)
{
char ch;
is >> ch;
if (ch!='{') error("vector must start with '{'");
T element;
while (true) {
is >> ch;
if (is && ch=='}') return is;
else is.unget();
is >> element;
if (is) v.push_back(element);
else error("invalid element");
}
return is;
}
int main()
try {
vector<double> vd;
vector<int> vi;
vector<string> vs;
cout << "Enter vector of doubles: ";
cin >> vd;
cout << "Enter vector of integers: ";
cin >> vi;
cout << "Enter vector of strings: ";
cin >> vs;
cout << vd << "\n" << vi << "\n" << vs << "\n";
}
catch (Range_error& re) {
cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| |
Add flag to remove common certs | // 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 "net/third_party/quiche/src/quic/core/crypto/common_cert_set.h"
#include <cstddef>
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
namespace quic {
namespace {
class CommonCertSetsEmpty : public CommonCertSets {
public:
// CommonCertSets interface.
quiche::QuicheStringPiece GetCommonHashes() const override {
return quiche::QuicheStringPiece();
}
quiche::QuicheStringPiece GetCert(uint64_t /* hash */,
uint32_t /* index */) const override {
return quiche::QuicheStringPiece();
}
bool MatchCert(quiche::QuicheStringPiece /* cert */,
quiche::QuicheStringPiece /* common_set_hashes */,
uint64_t* /* out_hash */,
uint32_t* /* out_index */) const override {
return false;
}
CommonCertSetsEmpty() {}
CommonCertSetsEmpty(const CommonCertSetsEmpty&) = delete;
CommonCertSetsEmpty& operator=(const CommonCertSetsEmpty&) = delete;
~CommonCertSetsEmpty() override {}
};
} // anonymous namespace
CommonCertSets::~CommonCertSets() {}
// static
const CommonCertSets* CommonCertSets::GetInstanceQUIC() {
static CommonCertSetsEmpty* certs = new CommonCertSetsEmpty();
return certs;
}
} // namespace quic
| |
Test that LargeAllocator unpoisons memory before releasing it to the OS. | // Test that LargeAllocator unpoisons memory before releasing it to the OS.
// RUN: %clangxx_asan %s -o %t
// RUN: ASAN_OPTIONS=quarantine_size=1 %t
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
int main() {
void *p = malloc(1024 * 1024);
free(p);
char *q = (char *)mmap(p, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(q);
assert(q <= p);
assert(q + 4096 > p);
memset(q, 42, 4096);
munmap(q, 4096);
return 0;
}
| |
Add test for type properties of std::reference_wrapper | //===----------------------------------------------------------------------===//
//
// 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>
// reference_wrapper
// Test that reference wrapper meets the requirements of TriviallyCopyable,
// CopyConstructible and CopyAssignable.
#include <functional>
#include <type_traits>
int main()
{
typedef std::reference_wrapper<int> T;
static_assert(std::is_copy_constructible<T>::value, "");
static_assert(std::is_copy_assignable<T>::value, "");
// Extension up for standardization: See N4151.
static_assert(std::is_trivially_copyable<T>::value, "");
}
| |
Add code to delete node in circular linked list | #include<iostream>
#include<cstdlib>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=this;
}
Node *insertNode(Node *head, int d){
Node *np=new Node(d);
Node *t=head;
if(head==NULL)
return np;
while(t->next!=head)
t=t->next;
t->next=np;
np->next=head;
return head;
}
Node *deleteNode(Node *head, int pos){
Node *t=head;
if(pos==1){
while(t->next!=head)
t=t->next;
t->next=head->next;
Node *tm=head;
head=head->next;
free(tm);
return head;
}
int c=1;
while(c<pos-1){
t=t->next;
c++;
}
Node *tm=t->next;
t->next=t->next->next;
free(tm);
return head;
}
void displayList(Node *head){
Node *t=head;
cout<<"\nElements of the list are:\n";
while(t->next!=head){
cout<<t->data<<"\n";
t=t->next;
}
cout<<t->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.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 test case for method to reverse null terminated string | /*
This programtests class reverse_str
*/
#include "reverse_str.h"
#include<iostream>
void test_single(char* s){
// avoid printing nullpointer
if(s!=nullptr)
std::cout<<"\nString: "<<s;
else
std::cout<<"\nnull";
std::cout<<"\nLength: "<<Reverse_str::get_length(s);
Reverse_str::reverse(s);
// avoid printing nullpointer
if(s!=nullptr)
std::cout<<"\nReversed: "<<s;
else
std::cout<<"\nnull";
std::cout<<"\n";
}
void test_all(){
// null pointer
char* s1 = nullptr;
test_single(s1);
// length 0
char s2[] = "";
test_single(s2);
// length 1
char s3[] = "r";
test_single(s3);
// length 2
char s4[] = "rk";
test_single(s4);
//length 3
char s5[] = "xyz";
test_single(s5);
// length 10
char s6[] = "what's up!";
test_single(s6);
// length 17
char s7[] = "let's do some c++";
test_single(s7);
std::cout<<"\n\n";
}
int main(){
// test all
test_all();
return 0;
} | |
Add Chapter 20, exercise 7 | // Chapter 20, Exercise 07: find the lexicographical last string in an unsorted
// vector<string>. Beware that "lexicographical" is not the same as "alphabeti-
// cal", as "Zzzz"<"aaa" (uppercase letters are lexicographically before lower-
// case letters).
#include "../lib_files/std_lib_facilities.h"
// returns an iterator to the biggest element of the argument
template<class Iterator>
Iterator biggest_element(Iterator first, Iterator last)
{
Iterator high = first;
while (first != last) {
if (*first>*high) high = first;
++first;
}
return high;
}
int main()
try {
vector<string> vs;
string s;
cout << "Enter a few words, Ctrl-Z to end: ";
while (cin>>s)
vs.push_back(s);
vector<string>::iterator last = biggest_element(vs.begin(),vs.end());
if (last!=vs.end())
cout << "The lexicographically last string in the vector is \""
<< *last << "\".\n";
else
cout << "Something went wrong.\n";
}
catch (Range_error& re) {
cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| |
Copy the existing regression test for remove-cstr-calls from the tooling branch to preserve its history. It's not yet functional. | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ -c %t/test.cpp","file":"%t/test.cpp"}]' > %t/compile_commands.json
// RUN: cp "%s" "%t/test.cpp"
// RUN: remove-cstr-calls "%t" "%t/test.cpp"
// RUN: cat "%t/test.cpp" | FileCheck %s
// FIXME: implement a mode for refactoring tools that takes input from stdin
// and writes output to stdout for easier testing of tools.
namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
basic_string();
basic_string(const C *p, const A& a = A());
const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm { struct StringRef { StringRef(const char *p); }; }
void f1(const std::string &s) {
f1(s.c_str());
// CHECK: void f1
// CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
std::string s;
f2(s.c_str());
// CHECK: std::string s;
// CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
std::string s;
f3(s.c_str());
// CHECK: std::string s;
// CHECK: f3(s)
}
| |
Add Chapter 20, exercise 13 | // Chapter 20, Exercise 13: modify exercise 12 to use 0 to represent the one
// past the last element (end()) instead of allocating a real Link
#include "../lib_files/std_lib_facilities.h"
template<class Elem> struct Link {
Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
:prev(p), succ(s), val(v) { }
Link* prev;
Link* succ;
Elem val;
};
template<class Elem> class my_list {
public:
my_list() :first(0) { }
class iterator;
iterator begin() { return iterator(first); }
iterator end() { return iterator(0); }
iterator insert(iterator p, const Elem& v); // insert v into list before p
iterator erase(iterator p); // remove p from the list
void push_back(const Elem& v);
void push_front(const Elem& v);
void pop_front();
void pop_back();
Elem& front() { return *first; }
Elem& back();
Link<Elem>* first;
};
template<class Elem> class my_list<Elem>::iterator {
Link<Elem>* curr;
public:
iterator(Link<Elem>* p) :curr(p) { }
// Link<Elem>* get_link() { return curr; }
iterator& operator++() { curr = curr->succ; return *this; } // forward
iterator& operator--() { curr = curr->prev; return *this; } // backward
Elem& operator*() { return curr->val; } // get value (dereference)
bool operator==(const iterator& b) const { return curr==b.curr; }
bool operator!=(const iterator& b) const { return curr!=b.curr; }
};
template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
first = new Link<Elem>(v,0,first);
}
template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
Iterator high = first;
for (Iterator p = first; p!=last; ++p)
if (*high<*p) high = p;
return high;
}
int main()
try {
my_list<int> lst;
int x;
while (cin >> x) lst.push_front(x);
my_list<int>::iterator p = high(lst.begin(),lst.end());
cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| |
Add chap8, ex2 + ex3 | #include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
/*Ex8.2:
Write a function print() that prints a vector of ints to cout. Give it
two arguments: a string for “labeling” the output and a vector.
*/
void print(string label, vector<int> v){
cout << label << ": " << endl;
for (int i = 0; i < v.size(); ++i)
cout << v[i] << " " ;
}
/*Ex8.3:
Create a vector of Fibonacci numbers and print them using the function
from exercise 2. To create the vector, write a function, fibonacci(x,y,v,n),
where integers x and y are ints, v is an empty vector<int>, and n is the number
of elements to put into v; v[0] will be x and v[1] will be y. A Fibonacci number
is one that is part of a sequence where each element is the sum of the two
previous ones. For example, starting with 1 and 2, we get 1, 2, 3, 5, 8, 13, 21,
. . . . Your fibonacci() function should make such a sequence starting with its
x and y arguments.
*/
void fibonacci(int x, int y, vector<int>& v, int n){
if(n <= 0) {
cout << "n can't <= 0" << endl;
return;
}
if(n == 1)
v = {x};
else if(n == 2)
v = {x,y};
else{
v.clear();
v.push_back(x);
v.push_back(y);
for(int i = 2; i < n; ++i)
v.push_back(v[i-1] + v[i-2]);
}
return;
}
int main(int argc, char const *argv[])
{
char exit = 'n';
int n;
int firstElem;
int secondElem;
vector<int> vFibonacci;
try{
while(exit != 'y' || exit != 'Y'){
cout << "Element of Fibonacci: n = ";
cin >> n;
cout << "\nfirstElem: ";
cin >> firstElem;
cout << "\nsecondElem: ";
cin >> secondElem;
fibonacci(firstElem,secondElem,vFibonacci,n);
print("Result: ",vFibonacci);
cout << "\nDo you what to exit? (y/n): ";
cin >> exit;
}
return 0;
}catch(runtime_error &e){
cout << e.what() << endl;
}catch(...){
cout << "Exiting..." << endl;
}
}
| |
Add memmove tests to app_suite | /* **********************************************************
* Copyright (c) 2011 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License, and no later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "gtest/gtest.h"
TEST(StringTests, Memmove) {
const char input[128] = "0123456789abcdefg"; // strlen(input) = 17.
char tmp[128];
// Trivial: aligned copy, no overlapping.
EXPECT_EQ(tmp, memmove(tmp, input, strlen(input) + 1));
ASSERT_STREQ(input, tmp);
strcpy(tmp, input);
// Overlapping copy forwards, should skip 1 byte before going to fastpath.
EXPECT_EQ(tmp+7, memmove(tmp+7, tmp+3, strlen(tmp) + 1 - 3));
EXPECT_STREQ("01234563456789abcdefg", tmp);
strcpy(tmp, input);
// Overlapping copy forwards, different alignment.
EXPECT_EQ(tmp+6, memmove(tmp+6, tmp+3, strlen(tmp) + 1 - 3));
EXPECT_STREQ("0123453456789abcdefg", tmp);
strcpy(tmp, input);
// Overlapping copy backwards, should skip 3 bytes before going to fastpath.
EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+7, strlen(tmp) + 1 - 7));
EXPECT_STREQ("012789abcdefg", tmp);
strcpy(tmp, input);
// Overlapping copy backwards, different alignment.
EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+6, strlen(tmp) + 1 - 6));
EXPECT_STREQ("0126789abcdefg", tmp);
}
| |
Add test program for mergesort | /*
This program tests merge sort
*/
#include<iostream>
#include<vector>
#include "mergesort.h" // My implementation of merge sort
// Displays vector
void printVector(std::vector<int> A){
for(auto x: A){
std::cout<<x<<" ";
}
std::cout<<std::endl;
}
// Tests merge sort on vector A
void testMergeSort(std::vector<int> A){
std::cout<<"Before: ";
printVector(A);
Mergesort::mergesort(A);
std::cout<<"After: ";
printVector(A);
}
// tests merge sort on several different inputs
void testMergeSort(){
std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1};
testMergeSort(v1);
std::vector<int> v2 = {5,4,3,2,1};
testMergeSort(v2);
std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10};
testMergeSort(v3);
std::vector<int> v4 = {6,5,4,7,8,9,9,5,4,9,2,0,3,1,5,9,8,7,4,5,6,3};
testMergeSort(v4);
// test on empty vector
std::vector<int> v5;
testMergeSort(v5);
std::vector<int> v6 = {2,4,-6,1,-9,3,0};
testMergeSort(v6);
std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0};
testMergeSort(v7);
}
int main(){
// test merge sort
testMergeSort();
return 0;
}
| |
Remove Duplicates from Sorted Array II | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<3) return nums.size();
int f=0,r=1;
while(r<nums.size()){
if(nums[f]==nums[r]){
if(r-f>1) nums.erase(nums.begin()+r,nums.begin()+r+1);
else r++;
}else{
f=r;
r++;
}
}
return nums.size();
}
};
| |
Add c++ solution to the hello World problem | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// Declare a variable named 'input_string' to hold our input.
string input_string;
// Read a full line of input from stdin (cin) and save it to our variable, input_string.
getline(cin, input_string);
// Print a string literal saying "Hello, World." to stdout using cout.
cout << "Hello, World." << endl;
cout << input_string << endl;
// TODO: Write a line of code here that prints the contents of input_string to stdout.
return 0;
}
| |
Add unit tests for format c bindings | #include <boost/test/unit_test.hpp>
#include <ygo/deck/c/Format.h>
#include <ygo/deck/c/DB.h>
struct Format_Fixture
{
Format_Fixture()
{
DB_NAME(set_path)("test/card.db");
}
};
BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)
BOOST_AUTO_TEST_CASE(Create)
{
int count;
auto formatDates = FORMAT_NAME(formatDates)(&count);
for (auto i = 0; i < count; i++) {
auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED,
formatDates[i]);
auto formatDateA = FORMAT_NAME(formatDate)(formatA);
auto formatFA = FORMAT_NAME(format)(formatA);
BOOST_CHECK_EQUAL(std::string(formatDateA), formatDates[i]);
BOOST_CHECK(formatFA == ygo_data_Format_ADVANCED);
FORMAT_NAME(delete_formatDate)(formatDateA);
auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL,
formatDates[i]);
auto formatDateT = FORMAT_NAME(formatDate)(formatT);
auto formatTA = FORMAT_NAME(format)(formatT);
BOOST_CHECK_EQUAL(std::string(formatDateT), formatDates[i]);
BOOST_CHECK(formatTA == ygo_data_Format_TRADITIONAL);
FORMAT_NAME(delete_formatDate)(formatDateT);
}
FORMAT_NAME(delete_formatDates)(formatDates, count);
}
BOOST_AUTO_TEST_CASE(Invalid)
{
auto format = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "InvalidFormat");
BOOST_CHECK(format == nullptr);
}
BOOST_AUTO_TEST_CASE(Limits)
{
auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "April 2004");
auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL, "April 2004");
BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatA, "Change of Heart"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Change of Heart"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatA, "Mage Power"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Mage Power"));
BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatA, "Creature Swap"));
BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatT, "Creature Swap"));
BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatA, "Kuriboh"));
BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatT, "Kuriboh"));
FORMAT_NAME(delete)(formatA);
FORMAT_NAME(delete)(formatT);
}
BOOST_AUTO_TEST_SUITE_END()
| |
Add job with SCIP support disabled | name: SCIP Disabled
on: [push, pull_request]
jobs:
# Building using the github runner environement directly.
cmake:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check cmake
run: cmake --version
- name: Configure
run: cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DBUILD_DEPS=ON -DUSE_SCIP=OFF
- name: Build
run: cmake --build build --config Release --target all -v
- name: Test
run: CTEST_OUTPUT_ON_FAILURE=1 cmake --build build --config Release --target test -v
- name: Install
run: cmake --build build --config Release --target install -v -- DESTDIR=install
| |
Add Chapter 23, exercise 14 | // Chapter 23, exercise 14: like the sample program from 23.8.7, but read input
// from file into memory and experiment with patterns including '\n'
#include<regex>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string ifname = "pics_and_txt/chapter23_ex12_in.txt";
ifstream ifs(ifname);
if (!ifs) throw runtime_error("Can't open " + ifname);
string line;
string text;
while (getline(ifs,line))
text += line + "\n";
regex pattern;
string pat;
string prompt = "Enter pattern (qqq to exit): ";
cout << prompt;
while (getline(cin,pat)) { // read pattern
if (pat=="qqq") break;
try {
pattern = pat; // this checks pat
}
catch (regex_error) {
cout << pat << " is not a valid regular expression\n";
exit(1);
}
smatch matches;
if (regex_search(text,matches,pattern))
cout << "Match found: " << matches[0] << '\n';
else
cout << "No match found\n";
cout << prompt;
}
}
| |
Add faster algorithm for working with sorting. | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector < ll > vl;
int main(){
vl data = {234234LL, 2322LL,1LL, -1LL, 3454LL};
sort(data.begin(), data.end());
for (int i=0; i< data.size(); i++)
printf("%lld ", data[i]);
return 0;
}
| |
Change tests in JPetAnalysisTools to use double instead of int | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_SUITE_END()
| #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
double epsilon = 0.0001;
BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}
BOOST_AUTO_TEST_SUITE_END()
|
Prepare exercise 6 from chapter 10. | // 10.exercise.06.cpp
//
// Define a Roman_int class for holding Roman numerals (as ints) with a << and
// >>. Provide Roman_int with an as_int() member that returns the int value,
// so that if r is a Roman_int, we can write cout << "Roman" << r << "equals"
// << r.as_int() << '\n';.
int main()
try
{
return 0;
}
catch (exception& e)
{
cerr << e.what() << '\n';
return 1;
}
catch (...)
cerr << "Unknown exception!!\n";
return 2;
}
| |
Add the first codeforces problem | /*
* Copyright (C) 2015 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
/* http://codeforces.com/contest/527/submission/11525645 */
#include <iostream>
int main() {
long long int a, b;
std::cin >> a >> b;
long long int ans = 0;
while (b > 0) {
ans += a / b;
a = a % b;
long long int temp = a;
a = b;
b = temp;
}
std::cout << ans << std::endl;
return 0;
}
| |
Implement rod cutting to maximize profit using DP | /**
* Rod Cutting
* Given a length of rod, sample lengths and its
* corresponding profits find the maximum profit
* that can be made given the length.
* @Author: wajahat siddiqui
*/
#include <iostream>
using namespace std;
inline unsigned int max(unsigned int a, unsigned int b) {
return (a > b) ? a : b;
}
void printArray(unsigned int **A, int M, int N) {
for (unsigned int i = 0; i <= M; i++) {
for (unsigned int j = 0; j <= N; j++){
cout<<A[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
/**
* @param N is the length of the rod for which max profit to be found
* @param M is the number of rods
*/
unsigned int findMaxProfit(int profit[], int M, int N) {
unsigned int solution;
unsigned int **T = new unsigned int *[M+1];
for (int i = 0; i <= M; i++)
T[i] = new unsigned int [N+1];
for (int i = 0; i <= M; i++)
T[i][0] = 0;
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++) {
if (j >= i) {
T[i][j] = max((T[i][j-i] + profit[i-1]), T[i-1][j]);
} else {
T[i][j] = T[i-1][j];
}
}
}
printArray(T, M, N);
solution = T[M][N];
for (int i = 0; i <= M; i++)
delete [] T[i];
delete [] T;
return solution;
}
int main() {
int N = 5; // Rod Length
int profit[] = {2, 5, 7, 8};
int M = sizeof(profit)/sizeof(profit[0]); // No. of rods
cout<<"Maximum profit that can be made from Rod Length: "<<N<<" is: "
<<findMaxProfit(profit, M, N);
return 0;
} | |
Add algorithm for Inverse FFT | /*
* @author Abhishek Datta
* @github_id abdatta
* @since 15th October, 2017
*
* The following algroithm takes complex coeeficients
* and calculates its inverse discrete fourier transform
*/
#include <complex>
#include <iostream>
#include <iomanip>
#include <valarray>
const double PI = std::acos(-1);
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
// recursive fft (in-place)
void fft(CArray& x)
{
const size_t N = x.size();
if (N <= 1) return;
// divide
CArray even = x[std::slice(0, N/2, 2)];
CArray odd = x[std::slice(1, N/2, 2)];
// conquer
fft(even);
fft(odd);
// combine
for (size_t k = 0; k < N/2; ++k)
{
Complex t = std::polar(1.0, 2 * PI * k / N) * odd[k];
x[k ] = even[k] + t;
x[k+N/2] = even[k] - t;
}
}
// inverse fft (in-place)
void ifft(CArray& x)
{
// conjugate the complex numbers
x = x.apply(std::conj);
// forward fft
fft( x );
// conjugate the complex numbers again
x = x.apply(std::conj);
// scale the numbers
x /= x.size();
}
int main()
{
int t; // no. of test cases to try on
std::cin>>t;
while(t--)
{
int n; // n is for order of the polynomial
std::cin>>n;
Complex test[n];
for (int i = 0; i < n; ++i)
{
double real, imag;
std::cin>>real>>imag; // reading each coefficient as a complex number
test[i].real(real); // setting real part to real
test[i].imag(imag); // and imaginary part to imaginary
}
CArray data(test, n);
ifft(data);
for (int i = 0; i < n; ++i)
{
std::cout << std::fixed << std::setprecision(6) << data[i].real() << " " << data[i].imag() << std::endl;
}
}
} | |
Mark a test as flaky on ChromeOS. | // Copyright (c) 2010 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/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars Infobars
#else
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
| // Copyright (c) 2010 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/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS)
#if defined (OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Flaky on ChromeOS, see http://crbug.com/40141.
#define MAYBE_Infobars FLAKY_Infobars
#endif
#else
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
|
Revert 235842 "fix android build by adding build_config.h" | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/i18n/timezone.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif
TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
std::string country_code = CountryCodeForCurrentTimezone();
EXPECT_EQ(2U, country_code.size());
}
} // namespace
} // namespace base
| // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/i18n/timezone.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif
TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
std::string country_code = CountryCodeForCurrentTimezone();
EXPECT_EQ(2U, country_code.size());
}
} // namespace
} // namespace base
|
Add oss-fuzz entrypoint for Polyutils fuzz | /*
* Copyright 2018 Google, LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "../Fuzz.h"
void fuzz_PolyUtils(Fuzz* f);
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size));
fuzz_PolyUtils(&fuzz);
return 0;
}
| |
Add Chapter 20, exercise 12 | // Chapter 20, Exercise 12: complete the definition of list from 20.4.1-2 and
// get the high() example to run. Allocate a Link to represent one past the end.
#include "../lib_files/std_lib_facilities.h"
template<class Elem> struct Link {
Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
:prev(p), succ(s), val(v) { }
Link* prev;
Link* succ;
Elem val;
};
template<class Elem> class my_list {
public:
my_list() :first(new Link<Elem>()), last(first) { }
class iterator;
iterator begin() { return iterator(first); }
iterator end() { return iterator(last); }
iterator insert(iterator p, const Elem& v); // insert v into list before p
iterator erase(iterator p); // remove p from the list
void push_back(const Elem& v);
void push_front(const Elem& v);
void pop_front();
void pop_back();
Elem& front() { return *first; }
Elem& back();
Link<Elem>* first;
Link<Elem>* last; // one beyond the last link
};
template<class Elem> class my_list<Elem>::iterator {
Link<Elem>* curr;
public:
iterator(Link<Elem>* p) :curr(p) { }
// Link<Elem>* get_link() { return curr; }
iterator& operator++() { curr = curr->succ; return *this; } // forward
iterator& operator--() { curr = curr->prev; return *this; } // backward
Elem& operator*() { return curr->val; } // get value (dereference)
bool operator==(const iterator& b) const { return curr==b.curr; }
bool operator!=(const iterator& b) const { return curr!=b.curr; }
};
template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
first = new Link<Elem>(v,0,first);
}
template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
Iterator high = first;
for (Iterator p = first; p!=last; ++p)
if (*high<*p) high = p;
return high;
}
int main()
try {
my_list<int> lst;
int x;
while (cin >> x) lst.push_front(x);
my_list<int>::iterator p = high(lst.begin(),lst.end());
cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| |
Add solution to third part of first problem. Replace the structure with class with getters and setters | #include <iostream>
#include <cmath>
using namespace std;
class Point2D {
double x;
double y;
public:
double getX() {
return x;
}
double getY() {
return y;
}
void setX(double newX) {
x = newX;
}
void setY(double newY) {
y = newY;
}
void translate(double dx, double dy) {
setX(getX() + dx);
setY(getY() + dy);
}
double distanceTo(Point2D other) {
return sqrt(pow(getX() - other.getX(), 2) + pow(getY() - other.getY(), 2));
}
void print() {
cout << '(' << getX() << ", " << getY() << ')' << '\n';
}
};
void testTranslate() {
Point2D point;
point.setX(3);
point.setY(5);
point.translate(2, 3);
point.print();
}
void testDistanceBetween() {
Point2D firstPoint;
firstPoint.setX(3);
firstPoint.setY(5);
Point2D secondPoint;
secondPoint.setX(4);
secondPoint.setY(1);
cout << firstPoint.distanceTo(secondPoint) << '\n';
}
int main() {
testTranslate();
testDistanceBetween();
return 0;
} | |
Implement minimum stack that will return the minimum element from the entire stack in O(1) time | /**
* To implement minimum stack that returns minimum element in O(1) time
*/
#include <iostream>
#include <stack>
using namespace std;
class MinStack {
private:
stack<int> min;
stack<int> s;
public:
void push(int data) {
if (min.empty()) {
min.push(data);
} else if (data < min.top()) {
min.push(data);
} else if (data > min.top()) {
min.push(min.top());
}
s.push(data);
}
void pop() {
min.pop();
s.pop();
}
int top() {
return s.top();
}
/**
* T(n) = O(1)
**/
int getMin() {
return min.top();
}
};
int main() {
MinStack minStack;
int keys[] = {3, 1, 2, -1, 0, 4, -6};
int size = sizeof(keys)/sizeof(keys[0]);
for (int i = 0; i < size; i++) {
cout<<"Pushing key: "<<keys[i]<<endl;
minStack.push(keys[i]);
cout<<"Current Minimum: "<<minStack.getMin()<<endl;
}
cout<<"Popping 5 values\n";
for (int i = 0; i < 5; i++) {
cout<<"Popping: "<<minStack.top()<<endl;
minStack.pop();
cout<<"Current Minimum: "<<minStack.getMin()<<endl;
}
return 0;
} | |
Add dequeue min task solution | #include <iostream>
#include <queue>
using std::cout;
using std::queue;
int dequeue_min(queue<int>& q) {
unsigned long queue_size = q.size();
int min = q.front();
q.pop();
for (int i = 1; i < queue_size; ++i) {
int front = q.front();
q.pop();
if (front < min) {
q.push(min);
min = front;
} else {
q.push(front);
}
}
return min;
}
void print_queue(queue<int> q) {
while (!q.empty()) {
cout << q.front() << ' ';
q.pop();
}
}
int main() {
queue<int> q;
q.push(4);
q.push(2);
q.push(6);
q.push(-1);
q.push(3);
cout << dequeue_min(q) << '\n';
print_queue(q);
cout << '\n';
return 0;
}
| |
Add period length of 1/n | /*
* Copyright 2010, NagaChaitanya Vellanki
*
* Author NagaChaitanya Vellanki
*
* Print length of the period 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;
cout << "Enter n(n > 1)" << endl;
cin >> n;
if(n <= 1) {
exit(0);
}
int32_t rem = 1;
int32_t i = 0;
// period of a fraction cannot be less than the period of sequence of
// remainders
while(i < n) {
rem = (10 * rem) % n;
i++;
}
// c is the (n + 1)th term in the sequence remainders
int32_t c = rem;
rem = (10 * rem) % n; // (n + 2)th term in the sequence of remainders
i = 1;
while(rem != c) {
rem = (rem * 10) % n;
i++;
}
cout << "The period length of " << 1 << "/" << n << " is " << i << endl;
return 0;
}
| |
Add solution for chapter 18, test 26, 27 | #include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Base1 {
void print(int i) const {
cout << "Base1::print(int)" << endl;
}
protected:
int ival;
double dval;
char cval;
private:
int *id;
};
struct Base2 {
void print(double d) const {
cout << "Base2::print(double)" << endl;
}
protected:
double fval;
private:
double dval;
};
struct Derived : public Base1 {
void print(string s) const {
cout << "Derived::print(string)" << endl;
}
protected:
string sval;
double dval;
};
struct MI : public Derived, public Base2 {
void print(vector<double> dvec) {
cout << "MI::print(vector<double>)" << endl;
}
//for test 18.26
void print(int i) const {
cout << "MI::print(int)" << endl;
Base1::print(i);
}
void foo(double);
protected:
int *ival;
vector<double> dvec;
};
int ival;
double dval;
//for test 18.27
void MI::foo(double cval) {
int dval;
dval = Base1::dval + Derived::dval;
Base2::fval = dvec[dvec.size() - 1];
sval[0] = Base1::cval;
}
int main() {
MI mi;
mi.print(42);
return 0;
}
| |
Add "write class type objects" sample | // Write class type objects to a stream
#include <iostream>
class foo
{
public:
foo(int x)
: x(x)
{ }
friend std::ostream& operator<<(std::ostream& stream,
foo const& f);
private:
int x;
};
std::ostream& operator<<(std::ostream& stream,
foo const& f)
{
return stream << "A foo with x = " << f.x;
}
int main()
{
foo f(10);
std::cout << f << std::endl;
}
// Write your class type objects to an output stream by implementing
// `operator<<`.
//
// We implement `operator<<` on [19-23], which takes a reference to an
// [`std::ostream`](cpp/io/basic_ostream) (the base class for all
// output streams) and the `foo` object we wish to write to the stream.
// On [22], we simply write a string representing the `foo` object to
// the steam and return a reference to the stream itself, allowing
// this call to be chained.
//
// Note that we declare this `operator<<` as a `friend` of `foo` on
// [12-13]. This gives it access to `foo`'s private member, `x`.
//
// On [27-28], we stream a `foo` object to [`std::cout`](cpp/io/cout).
| |
Remove comment. Just a trigger for a new build. | #include <iostream>
// yaml-cpp includes
#include "yaml-cpp/yaml.h"
int main()
{
YAML::Emitter out;
out << "Hello, World!";
std::cout << "Here's the output YAML:\n" << out.c_str();
return 0;
}
| #include <iostream>
#include <yaml-cpp/yaml.h>
int main()
{
YAML::Emitter out;
out << "Hello, World!";
std::cout << "Here's the output YAML:\n" << out.c_str();
return 0;
}
|
Add toy example showing use of the interface | #include <cmath>
#include <memory>
#include <vector>
#include <parfil/robot.h>
#include <parfil/filter.h>
void TestCase1(std::vector<parfil::Motion>& motions, std::vector<parfil::Measurement>& measurements) {
// fill in motions
int num_motions = 8;
motions.resize(num_motions);
for (int i=0; i<num_motions; ++i) {
motions[i].steering_angle = 2.0*M_PI/10.0;
motions[i].forward_distance = 20.0;
}
// fill in measurements
double[] measurements_arr = {
4.746936, 3.859782, 3.045217, 2.045506,
3.510067, 2.916300, 2.146394, 1.598332,
2.972469, 2.407489, 1.588474, 1.611094,
1.906178, 1.193329, 0.619356, 0.807930,
1.352825, 0.662233, 0.144927, 0.799090,
0.856150, 0.214590, 5.651497, 1.062401,
0.194460, 5.660382, 4.761072, 2.471682,
5.717342, 4.736780, 3.909599, 2.342536
};
int num_measurements = 8;
int measurement_dimension = 4;
measurements.resize(8);
for (int i=0; i<num_measurements; ++i) {
measurements[i].resize(measurement_dimension);
double* from = measurements_arr + measurement_dimension*i;
double* to = from + measurement_dimension;
measurements[i].assign(from,to);
}
}
int main(int, char**) {
int num_particles = 500;
std::unique_ptr<parfil::Filter> filter(new parfil::Filter(num_particles));
std::vector<parfil::Motion> motions;
std::vector<parfil::Measurement> measurements;
TestCase1(motions,measurements);
filter->run(motions,measurements);
double x,y,heading;
filter->GetPose(x,y,heading);
std::cout << "x: " << x << " y: " << y << " heading: " << heading << std::endl;
return 0;
}
| |
Add missing file from the previous commit. | #include "cvd/internal/load_and_save.h"
#include "cvd/internal/io/bmp.h"
#include <vector>
using namespace std;
using namespace CVD;
namespace CVD{
namespace BMP{
void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, std::ostream& out);
class WritePimpl
{
public:
WritePimpl(ostream& o_, ImageRef sz, const string& t)
:o(o_),size(sz)
{
int ch;
if(t == "unsigned char")
ch=1;
else if(t == "CVD::Rgb<unsigned char>")
{
ch=3;
int l=size.x*3;
if(l%4 != 0)
l = (l/4+1)*4;
buf.resize(l);
}
else
throw Exceptions::Image_IO::UnsupportedImageSubType("BMP", t);
writeBMPHeader(size.x, size.y, ch, o);
pad = ((ch*size.x) % 4) ? (4 - ((ch*size.x) % 4)) : 0;
}
void write_raw_pixel_line(const byte* r)
{
char zeros[]={0,0,0,0};
o.write((const char*)r, size.x);
o.write(zeros,pad);
}
void write_raw_pixel_line(const Rgb<byte>* r)
{
//Transform to BGR
for(int i=0; i < size.x; i++)
{
buf[i*3+0] = r[i].blue;
buf[i*3+1] = r[i].green;
buf[i*3+2] = r[i].red;
}
o.write(&buf[0], buf.size());
}
private:
ostream& o;
ImageRef size;
int pad;
vector<char> buf;
};
Writer::Writer(std::ostream&o, ImageRef size, const std::string& type, const std::map<std::string, Parameter<> >&)
:t(new WritePimpl(o, size, type))
{}
Writer::~Writer()
{}
void Writer::write_raw_pixel_line(const byte* l)
{
t->write_raw_pixel_line(l);
}
void Writer::write_raw_pixel_line(const Rgb<byte>* l)
{
t->write_raw_pixel_line(l);
}
}
}
| |
Add test for using declaration in classes. | // RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility -fmodules-cache-path=%t %s -verify
// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify
// expected-no-diagnostics
#pragma clang module build A
module A { }
#pragma clang module contents
#pragma clang module begin A
struct A {
virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild
#pragma clang module build B
module B { }
#pragma clang module contents
#pragma clang module begin B
#pragma clang module import A
struct B : A {
using A::Foo;
virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import B
int main() {
B b;
b.Foo(1.0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.