Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add C++ Bindings to Lua | extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include "RtMidi.h"
static RtMidiOut midi;
int midi_send(lua_State* L)
{
double status = lua_tonumber(L, -3);
double data1 = lua_tonumber(L, -2);
double data2 = lua_tonumber(L, -1);
std::vector<unsigned char> message(3);
message[0] = static_cast<unsigned char> (status);
message[1] = static_cast<unsigned char> (data1);
message[2] = static_cast<unsigned char> (data2);
midi.sendMessage(&message);
return 0;
}
int main(int argc, char const* argv[])
{
if (argc < 1) { return -1; }
unsigned int ports = midi.getPortCount();
if (ports < 1) { return -1; }
midi.openPort(0);
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, midi_send);
lua_setglobal(L, "midi_send");
luaL_dofile(L, argv[1]);
lua_close(L);
return 0;
}
| |
Test to ensure stack allocations can be reused. | #include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f, g, h;
Var x;
// Create a simple function computed at root.
f(x) = x;
f.compute_root();
// Create a function that uses an undefined buffer after f is
// freed.
g(x) = undef<int>() + f(x);
g(x) += 1;
g.compute_root();
// This just forces g to be stored somewhere (the re-used buffer).
h(x) = g(x);
h.compute_root();
// Bound it so the allocations go on the stack.
h.bound(x, 0, 16);
Image<int> result = h.realize(16);
for (int i = 0; i < result.width(); i++) {
if (result(i) != i + 1) {
printf("Error! Allocation did not get reused at %d (%d != %d)\n", i, result(i), i + 1);
return -1;
}
}
printf("Success!\n");
return 0;
}
| |
Convert Binary Number in a Linked List to Integer | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int getDecimalValue(ListNode* head) {
std::vector<int> v;
while (head) {
v.emplace_back(head->val);
head = head->next;
}
int ret = 0, index = 1;
for (int i = 0; i < v.size(); ++i) {
ret += v[v.size()-i-1] * index;
index *= 2;
}
return ret;
}
};
| |
Add 004 Median of Two Sorted Array | // 4 Median of Two Sorted Array
/**
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
*
* Tag: Divide and Conquer, Array, Binary Search
*
* Author: Yanbin Lu
*/
#include <stddef.h>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
// always consider nums1 is shorter than nums2
if(len1 > len2) return findMedianSortedArrays(nums2, nums1);
int mid = (len1 + len2 -1) / 2;
int leftin1 = 0, rightin1 = len1; // the rightin1 is a boundary, not an actual index
while(leftin1 < rightin1){
int mid1 = (leftin1 + rightin1) / 2; // mid point in array 1
int mid2 = mid - mid1; // mid point in array 2
if(nums1[mid1] < nums2[mid2])
leftin1 = mid1 + 1;
else
rightin1 = mid1;
}
//len1 + len2 is odd
// median is either nums1[leftin1 - 1] or nums2[mid - leftin1]
int temp1 = max(leftin1 > 0 ? nums1[leftin1 - 1] : INT_MIN, mid - leftin1 >= 0 ? nums2[mid - leftin1] :INT_MIN);
if ((len1 + len2) % 2 == 1)
return (double) temp1;
//len1 + len2 is even
// median is either nums1[leftin1] or nums2[mid - leftin1 + 1]
int temp2 = min(leftin1 < len1 ? nums1[leftin1] : INT_MAX, mid - leftin1 + 1 < len2 ? nums2[mid - leftin1 + 1] : INT_MAX);
return (temp1 + temp2) / 2.0;
}
};
int main()
{
vector<int> nums1;
nums1.push_back(1);
nums1.push_back(2);
nums1.push_back(4);
nums1.push_back(5);
vector<int> nums2;
nums2.push_back(3);
nums2.push_back(3);
nums2.push_back(4);
nums2.push_back(5);
nums2.push_back(6);
Solution* sol = new Solution();
cout << sol->findMedianSortedArrays(nums1, nums2) << endl;
char c;
std::cin>>c;
return 0;
}
| |
Implement solution Longest increasing subsequence. | #include <bits/stdc++.h>
using namespace std;
//Compute the largest increasing subsequence
int lis( int arr[], int n ){
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
for (i = 0; i < n; i++ )
lis[i] = 1;
for (i = 1; i < n; i++ )
for (j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
for (i = 0; i < n; i++ )
if (max < lis[i])
max = lis[i];
free(lis);
return max;
}
int main(){
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of lis is %d\n", lis( arr, n ) );
//sol = 10, 22, 33, 50, 60
return 0;
}
| |
Add negotiator plugin prototype for ODS contrib | /*
* Copyright 2009-2011 Red Hat, 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 "condor_common.h"
// mongodb-devel includes
#include <mongo/client/dbclient.h>
// seems boost meddles with assert defs
#include "assert.h"
#include "condor_config.h"
#include "../condor_negotiator.V6/NegotiatorPlugin.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "get_daemon_name.h"
using namespace mongo;
DBClientConnection c;
std::string db_name("condor.negotiator");
void writeJobAd(ClassAd* ad) {
clock_t start, end;
double elapsed;
ExprTree *expr;
const char *name;
ad->ResetExpr();
BSONObjBuilder b;
start = clock();
while (ad->NextExpr(name,expr)) {
b.append(name,ExprTreeToString(expr));
}
try {
c.insert(db_name, b.obj());
}
catch(DBException& e) {
cout << "caught DBException " << e.toString() << endl;
}
end = clock();
elapsed = ((float) (end - start)) / CLOCKS_PER_SEC;
std:string last_err = c.getLastError();
if (!last_err.empty()) {
printf("getLastError: %s\n",last_err.c_str());
}
printf("Time elapsed: %1.9f sec\n",elapsed);
}
struct ODSNegotiatorPlugin : public Service, NegotiatorPlugin
{
void
initialize()
{
char *tmp;
std::string mmName;
dprintf(D_FULLDEBUG, "ODSNegotiatorPlugin: Initializing...\n");
// pretty much what the daemon does
tmp = default_daemon_name();
if (NULL == tmp) {
mmName = "UNKNOWN NEGOTIATOR HOST";
} else {
mmName = tmp;
free(tmp); tmp = NULL;
}
c.connect("localhost");
}
void
shutdown()
{
dprintf(D_FULLDEBUG, "ODSNegotiatorPlugin: shutting down...\n");
}
void
update(const ClassAd &ad)
{
writeJobAd(const_cast<ClassAd*>(&ad));
}
};
static ODSNegotiatorPlugin instance;
| |
Add a testcase for start+end implementations of std::initializer_list. | // RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s
namespace std {
typedef decltype(sizeof(int)) size_t;
// libc++'s implementation with __size_ replaced by __end_
template <class _E>
class initializer_list
{
const _E* __begin_;
const _E* __end_;
initializer_list(const _E* __b, const _E* __e)
: __begin_(__b),
__end_(__e)
{}
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
initializer_list() : __begin_(nullptr), __end_(nullptr) {}
size_t size() const {return __end_ - __begin_;}
const _E* begin() const {return __begin_;}
const _E* end() const {return __end_;}
};
}
void fn1(int i) {
// CHECK: define void @_Z3fn1i
// temporary array
// CHECK: [[array:%[^ ]+]] = alloca [3 x i32]
// CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0
// CHECK-NEXT: store i32 1, i32*
// CHECK-NEXT: getelementptr
// CHECK-NEXT: store
// CHECK-NEXT: getelementptr
// CHECK-NEXT: load
// CHECK-NEXT: store
// init the list
// CHECK-NEXT: getelementptr
// CHECK-NEXT: getelementptr inbounds [3 x i32]*
// CHECK-NEXT: store i32*
// CHECK-NEXT: getelementptr
// CHECK-NEXT: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0, i{{32|64}} 3
// CHECK-NEXT: store i32*
std::initializer_list<int> intlist{1, 2, i};
}
struct destroyme1 {
~destroyme1();
};
struct destroyme2 {
~destroyme2();
};
void fn2() {
// CHECK: define void @_Z3fn2v
void target(std::initializer_list<destroyme1>);
// objects should be destroyed before dm2, after call returns
target({ destroyme1(), destroyme1() });
// CHECK: call void @_ZN10destroyme1D1Ev
destroyme2 dm2;
// CHECK: call void @_ZN10destroyme2D1Ev
}
void fn3() {
// CHECK: define void @_Z3fn3v
// objects should be destroyed after dm2
auto list = { destroyme1(), destroyme1() };
destroyme2 dm2;
// CHECK: call void @_ZN10destroyme2D1Ev
// CHECK: call void @_ZN10destroyme1D1Ev
}
| |
Add Chapter 25, exercise 8 | // Chapter 25, exercise 8: write out the numerical values of each character on
// your keyboard
#include<iostream>
using namespace std;
void print(char ch)
{
cout << ch << ": " << int(ch) << '\t';
}
int main()
{
print('');
print('+');
print('"');
print('*');
print('');
print('%');
print('&');
print('/');
print('(');
print(')');
print('=');
print('?');
print('`');
print('');
print('1');
print('2');
cout << '\n';
print('3');
print('4');
print('5');
print('6');
print('7');
print('8');
print('9');
print('0');
print('\'');
print('^');
print('');
print('@');
print('#');
print('');
print('|');
print('');
cout << '\n';
print('');
print('~');
print('Q');
print('W');
print('E');
print('R');
print('T');
print('Z');
print('U');
print('I');
print('O');
print('P');
print('');
print('!');
print('q');
print('w');
cout << '\n';
print('e');
print('r');
print('t');
print('z');
print('u');
print('i');
print('o');
print('p');
print('');
print('');
print('');
print('[');
print(']');
print('A');
print('B');
print('C');
cout << '\n';
print('D');
print('E');
print('F');
print('G');
print('H');
print('J');
print('K');
print('L');
print('');
print('');
print('');
print('a');
print('s');
print('d');
print('f');
print('g');
cout << '\n';
print('h');
print('j');
print('k');
print('l');
print('');
print('');
print('$');
print('{');
print('}');
print('>');
print('Y');
print('X');
print('C');
print('V');
print('B');
print('N');
cout << '\n';
print('M');
print(';');
print(':');
print('_');
print('<');
print('y');
print('x');
print('c');
print('v');
print('b');
print('n');
print('m');
print(',');
print('.');
print('-');
print('\\');
cout << '\n';
}
| |
Add test missed from r278983. | // RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s
template<int N, typename T> struct X : X<N+1, T*> {};
// expected-error-re@3 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}}
// expected-note@3 {{instantiation of template class}}
// expected-note@3 {{skipping 1023 contexts in backtrace}}
// expected-note@3 {{use -ftemplate-depth=N to increase recursive template instantiation depth}}
X<0, int> x; // expected-note {{in instantiation of}}
| |
Add code to insert node in linked list | #include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=NULL;
}
Node *insertElement(Node *head,int d){
Node *np=new Node(d);
Node *tmp=head;
if(head==NULL)
return np;
else
while(tmp->next)
tmp=tmp->next;
tmp->next=np;
return head;
}
Node *insertElementPos(Node *head, int d, int pos){
Node *np=new Node(d);
Node *tmp=head;
int cnt=1;
if(pos==1){
np->next=tmp;
return np;
}
while(cnt!=pos-1){
tmp=tmp->next;
cnt++;
}
np->next=tmp->next;
tmp->next=np;
return head;
}
void displayList(Node *head){
Node *tmp=head;
if(head==NULL)
cout<<"No elements in the list! :(\n";
else{
cout<<"Elements are: \n";
while(tmp){
cout<<tmp->data<<"\n";
tmp=tmp->next;
}
}
}
};
int main()
{
int n,p,pos,d;
Node np;
Node *head=NULL;
cout<<"Enter the size of linked list: ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"\nEnter element "<<i+1<<": ";
cin>>p;
head=np.insertElement(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.insertElementPos(head,d,pos);
}
np.displayList(head);}
| |
Add a test for r261425. | // RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -fexceptions -fcxx-exceptions -fexternc-nounwind | FileCheck %s
namespace test1 {
struct Cleanup { ~Cleanup(); };
extern "C" void never_throws();
void may_throw();
void caller() {
Cleanup x;
never_throws();
may_throw();
}
}
// CHECK-LABEL: define void @"\01?caller@test1@@YAXXZ"(
// CHECK: call void @never_throws(
// CHECK: invoke void @"\01?may_throw@test1@@YAXXZ"(
| |
Set Zeroes in a Matrix | #include <iostream>
#include <set>
#include <vector>
using namespace std;
void setZeroes(vector<vector<int> > &matrix) {
set<int> rows;
set<int> columns;
int noRows = matrix.size();
int noColumns = matrix.at(0).size();
for (int i = 0; i < noRows; ++i) {
for (int j = 0; j < noColumns; ++j) {
if (matrix[i][j] == 0) {
if (!rows.count(i)) {
rows.insert(i);
}
if (!columns.count(j)) {
columns.insert(j);
}
}
}
}
for (set<int>::iterator i = rows.begin(); i != rows.end(); ++i) {
for (int k = 0; k < noColumns; ++k) {
matrix[*i][k] = 0;
}
}
for (set<int>::iterator i = columns.begin(); i != columns.end(); ++i) {
for (int k = 0; k < noRows; ++k) {
matrix[k][*i] = 0;
}
}
}
| |
Add program to test quicksort | /*
This program tests Quick sort
*/
#include<iostream>
#include<vector>
#include "quicksort.h" // My implementation of Quick sort
// Displays vector
void printVector(std::vector<int> A){
for(auto x: A){
std::cout<<x<<" ";
}
std::cout<<std::endl;
}
// Tests Quick sort on vector A
void testQuickSort(std::vector<int> A){
std::cout<<"Before: ";
printVector(A);
Quicksort::quicksort(A);
std::cout<<"After: ";
printVector(A);
}
// tests Quick sort on several different inputs
void testQuickSort(){
std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1};
testQuickSort(v1);
std::vector<int> v2 = {5,4,3,2,1};
testQuickSort(v2);
std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10};
testQuickSort(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};
testQuickSort(v4);
// test on empty vector
std::vector<int> v5;
testQuickSort(v5);
std::vector<int> v6 = {2,4,-6,1,-9,3,0};
testQuickSort(v6);
std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0};
testQuickSort(v7);
}
int main(){
// test Quick sort
testQuickSort();
return 0;
}
| |
Add unit test to ensure that inserting the same name twice raises an error | // This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2020 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>.
#include <gtest/gtest.h>
#include "mha_parser.hh"
#include "mha_error.hh"
TEST(mha_parser, insert_2_subparsers_with_same_name_fails)
{
// create a parser
MHAParser::parser_t parser;
// create two parser variables
MHAParser::int_t i1("i1 help","0","[,]");
MHAParser::int_t i2("i2 help","0","[,]");
// try to register both parser variables under the same name
parser.insert_item("i", &i1);
EXPECT_THROW(parser.insert_item("i", &i2), MHA_Error);
// try again to check the error message content
try {
parser.insert_item("i", &i2);
FAIL() << "parser.insert_item should have thrown an exception";
} catch(MHA_Error & e) {
ASSERT_STREQ("(mha_parser) The entry \"i\" already exists.", e.get_msg());
}
}
// Local Variables:
// compile-command: "make -C .. unit-tests"
// coding: utf-8-unix
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
| |
Add and test cookie tracking to microhttpd. | #include <thread>
#include <iostream>
#include <silicon/mhd_serve.hh>
#include <silicon/api.hh>
#include <silicon/client.hh>
using namespace sl;
int main()
{
auto api = make_api(
@my_tracking_id = [] (tracking_cookie c) {
return D(@id = c.id());
}
);
// Start server.
std::thread t([&] () { mhd_json_serve(api, 12345); });
usleep(.1e6);
// Test.
auto c = json_client(api, "127.0.0.1", 12345);
auto r1 = c.my_tracking_id();
auto r2 = c.my_tracking_id();
std::cout << r1.response.id << std::endl;
std::cout << r2.response.id << std::endl;
assert(r1.response.id == r2.response.id);
exit(0);
}
| |
Add a solution for problem 23: Merge k Sorted Lists. | // Naive solution would iterate all lists to take the smallest head every time to
// add to the merged list. Actually we have a efficient data structure to retrieve
// the smallest element from a bunch of elements. That is a "min heap".
// In the implementation below, I created a wrapper for list so that we could use
// heap provided by STL more smoothly.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct Proxy {
ListNode* list;
Proxy(){}
Proxy(ListNode* head): list(head){}
bool next() {
list = list->next;
return list != nullptr;
}
bool operator < (const Proxy& rhs) const {
return list->val > rhs.list->val;
}
};
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<Proxy> heads;
for (auto l: lists) {
if (l != nullptr) {
heads.push_back(Proxy(l));
}
}
make_heap(heads.begin(), heads.end());
ListNode dummy(0);
ListNode* merged_list = &dummy;
while (!heads.empty()) {
pop_heap(heads.begin(), heads.end());
Proxy& smallest = heads.back();
merged_list->next = smallest.list;
merged_list = merged_list->next;
if (smallest.next()) {
push_heap(heads.begin(), heads.end());
} else {
heads.pop_back();
}
}
return dummy.next;
}
}; | |
Raise the message size limit. | // 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 "content/app/mojo/mojo_init.h"
#include "base/memory/scoped_ptr.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
namespace content {
void InitializeMojo() {
mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
new mojo::embedder::SimplePlatformSupport()));
}
} // namespace content
| // 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 "content/app/mojo/mojo_init.h"
#include "base/memory/scoped_ptr.h"
#include "mojo/edk/embedder/configuration.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"
namespace content {
void InitializeMojo() {
// Things like content_shell and DevTools ocassionally send big
// message which includes whole rendered screen or all loaded
// scripts. The buffer size has to be big enough to allow such use
// cases.
mojo::embedder::GetConfiguration()->max_message_num_bytes = 64*1024*1024;
mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
new mojo::embedder::SimplePlatformSupport()));
}
} // namespace content
|
Add fixed solution to fast tast "Kozichki" | #include<iostream>
int main()
{
unsigned N,K;
unsigned Ai[1000],VarAi[1000];
unsigned max=0,capacity,varIndx,v_capacity;
unsigned big,hasMoreValues,flag=1;
do
{
std::cin>>N;
}while(N<1 || N>1000);
do
{
std::cin>>K;
}while(K<1 || K>1000);
for(int i=0;i<N;i++)
{
do
{
std::cin>>Ai[i];
}while(Ai[i]<1 || Ai[i]>100000);
if(Ai[i]>max)
{
max=Ai[i];
}
}
capacity=max;
while(1)
{
flag=1;
for(int h=0;h<N;h++)
{
VarAi[h]=Ai[h];
}
for(int i=0;i<K;i++)
{
v_capacity=capacity;
while(1)
{
big=0;
hasMoreValues=0;
for(int j=0;j<N;j++)
{
if(VarAi[j]>big && VarAi[j]<=v_capacity)
{
hasMoreValues=1;
big=VarAi[j];
varIndx=j;;
}
}
if(hasMoreValues)
{
VarAi[varIndx]=0;
v_capacity-=big;
continue;
}
else
{
break;
}
}
}
for(int k=0;k<N;k++)
{
if(VarAi[k]!=0)
flag=0;
}
if(flag)
{
std::cout<<capacity;
break;
}
else
capacity++;
}
return 0;
}
| |
Add qsort with lambda function in c++11 standard. | #include <iostream>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
int main() {
vector<int> vec(10000);
generate(vec.begin(), vec.end(), rand);
sort(vec.begin(), vec.end(), [](int a, int b) -> bool { return a > b; });
for (auto &a : vec) {
cout << a << " ";
}
cout << endl;
return 0;
} | |
Add functions up to elaboration (Ed Carter) | #include "PTask.h"
PFunction::PFunction(svector<PWire*>*p, Statement*s)
: ports_(p), statement_(s)
{
}
PFunction::~PFunction()
{
}
| |
Enable to pass mjpeg stream from node to c++ | #include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \
|| defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
# include <io.h>
# include <fcntl.h>
# define SET_BINARY_MODE(handle) setmode(handle, O_BINARY)
#else
# define SET_BINARY_MODE(handle) ((void)0)
#endif
#define BUFSIZE 10240
int main ( int argc, char **argv )
{
SET_BINARY_MODE(fileno(stdin));
std::vector<char> data;
bool skip=true;
bool imgready=false;
bool ff=false;
int readbytes=-1;
while (1)
{
char ca[BUFSIZE];
uchar c;
if (readbytes!=0)
{
readbytes=read(fileno(stdin),ca,BUFSIZE);
for(int i=0;i<readbytes;i++)
{
c=ca[i];
if(ff && c==(uchar)0xd8)
{
skip=false;
data.push_back((uchar)0xff);
}
if(ff && c==0xd9)
{
imgready=true;
data.push_back((uchar)0xd9);
skip=true;
}
ff=c==0xff;
if(!skip)
{
data.push_back(c);
}
if(imgready)
{
if(data.size()!=0)
{
cv::Mat data_mat(data);
cv::Mat frame(imdecode(data_mat,1));
imshow("frame",frame);
waitKey(1);
}else
{
printf("warning");
}
imgready=false;
skip=true;
data.clear();
}
}
}
else
{
throw std::string("zero byte read");
}
}
}
| |
Add a solution for task 4a | #include <cstdio>
#include <cctype>
using namespace std;
int a[10];
void print_number(int a[])
{
for (int i = 9; i >= 0; i--)
{
while (a[i] > 0)
{
printf("%d", i);
a[i]--;
}
}
printf("\n");
}
int main()
{
char x;
while (scanf("%c", &x) != EOF)
{
if (x == ' ')
{
print_number(a);
}
else if (isdigit(x))
{
a[x - '0']++;
}
}
print_number(a);
return 0;
}
| |
Add Solution for Problem 005 | // 005. Longest Palindromic Substring
/**
* Given a string S, find the longest palindromic substring in S.
* You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
*
* Tags: String
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
if (n < 2)
{
return s;
}
int start = 0, maxLen = 0, left = 0, right = 0, index = 0;
// stop if max length is larger than twice the length from index to end
while ((index < n) && (maxLen < 2 * (n - index)))
{
left = right = index;
while ((right < n - 1) && (s[right + 1] == s[right]))
{
right++; // skip all duplicates
}
index = right + 1; // set next index
while ((left > 0) && (right < n - 1) && (s[left - 1] == s[right + 1]))
{
left--;
right++;
}
// current maxlength at index
int curLen = right - left + 1;
if (curLen > maxLen)
{
maxLen = curLen;
start = left;
}
}
return s.substr(start, maxLen);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
string s("abcbababc");
Solution mySolution;
string res = mySolution.longestPalindrome(s);
cout << res << endl;
system("pause");
return 0;
}
| |
Allow specific files and multiple inputs for picture testing tools. | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "picture_utils.h"
#include "SkString.h"
static void test_filepath_creation(skiatest::Reporter* reporter) {
SkString result;
SkString filename("test");
const char* dir = "test/path";
sk_tools::make_filepath(&result, dir, filename);
REPORTER_ASSERT(reporter, result.equals("test/path/test"));
}
static void test_get_basename(skiatest::Reporter* reporter) {
SkString result;
SkString path("/path/basename");
sk_tools::get_basename(&result, path);
REPORTER_ASSERT(reporter, result.equals("basename"));
result.reset();
path.set("/path/dir/");
sk_tools::get_basename(&result, path);
REPORTER_ASSERT(reporter, result.equals("dir"));
result.reset();
path.set("path");
sk_tools::get_basename(&result, path);
REPORTER_ASSERT(reporter, result.equals("path"));
#if defined(SK_BUILD_FOR_WIN)
result.reset();
path.set("path\\winbasename");
sk_tools::get_basename(&result, path);
REPORTER_ASSERT(reporter, result.equals("winbasename"));
result.reset();
path.set("path\\windir\\");
sk_tools::get_basename(&result, path);
REPORTER_ASSERT(reporter, result.equals("windir"));
#endif
}
static void TestPictureUtils(skiatest::Reporter* reporter) {
test_filepath_creation(reporter);
test_get_basename(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("PictureUtils", PictureUtilsTestClass, TestPictureUtils)
| |
Add Solution for 459 Repeated Substring Pattern | // 459. Repeated Substring Pattern
/**
* Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
* You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
*
* Example 1:
*
* Input: "abab"
* Output: True
* Explanation: It's the substring "ab" twice.
*
* Example 2:
*
* Input: "aba"
* Output: False
*
* Example 3:
*
* Input: "abcabcabcabc"
* Output: True
* Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
*
*
* Tags: String
*
* Similar Problems: (E) Implement strStr()
*
* Author: Kuang Qin
*/
#include <iostream>
#include <string>
using namespace std;
// build new string to check repeated pattern
class Solution2 {
public:
bool repeatedSubstringPattern(string str) {
int n = str.size();
// start from n/2 to check its possible substring
for (int i = n / 2; i > 0; i--) {
if (n % i == 0) {
int m = n / i; // repeated m times
string s = str.substr(0, i);
string p = "";
while (m--) {
p += s; // create a new patterned string to compare
}
if (p == str) { // if equal return true
return true;
}
}
}
return false;
}
};
// check prefix and suffix inspired by KMP
class Solution {
public:
bool repeatedSubstringPattern(string str) {
int n = str.size();
// start from n/2 to check its possible substring
for (int i = n / 2; i > 0; i--) {
if (n % i == 0) {
string pre = str.substr(0, n - i); // prefix
string suf = str.substr(i); // suffix
if (pre == suf) { // if equal return true
return true;
}
}
}
return false;
}
};
int main() {
string str = "aaaaa";
Solution sol;
bool ans = sol.repeatedSubstringPattern(str);
cout << ans << endl;
cin.get();
return 0;
} | |
Add test file missed from r341097. | // RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wc++14-compat-pedantic -verify %s
// RUN: %clang_cc1 -fsyntax-only -std=c++17 -Wc++14-compat-pedantic -verify %s
#if __cplusplus < 201402L
// expected-no-diagnostics
// FIXME: C++11 features removed or changed in C++14?
#else
static_assert(true); // expected-warning {{incompatible with C++ standards before C++17}}
template<int ...N> int f() { return (N + ...); } // expected-warning {{incompatible with C++ standards before C++17}}
namespace [[]] NS_with_attr {} // expected-warning {{incompatible with C++ standards before C++17}}
enum { e [[]] }; // expected-warning {{incompatible with C++ standards before C++17}}
template<typename T = int> struct X {};
X x; // expected-warning {{class template argument deduction is incompatible with C++ standards before C++17}}
template<template<typename> class> struct Y {};
Y<X> yx; // ok, not class template argument deduction
template<typename T> void f(T t) {
X x = t; // expected-warning {{incompatible}}
}
template<typename T> void g(T t) {
typename T::X x = t; // expected-warning {{incompatible}}
}
struct A { template<typename T> struct X { X(T); }; };
void h(A a) { g(a); } // expected-note {{in instantiation of}}
#endif
| |
Set window name to activities | // 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 "athena/content/content_activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/content/app_activity.h"
#include "athena/content/web_activity.h"
#include "base/logging.h"
namespace athena {
ContentActivityFactory::ContentActivityFactory() {
}
ContentActivityFactory::~ContentActivityFactory() {}
Activity* ContentActivityFactory::CreateWebActivity(
content::BrowserContext* browser_context,
const base::string16& title,
const GURL& url) {
Activity* activity = new WebActivity(browser_context, title, url);
ActivityManager::Get()->AddActivity(activity);
return activity;
}
Activity* ContentActivityFactory::CreateWebActivity(
content::WebContents* contents) {
Activity* activity = new WebActivity(contents);
ActivityManager::Get()->AddActivity(activity);
return activity;
}
Activity* ContentActivityFactory::CreateAppActivity(
const std::string& app_id,
views::WebView* web_view) {
Activity* activity = new AppActivity(app_id, web_view);
ActivityManager::Get()->AddActivity(activity);
return activity;
}
ActivityFactory* CreateContentActivityFactory() {
return new ContentActivityFactory();
}
} // namespace athena
| // 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 "athena/content/content_activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/content/app_activity.h"
#include "athena/content/web_activity.h"
#include "base/logging.h"
#include "ui/aura/window.h"
namespace athena {
ContentActivityFactory::ContentActivityFactory() {
}
ContentActivityFactory::~ContentActivityFactory() {}
Activity* ContentActivityFactory::CreateWebActivity(
content::BrowserContext* browser_context,
const base::string16& title,
const GURL& url) {
Activity* activity = new WebActivity(browser_context, title, url);
ActivityManager::Get()->AddActivity(activity);
activity->GetWindow()->SetName("WebActivity");
return activity;
}
Activity* ContentActivityFactory::CreateWebActivity(
content::WebContents* contents) {
Activity* activity = new WebActivity(contents);
ActivityManager::Get()->AddActivity(activity);
return activity;
}
Activity* ContentActivityFactory::CreateAppActivity(
const std::string& app_id,
views::WebView* web_view) {
Activity* activity = new AppActivity(app_id, web_view);
ActivityManager::Get()->AddActivity(activity);
activity->GetWindow()->SetName("AppActivity");
return activity;
}
ActivityFactory* CreateContentActivityFactory() {
return new ContentActivityFactory();
}
} // namespace athena
|
Add solution for chapter 17 test 28 | #include <iostream>
#include <random>
using namespace std;
int generate_random_number(const int a = 0, const int b = 9) {
static default_random_engine e;
static uniform_int_distribution<unsigned> u(a, b);
return u(e);
}
int main() {
for(int i = 0; i != 20; ++ i) {
cout << generate_random_number() << endl;
}
return 0;
}
| |
Test object identity with shared_ptr_converter. | // Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/detail/shared_ptr_converter.hpp>
struct X
{
X(int value)
: value(value)
{}
int value;
};
int get_value(boost::shared_ptr<X> const& p)
{
return p->value;
}
void test_main(lua_State* L)
{
using namespace luabind;
module(L) [
class_<X>("X")
.def(constructor<int>()),
def("get_value", &get_value)
];
DOSTRING(L,
"x = X(1)\n"
"assert(get_value(x) == 1)\n"
);
}
| // Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/shared_ptr_converter.hpp>
struct X
{
X(int value)
: value(value)
{}
int value;
};
int get_value(boost::shared_ptr<X> const& p)
{
return p->value;
}
boost::shared_ptr<X> filter(boost::shared_ptr<X> const& p)
{
return p;
}
void test_main(lua_State* L)
{
using namespace luabind;
module(L) [
class_<X>("X")
.def(constructor<int>()),
def("get_value", &get_value),
def("filter", &filter)
];
DOSTRING(L,
"x = X(1)\n"
"assert(get_value(x) == 1)\n"
);
DOSTRING(L,
"assert(x == filter(x))\n"
);
}
|
Call substr only once to check isRotation of strings | /*
Assume you have a method isSubstring which checks
if one word is a substring of another string.
Given two strings s1, and s2. write code to check
if s2 is a rotation of s1 using only one call to
isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
*/
# include <iostream>
using namespace std;
bool isSubstring(string str1, string str2) {
return (str1.find(str2) != string::npos);
}
bool isRotation(string s1, string s2) {
string tmp = s1 + s1;
return isSubstring(tmp, s2);
}
int main() {
string str1 = "erbottlewat";
string str2 = "waterbottle";
cout << "Is Rotation? " << isRotation(str1, str2);
}
| |
Add dllexport default ctor closure PCH regression test for PR31121 | // Make sure we emit the MS ABI default ctor closure with PCH.
//
// Test this without pch.
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -include %s -emit-llvm -o - %s | FileCheck %s
// Test with pch.
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -emit-pch -o %t %s
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -include-pch %t -emit-llvm -o - %s | FileCheck %s
#ifndef HEADER
#define HEADER
struct __declspec(dllexport) Foo {
enum E { E0 } e;
Foo(E e = E0) : e(e) {}
};
// Demangles as:
// void Foo::`default constructor closure'(void)
// CHECK: define weak_odr dllexport void @"\01??_FFoo@@QEAAXXZ"(%struct.Foo*{{.*}})
// CHECK: call %struct.Foo* @"\01??0Foo@@QEAA@W4E@0@@Z"(%struct.Foo* {{.*}}, i32 0)
#else
#endif
| |
Add Chapter 19, exercise 10 | // Chapter 19, exercise 10: implement a simple auto_ptr supporting only a
// constructor, destructor, ->, * and release() - don't try assignment or copy
// constructor
#include "../lib_files/std_lib_facilities.h"
//------------------------------------------------------------------------------
struct Tracer {
Tracer() { cout << "Tracer()\n"; }
~Tracer() { cout << "~Tracer()\n"; }
};
//------------------------------------------------------------------------------
template<class T> class auto_pntr {
T* val;
public:
auto_pntr(T* arg) : val(arg) { }
~auto_pntr() { delete val; }
T operator*() const { return *val; }
T* operator->() const { return val; }
T* release()
{
T* temp = val;
val = 0;
return temp;
}
};
//------------------------------------------------------------------------------
// demonstrates how only destructor of object held by auto_pntr is called
Tracer* f()
{
Tracer* p1 = new Tracer(); // destructor never called
auto_pntr<Tracer> p2(new Tracer()); // destructor called when out of scope
auto_pntr<Tracer> p3(new Tracer()); // released from auto_pntr
return p3.release();
}
//------------------------------------------------------------------------------
int main()
try {
Tracer* p = f();
delete p;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
}
catch (...) {
cerr << "exception\n";
}
| |
Test for non-canonical decl and vtables. | // RUN: clang-cc %s -emit-llvm-only
class Base {
public:
virtual ~Base();
};
Base::~Base()
{
}
class Foo : public Base {
public:
virtual ~Foo();
};
Foo::~Foo()
{
}
| |
Add a solution for problem 219: Contains Duplicate II. | // https://leetcode.com/problems/contains-duplicate-ii/
// Compared to 'contains duplicate i', now we also need to know the index of number for
// query. So we use a number to index map.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, size_t> value_index_map;
for (size_t i = 0; i < nums.size(); ++i) {
auto itr = value_index_map.find(nums[i]);
if (itr != value_index_map.end() && i - itr->second <= k) {
return true;
}
value_index_map[nums[i]] = i;
}
return false;
}
}; | |
Add the solution to "Phone Patterns". | #include <iostream>
#include <string>
#include <list>
#include <map>
using namespace std;
char convert(char x)
{
if (x >= 'A' && x <= 'P') {
return ((x - 'A') / 3 + 2) + '0';
}
if (x >= 'R' && x <= 'Y') {
return ((x - 'A' - 1) / 3 + 2) + '0';
}
else {
return x;
}
}
string mapper(string s)
{
string res = "";
for (string::size_type i = 0; i != s.size(); i++) {
if (s[i] != '-') {
res.push_back(convert(s[i]));
}
}
return res;
}
int main()
{
int T;
cin >> T;
while (T--) {
list<string> str_list;
int k;
cin >> k;
while (k--) {
string s;
cin >> s;
str_list.push_back(mapper(s));
}
map<string, int> str_int_map;
for (list<string>::iterator iter = str_list.begin(); iter != str_list.end(); iter++) {
map<string, int>::iterator map_iter = str_int_map.find(*iter);
if (map_iter == str_int_map.end()) {
str_int_map.insert(pair<string, int>(*iter, 1));
}
else {
map_iter->second++;
}
}
for (map<string, int>::iterator iter = str_int_map.begin(); iter != str_int_map.end(); iter++) {
if (iter->second >= 2) {
string res = iter->first;
cout << res.substr(0, 3) + "-" + res.substr(3,4) + " " << iter->second << endl ;
}
}
}
return 0;
} | |
Add 3101 astronomy cpp version, which doesn't handle the big integer and WA. JAVA was used instead to AC | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned long long p[3];
unsigned long long* gcdEx(unsigned long long a, unsigned long long b, unsigned long long *p) {
if (b == 0) {
p[0] = 1, p[1] = 0, p[2] = a;
return p;
} else {
p = gcdEx(b, b%a, p);
unsigned long long t = p[0];
p[0] = p[1];
p[1] = t - a/b*p[1];
return p;
}
}
void swap(unsigned long long &a, unsigned long long &b) {
if (a != b) {
a ^= b ^= a ^= b;
}
}
unsigned long long gcd(unsigned long long a, unsigned long long b) {
if (a == 0 || b == 0) return 0;
while (a && b) b%=a^=b^=a^=b;
return a+b;
}
void solve() {
unsigned long long n;
scanf("%llu", &n);
// ans = ans1 / ans2;
unsigned long long ans1, ans2;
unsigned long long a, b;
scanf("%llu", &a);
scanf("%llu", &b);
if (a > b) {
swap(a, b);
}
ans1 = a * b;
ans2 = 2 * (b - a);
unsigned long long g = gcd(ans1, ans2);
if (g != 0) {
ans1 /= g;
ans2 /= g;
} else {
ans1 = 0;
ans2 = 1;
}
for (unsigned long long i = 2; i < n; ++ i) {
scanf("%llu", &b);
if (a > b) {
swap(a, b);
}
unsigned long long newans1, newans2;
newans1 = a * b;
newans2 = 2 * (b - a);
unsigned long long g = gcd(newans1, newans2);
if (g != 0) {
newans1 /= g;
newans2 /= g;
} else {
continue;
}
if (ans1 == 0) {
ans1 = newans1;
ans2 = newans2;
continue;
}
g = gcd(ans1 * newans2, newans1 * ans2);
ans1 *= newans1 * ans2 / g;
g = gcd(ans1, ans2);
ans1 /= g;
ans2 /= g;
}
printf("%llu %llu", ans1, ans2);
}
void test() {
gcdEx(8, 5, p);
printf("%llu %llu %llu\n", p[0], p[1], p[2]);
}
int main() {
solve();
return 0;
}
| |
Add Solution for Problem 134 | // 134. Gas Station
/**
* There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
*
* You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
*
* Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
*
* Note:
* The solution is guaranteed to be unique.
*
* Tags: Greedy
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <vector>
using namespace std;
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int start = 0, sum = 0, total = 0;
// start: the starting point
// sum: remaining gas from start up to current station
// total: overall remaining gas
for (int i = 0; i < n; i++)
{
int remain = gas[i] - cost[i]; // remaining gas at station i
sum += remain;
total += remain;
if (sum < 0) // no gas at this point
{
sum = 0; // reset sum
start = i + 1; // start from next station
}
}
if (total < 0) // unable to travel once if the total is negative
{
return -1;
}
// Conclusion:
// If the total remaining gas is positive, the circuit can be travelled around once from the start position
// (at any station, the cumulative remaining gas from the start station is positive)
//
// Proof:
// from the for loop we know that from start to n the sum is positive, so
//
// remain[start] + ... + remain[n - 1] >= 0
//
// also, it is the last time where sum < 0 at station (start - 1), it means that the cumulative total:
//
// remain[0] + ... + remain[start - 1] is the minimum
//
// so if the total remaining gas is positive, given any station j we have the wrap around total:
//
// remain[start] + ... + remain[n - 1] + remain[0] + ... + remain[j]
// >= remain[start] + ... + remain[n - 1] + remain[0] + ... + remain[start - 1]
// = remain[0] + remain[n - 1] = total > 0
return start;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| |
Print the file name and file extension name of all arguments | #include <string>
#include <cstdio>
std::string GetFilenameExt(std::string filename) {
std::string ext_name("");
std::string::size_type index = filename.rfind('.');
if(index != std::string::npos)
ext_name = filename.substr(index+1);
return ext_name;
}
int main (int argc, char *argv[]) {
for(unsigned int index = 1; index < argc; index++) {
printf("DEBUG: File name: %s. ext name: %s\n",argv[index], GetFilenameExt(argv[index]).c_str());
}
} | |
Add solution for chapter 16 test 35 | #include <iostream>
using namespace std;
template <typename T>
T calc(T a, int i) {
return a;
}
template <typename T>
T fcn(T a, T b) {
return a;
}
int main() {
double d;
float f;
char c = 'a';
calc(c, 'c');//good
calc(d, f);//good
cout << fcn(c, 'c');
// fcn(d, f);
}
| |
Add solution for chapter 17 test 20 | #include <iostream>
#include <string>
#include <regex>
using namespace std;
bool valid(const smatch &m) {
if(m[1].matched) {
return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
} else {
return m[3].matched == 0 && m[4].str() == m[6].str();
}
}
int main() {
string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex r(phone);
string s;
while(getline(cin, s)) {
for(sregex_iterator it(s.begin(), s.end(), r), it_end; it != it_end; ++ it) {
if(valid(*it)) {
cout << "valid: " << it -> str() << endl;
} else {
cout << "not valid: " << it -> str() << endl;
}
}
}
return 0;
}
| |
Add initial foundation cpp file. | // Copyright (c) 1997-2018 The CSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
///////////////////////////////////////////////////////////////////////////////
// Foundation.cpp -- interface to Kiva
///////////////////////////////////////////////////////////////////////////////
#include "cnglob.h"
#include "libkiva/Ground.hpp"
| |
Add a solution for task 3a | #include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int taken[22];
int n, k;
bool found = false;
vector<int> numbers;
void rec(int i)
{
if (found) return;
if (i == n)
{
int sum = 0;
for (int j = 0; j < n; j++)
{
// cout << taken[j] << " ";
if (taken[j] == 0)
{
sum += numbers[j];
}
else
{
sum -= numbers[j];
}
}
//cout << " - " << sum << endl;
if (sum == k)
{
for (int j = 0; j < n; j++)
{
if (taken[j] == 1)
{
cout << -numbers[j];
}
else
{
if (j > 0) cout << '+';
cout << numbers[j];
}
}
cout << "=" << k << endl;
found = true;
}
return;
}
rec(i + 1);
taken[i] = 1;
rec(i + 1);
taken[i] = 0;
}
int main()
{
string line;
int enterNumber;
while (getline(cin, line))
{
istringstream iss(line);
while (iss >> enterNumber)
{
numbers.push_back(enterNumber);
}
k = numbers[numbers.size() - 1];
numbers.pop_back();
n = numbers.size();
rec(1);
if (!found) cout << endl;
found = false;
numbers.clear();
for (int i = 0; i < 22; i++) taken[i] = 0;
}
return 0;
}
| |
Add unit tests for user C bindings | #include <boost/test/unit_test.hpp>
#include <ygo/deck/c/User.h>
#include <ygo/deck/c/DB.h>
struct User_Fixture
{
User_Fixture()
{
DB_NAME(set_path)("test/card.db");
}
};
BOOST_FIXTURE_TEST_SUITE(User, User_Fixture)
BOOST_AUTO_TEST_CASE(Create)
{
auto user = USER_NAME(new_create)("Test");
auto name = USER_NAME(name)(user);
BOOST_CHECK_EQUAL(std::string(name), "Test");
USER_NAME(delete_name)(name);
USER_NAME(delete)(user);
}
BOOST_AUTO_TEST_CASE(Open)
{
auto user = USER_NAME(new)("Test");
auto name = USER_NAME(name)(user);
BOOST_CHECK_EQUAL(std::string(name), "Test");
USER_NAME(delete_name)(name);
USER_NAME(delete)(user);
}
BOOST_AUTO_TEST_CASE(Unknown)
{
auto user = USER_NAME(new)("NotKnown");
BOOST_CHECK(user == nullptr);
}
BOOST_AUTO_TEST_CASE(Remove)
{
auto user = USER_NAME(new)("Test");
auto name = USER_NAME(name)(user);
BOOST_CHECK_EQUAL(std::string(name), "Test");
USER_NAME(remove)(user);
USER_NAME(delete_name)(name);
USER_NAME(delete)(user);
auto user2 = USER_NAME(new)("Test");
BOOST_CHECK(user2 == nullptr);
}
BOOST_AUTO_TEST_SUITE_END()
| |
Use container to store acceptable instructions | //#include "InstructionParser.h"
#include <string>
#include <stdexcept>
#include "gtest/gtest.h"
class InstructionParser
{
public:
class UnknownInstruction : public std::runtime_error
{
public:
UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
{}
};
void parseInstructions(const std::string& instruction)
{
if (instruction != "ld a," && instruction != "out (0),a")
{
throw UnknownInstruction{"Unknown instruction" + instruction};
}
}
};
TEST(InstructionParser, ParserShouldDeclineUnknownInstruction)
{
InstructionParser parser;
EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}
TEST(InstructionParser, ParserShouldAcceptInstuctionLd)
{
InstructionParser parser;
EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}
TEST(InstructionParser, ParserShouldAcceptInstructionOut)
{
InstructionParser parser;
EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
} | //#include "InstructionParser.h"
#include <string>
#include <stdexcept>
#include "gtest/gtest.h"
class InstructionParser
{
public:
class UnknownInstruction : public std::runtime_error
{
public:
UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
{}
};
void parseInstructions(const std::string& instruction)
{
const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"};
if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end())
{
throw UnknownInstruction{"Unknown instruction" + instruction};
}
}
};
TEST(InstructionParser, ParserShouldDeclineUnknownInstruction)
{
InstructionParser parser;
EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}
TEST(InstructionParser, ParserShouldAcceptInstuctionLd)
{
InstructionParser parser;
EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}
TEST(InstructionParser, ParserShouldAcceptInstructionOut)
{
InstructionParser parser;
EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
} |
Add test for the graphnode. | #include "graph_node.h"
#include "gtest\gtest.h"
/*
This file will includ all the test for the GraphNode class.
*/
/*
This test will check if neighbors can be added.
*/
TEST(GraphNodeTest, Add) {
//Initialize a node with some children
GraphNode<int> root1;
GraphNode<int> neighbor1;
GraphNode<int> neighbor2;
root1.addNeighbor(&neighbor1);
root1.addNeighbor(&neighbor2);
EXPECT_EQ(root1.getNeighbors().size(), 2);
}
/*
This test will check if neighbors can be removed.
*/
TEST(GraphNodeTest, Remove) {
//Initialize a node with some children
GraphNode<int> root1;
GraphNode<int> neighbor1;
GraphNode<int> neighbor2;
root1.addNeighbor(&neighbor1);
root1.addNeighbor(&neighbor2);
EXPECT_EQ(root1.getNeighbors().size(), 2);
// Remove one neighbor and check it is removed
root1.removeNeighbor(1);
EXPECT_EQ(root1.getNeighbors().size(), 1);
// Remove the last neighbor and check it the neighbors list is empty
root1.removeNeighbor(0);
EXPECT_EQ(root1.getNeighbors().size(), 0);
// Check if removing when there is no neighbors will chrash
EXPECT_NO_THROW(root1.removeNeighbor(0));
}
/*
This test will check if the value for each node can be set and extracted.
*/
TEST(GraphNodeTest, Value) {
//Initialize a node with some children
GraphNode<int> root1;
root1.setValue(1);
EXPECT_EQ(root1.getValue(), 1);
} | |
Check if given binary tree is BST or not. | // Program to check if given tree is a BST or not.
#include <iostream>
#define MAX 1000
using namespace std;
int A[MAX];
int index = 0;
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node *newNode(int x){
struct Node *newptr = new Node;
newptr->data = x;
newptr->left = NULL;
newptr->right = NULL;
return newptr;
}
void printInorder(struct Node *root){
if(root == NULL)
return;
printInorder(root->left);
cout<<root->data<<" ";
A[index] = root->data;
index++;
printInorder(root->right);
}
struct Node *insertBST(struct Node *root, int x){
if(root == NULL)
return newNode(x);
else{
if(root->data > x)
root->left = insertBST(root->left, x);
else
root->right = insertBST(root->right, x);
}
return root;
}
int main(){
struct Node *root = NULL;
root = insertBST(root, 10);
insertBST(root, 20);
insertBST(root, -9);
insertBST(root, 100);
int i, check;
check = 1;
printInorder(root);
for(i=0; i<index-1; i++){
if(A[i] > A[i+1]){
check = 0;
break;
}
}
if(check)
cout<<"BST!\n";
else
cout<<"Not BST!\n";
return 0;
}
| |
Add minimum template for programming contest | #include <cstdlib>
#include <iostream>
int
main(void)
{
std::cin.tie(0);
std::ios::sync_with_stdio(false);
int n;
while (std::cin >> n) {
std::cout << n << std::endl;
}
return EXIT_SUCCESS;
}
| |
Add solution for chapter 18, test 23 | #include <iostream>
using namespace std;
class A {
public:
A() {
cout << "A()" << endl;
}
};
class B : public A {
public:
B() {
cout << "B()" << endl;
}
};
class C : public B {
public:
C() {
cout << "C()" << endl;
}
};
class X {
public:
X() {
cout << "X()" << endl;
}
};
class Y {
public:
Y() {
cout << "Y()" << endl;
}
};
class Z : public X, public Y {
public:
Z() {
cout << "Z()" << endl;
}
};
class MI : public C, public Z {
public:
MI() {
cout << "MI()" << endl;
}
};
class D : public X, public C {
public:
D() {
cout << "D()" << endl;
}
};
int main() {
D* pd = new D;
X *px = pd;
A *pa = pd;
B *pb = pd;
C *pc = pd;
delete pc;
delete pb;
delete pa;
delete pd;
delete px;
}
| |
Add Coverity Scan model file. | /**
* Coverity Scan model
*
* Manage false positives by giving coverity some hints.
*
* Updates to this file must be manually submitted by an admin to:
*
* https://scan.coverity.com/projects/1222
*
*/
// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
if (tag == 1 || tag == 2) {
__coverity_panic__();
}
}
| |
Add Solution for Problem 122 | // 122. Best Time to Buy and Sell Stock II
/**
* Say you have an array for which the ith element is the price of a given stock on day i.
*
* Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times).
* However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
*
* Tags: Array, Greedy
*
* Similar Problems: (M) Best Time to Buy and Sell Stock, (H) Best Time to Buy and Sell Stock III,
* (H) Best Time to Buy and Sell Stock IV, (M) Best Time to Buy and Sell Stock with Cooldown
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n < 2)
{
return 0;
}
int res = 0;
for (int i = 1; i < n; i++)
{
// add to profit if the price is increasing
if (prices[i] > prices[i - 1])
{
res += prices[i] - prices[i - 1];
}
}
return res;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> profit;
profit.push_back(4);
profit.push_back(2);
profit.push_back(3);
profit.push_back(1);
Solution mySolution;
int result = mySolution.maxProfit(profit);
cout << result << endl;
system("pause");
return 0;
}
| |
Add solution for chapter 16 test 65 66 67 | #include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <typename T>
string debug_rep(const T &t) {
ostringstream ret;
ret << t;
return ret.str();
}
template <typename T>
string debug_rep(T *p) {
ostringstream ret;
ret << "pointer: " << p;
if(p) {
ret << " content: " << debug_rep(*p);
} else {
ret << " null pointer";
}
return ret.str();
}
template <>
string debug_rep(char *p) {
cout << "debug_rep(char*p) ";
return debug_rep(string(p));
}
template <>
string debug_rep(const char *p) {
cout << "debug_rep(const char *) ";
return debug_rep(string(p));
}
//string debug_rep(const string &s) {
// return '"' + s + '"' + "no template";
//}
int main() {
string s("hi");
cout << debug_rep(s) << endl;//call debug_rep(const T&t), T is string, when the third function is commented
cout << debug_rep(&s) << endl;//call debug_rep(T*p), T is string
const string *sp = &s;
cout << debug_rep(sp) << endl;//call debug_rep(T* p), T is const string, this one is more specialize
//const char*
cout << debug_rep("hi world!") << endl;
//char*
char* cp = "hello";
cout << debug_rep(cp) << endl;
}
| |
Add additional test case for multiline comments | #include <iostream>
#include <cstdlib>
/* This is our main function */
int main() {
// print Hello world!
std::cout << "HELLO WORLD!" << std::endl;
return 1;
/* TESTING
MULTILINE
COMMENTS
YAY */
}
| |
Add solution for chapter 17 test 14 | #include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
try {
//[z-a]+\\.(cpp|cxx|cc)$ code 4
//
string pattern("[[:alnum:]]+\\.cpp|cxx|cc)$", regex::icase);
regex r(pattern);
smatch results;
} catch(regex_error e) {
cout << e.what() << "\ncode: " << e.code() << endl;
}
return 0;
}
| |
Print linked list in reverse | /*
Print elements of a linked list in reverse order as standard output
head pointer could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
void ReversePrint(Node *head)
{
if (head != NULL) {
ReversePrint(head->next);
cout << head->data << endl;
}
}
| |
Add hack to allow ubsan to work w/o compiler-rt (__muloti4 is undefined) | /*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
*
* 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.
*
* ===----------------------------------------------------------------------===
*
* This file implements __muloti4, and is stolen from the compiler_rt library.
*
* FIXME: we steal and re-compile it into filesystem, which uses __int128_t,
* and requires this builtin when sanitized. See llvm.org/PR30643
*
* ===----------------------------------------------------------------------===
*/
#include "__config"
#include "climits"
#ifndef _LIBCPP_HAS_NO_INT128
__attribute__((no_sanitize("undefined"))) extern "C" __int128_t
__muloti4(__int128_t a, __int128_t b, int* overflow) {
const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
const __int128_t MIN = (__int128_t)1 << (N - 1);
const __int128_t MAX = ~MIN;
*overflow = 0;
__int128_t result = a * b;
if (a == MIN) {
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN) {
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
__int128_t sa = a >> (N - 1);
__int128_t abs_a = (a ^ sa) - sa;
__int128_t sb = b >> (N - 1);
__int128_t abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb) {
if (abs_a > MAX / abs_b)
*overflow = 1;
} else {
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
| |
Implement action that prints file names | #include <iostream>
#include <string>
#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <llvm/Support/CommandLine.h>
using namespace llvm;
using namespace clang::tooling;
using std::string;
static cl::OptionCategory OptionsCategory("Options");
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, OptionsCategory);
for(auto s : OptionsParser.getSourcePathList()) {
std::cout << s << std::endl;
}
return 0;
}
| #include <iostream>
#include <string>
#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/AST/ASTConsumer.h>
#include <llvm/Support/CommandLine.h>
using namespace llvm;
using namespace clang;
using namespace clang::tooling;
using std::string;
class MyFrontendAction : public ASTFrontendAction {
public:
MyFrontendAction() {}
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
std::cout << InFile.str() << std::endl;
return nullptr;
}
};
static cl::OptionCategory OptionsCategory("skel options");
int main(int argc, const char **argv) {
CommonOptionsParser op(argc, argv, OptionsCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
return Tool.run(newFrontendActionFactory<MyFrontendAction>().get());
}
|
Clean input to evm2wasm CLI from any whitespace | #include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <evm2wasm.h>
using namespace std;
int main(int argc, char **argv) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
return 1;
}
bool wast = false;
if (argc == 3) {
wast = (string(argv[2]) == "--wast");
if (!wast) {
cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
return 1;
}
}
ifstream input(argv[1]);
if (!input.is_open()) {
cerr << "File not found: " << argv[1] << endl;
return 1;
}
string str(
(std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>()
);
if (wast) {
cout << evm2wasm::evmhex2wast(str) << endl;
} else {
cout << evm2wasm::evmhex2wasm(str) << endl;
}
return 0;
}
| #include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <algorithm>
#include <evm2wasm.h>
using namespace std;
int main(int argc, char **argv) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
return 1;
}
bool wast = false;
if (argc == 3) {
wast = (string(argv[2]) == "--wast");
if (!wast) {
cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
return 1;
}
}
ifstream input(argv[1]);
if (!input.is_open()) {
cerr << "File not found: " << argv[1] << endl;
return 1;
}
string str(
(std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>()
);
// clean input of any whitespace (including space and new lines)
str.erase(remove_if(str.begin(), str.end(), [](unsigned char x){return std::isspace(x);}), str.end());
if (wast) {
cout << evm2wasm::evmhex2wast(str) << endl;
} else {
cout << evm2wasm::evmhex2wasm(str) << endl;
}
return 0;
}
|
Fix string literal compile error that didn't show up before | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setOrganizationName("ToolWindowManagerTest");
a.setApplicationName("ToolWindowManagerTest");
MainWindow* w = new MainWindow();
w->show();
return a.exec();
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setOrganizationName(QStringLiteral("ToolWindowManagerTest"));
a.setApplicationName(QStringLiteral("ToolWindowManagerTest"));
MainWindow* w = new MainWindow();
w->show();
return a.exec();
}
|
Use immediate base class method | #include "Moves/En_Passant.h"
#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"
//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
is_en_passant_move = true;
}
//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
return board.is_en_passant_targetable(end());
}
//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
board.remove_piece({end().file(), start().rank()});
Pawn_Move::side_effects(board);
}
| #include "Moves/En_Passant.h"
#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"
//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
is_en_passant_move = true;
}
//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
return board.is_en_passant_targetable(end());
}
//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
board.remove_piece({end().file(), start().rank()});
Pawn_Capture::side_effects(board);
}
|
Add a dummy for testing Boost dependencies within CMake | #include <iostream>
int main () {
std::cout << "Hello word!" << std::endl;
} | #include <iostream>
#include <boost/asio.hpp>
int main () {
boost::asio::io_service io_dummy;
boost::asio::deadline_timer t(io_dummy, boost::posix_time::seconds(5));
t.wait();
std::cout << "Hello word!" << std::endl;
} |
Change year in About Dialog | /*
* Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "App.hpp"
#include "Window.hpp"
SuperFreeCell::SuperFreeCell()
:
BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
Window* win=new Window();
win->Lock();
win->Show();
win->Unlock();
}
SuperFreeCell::~SuperFreeCell()
{
}
void
SuperFreeCell::AboutRequested()
{
BString aboutText="";
aboutText << "SuperFreeCell 0.1 \n";
aboutText << "A freecell clone for Haiku \n";
aboutText << "\n";
aboutText << "2014 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
aboutText << "Licensed under the MIT license\n";
BAlert* about=new BAlert("About",aboutText,"OK");
about->Go();
}
int
main(int argc, char** argv)
{
SuperFreeCell app;
app.Run();
return 0;
}
| /*
* Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "App.hpp"
#include "Window.hpp"
SuperFreeCell::SuperFreeCell()
:
BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
Window* win=new Window();
win->Lock();
win->Show();
win->Unlock();
}
SuperFreeCell::~SuperFreeCell()
{
}
void
SuperFreeCell::AboutRequested()
{
BString aboutText="";
aboutText << "SuperFreeCell 0.1 \n";
aboutText << "A freecell clone for Haiku \n";
aboutText << "\n";
aboutText << "2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
aboutText << "Licensed under the MIT license\n";
BAlert* about=new BAlert("About",aboutText,"OK");
about->Go();
}
int
main(int argc, char** argv)
{
SuperFreeCell app;
app.Run();
return 0;
}
|
Add a little padding to the radius | /******************************************************************************
This source file is part of the Avogadro project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "scene.h"
#include "geometryvisitor.h"
#include <Eigen/Geometry>
namespace Avogadro {
namespace Rendering {
Scene::Scene() : m_center(Vector3f::Zero()), m_radius(4.0f)
{
}
Scene::~Scene()
{
}
Vector3f Scene::center()
{
GeometryVisitor visitor;
m_rootNode.accept(visitor);
// For an empty scene ensure that a minimum radius of 4.0 (gives space).
m_center = visitor.center();
m_radius = std::max(4.0f, visitor.radius());
return m_center;
}
float Scene::radius()
{
// We need to know where the center is to get the radius
center();
return m_radius;
}
void Scene::clear()
{
m_rootNode.clear();
}
} // End Rendering namespace
} // End Avogadro namespace
| /******************************************************************************
This source file is part of the Avogadro project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "scene.h"
#include "geometryvisitor.h"
#include <Eigen/Geometry>
namespace Avogadro {
namespace Rendering {
Scene::Scene() : m_center(Vector3f::Zero()), m_radius(4.0f)
{
}
Scene::~Scene()
{
}
Vector3f Scene::center()
{
GeometryVisitor visitor;
m_rootNode.accept(visitor);
// For an empty scene ensure that a minimum radius of 4.0 (gives space).
m_center = visitor.center();
m_radius = std::max(4.0f, visitor.radius()) + 2.0f;
return m_center;
}
float Scene::radius()
{
// We need to know where the center is to get the radius
center();
return m_radius;
}
void Scene::clear()
{
m_rootNode.clear();
}
} // End Rendering namespace
} // End Avogadro namespace
|
Fix memory leak; Improve command-line argument handling | #include "main_window.hpp"
#include <QApplication>
#include <iostream>
using namespace std;
using namespace datavis;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto main_win = new MainWindow;
auto args = app.arguments();
if (args.size() > 1)
{
auto file_path = args[1];
if (file_path.endsWith(".h5"))
{
cout << "Opening data file: " << file_path.toStdString() << endl;
main_win->openDataFile(file_path);
}
else if (file_path.endsWith(".datavis"))
{
cout << "Opening project file: " << file_path.toStdString() << endl;
main_win->openProjectFile(file_path);
}
else
{
cout << "Unknown file type: " << file_path.toStdString() << endl;
return 1;
}
}
main_win->resize(400,500);
main_win->move(50,50);
main_win->show();
return app.exec();
}
| #include "main_window.hpp"
#include <QApplication>
#include <iostream>
using namespace std;
using namespace datavis;
namespace datavis {
enum File_Type
{
Unknown_File_Type,
Data_File_Type,
Project_File_Type
};
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto args = app.arguments();
QString file_path;
File_Type file_type = Unknown_File_Type;
if (args.size() > 1)
{
file_path = args[1];
if (file_path.endsWith(".h5"))
{
file_type = Data_File_Type;
}
else if (file_path.endsWith(".datavis"))
{
file_type = Project_File_Type;
}
else
{
cout << "Unknown file type: " << file_path.toStdString() << endl;
return 1;
}
}
auto main_win = new MainWindow;
if (!file_path.isEmpty())
{
switch(file_type)
{
case Data_File_Type:
{
cout << "Opening data file: " << file_path.toStdString() << endl;
main_win->openDataFile(file_path);
break;
}
case Project_File_Type:
{
cout << "Opening project file: " << file_path.toStdString() << endl;
main_win->openProjectFile(file_path);
break;
}
default:
{
cerr << "Error: Unexpected file type " << file_type << " for file: " << file_path.toStdString() << endl;
}
}
}
main_win->resize(400,500);
main_win->move(50,50);
main_win->show();
int status = app.exec();
delete main_win;
return status;
}
|
Change exit code to 1 if build unsuccessful | #include "mem/Compiler.hpp"
int main (int argc, char** argv)
{
opt::Options opts;
opts.addStrOpt("--dump-ast-xml", "",
"Dump the Abstract Syntax Tree as XML");
opts.addStrOpt("--emit-llvm-bc", "",
"Emit LLVM bytecode");
opts.addStrOpt("--log-formatter", "",
"Set the log formatter");
opts.addIntEnumOpt("--log-level", "",
"Set the minimum log level")
->bind("unknown", log::UNKNOWN)
->bind("debug", log::DEBUG)
->bind("info", log::INFO)
->bind("warning", log::WARNING)
->bind("error", log::ERROR)
->bind("fatal-error", log::FATAL_ERROR);
opts.addBoolOpt("--help", "",
"Show help");
opts.addStrOpt("--output", "",
"Path to the output file");
opts.addBoolOpt("--version", "",
"Show version");
opts.addStrOpt("--dump-st-xml", "",
"Dump the Symbol Table as XML");
opts.parse(argc, argv);
Compiler memc;
memc.setOptions(&opts);
memc.run();
return 0;
}
| #include "mem/Compiler.hpp"
int main (int argc, char** argv)
{
opt::Options opts;
opts.addStrOpt("--dump-ast-xml", "",
"Dump the Abstract Syntax Tree as XML");
opts.addStrOpt("--emit-llvm-bc", "",
"Emit LLVM bytecode");
opts.addStrOpt("--log-formatter", "",
"Set the log formatter");
opts.addIntEnumOpt("--log-level", "",
"Set the minimum log level")
->bind("unknown", log::UNKNOWN)
->bind("debug", log::DEBUG)
->bind("info", log::INFO)
->bind("warning", log::WARNING)
->bind("error", log::ERROR)
->bind("fatal-error", log::FATAL_ERROR);
opts.addBoolOpt("--help", "",
"Show help");
opts.addStrOpt("--output", "",
"Path to the output file");
opts.addBoolOpt("--version", "",
"Show version");
opts.addStrOpt("--dump-st-xml", "",
"Dump the Symbol Table as XML");
opts.parse(argc, argv);
Compiler memc;
memc.setOptions(&opts);
memc.run();
return memc.isBuildSuccessful() ? 0 : 1;
}
|
Add regression test for PR12331. | // RUN: %clang_cc1 -fsyntax-only -verify %s
template<typename T>
struct X0 {
typedef T* type;
void f0(T);
void f1(type);
};
template<> void X0<char>::f0(char);
template<> void X0<char>::f1(type);
namespace PR6161 {
template<typename _CharT>
class numpunct : public locale::facet // expected-error{{use of undeclared identifier 'locale'}} \
// expected-error{{expected class name}}
{
static locale::id id; // expected-error{{use of undeclared identifier}}
};
numpunct<char>::~numpunct(); // expected-error{{expected the class name after '~' to name a destructor}}
}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
template<typename T>
struct X0 {
typedef T* type;
void f0(T);
void f1(type);
};
template<> void X0<char>::f0(char);
template<> void X0<char>::f1(type);
namespace PR6161 {
template<typename _CharT>
class numpunct : public locale::facet // expected-error{{use of undeclared identifier 'locale'}} \
// expected-error{{expected class name}}
{
static locale::id id; // expected-error{{use of undeclared identifier}}
};
numpunct<char>::~numpunct(); // expected-error{{expected the class name after '~' to name a destructor}}
}
namespace PR12331 {
template<typename T> struct S {
struct U { static const int n = 5; };
enum E { e = U::n }; // expected-note {{implicit instantiation first required here}}
int arr[e];
};
template<> struct S<int>::U { static const int n = sizeof(int); }; // expected-error {{explicit specialization of 'U' after instantiation}}
}
|
Add status echo to PPG node for debug | #include "ros/ros.h"
#include "pattern_posture_generator_node.hpp"
int main(int argc, char* argv[]) {
ros::init(argc, argv, "pattern_posture_generator");
ros::NodeHandle nh;
PatternPostureGenerator ppg(nh);
ros::spin();
return 0;
}
PatternPostureGenerator::PatternPostureGenerator(){}
PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
if (!nh.getParam("pattern", pattern_names)) return;
for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
it != pattern_names.end();
it++) {
std::vector<double> posture;
if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
}
key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}
bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req,
pattern_posture_generator::PatternKeyPosture::Response& res) {
std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
return true;
}
| #include "ros/ros.h"
#include "pattern_posture_generator_node.hpp"
int main(int argc, char* argv[]) {
ros::init(argc, argv, "pattern_posture_generator");
ros::NodeHandle nh;
PatternPostureGenerator ppg(nh);
ROS_INFO("Ready. getPostureKey");
ros::spin();
return 0;
}
PatternPostureGenerator::PatternPostureGenerator(){}
PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
if (!nh.getParam("pattern", pattern_names)) return;
ROS_INFO("Get map of patterns parent");
for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
it != pattern_names.end();
it++) {
std::vector<double> posture;
if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
ROS_INFO(std::string("Found posture of ").append(it->second).c_str());
}
key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}
bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req,
pattern_posture_generator::PatternKeyPosture::Response& res) {
std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
return true;
}
|
Set gazebo to run at real time (if possible) for debugging The previous default was too fast for proper manual control of the robot | #include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>
using namespace std;
namespace gazebo
{
class SetupWorld : public WorldPlugin
{
public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
{
cout << "Setting up world..." << flush;
// Create a new transport node
transport::NodePtr node(new transport::Node());
// Initialize the node with the world name
node->Init(_parent->GetName());
// Create a publisher on the ~/physics topic
transport::PublisherPtr physicsPub =
node->Advertise<msgs::Physics>("~/physics");
msgs::Physics physicsMsg;
physicsMsg.set_type(msgs::Physics::ODE);
// Set the step time
physicsMsg.set_max_step_size(0.001);
// Set the real time update rate
physicsMsg.set_real_time_update_rate(0.0);
// Change gravity
//msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));
physicsPub->Publish(physicsMsg);
cout << " done." << endl;
}
};
// Register this plugin with the simulator
GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}
| #include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>
using namespace std;
namespace gazebo
{
class SetupWorld : public WorldPlugin
{
public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
{
cout << "Setting up world..." << flush;
// Create a new transport node
transport::NodePtr node(new transport::Node());
// Initialize the node with the world name
node->Init(_parent->GetName());
// Create a publisher on the ~/physics topic
transport::PublisherPtr physicsPub =
node->Advertise<msgs::Physics>("~/physics");
msgs::Physics physicsMsg;
physicsMsg.set_type(msgs::Physics::ODE);
// Set the step time
physicsMsg.set_max_step_size(0.001);
// Set the real time update rate
physicsMsg.set_real_time_update_rate(1000.0);
// Change gravity
//msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));
physicsPub->Publish(physicsMsg);
cout << " done." << endl;
}
};
// Register this plugin with the simulator
GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}
|
Add sync_with_stdio(false), tour c++ pg132 | #include <stdexcept>
#include <iostream>
int opt_parse(int argc, char** argv) {
// implement option parsing and call the real main
// with everything ready to use
return 0;
}
int main(int argc, char** argv) {
try {
return opt_parse(argc, argv);
} catch (std::exception& e) {
std::cerr << "Standard exception. What: " << e.what() << "\n";
return 10;
} catch (...) {
std::cerr << "Unknown exception.\n";
return 11;
}
}
| #include <stdexcept>
#include <iostream>
int opt_parse(int argc, char** argv) {
// implement option parsing and call the real main
// with everything ready to use
return 0;
}
int main(int argc, char** argv) {
//unless one needs C-style I/O
std::ios_base::sync_with_stdio(false);
try {
return opt_parse(argc, argv);
} catch (std::exception& e) {
std::cerr << "Standard exception. What: " << e.what() << "\n";
return 10;
} catch (...) {
std::cerr << "Unknown exception.\n";
return 11;
}
}
|
Fix endline character problem on Windows | /*
* =========================================================================================
* Name : eventLib.cpp
* Author : Duc Dung Nguyen
* Email : nddung@hcmut.edu.vn
* Copyright : Faculty of Computer Science and Engineering - Bach Khoa University
* Description : library for Assignment 1 - Data structures and Algorithms - Spring 2017
* This library contains functions used for event management
* =========================================================================================
*/
#include "eventLib.h"
/// NOTE: each event will be separated by spaces, or endline character
void loadEvents(char* fName, L1List<busEvent_t> &eList) {
ifstream inFile(fName);
if (inFile) {
string line;
while (getline(inFile , line)) {
istringstream iss(line);
while (iss) {
string sub;
iss >> sub;
busEvent_t __e(sub);
eList.insertHead(__e);
}
}
eList.reverse();
inFile.close();
}
else {
cout << "The file is not found!";
}
}
| /*
* =========================================================================================
* Name : eventLib.cpp
* Author : Duc Dung Nguyen
* Email : nddung@hcmut.edu.vn
* Copyright : Faculty of Computer Science and Engineering - Bach Khoa University
* Description : library for Assignment 1 - Data structures and Algorithms - Spring 2017
* This library contains functions used for event management
* =========================================================================================
*/
#include "eventLib.h"
/// NOTE: each event will be separated by spaces, or endline character
void loadEvents(char* fName, L1List<busEvent_t> &eList) {
ifstream inFile(fName);
if (inFile) {
string line;
while (getline(inFile , line)) {
/// On Windows, lines on file ends with \r\n. So you have to remove \r
if (line[line.length() - 1] == '\r')
line.erase(line.length() - 1);
istringstream iss(line);
while (iss) {
string sub;
iss >> sub;
busEvent_t __e(sub);
eList.insertHead(__e);
}
}
eList.reverse();
inFile.close();
}
else {
cout << "The file is not found!";
}
}
|
Fix regression where we didn't ever start watching for network address changes on Windows. | // 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 "net/base/network_change_notifier_win.h"
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment(lib, "iphlpapi.lib")
namespace net {
NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
addr_overlapped_.hEvent = WSACreateEvent();
}
NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
CancelIPChangeNotify(&addr_overlapped_);
addr_watcher_.StopWatching();
WSACloseEvent(addr_overlapped_.hEvent);
}
void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
NotifyObserversOfIPAddressChange();
// Start watching for the next address change.
WatchForAddressChange();
}
void NetworkChangeNotifierWin::WatchForAddressChange() {
HANDLE handle = NULL;
DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
CHECK(ret == ERROR_IO_PENDING);
addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}
} // namespace net
| // 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 "net/base/network_change_notifier_win.h"
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment(lib, "iphlpapi.lib")
namespace net {
NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
addr_overlapped_.hEvent = WSACreateEvent();
WatchForAddressChange();
}
NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
CancelIPChangeNotify(&addr_overlapped_);
addr_watcher_.StopWatching();
WSACloseEvent(addr_overlapped_.hEvent);
}
void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
NotifyObserversOfIPAddressChange();
// Start watching for the next address change.
WatchForAddressChange();
}
void NetworkChangeNotifierWin::WatchForAddressChange() {
HANDLE handle = NULL;
DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
CHECK(ret == ERROR_IO_PENDING);
addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}
} // namespace net
|
Update syntax for message passing example | #include <bulk.hpp>
#include <iostream>
int main() {
bulk::spawn(bulk::available_processors(), [](int s, int p) {
for (int t = 0; t < p; ++t) {
bulk::send<int, int>(t, s, s);
}
bulk::sync();
if (s == 0) {
for (auto message : bulk::messages<int, int>()) {
std::cout << message.tag << ", " << message.content << std::endl;
}
}
});
return 0;
}
| #include <bulk.hpp>
#include <iostream>
int main() {
auto center = bulk::center();
center.spawn(center.available_processors(), [¢er](int s, int p) {
for (int t = 0; t < p; ++t) {
center.send<int, int>(t, s, s);
}
center.sync();
if (s == 0) {
for (auto message : center.messages<int, int>()) {
std::cout << message.tag << ", " << message.content << std::endl;
}
}
});
return 0;
}
|
Remove require.map() from the script prologue | // Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
#include "bindings/script_prologue.h"
namespace bindings {
// NOTE: Line breaks will be removed from these scripts before their execution in the
// JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
// as that will cause the first line of the user script to be ignored.
// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
enumerable: true,
configurable: false,
writable: false,
value: (() => {
let _script_cache = {};
let _script_mappings = {};
/** require(script) **/
let _function = (script) => {
if (_script_mappings.hasOwnProperty(script))
script = _script_mappings[script];
if (!_script_cache.hasOwnProperty(script))
_script_cache[script] = requireImpl(script);
return _script_cache[script];
};
/** require.map(source, destination) **/
_function.map = (script, destination) =>
_script_mappings[script] = destination;
return _function;
})()
});
)";
const char kModulePrologue[] = R"(
(function() {
let exports = {};
let module = {};
return (function(require, exports, module, global) {
)";
const char kModuleEpilogue[] = R"(
; return exports;
})(require, exports, module, self);
})();
)";
} // namespace bindings
| // Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
#include "bindings/script_prologue.h"
namespace bindings {
// NOTE: Line breaks will be removed from these scripts before their execution in the
// JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
// as that will cause the first line of the user script to be ignored.
// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
enumerable: true,
configurable: false,
writable: false,
value: (() => {
let _script_cache = {};
/** require(script) **/
let _function = (script) => {
if (!_script_cache.hasOwnProperty(script))
_script_cache[script] = requireImpl(script);
return _script_cache[script];
}
return _function;
})()
});
)";
const char kModulePrologue[] = R"(
(function() {
let exports = {};
let module = {};
return (function(require, exports, module, global) {
)";
const char kModuleEpilogue[] = R"(
; return exports;
})(require, exports, module, self);
})();
)";
} // namespace bindings
|
Delete Node in a Linked List | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
| /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
|
Fix outerwall inset for thin parts | //Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "OuterWallInsetBeadingStrategy.h"
#include <algorithm>
namespace cura
{
BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret = parent->compute(thickness, bead_count);
// Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signalling' walls.
bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; });
// Early out when the only walls are outer.
if (bead_count < 3)
{
return ret;
}
// Actually move the outer wall inside.
ret.toolpath_locations[0] = ret.toolpath_locations[0] + outer_wall_offset;
return ret;
}
} // namespace cura
| //Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "OuterWallInsetBeadingStrategy.h"
#include <algorithm>
namespace cura
{
BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret = parent->compute(thickness, bead_count);
// Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signalling' walls.
bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; });
// Early out when the only walls are outer.
if (bead_count < 2)
{
return ret;
}
// Actually move the outer wall inside. Ensure that the outer wall never goes beyond the middle line.
ret.toolpath_locations[0] = std::min(ret.toolpath_locations[0] + outer_wall_offset, thickness / 2);
return ret;
}
} // namespace cura
|
Revert "10-bit normalased internal frames" | #include "frames.h"
frameGPUi::frameGPUi (int w, int h, bool full) {
glGenTextures (1, &plane);
glBindTexture (GL_TEXTURE_2D, plane);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB10_A2, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, NULL);
timecode = 0;
}
frameGPUi::~frameGPUi () {
glDeleteTextures (1, &plane);
}
| #include "frames.h"
frameGPUi::frameGPUi (int w, int h, bool full) {
glGenTextures (1, &plane);
glBindTexture (GL_TEXTURE_2D, plane);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);
timecode = 0;
}
frameGPUi::~frameGPUi () {
glDeleteTextures (1, &plane);
}
|
Add default clause to switch | /*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2013 Thomas Sanchez. All rights reserved.
*
*/
#include "httpp/http/HttpCode.hpp"
std::string HTTPP::HTTP::getDefaultMessage(HttpCode code)
{
switch (code)
{
case HttpCode::Continue:
return "Continue";
case HttpCode::Ok:
return "Ok";
case HttpCode::Created:
return "Created";
case HttpCode::Accepted:
return "Accepted";
case HttpCode::NoContent:
return "NoContent";
case HttpCode::MultipleChoice:
return "MultipleChoice";
case HttpCode::MovedPermentaly:
return "MovedPermentaly";
case HttpCode::MovedTemporarily:
return "MovedTemporarily";
case HttpCode::NotModified:
return "NotModified";
case HttpCode::BadRequest:
return "BadRequest";
case HttpCode::Unauthorized:
return "Unauthorized";
case HttpCode::Forbidden:
return "Forbidden";
case HttpCode::NotFound:
return "NotFound";
case HttpCode::InternalServerError:
return "InternalServerError";
case HttpCode::NotImplemented:
return "NotImplemented";
case HttpCode::BadGateway:
return "BadGateway";
case HttpCode::ServiceUnavailable:
return "ServiceUnavailable";
case HttpCode::HttpVersionNotSupported:
return "HttpVersionNotSupported";
}
}
| /*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2013 Thomas Sanchez. All rights reserved.
*
*/
#include "httpp/http/HttpCode.hpp"
std::string HTTPP::HTTP::getDefaultMessage(HttpCode code)
{
switch (code)
{
default:
return "Unknown";
case HttpCode::Continue:
return "Continue";
case HttpCode::Ok:
return "Ok";
case HttpCode::Created:
return "Created";
case HttpCode::Accepted:
return "Accepted";
case HttpCode::NoContent:
return "NoContent";
case HttpCode::MultipleChoice:
return "MultipleChoice";
case HttpCode::MovedPermentaly:
return "MovedPermentaly";
case HttpCode::MovedTemporarily:
return "MovedTemporarily";
case HttpCode::NotModified:
return "NotModified";
case HttpCode::BadRequest:
return "BadRequest";
case HttpCode::Unauthorized:
return "Unauthorized";
case HttpCode::Forbidden:
return "Forbidden";
case HttpCode::NotFound:
return "NotFound";
case HttpCode::InternalServerError:
return "InternalServerError";
case HttpCode::NotImplemented:
return "NotImplemented";
case HttpCode::BadGateway:
return "BadGateway";
case HttpCode::ServiceUnavailable:
return "ServiceUnavailable";
case HttpCode::HttpVersionNotSupported:
return "HttpVersionNotSupported";
}
}
|
Remove explicit by constructor has too many args. | #include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"
#include <string>
#include "krs_servo_driver.hpp"
class KrsServoNode {
public:
KrsServoNode();
explicit KrsServoNode(ros::NodeHandle& nh, const char* path);
private:
void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);
ros::Subscriber sub;
KrsServoDriver krs;
};
int main(int argc, char** argv) {
ros::init(argc, argv, "krs_servo_node");
ros::NodeHandle nh;
std::string path;
nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");
KrsServoNode ksn(nh, path.c_str());
ros::spin();
return 0;
}
KrsServoNode::KrsServoNode()
: krs()
{}
KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
: krs(path)
{
sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}
void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
krs.sendAngle(msg->id, msg->angle);
}
| #include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"
#include <string>
#include "krs_servo_driver.hpp"
class KrsServoNode {
public:
KrsServoNode();
KrsServoNode(ros::NodeHandle& nh, const char* path);
private:
void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);
ros::Subscriber sub;
KrsServoDriver krs;
};
int main(int argc, char** argv) {
ros::init(argc, argv, "krs_servo_node");
ros::NodeHandle nh;
std::string path;
nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");
KrsServoNode ksn(nh, path.c_str());
ros::spin();
return 0;
}
KrsServoNode::KrsServoNode()
: krs()
{}
KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
: krs(path)
{
sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}
void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
krs.sendAngle(msg->id, msg->angle);
}
|
Change fill mode of transitions to backwards not both | // 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 "config.h"
#include "core/animation/css/CSSTransitionData.h"
#include "core/animation/Timing.h"
namespace blink {
CSSTransitionData::CSSTransitionData()
{
m_propertyList.append(initialProperty());
}
CSSTransitionData::CSSTransitionData(const CSSTransitionData& other)
: CSSTimingData(other)
, m_propertyList(other.m_propertyList)
{
}
bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const
{
return m_propertyList == other.m_propertyList;
}
Timing CSSTransitionData::convertToTiming(size_t index) const
{
ASSERT(index < m_propertyList.size());
// Note that the backwards fill part is required for delay to work.
Timing timing = CSSTimingData::convertToTiming(index);
timing.fillMode = Timing::FillModeBoth;
return timing;
}
} // namespace blink
| // 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 "config.h"
#include "core/animation/css/CSSTransitionData.h"
#include "core/animation/Timing.h"
namespace blink {
CSSTransitionData::CSSTransitionData()
{
m_propertyList.append(initialProperty());
}
CSSTransitionData::CSSTransitionData(const CSSTransitionData& other)
: CSSTimingData(other)
, m_propertyList(other.m_propertyList)
{
}
bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const
{
return m_propertyList == other.m_propertyList;
}
Timing CSSTransitionData::convertToTiming(size_t index) const
{
ASSERT(index < m_propertyList.size());
// Note that the backwards fill part is required for delay to work.
Timing timing = CSSTimingData::convertToTiming(index);
timing.fillMode = Timing::FillModeBackwards;
return timing;
}
} // namespace blink
|
Implement ranking system based on web, title, and pageindex. | #include <iostream>
using namespace std;
int main()
{
cout << "TODO" << endl;
return -1;
}
| #include <iostream>
#include <string>
#include <fstream>
#include <array>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include "IndexHelper.hpp"
using namespace std;
const array<pair<int, string>, 3> INDEXWEIGHTS {{
{16, "titleindex"},
{4, "webindex"},
{1, "pageindex"}
}};
string getQueryString()
{
ifstream input("query.txt");
string query;
getline(input, query);
return query;
}
map<string, int> getWeightedResults(const string& query)
{
map<string, int> results;
IndexHelper helper;
// Add the base score from the index
for (const auto index : INDEXWEIGHTS) {
for (auto link : helper.getLinksFromIndex(query, index.second)) {
results[link] += index.first;
}
}
// TODO: Add the link score
return results;
}
vector<string> getResults(string query)
{
vector<pair<int, string>> orderedResults;
for (auto entry : getWeightedResults(query)) {
orderedResults.emplace_back(entry.second, entry.first);
}
sort(orderedResults.begin(), orderedResults.end(), greater<pair<int, string>>());
vector<string> results;
for (auto result : orderedResults) {
results.emplace_back(result.second);
}
return results;
}
int main()
{
string query = "liacs";
for (auto result : getResults(query)) {
cout << result << endl;
}
return 0;
}
|
Update testcase for upstream LLVM changes (r302469). | // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
virtual void VariadicFunction(...);
};
class Derived : public virtual Base {
virtual void VariadicFunction(...);
};
void Derived::VariadicFunction(...) { }
// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
| // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
virtual void VariadicFunction(...);
};
class Derived : public virtual Base {
virtual void VariadicFunction(...);
};
void Derived::VariadicFunction(...) { }
// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP_I:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC_I:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
// CHECK: ![[SP_I]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC_I]] = !DILocation({{.*}}scope: ![[SP_I]])
|
Change space 8 to 4 | #include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
}
| #include <iostream>
int main()
{
std::cout << "Hello, world! \n";
}
|
Remove test with int128 printing since it breaks on some platforms. | // RUN: %clang_cc1 %s -fsyntax-only -verify
// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}
template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}
template <__int128_t T> class Type3 {};
template <__int128_t T> void Function3(Type3<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type3<-42>' to 'Type3<-42i128> &' for 1st argument;}}
template <__uint128_t T> class Type4 {};
template <__uint128_t T> void Function4(Type4<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type4<42>' to 'Type4<42Ui128> &' for 1st argument;}}
void Function() {
Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
Function3(Type3<-42>()); // expected-error{{no matching function for call to 'Function3'}}
Function4(Type4<42>()); // expected-error{{no matching function for call to 'Function4'}}
}
| // RUN: %clang_cc1 %s -fsyntax-only -verify
// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}
template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}
void Function() {
Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
}
|
Test change to test both branch functionality and approval process | // MathLib.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <unittest.h>
int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
run_tests();
return 0;
}
| // MathLib.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <unittest.h>
int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
//test change
run_tests();
return 0;
}
|
Remove unnecessary output redirection in a test. | // RUN: %clang_cc1 -std=c++11 -ast-dump %s 2>&1 | FileCheck %s
char c8[] = u8"test\0\\\"\t\a\b\234";
// CHECK: char c8[12] = (StringLiteral {{.*}} lvalue u8"test\000\\\"\t\a\b\234")
char16_t c16[] = u"test\0\\\"\t\a\b\234\u1234";
// CHECK: char16_t c16[13] = (StringLiteral {{.*}} lvalue u"test\000\\\"\t\a\b\234\u1234")
char32_t c32[] = U"test\0\\\"\t\a\b\234\u1234\U0010ffff"; // \
// CHECK: char32_t c32[14] = (StringLiteral {{.*}} lvalue U"test\000\\\"\t\a\b\234\u1234\U0010FFFF")
wchar_t wc[] = L"test\0\\\"\t\a\b\234\u1234\xffffffff"; // \
// CHECK: wchar_t wc[14] = (StringLiteral {{.*}} lvalue L"test\000\\\"\t\a\b\234\x1234\xFFFFFFFF")
| // RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s
char c8[] = u8"test\0\\\"\t\a\b\234";
// CHECK: char c8[12] = (StringLiteral {{.*}} lvalue u8"test\000\\\"\t\a\b\234")
char16_t c16[] = u"test\0\\\"\t\a\b\234\u1234";
// CHECK: char16_t c16[13] = (StringLiteral {{.*}} lvalue u"test\000\\\"\t\a\b\234\u1234")
char32_t c32[] = U"test\0\\\"\t\a\b\234\u1234\U0010ffff"; // \
// CHECK: char32_t c32[14] = (StringLiteral {{.*}} lvalue U"test\000\\\"\t\a\b\234\u1234\U0010FFFF")
wchar_t wc[] = L"test\0\\\"\t\a\b\234\u1234\xffffffff"; // \
// CHECK: wchar_t wc[14] = (StringLiteral {{.*}} lvalue L"test\000\\\"\t\a\b\234\x1234\xFFFFFFFF")
|
Set organization name to SystemsGenetics | #if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"
using namespace std;
int main(int argc, char *argv[])
{
EApplication application(""
,"kinc"
,MAJOR_VERSION
,MINOR_VERSION
,REVISION
,unique_ptr<DataFactory>(new DataFactory)
,unique_ptr<AnalyticFactory>(new AnalyticFactory)
,argc
,argv);
return application.exec();
}
| #if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"
using namespace std;
int main(int argc, char *argv[])
{
EApplication application("SystemsGenetics"
,"kinc"
,MAJOR_VERSION
,MINOR_VERSION
,REVISION
,unique_ptr<DataFactory>(new DataFactory)
,unique_ptr<AnalyticFactory>(new AnalyticFactory)
,argc
,argv);
return application.exec();
}
|
Remove unnecessary variable assignment (is implicit return, imho) | #include <ncurses.h>
#include <string>
#include "game.h"
using namespace std;
int main(int argc, char **argv) {
int initStatus = init();
if (initStatus == 0) run();
close();
printf("GAME OVER\n");
return 0;
}
| #include <ncurses.h>
#include <string>
#include "game.h"
using namespace std;
int main(int argc, char **argv) {
if (init() == 0) run();
close();
printf("GAME OVER\n");
return 0;
}
|
Declare an application name and version. | #include "HumbugWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
HumbugWindow w;
if (argc == 3 && QString(argv[1]) == QString("--site")) {
w.setUrl(QUrl(argv[2]));
}
w.show();
return a.exec();
}
| #include "HumbugWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationName("Humbug Desktop");
a.setApplicationVersion("0.1");
HumbugWindow w;
if (argc == 3 && QString(argv[1]) == QString("--site")) {
w.setUrl(QUrl(argv[2]));
}
w.show();
return a.exec();
}
|
Update the page tests to work with the new API | #include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>
using namespace Pith;
TEST(TestPage, stackAllocate) {
[[gnu::unused]] Page p;
}
TEST(TestPage, mapOnePage) {
Span<Page> pages{nullptr, 1};
auto result = Page::map(pages);
EXPECT_TRUE(result);
EXPECT_NE(result(), nullptr);
pages.value(result());
EXPECT_EQ(Page::unmap(pages), 0);
}
TEST(TestPage, setPermissions) {
Span<Page> pages{nullptr, 1};
}
TEST(TestPage, setPermissionsOnUnmappedPage) {
Span<Page> pages{nullptr, 1};
// Get a fresh page.
{
auto r = Page::map(pages);
ASSERT_TRUE(r);
pages.value(r());
}
// Explicitly unmap it.
{
auto e = Page::unmap(pages);
ASSERT_EQ(e, 0);
}
// Fail to set permissions on unmapped page.
{
auto e = Page::setPermissions(pages, Page::Permissions::READ);
ASSERT_NE(e, 0);
}
}
#if 0
TEST(PageSpan, mapAndUnmap) {
PageSpan pages{nullptr, 1};
auto map = pages.map();
map.unmap();
}
#endif // 0 | #include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>
using namespace Pith;
TEST(TestPage, pageSize) {
Process::init();
EXPECT_NE(Page::size(), std::size_t{0});
Process::kill();
}
TEST(TestPage, mapOnePage) {
Process::init();
auto size = Page::size();
auto addr = Page::map(size);
Page::unmap(addr, size);
Process::kill();
}
|
Change unit test for JPetTaskLoader. | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskLoaderTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( my_test1 )
{
BOOST_REQUIRE(1==0);
}
BOOST_AUTO_TEST_SUITE_END()
| #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskLoaderTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(defaultConstrutocTest)
{
/*JPetOptions::Options options = {
{"inputFile", "data_files/cosm_barrel.hld.root"},
{"inputFileType", "hld"},
{"outputFile", "data_files/cosm_barrel.tslot.raw.out.root"},
{"outputFileType", "tslot.raw"},
{"firstEvent", "1"},
{"lastEvent", "10"},
{"progressBar", "false"}
};
JPetTaskLoader taskLoader;
taskLoader.init(options);*/
}
BOOST_AUTO_TEST_SUITE_END()
|
Use a different define to decide which CRC library to use. | // Copyright (c) 2009 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.
// Calculate Crc by calling CRC method in LZMA SDK
#include "courgette/crc.h"
extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
CrcGenerateTable();
uint32 crc = 0xffffffffL;
crc = ~CrcCalc(buffer, size);
return crc;
}
} // namespace
| // 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 "courgette/crc.h"
#ifdef COURGETTE_USE_CRC_LIB
# include "zlib.h"
#else
extern "C" {
# include "third_party/lzma_sdk/7zCrc.h"
}
#endif
#include "base/basictypes.h"
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
uint32 crc;
#ifdef COURGETTE_USE_CRC_LIB
// Calculate Crc by calling CRC method in zlib
crc = crc32(0, buffer, size);
#else
// Calculate Crc by calling CRC method in LZMA SDK
CrcGenerateTable();
crc = CrcCalc(buffer, size);
#endif
return ~crc;
}
} // namespace
|
Set Uart Baudrate to 38.4kBaud, for minimal error. | // coding: utf-8
#include "hardware.hpp"
// system tick timer
ISR(TIMER2_COMPA_vect)
{
xpcc::Clock::increment();
}
// main function \o/
int
main(void)
{
// set the led pins
initializeLeds();
RedLedPin::setOutput();
GreenLedPin::setOutput();
BlueLedPin::setOutput();
LightSensorPin::setInput();
// set up the oversampling of the photosensitive diode
AdcInterrupt::initialize(AdcInterrupt::Reference::ExternalARef, AdcInterrupt::Prescaler::Div32);
lightSensor::initialize(adcMap, &lightSensorData);
GpioD0::connect(Uart::Rx);
GpioD1::connect(Uart::Tx);
Uart::initialize<Uart::B115200>();
xpcc::atmega::enableInterrupts();
XPCC_LOG_INFO << "\n\nRESTART\n\n";
while(1)
{
dreamer.run();
}
return 0;
}
| // coding: utf-8
#include "hardware.hpp"
// system tick timer
ISR(TIMER2_COMPA_vect)
{
xpcc::Clock::increment();
}
// main function \o/
int
main(void)
{
// set the led pins
initializeLeds();
RedLedPin::setOutput();
GreenLedPin::setOutput();
BlueLedPin::setOutput();
LightSensorPin::setInput();
// set up the oversampling of the photosensitive diode
AdcInterrupt::initialize(AdcInterrupt::Reference::ExternalARef, AdcInterrupt::Prescaler::Div32);
lightSensor::initialize(adcMap, &lightSensorData);
GpioD0::connect(Uart::Rx);
GpioD1::connect(Uart::Tx);
Uart::initialize<Uart::B38400>();
xpcc::atmega::enableInterrupts();
XPCC_LOG_INFO << "\n\nRESTART\n\n";
while(1)
{
dreamer.run();
}
return 0;
}
|
Disable the right RUN line | // FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY | FileCheck %s -check-prefix=TRY
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW
void external();
inline void not_emitted() {
throw int(13); // no error
}
int main() {
int rv = 0;
#ifdef TRY
try {
external(); // TRY: invoke void @"\01?external@@YAXXZ"
} catch (int) {
rv = 1;
// TRY: call i8* @llvm.eh.begincatch
// TRY: call void @llvm.eh.endcatch
}
#endif
#ifdef THROW
// THROW: call void @"\01?terminate@@YAXXZ"
throw int(42);
#endif
return rv;
}
| // FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW
void external();
inline void not_emitted() {
throw int(13); // no error
}
int main() {
int rv = 0;
#ifdef TRY
try {
external(); // TRY: invoke void @"\01?external@@YAXXZ"
} catch (int) {
rv = 1;
// TRY: call i8* @llvm.eh.begincatch
// TRY: call void @llvm.eh.endcatch
}
#endif
#ifdef THROW
// THROW: call void @"\01?terminate@@YAXXZ"
throw int(42);
#endif
return rv;
}
|
Add additional test for the random bytes utility | /*
* SOPMQ - Scalable optionally persistent message queue
* Copyright 2014 InWorldz, LLC
*
* 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 "util.h"
#include <string>
using sopmq::shared::util;
TEST(UtilTest, HexEncoderWorks)
{
std::string testStr("abcde");
std::string result = util::hex_encode((const unsigned char*)testStr.c_str(), testStr.size());
ASSERT_EQ("6162636465", result);
} | /*
* SOPMQ - Scalable optionally persistent message queue
* Copyright 2014 InWorldz, LLC
*
* 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 "util.h"
#include <string>
using sopmq::shared::util;
TEST(UtilTest, HexEncoderWorks)
{
std::string testStr("abcde");
std::string result = util::hex_encode((const unsigned char*)testStr.c_str(), testStr.size());
ASSERT_EQ("6162636465", result);
}
TEST(UtilTest, RandomBytes)
{
std::string bytes = util::random_bytes(1024);
ASSERT_EQ(1024, bytes.length());
} |
Add needed header for travis-ci build | // Copyright (C) 2015 Jack Maloney. All Rights Reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "voltz-internal.h"
double StartupTime;
int main(int argc, const char** argv) {
clock_t begin, end;
begin = clock();
vz_bootstrap_runtime(argc, argv);
end = clock();
StartupTime = (end - begin) / CLOCKS_PER_SEC;
#ifdef VOLTZ_DEBUG
printf("Took %f seconds to startup.\n", StartupTime);
#endif
vz_linker_entry(nil, nil);
}
| // Copyright (C) 2015 Jack Maloney. All Rights Reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "voltz-internal.h"
#include <ctime>
#include <cstdio>
double StartupTime;
int main(int argc, const char** argv) {
clock_t begin, end;
begin = clock();
vz_bootstrap_runtime(argc, argv);
end = clock();
StartupTime = (end - begin) / CLOCKS_PER_SEC;
#ifdef VOLTZ_DEBUG
printf("Took %f seconds to startup.\n", StartupTime);
#endif
vz_linker_entry(nil, nil);
}
|
Fix * instead of + | #include<iostream>
int main()
{
int value1 = 0, value2 = 0;
std::cin >> value1 >> value2;
std::cout << "The product of " << value1 << " and " << value2 << " equals " << value1 + value2 << std::endl;
return 0;
}
| #include<iostream>
int main()
{
int value1 = 0, value2 = 0;
std::cin >> value1 >> value2;
std::cout << "The product of " << value1 << " and " << value2 << " equals " << value1 * value2 << std::endl;
return 0;
}
|
Add test cases for unsigned int to floating point | #include "output.h"
Output output;
float a = 123.0;
int b = 79;
unsigned int c = 24;
int main()
{
float d = b;
float e = c;
output << (int) a; // CHECK: 0x0000007b
output << (unsigned int) a; // CHECK: 0x0000007b
output << (int) d; // CHECK: 0x0000004f
// output << (int) e; // XXX should be 0x18, but is 0x17 for some reason
}
| #include "output.h"
Output output;
float a = 123.0;
int b = 79;
unsigned int c = 24;
unsigned int f = 0x81234000;
int main()
{
float d = b;
float e = c;
float g = f;
output << (int) a; // CHECK: 0x0000007b
output << (unsigned int) a; // CHECK: 0x0000007b
output << (int) d; // CHECK: 0x0000004f
output << (int) e; // CHECK: 0x00000018
output << (unsigned int) g; // CHECK: 0x81234000
}
|
Fix another use of the driver. | // Check the value profiling instrinsics emitted by instrumentation.
// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s
void (*foo) (void);
int main(int argc, const char *argv[]) {
// CHECK: [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT: [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT: call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT: invoke void [[REG1]]()
try {
foo();
} catch (int) {}
return 0;
}
// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)
| // Check the value profiling instrinsics emitted by instrumentation.
// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument=clang -mllvm -enable-value-profiling -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck %s
void (*foo) (void);
int main(int argc, const char *argv[]) {
// CHECK: [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT: [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT: call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT: invoke void [[REG1]]()
try {
foo();
} catch (int) {}
return 0;
}
// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)
|
Disable HTTPTest if 'headless', seems to hang travis-ci now | //------------------------------------------------------------------------------
// HTTPFileSystemTest.cc
// Test HTTP file system functionality.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "HTTP/HTTPFileSystem.h"
#include "IO/IO.h"
using namespace Oryol;
#if !ORYOL_EMSCRIPTEN
TEST(HTTPFileSystemTest) {
Core::Setup();
// setup an IO facade, and associate http: with the HTTPFileSystem
IOSetup ioSetup;
ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
IO::Setup(ioSetup);
// asynchronously load the index.html file
Ptr<IORead> req = IO::LoadFile("http://www.flohofwoe.net/index.html");
// trigger the runloop until the request has been handled
while (!req->Handled) {
Core::PreRunLoop()->Run();
}
// check what we got
CHECK(req->Status == IOStatus::OK);
CHECK(!req->Data.Empty());
CHECK(req->Data.Size() > 0);
if (req->Data.Size() > 0) {
String content((const char*)req->Data.Data(), 0, req->Data.Size());
Log::Info("%s\n", content.AsCStr());
}
req = 0;
IO::Discard();
Core::Discard();
}
#endif
| //------------------------------------------------------------------------------
// HTTPFileSystemTest.cc
// Test HTTP file system functionality.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "HTTP/HTTPFileSystem.h"
#include "IO/IO.h"
using namespace Oryol;
#if !ORYOL_EMSCRIPTEN && !ORYOL_UNITTESTS_HEADLESS
TEST(HTTPFileSystemTest) {
Core::Setup();
// setup an IO facade, and associate http: with the HTTPFileSystem
IOSetup ioSetup;
ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
IO::Setup(ioSetup);
// asynchronously load the index.html file
Ptr<IORead> req = IO::LoadFile("http://www.flohofwoe.net/index.html");
// trigger the runloop until the request has been handled
while (!req->Handled) {
Core::PreRunLoop()->Run();
}
// check what we got
CHECK(req->Status == IOStatus::OK);
CHECK(!req->Data.Empty());
CHECK(req->Data.Size() > 0);
if (req->Data.Size() > 0) {
String content((const char*)req->Data.Data(), 0, req->Data.Size());
Log::Info("%s\n", content.AsCStr());
}
req = 0;
IO::Discard();
Core::Discard();
}
#endif
|
Clear spurious timing code from bounds_interence | #include <Halide.h>
#include <sys/time.h>
using namespace Halide;
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
int main(int argc, char **argv) {
Func f, g, h; Var x, y;
h(x) = x;
g(x) = h(x-1) + h(x+1);
f(x, y) = (g(x-1) + g(x+1)) + y;
h.root();
g.root();
if (use_gpu()) {
f.cudaTile(x, y, 16, 16);
g.cudaTile(x, 128);
h.cudaTile(x, 128);
}
Image<int> out = f.realize(32, 32);
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
if (out(x, y) != x*4 + y) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
| #include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f, g, h; Var x, y;
h(x) = x;
g(x) = h(x-1) + h(x+1);
f(x, y) = (g(x-1) + g(x+1)) + y;
h.root();
g.root();
if (use_gpu()) {
f.cudaTile(x, y, 16, 16);
g.cudaTile(x, 128);
h.cudaTile(x, 128);
}
Image<int> out = f.realize(32, 32);
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
if (out(x, y) != x*4 + y) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
|
Add implementation for adding/removing subspecies functions | #include "fish_detector/common/species_dialog.h"
#include "ui_species_dialog.h"
namespace fish_detector {
SpeciesDialog::SpeciesDialog(QWidget *parent)
: QDialog(parent)
, ui_(new Ui::SpeciesDialog) {
ui_->setupUi(this);
}
void SpeciesDialog::on_ok_clicked() {
}
void SpeciesDialog::on_cancel_clicked() {
}
void SpeciesDialog::on_removeSubspecies_clicked() {
}
void SpeciesDialog::on_addSubspecies_clicked() {
}
Species SpeciesDialog::getSpecies() {
Species species;
return species;
}
#include "../../include/fish_detector/common/moc_species_dialog.cpp"
} // namespace fish_detector
| #include "fish_detector/common/species_dialog.h"
#include "ui_species_dialog.h"
namespace fish_detector {
SpeciesDialog::SpeciesDialog(QWidget *parent)
: QDialog(parent)
, ui_(new Ui::SpeciesDialog) {
ui_->setupUi(this);
}
void SpeciesDialog::on_ok_clicked() {
accept();
}
void SpeciesDialog::on_cancel_clicked() {
reject();
}
void SpeciesDialog::on_removeSubspecies_clicked() {
QListWidgetItem *current = ui_->subspeciesList->currentItem();
if(current != nullptr) {
delete current;
}
}
void SpeciesDialog::on_addSubspecies_clicked() {
QListWidgetItem *item = new QListWidgetItem("New subspecies");
item->setFlags(item->flags() | Qt::ItemIsEditable);
ui_->subspeciesList->addItem(item);
ui_->subspeciesList->editItem(item);
}
Species SpeciesDialog::getSpecies() {
Species species;
return species;
}
#include "../../include/fish_detector/common/moc_species_dialog.cpp"
} // namespace fish_detector
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.