Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add Solution for 155 Min Stack | // 155. Min Stack
/**
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
*
* push(x) -- Push element x onto stack.
* pop() -- Removes the element on top of the stack.
* top() -- Get the top element.
* getMin() -- Retrieve the minimum element in the stack.
*
* Example:
*
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> Returns -3.
* minStack.pop();
* minStack.top(); --> Returns 0.
* minStack.getMin(); --> Returns -2.
*
* Tags: Stack Design
*
* Similar Problems: (H) Sliding Window Maximum
*
* Author: Kuang Qin
*/
using namespace std;
#include <stack>
#include <iostream>
class MinStack {
private:
stack<int> s1; // s1 as the original stack
stack<int> s2; // s2 always keeps the current minimun element on the top
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s1.push(x);
if (s2.empty() || x <= getMin())
s2.push(x); // keep the top element of s2 the minimum
}
void pop() {
if (s1.top() == getMin())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
int main()
{
MinStack obj;
obj.push(0);
obj.push(1);
obj.push(0);
int param_1 = obj.getMin();
obj.pop();
int param_2 = obj.top();
int param_3 = obj.getMin();
cout << param_1 << " " << param_2 << " " << param_3 << endl;
system("pause");
return 0;
} | |
Add the solution to "The Full Counting Sort". | #include <iostream>
#include <string>
#include <map>
#include <list>
using namespace std;
typedef struct node
{
int num;
string str;
}c_node;
int main()
{
int n;
cin >> n;
c_node *a = new c_node[n];
for (int i = 0; i < n; i++) {
cin >> a[i].num >> a[i].str;
}
map< int, list<string> > int_list_map;
for (int i = 0; i < n; i++) {
if (i < n / 2) {
a[i].str = "-";
}
map< int, list<string> >::iterator iter = int_list_map.find(a[i].num);
if (iter == int_list_map.end()) {
list<string> str_list;
str_list.push_back(a[i].str);
int_list_map.insert(pair< int, list<string> > (a[i].num, str_list));
}
else {
iter->second.push_back(a[i].str);
}
}
for (map< int, list<string> >::iterator i = int_list_map.begin(); i != int_list_map.end(); i++) {
while (!i->second.empty()) {
cout << i->second.front() << " ";
i->second.pop_front();
}
}
delete [] a;
return 0;
} | |
Add a test for r158229 (overlapping fixits). This was PR10696! | // RUN: %clang_cc1 -fsyntax-only -std=c++11 2>&1 %s | FileCheck -strict-whitespace %s
struct A {
unsigned int a;
};
// PR10696
void testOverlappingInsertions(int b) {
A var = { b };
// CHECK: A var = { b };
// CHECK: ^
// CHECK: static_cast<unsigned int>( )
}
| |
Add Solution for Problem 035 | // 035. Search Insert Position
/**
* Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
*
* You may assume no duplicates in the array.
*
* Here are few examples.
* [1,3,5,6], 5 -> 2
* [1,3,5,6], 2 -> 1
* [1,3,5,6], 7 -> 4
* [1,3,5,6], 0 -> 0
*
* Tags: Array, Binary Search
*
* Similar Problems: (E) First Bad Version
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
if (n == 0)
{
return 0;
}
int left = 0, right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (target == nums[mid])
{
return mid;
}
else if (target > nums[mid])
{
left = mid + 1;
}
else // target < nums[mid]
{
right = mid - 1;
}
}
return left;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> nums;
nums.push_back(1);
nums.push_back(3);
nums.push_back(5);
nums.push_back(6);
int target = 0;
Solution mySolution;
int res = mySolution.searchInsert(nums, target);
cout << res << endl;
system("pause");
return 0;
}
| |
Print top view of the binary tree. | #include <stdio.h>
#include <map>
#include <vector>
typedef struct _NODE {
int data;
_NODE* left;
_NODE* right;
} NODE;
NODE* NewNode(int data) {
NODE* node = new NODE();
node->data = data;
node->left = node->right = nullptr;
return node;
}
void PrintTopViewUtil(NODE* node, int level, std::map<int, int>& map) {
if (node) {
PrintTopViewUtil(node->left, level - 1, map);
PrintTopViewUtil(node->right, level + 1, map);
map[level] = node->data;
}
}
void PrintTopView(NODE* node) {
std::map<int, int> map;
PrintTopViewUtil(node, 0, map);
std::map<int, int>::iterator it;
for (it = map.begin(); it != map.end(); it++) {
printf("%d ", it->second);
}
}
int main(int argc, char** argv) {
NODE* root = NewNode(1);
root->left = NewNode(2);
root->right = NewNode(3);
root->left->right = NewNode(4);
root->left->right->right = NewNode(5);
root->left->right->right->right = NewNode(6);
PrintTopView(root);
return 0;
}
| |
Add test program for slur parsing. | // Description: Print slur linking info
#include "humlib.h"
using namespace hum;
int main(int argc, char** argv) {
if (argc != 2) {
return 1;
}
HumdrumFile infile;
if (!infile.read(argv[1])) {
return 1;
}
cerr << "ANALYZING SLURS" << endl;
infile.analyzeKernSlurs();
cerr << "DONE ANALYZING SLURS" << endl;
return 0;
}
| |
Add a solution for time converter task | #include <iostream>
#include <string>
using namespace std;
int main()
{
string time12;
cin >> time12;
char p = time12[time12.size() - 2];
if (p == 'P')
{
int t = (int)time12[0] - '0';
t = t * 10;
t += (int)time12[1] - '0';
if (t < 12)
{
t += 12;
}
cout << t;
for (int i = 2; i < time12.size() - 2; i++)
{
cout << time12[i];
}
cout << endl;
}
else
{
int t = (int)time12[0] - '0';
t = t * 10;
t += (int)time12[1] - '0';
if (t == 12)
{
t = 0;
}
if (t < 10) cout << 0;
cout << t;
for (int i = 2; i < time12.size() - 2; i++)
{
cout << time12[i];
}
cout << endl;
}
return 0;
}
| |
Update example to demonstrate version numbers. | #include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
| #include <iostream>
#include <stdlib.h>
#include "exampleConfig.h"
#include "example.h"
/*
* Simple main program that demontrates how access
* CMake definitions (here the version number) from source code.
*/
int main() {
std::cout << "C++ Boiler Plate v"
<< PROJECT_VERSION_MAJOR
<< "."
<< PROJECT_VERSION_MINOR
<< std::endl;
std::system("cat ../LICENCE");
// Bring in the dummy class from the example source,
// just to show that it is accessible from main.cpp.
Dummy d = Dummy();
return d.doSomething() ? 0 : -1;
}
|
Add a solution of prob 2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/heap.hpp"
#include "../excercise04/sort/swap.hpp"
#include "priority_queue/priority_queue.hpp"
#define MIN_SIZE 100
#define MAX_SIZE 100000
#define SIZE_STEP 10
#define M 100
int main(void)
{
srand(time(NULL));
int *original = make_random_data(MAX_SIZE);
for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)
{
printf("SIZE OF DATA: %d\n", size_of_data);
{
const int capacity = size_of_data * 3;
int data[capacity];
memcpy(data, original, sizeof(int) * size_of_data);
convert_to_binary_max_heap(data, size_of_data);
clock_t before = clock();
int count = size_of_data;
for(int i = 0; i < M; ++i)
{
if(rand() % 2 == 0)
push_priority_queue(data, capacity, count, original[count]);
else
pop_priority_queue(data, count);
}
clock_t after = clock();
printf("Using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
}
{
int data[size_of_data];
memcpy(data, original, sizeof(int) * size_of_data);
clock_t before = clock();
int count = size_of_data;
for(int i = 0; i < M; ++i)
{
int max = data[0];
if(rand() % 2 == 0) /* Push */
{
data[count] = original[count++];
}
else /* Pop */
{
for(int i = 0; i < count; ++i)
if(data[i] > max)
{
max = data[i];
swap(data[i], data[count--]);
}
}
}
clock_t after = clock();
printf("Not using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
}
putchar('\n');
}
free_random_data(original);
return 0;
}
| |
Add solution to problem 15 in C++. | /*
* Lattice paths
*
* Starting in the top left corner of a 2×2 grid, and only being able to move
* to the right and down, there are exactly 6 routes to the bottom right corner.
*
* How many such routes are there through a 20×20 grid?
*/
#include <iostream>
using Long = unsigned long long int;
// Forward declaration
constexpr Long binomial(unsigned n, unsigned k);
constexpr unsigned cols = 20;
constexpr unsigned rows = 20;
int main(int, char **) {
// The number of paths through an n×m lattice is binomial(n+m, n).
auto paths = binomial(rows + cols, rows);
std::cout << "Project Euler - Problem 15: Lattice paths\n\n";
std::cout << "The number of paths through a " << rows << u8"×" << cols
<< " lattice is\n"
<< paths << '\n';
}
/**
* Compute the binomial coefficient <i>n</i> over <i>k</i>.
*
* @param n Parameter <i>n</i>.
* @param k Parameter <i>k</i>.
* @return The binomial coefficient, or 0 if <i>k > n</i>.
*/
constexpr Long binomial(unsigned n, unsigned k) {
if(k > n) {
return 0;
}
if(k > (n + 1) / 2) {
return binomial(n, n - k);
}
Long result = 1;
for(unsigned j = 1; j <= k; j++) {
result = result * (n + 1 - j) / j;
}
return result;
}
| |
Add the solution to "Mark and Toys". | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, money;
cin >> n >> money;
int *toys = new int[n];
for (int i = 0; i < n ; i++) {
cin >> toys[i];
}
sort(toys, toys + n);
int sum = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (sum + toys[i] > money) {
break;
}
else {
sum += toys[i];
count++;
}
}
cout << count;
delete [] toys;
return 0;
} | |
Add stub for engine test with test plan | // Copyright [2016] <Malinovsky Rodion>
#include "core/engine.h"
#include "gtest/gtest.h"
// Implement Engine test
// 1. Create a fixture, take base code from EngineLauncher
// 2. create cond var, which will emulate SIGINT
// 3. run engine -> create server socket
// 4. create tcp client and write data to server socket
// 5. verify output of the echo server.
#error missing-implementation
| |
Add test to check implicit upcasting of float16_t works. | #include "Halide.h"
#include <stdio.h>
#include <cmath>
using namespace Halide;
// FIXME: We should use a proper framework for this. See issue #898
void h_assert(bool condition, const char *msg) {
if (!condition) {
printf("FAIL: %s\n", msg);
abort();
}
}
int main() {
Halide::Func f;
Halide::Var x, y;
// Function mixes type, the float16_t should be implicitly upcast
// to a float
f(x, y) = 0.25f + float16_t(0.75);
// Use JIT for computation
Image<float> simple = f.realize(10, 3);
// Assert some basic properties of the image
h_assert(simple.extent(0) == 10, "invalid width");
h_assert(simple.extent(1) == 3, "invalid height");
h_assert(simple.min(0) == 0, "unexpected non zero min in x");
h_assert(simple.min(1) == 0, "unexpected non zero min in y");
h_assert(simple.channels() == 1, "invalid channels");
h_assert(simple.dimensions() == 2, "invalid number of dimensions");
// Read result back
for (int x = simple.min(0); x < simple.extent(0); ++x) {
for (int y = simple.min(1); y < simple.extent(1); ++y) {
h_assert(simple(x, y) == 1.0f, "Invalid value read back");
}
}
printf("Success!\n");
return 0;
}
| |
Add node test. Fails for now. Need to figure out a way to handle osgInit. |
#include <UnitTest++.h>
// Unit tests for vec classes
#include <OpenSG/OSGNode.h>
#include <OpenSG/OSGNameAttachment.h>
TEST(CreateNode)
{
OSG::NodePtr n = OSG::Node::create();
CHECK(n != OSG::NullFC);
}
// --- Cloning --- //
TEST(TreeCloningName)
{
OSG::NodePtr root = OSG::Node::create();
OSG::NodePtr child_node = OSG::Node::create();
root->addChild(child_node);
OSG::setName(root, "root");
OSG::setName(child_node, "child_node");
OSG::NodePtr new_root = OSG::cloneTree(root);
CHECK(new_root->getNChildren() == 1);
CHECK(new_root != root);
CHECK(new_root->getChild(0) != child_node);
std::string new_name = OSG::getName(new_root);
CHECK(new_name == "root");
}
| |
Add fuzzing driver to classads HTCONDOR-814 | #include "classad/classad_distribution.h"
#include <string>
#include <string.h>
#include <sys/types.h>
/* This is the driver for the classad fuzz tester.
* Note this is intentionally not in the cmake file, it should not be built
* by default.
*
* To use, compile all of classads with clang -fsanitize=fuzzer-nolink,address
* then recompile this one file with clang -fsanitize=fuzzer
* This adds a magic main function here.
* Then, just run ./a.out and let it run for a long time.
*/
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *input, size_t len) {
classad::ClassAdParser parser;
classad::ExprTree *tree;
std::string s(input, input + len);
tree = parser.ParseExpression(s);
delete tree;
return 0;
}
| |
Add 145 Binary Tree Postorder Traversal | // 145 Binary Tree PostOrder Tranversal
/**
* Given a binary tree, return the postorder traversal of its nodes' values.
*
* For example:
* Given binary tree {1,#,2,3},
* 1
* \
* 2
* /
* 3
* return [3,2,1].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
* Tag: Tree, Stack
*
* 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;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
s.push(root);
TreeNode* pre = NULL;
TreeNode* cur;
while (!s.empty()) {
cur = s.top();
// !pre coresponds to the root case, otherwise going down
if(!pre || pre->left == cur || pre->right == cur){
if(cur->left) // to left child if exist
s.push(cur->left); // t right child if left child doesnt exist
else if(cur->right)
s.push(cur->right);
else{ // this is the leaf
s.pop();
res.push_back(cur->val);
}
}
// going up from the left child
else if(cur->left == pre){
if(cur->right)
s.push(cur->right); // to the right child if exist
else{
s.pop();
res.push_back(cur->val);
}
}
// going up from the right side, done from this point dowm
else if(cur->right == pre){
s.pop();
res.push_back(cur->val);
}
pre = cur;
}
return res;
}
};
int main()
{
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(3);
root->right = new TreeNode(4);
root->left->right = new TreeNode(5);
Solution* sol = new Solution();
vector<int> res = sol->postorderTraversal(root);
for(int i = 0; i < res.size(); i++)
cout << res[i] << endl;
char c;
std::cin>>c;
return 0;
}
| |
Check if sum exists in two arrays | /*******************************************************************************
Sum exists in two arrays
========================
--------------------------------------------------------------------------------
Problem
=======
Given two arrays A[] and B[] and a number K, check if a + b == K where a belongs
to A and b to B.
--------------------------------------------------------------------------------
Time Complexity
===============
O(nlogn)
--------------------------------------------------------------------------------
Output
======
Array A is initially: 7 3 1 9 5 5 2
Array B is initially: 9 0 2 4 4 8 3
17 sum exists
20 sum does NOT exist
*******************************************************************************/
#include <stdio.h>
void printArray(int arr[], int n) {
for(int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
int partition(int arr[], int l, int r) {
int pivot = arr[r];
int i = l;
for (int j = l; j < r; j++) {
if (arr[j] <= pivot) {
swap(&arr[i++], &arr[j]);
}
}
swap(&arr[i], &arr[r]);
return i;
}
void quickSort(int arr[], int l, int r) {
if (l < r) {
int p = partition(arr, l, r);
quickSort(arr, l, p - 1);
quickSort(arr, p + 1, r);
}
}
bool binarySearch(int A[], int l, int r, int k) {
while (l <= r) {
int mid = (l + r)/2;
if (A[mid] == k) {
return true;
}
else if (A[mid] < k) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return false;
}
void checkSum(int A[], int B[], int n, int k) {
quickSort(A, 0, n - 1);
for (int i = 0; i < n; i++) {
int c = k - B[i];
if (binarySearch(A, 0, n - 1, c)) {
printf("%d sum exists\n", k);
return;
}
}
printf("%d sum does NOT exist\n", k);
}
int main() {
int A[] = {7, 3, 1, 9, 5, 5, 2};
int B[] = {9, 0, 2, 4, 4, 8, 3};
printf("Array A is initially: ");
printArray(A, 7);
printf("Array B is initially: ");
printArray(B, 7);
checkSum(A, B, 7, 17);
checkSum(A, B, 7, 20);
return 0;
}
| |
Add placeholder Windows path code | #include "path.hpp"
void Path::init()
{
// FIXME: unimplemented
}
#include <stdlib.h>
IFile *Path::openIFile(std::string const &path)
{
// FIXME: unimplemented
abort();
return NULL;
}
| |
Add test case to insure that implicit builtin declarations for C library functions aren't created in C++ | // RUN: clang -fsyntax-only -verify %s
void f() {
void *p = malloc(sizeof(int) * 10); // expected-error{{no matching function for call to 'malloc'}}
}
int malloc(double);
| |
ADD floating point format library example. | #include <cmath>
#include <fmt/format.h>
struct ieee754 {
int sign;
int biased_exponent;
uint64_t fraction;
uint64_t significand() const { return 0x10'0000'0000'0000 | fraction; }
int exponent() const { return biased_exponent - 1023; }
explicit ieee754(double value) {
auto bits = fmt::internal::bit_cast<uint64_t>(value);
sign = bits >> 63;
biased_exponent = static_cast<int>(bits >> 52) & 0x7ff;
fraction = bits & 0xf'ffff'ffff'ffff;
}
};
template <>
struct fmt::formatter<ieee754> {
auto parse(format_parse_context& ctx) { return ctx.begin(); }
auto format(ieee754 n, format_context& ctx) {
return format_to(ctx.out(), "{} {:011b} {:052b} [e = {}]", n.sign, n.biased_exponent, n.fraction, n.exponent());
}
};
int main(int argc, char* argv[]) {
fmt::print("{}\n", ieee754(M_PI));
return 0;
}
| |
Add test for Clamp function in math/utils | // Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <bandit/bandit.h>
#include "core/math/utils.h"
using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;
go_bandit([]() {
describe("::Clamp", []() {
it("should not do anything if in the range", [] {
AssertThat(Clamp(5.0f, 0.0f, 10.0f), Equals(5.0f));
AssertThat(Clamp(5, 0, 10), Equals(5));
});
it("should Clamp the value back in the range is value is smaller than min", [] {
AssertThat(Clamp(-5.0f, 0.0f, 10.0f), Equals(0.0f));
AssertThat(Clamp(-5, 0, 10), Equals(0));
});
it("should Clamp the value back in the range is value is bigger than max", [] {
AssertThat(Clamp(15.0f, 0.0f, 10.0f), Equals(10.0f));
AssertThat(Clamp(15, 0, 10), Equals(10));
});
});
}); | |
Set NoOutputs as the shape inference function for the FileSystemSetConfiguration op. | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
// Filesystem Ops ----------------------------------------------------------
REGISTER_OP("FileSystemSetConfiguration")
.Input("scheme: string")
.Input("key: string")
.Input("value: string")
.SetIsStateful()
.SetShapeFn(shape_inference::ScalarShape);
} // namespace tensorflow
| /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
// Filesystem Ops ----------------------------------------------------------
REGISTER_OP("FileSystemSetConfiguration")
.Input("scheme: string")
.Input("key: string")
.Input("value: string")
.SetIsStateful()
.SetShapeFn(shape_inference::NoOutputs);
} // namespace tensorflow
|
Fix missing qualifier for std::string | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/cuda_libdevice_path.h"
#include <stdlib.h>
#include <vector>
#include "tensorflow/core/platform/platform.h"
#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
std::vector<string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
return {TF_CUDA_TOOLKIT_PATH, string("/usr/local/cuda")};
#else
return {string("/usr/local/cuda")};
#endif
}
bool PreferPtxasFromPath() { return true; }
} // namespace tensorflow
| /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/cuda_libdevice_path.h"
#include <stdlib.h>
#include <string>
#include <vector>
#include "tensorflow/core/platform/platform.h"
#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
std::vector<std::string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
return {TF_CUDA_TOOLKIT_PATH, std::string("/usr/local/cuda")};
#else
return {std::string("/usr/local/cuda")};
#endif
}
bool PreferPtxasFromPath() { return true; }
} // namespace tensorflow
|
Add solution for chapter 17 test 10 | #include <iostream>
#include <bitset>
#include <vector>
using namespace std;
int main() {
vector<int> ivec = {1, 2, 3, 5, 8, 13, 21};
unsigned long val = 0UL;
for(auto i : ivec) {
val |= 1UL << i;
}
cout << val << endl;
bitset<32> b(val);
cout << b << endl;
bitset<32> bb;
for(auto i : ivec) {
bb.set(i);
}
cout << bb << endl;
if(b == bb) {
cout << "b == bb" << endl;
}
}
| |
Revert "Revert "add test file to show the max open files."" | /**
g++ pipe_fds.cpp -g -O0 -o pipe_fds
About the limits:
[winlin@dev6 srs]$ ulimit -n
1024
[winlin@dev6 srs]$ sudo lsof -p 21182
pipe_fds 21182 winlin 0u CHR 136,4 0t0 7 /dev/pts/4
pipe_fds 21182 winlin 1u CHR 136,4 0t0 7 /dev/pts/4
pipe_fds 21182 winlin 2u CHR 136,4 0t0 7 /dev/pts/4
pipe_fds 21182 winlin 3r FIFO 0,8 0t0 464543 pipe
pipe_fds 21182 winlin 1021r FIFO 0,8 0t0 465052 pipe
pipe_fds 21182 winlin 1022w FIFO 0,8 0t0 465052 pipe
So, all fds can be open is <1024, that is, can open 1023 files.
The 0, 1, 2 is opened file, so can open 1023-3=1020files,
Where 1020/2=512, so we can open 512 pipes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, char** argv)
{
if (argc <= 1) {
printf("Usage: %s <nb_pipes>\n"
" nb_pipes the pipes to open.\n"
"For example:\n"
" %s 1024\n", argv[0], argv[0]);
exit(-1);
}
int nb_pipes = ::atoi(argv[1]);
for (int i = 0; i < nb_pipes; i++) {
int fds[2];
if (pipe(fds) < 0) {
printf("failed to create pipe. i=%d, errno=%d(%s)\n",
i, errno, strerror(errno));
break;
}
}
printf("Press CTRL+C to quit, use bellow command to show the fds opened:\n");
printf(" sudo lsof -p %d\n", getpid());
sleep(-1);
return 0;
}
| |
Implement Outputting Text Program in C++ | #include <iostream>
using namespace std;
int main(){
cout << "Starting Program..." << flush;
cout << "This is the first line" << endl;
cout << "-Item 1. " << "-Item 2. " << "-Item 3." << endl;
cout << "The Program is ending." << endl;
return 0;
} | |
Add Chapter 25, exercise 7 | // Chapter 25, exercise 7: write out the hexadecimal values from 0 to 400; write
// out the hexadecimal values from -200 to 200
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout << "0 to 400:\n\n";
for (int i = 0; i<=400; ++i)
cout << hex << i << (i%16 ? '\t' : '\n');
cout << "\n\n-200 to 200:\n\n";
for (int i = -200; i<=200; ++i)
cout << hex << i << (i%8 ? '\t' : '\n');
}
| |
Add solution for chapter 16 test 48. | #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();
}
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;
}
| |
Add "run-time decorator pattern" sample | // Decorator (run-time)
class foo
{
public:
virtual void do_work() = 0;
};
class foo_concrete : public foo
{
public:
virtual void do_work()
{ }
};
class foo_decorator : public foo
{
public:
foo_decorator(foo& f)
: f(f)
{ }
virtual void do_work() {
// Do something else here to decorate
// the do_work function
f.do_work();
}
private:
foo& f;
};
void bar(foo& f)
{
f.do_work();
}
int main()
{
foo_concrete f;
foo_decorator decorated_f{f};
bar(decorated_f);
}
// Wrap a class with a decorator to extend its functionality.
//
// On [9-14], we define the class that we wish to decorate,
// `foo_concrete`, which implements the `foo` interface.
//
// The `foo_decorator` class, on [16-31], also implements the
// `foo` interface. This decorator class wraps any other `foo`
// object, which is passed to the constructor by reference[19-21]
// and decorates its member functions. That is, the
// `foo_decorator::do_work` function ([23-27]) simply calls the
// wrapped object's `do_work` function, while doing some extra work.
//
// To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on
// [40-41], and pass it to the `bar` function on [43], which takes a
// reference to any `foo` object and calls `do_work` on it. In this
// case, the call will be decorated by `foo_decorator`.
| |
Add a test for a subtle instantiation pattern that showed up within a Boost miscompile reduction. Clang already handles this correctly, but let's make sure it stays that way. | // RUN: %clang_cc1 -fsyntax-only -verify %s
// This is the function actually selected during overload resolution, and the
// only one defined.
template <typename T> void f(T*, int) {}
template <typename T> struct S;
template <typename T> struct S_ : S<T> { typedef int type; }; // expected-note{{in instantiation}}
template <typename T> struct S {
// Force T to have a complete type here so we can observe instantiations with
// incomplete types.
T t; // expected-error{{field has incomplete type}}
};
// Provide a bad class and an overload that instantiates templates with it.
class NoDefinition; // expected-note{{forward declaration}}
template <typename T> S_<NoDefinition>::type f(T*, NoDefinition*); // expected-note{{in instantiation}}
void test(int x) {
f(&x, 0);
}
| |
Add error test for inlined stages | #include "Halide.h"
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f, g;
Var x, y;
f(x) = x;
f(x) += x;
g(x) = f(x);
// f is inlined, so this schedule is bad.
f.vectorize(x, 4);
g.realize(10);
printf("There should have been an error\n");
return 0;
}
| |
Add test for (properly escaped) XML output. | // RUN: clang-format -output-replacements-xml -sort-includes %s > %t.xml
// RUN: FileCheck -strict-whitespace -input-file=%t.xml %s
// CHECK: <?xml
// CHECK-NEXT: {{<replacements.*incomplete_format='false'}}
// CHECK-NEXT: {{<replacement.*#include <a> #include <b><}}
// CHECK-NEXT: {{<replacement.*> <}}
// CHECK-NEXT: {{<replacement.*> <}}
#include <b>
#include <a>
int a;int*b;
| |
Add code to delete a Linked List | #include<iostream>
#include<cstdlib>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=NULL;
}
Node *insertElement(Node *head,int d){
Node *np=new Node(d);
Node *tmp=head;
if(head==NULL)
return np;
else
while(tmp->next)
tmp=tmp->next;
tmp->next=np;
return head;
}
void deleteList(Node *head){
while(head->next!=NULL){
Node *t=head;
cout<<"Freeing "<<t->data<<".\n";
head=head->next;
free(t);
}
cout<<"Freeing "<<head->data<<".\n";
free(head);
cout<<"The list is empty now.\n";
}
};
int main()
{
int n,p;
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);
}
np.deleteList(head);
}
| |
Add solution to the matching parentheses problem with multiple kinds of parentheses. This solution uses stack data structure | #include <iostream>
#include <stack>
#include <utility>
using std::cout;
using std::boolalpha;
using std::stack;
using std::pair;
class ParenthesesPair {
pair<char, char> parentheses;
public:
ParenthesesPair(char opening, char closing): parentheses(opening, closing) {}
char opening() const {
return parentheses.first;
}
char closing() const {
return parentheses.second;
}
bool operator==(const ParenthesesPair& other_parentheses_pair) const {
return opening() == other_parentheses_pair.opening() &&
closing() == other_parentheses_pair.closing();
}
};
ParenthesesPair parentheses_pairs[4] {
{'(', ')'},
{'[', ']'},
{'{', '}'},
{'<', '>'}
};
bool is_opening_parenthesis(char character) {
for (int i = 0; i < 4; ++i) {
if (parentheses_pairs[i].opening() == character) {
return true;
}
}
return false;
}
bool is_closing_parenthesis(char character) {
for (int i = 0; i < 4; ++i) {
if (parentheses_pairs[i].closing() == character) {
return true;
}
}
return false;
}
bool parentheses_match(const ParenthesesPair& parentheses_pair) {
for (int i = 0; i < 4; ++i) {
if (parentheses_pairs[i] == parentheses_pair) {
return true;
}
}
return false;
}
bool are_parentheses_correct(const char* expression) {
stack<char> opening_parentheses;
while (*expression) {
if (is_opening_parenthesis(*expression)) {
opening_parentheses.push(*expression);
} else if (is_closing_parenthesis(*expression)) {
if (!opening_parentheses.empty() &&
parentheses_match(ParenthesesPair(opening_parentheses.top(), *expression))) {
opening_parentheses.pop();
} else {
return false;
}
}
++expression;
}
return opening_parentheses.empty();
}
int main() {
cout << boolalpha << are_parentheses_correct("{(1 + 2) * [(2 + 3) / 2]}") << '\n';
cout << boolalpha << are_parentheses_correct("(1 + 2) * [(2 + 3] / 2]") << '\n';
cout << boolalpha << are_parentheses_correct("(1 + 2))( * [(2 + 3) / 2]") << '\n';
return 0;
}
| |
Add test for pointer qualification conversion. | //===------------------------- catch_ptr_02.cpp ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cassert>
struct A {};
A a;
const A ca = A();
void test1 ()
{
try
{
throw &a;
assert(false);
}
catch ( const A* )
{
}
catch ( A *)
{
assert (false);
}
}
void test2 ()
{
try
{
throw &a;
assert(false);
}
catch ( A* )
{
}
catch ( const A *)
{
assert (false);
}
}
void test3 ()
{
try
{
throw &ca;
assert(false);
}
catch ( const A* )
{
}
catch ( A *)
{
assert (false);
}
}
void test4 ()
{
try
{
throw &ca;
assert(false);
}
catch ( A *)
{
assert (false);
}
catch ( const A* )
{
}
}
int main()
{
test1();
test2();
test3();
test4();
}
| |
Add basic structure and interface | #include <iostream>
#include <string>
void findPossiblePlainTexts(const std::string&, int);
char* decrypt(const char*);
int main(int argc, char** argv)
{
std::cout << "Letter Frequency attack on additive cipher\n";
std::cout << "Enter the cipher text: ";
std::string ciphertext;
std::cin >> ciphertext;
int num;
std::cout << "Total possible plaintext sets: ";
std::cin >> num;
findPossiblePlainTexts(ciphertext, num);
}
void findPossiblePlainTexts(const std::string& cipherText, int num)
{
int i = 0;
const char *array = cipherText.c_str();
while (i < num) {
std::cout << i + 1 << decrypt(array) << "\n";
}
}
char* decrypt(const char *cipherText)
{
return nullptr;
}
| |
Insert libkldap catalog to translate dialogbox when we "add host" | /*
This file is part of KAddressBook.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kcmkabldapconfig.h"
#include <QtGui/QCheckBox>
#include <QtGui/QVBoxLayout>
#include <kaboutdata.h>
#include <kcomponentdata.h>
#include <kdemacros.h>
#include <kgenericfactory.h>
#include <klocale.h>
#include "ldapoptionswidget.h"
K_PLUGIN_FACTORY(KCMKabLdapConfigFactory, registerPlugin<KCMKabLdapConfig>();)
K_EXPORT_PLUGIN(KCMKabLdapConfigFactory( "kcmkabldapconfig" ))
KCMKabLdapConfig::KCMKabLdapConfig( QWidget *parent, const QVariantList & )
: KCModule( KCMKabLdapConfigFactory::componentData(), parent )
{
KGlobal::locale()->insertCatalog( "libkldap" );
QVBoxLayout *layout = new QVBoxLayout( this );
mConfigWidget = new LDAPOptionsWidget( this );
layout->addWidget( mConfigWidget );
connect( mConfigWidget, SIGNAL( changed( bool ) ), SIGNAL( changed( bool ) ) );
load();
KAboutData *about = new KAboutData( I18N_NOOP( "kcmkabldapconfig" ), 0,
ki18n( "KAB LDAP Configure Dialog" ),
0, KLocalizedString(), KAboutData::License_GPL,
ki18n( "(c), 2003 - 2004 Tobias Koenig" ) );
about->addAuthor( ki18n("Tobias Koenig"), KLocalizedString(), "tokoe@kde.org" );
setAboutData( about );
}
void KCMKabLdapConfig::load()
{
mConfigWidget->restoreSettings();
}
void KCMKabLdapConfig::save()
{
mConfigWidget->saveSettings();
}
void KCMKabLdapConfig::defaults()
{
mConfigWidget->defaults();
}
#include "kcmkabldapconfig.moc"
| |
Fix TPU VM tf-nightly build | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#endif
namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
} // namespace
} // namespace tpu
} // namespace tensorflow
| /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#include "tensorflow/core/platform/status.h"
#endif
namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
} // namespace
} // namespace tpu
} // namespace tensorflow
|
Check in test that demonstrates ABI break for std::function. | // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// REQUIRES: clang
// XFAIL: *
// This tests is meant to demonstrate an existing ABI bug between the
// C++03 and C++11 implementations of std::function. It is not a real test.
// RUN: %cxx -c %s -o %t.first.o %flags %compile_flags -std=c++03 -g
// RUN: %cxx -c %s -o %t.second.o -DWITH_MAIN %flags %compile_flags -g -std=c++11
// RUN: %cxx -o %t.exe %t.first.o %t.second.o %flags %link_flags -g
// RUN: %run
#include <functional>
#include <cassert>
typedef std::function<void(int)> Func;
Func CreateFunc();
#ifndef WITH_MAIN
// In C++03, the functions call operator, which is a part of the vtable,
// is defined as 'void operator()(int)', but in C++11 it's
// void operator()(int&&)'. So when the C++03 version is passed to C++11 code
// the value of the integer is interpreted as its address.
void test(int x) {
assert(x == 42);
}
Func CreateFunc() {
Func f(&test);
return f;
}
#else
int main() {
Func f = CreateFunc();
f(42);
}
#endif
| |
Add all greater nodes to a node in BST. | // Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node.
#include <iostream>
using namespace std;
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 displayInorder(struct Node *root){
if(root == NULL)
return;
displayInorder(root->left);
cout<<root->data<<" ";
displayInorder(root->right);
}
struct Node *insertNode(struct Node *root, int x){
struct Node *newptr = newNode(x);
if(root == NULL)
return newptr;
if(x > root->data)
root->right = insertNode(root->right, x);
else
root->left = insertNode(root->left, x);
return root;
}
void modifyBSTUtil(struct Node *root, int *sum){
// Base case
if(root == NULL)
return;
// Recur for right subtree
modifyBSTUtil(root->right, sum);
// Now *sum has sum of nodes in right subtree, add root->data to sum and update root->data
*sum = *sum + root->data;
root->data = *sum;
// Recur for left subtree
modifyBSTUtil(root->left, sum);
}
void modifyBST(struct Node *root){
int sum = 0;
modifyBSTUtil(root, &sum);
}
int main(){
struct Node *root = NULL;
int num, size;
cout<<"Enter the number of elements in BST\n";
cin>>size;
cout<<"Enter the elements of BST\n";
while(size--){
cin>>num;
root = insertNode(root, num);
}
cout<<"Inorder traversal of original BST is\n";
displayInorder(root);
modifyBST(root);
cout<<"\nInorder traversal of modified BST is\n";
displayInorder(root);
return 0;
}
| |
Add longest increasing subsequence in c++ | #include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[9] = { 1, 4, 2, 3, 8, 3, 4, 1, 9}; // LIS should be {1, 2, 3, 8, 9}
int f[9] = {}, LIS[9] = {}, max = 1, L = 0; // f used to record previous location of LIS
for (int i = 0; i < 9; i++)
{
LIS[i] = 1;
f[i] = i;
}
for (int i = 1; i < 9; i++)
{
for (int j = 0; j <= i; j++)
{
if (arr[j] < arr[i] && LIS[j]+1 > LIS[i])
{
LIS[i] = LIS[j] + 1;
if (LIS[i] > max)
{
max = LIS[i];
L = i;
}
f[i] = j;
}
}
}
int tmp = L;
while(LIS[L]--)
{
cout << arr[tmp] << " ";
tmp = f[tmp];
}
cout << endl;
return 0;
}
| |
Fix includes for compiling the bitcoin import stub used when berkeley db is not available | #include <algorithm>
#include <bts/import_bitcoin_wallet.hpp>
#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>
#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>
namespace bts { namespace bitcoin {
std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
} } // bts::bitcoin
| #include <algorithm>
#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>
#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/filesystem.hpp>
namespace bts { namespace bitcoin {
std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
} } // bts::bitcoin
|
Add Solution for Problem 058 | // 58. Length of Last Word
/**
* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
*
* If the last word does not exist, return 0.
*
* Note: A word is defined as a character sequence consists of non-space characters only.
*
* For example,
* Given s = "Hello World",
* return 5.
*
* Tags: String
*
* Author: Kuang Qin
*/
#include "stdafx.h"
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size();
if (n == 0)
{
return 0;
}
// remove trailing spaces
int last = n - 1;
while (last >= 0 && s[last] == ' ')
{
last--;
}
// start to count of the last word
int len = 0;
while (last >= 0 && s[last] != ' ')
{
len++;
last--;
}
return len;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| |
Add test for Stereographic projection for real. | //
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "StereographicProjection.h"
#include "ViewportParams.h"
#include "TestUtils.h"
namespace Marble
{
class StereographicProjectionTest : public QObject
{
Q_OBJECT
private slots:
void screenCoordinatesOfCenter_data();
void screenCoordinatesOfCenter();
};
void StereographicProjectionTest::screenCoordinatesOfCenter_data()
{
ViewportParams stereographic;
stereographic.setProjection( Stereographic );
QTest::addColumn<QPoint>( "screenCoordinates" );
QTest::addColumn<GeoDataCoordinates>( "expected" );
addRow() << QPoint( 5, 15 ) << GeoDataCoordinates( -45, 76.135, 0, GeoDataCoordinates::Degree );
addRow() << QPoint( 15, 5 ) << GeoDataCoordinates( 135, 76.135, 0, GeoDataCoordinates::Degree );
}
void StereographicProjectionTest::screenCoordinatesOfCenter()
{
QFETCH( QPoint, screenCoordinates );
QFETCH( GeoDataCoordinates, expected );
ViewportParams viewport;
viewport.setProjection( Stereographic );
viewport.setRadius( 180 / 4 ); // for easy mapping of lon <-> x
viewport.setSize( QSize( 20, 20 ) );
viewport.centerOn( 0 * DEG2RAD, 90 * DEG2RAD );
{
qreal lon, lat;
const bool retval = viewport.geoCoordinates( screenCoordinates.x(), screenCoordinates.y(), lon, lat, GeoDataCoordinates::Degree );
QVERIFY( retval ); // we want valid coordinates
QCOMPARE( lon, expected.longitude( GeoDataCoordinates::Degree ) );
QFUZZYCOMPARE( lat, expected.latitude( GeoDataCoordinates::Degree ), 0.0001 );
}
}
}
QTEST_MAIN( Marble::StereographicProjectionTest )
#include "StereographicProjectionTest.moc"
| |
Call OpenExternal with new true default to activate arg | // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"
using content::BrowserThread;
namespace atom {
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}
bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
const GURL& url,
int render_process_id,
int render_view_id,
bool is_main_frame,
ui::PageTransition transition,
bool has_user_gesture) {
GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(
base::IgnoreResult(platform_util::OpenExternal), escaped_url, false));
return true;
}
content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) {
return new LoginHandler(auth_info, request);
}
} // namespace atom
| // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"
using content::BrowserThread;
namespace atom {
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}
bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
const GURL& url,
int render_process_id,
int render_view_id,
bool is_main_frame,
ui::PageTransition transition,
bool has_user_gesture) {
GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(
base::IgnoreResult(platform_util::OpenExternal), escaped_url, true));
return true;
}
content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) {
return new LoginHandler(auth_info, request);
}
} // namespace atom
|
Add empty chip::lowLevelInitialization() for STM32L0 | /**
* \file
* \brief chip::lowLevelInitialization() implementation for STM32L0
*
* \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/lowLevelInitialization.hpp"
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
}
} // namespace chip
} // namespace distortos
| |
Remove All Adjacent Duplicates In String | class Solution {
public:
string removeDuplicates(string s) {
int index = 0;
while (!s.empty() && index < (s.size()-1)) {
if (s[index] == s[index+1]) {
if ((index+2) < s.size()) {
s = s.substr(0, index) + s.substr(index+2);
} else {
s = s.substr(0, index);
}
if (index > 0)
--index;
} else {
++index;
}
}
return s;
}
};
| |
Add pseudo code for performing an Inverse Kinematics analysis. Perform IK without using a Tool or any Analyses. |
#include <OpenSim/OpenSim.h>
main() {
// A study is the top level component that contains the model and other
// computational components.
Study inverseKinematicsStudy;
Model model("subject_01.osim");
inverseKinematicsStudy.addComponent(model);
// A data Source component wraps a TimeSeriesTables and access rows by time
// Each column is given its own Output by name unless specified otherwise
Source markers("subject01_trial2.trc");
// Source markers("subject01_trial2.trc", Vec2(0, 5)); // by range
// Source markers("subject01_trial2.trc", {"aa, "ai", ac"}); //by name
inverseKinematicsStudy.addComponent(markers);
// InverseKinematicsSolver is wrapped by a component (or one itself?)
// dependency on model, and marker inputs (outputs of a source) wired
// upon connect
InverseKinematics ik(model, markers);
inverseKinematicsStudy.addComponent(ik);
// Now handle IK Outputs
// Extract the outputs from the model and the state via a reporter
// Do not need to know type BUT cannot combine different types
// Coordinates are doubles and modelMarkers are Vec3's
OutputReporter coordinateReporter();
OutputReporter modelMarkerReporter();
// Output coordinates from IK
for(const auto& coord: mode.getCoordinates())
coordinateReporter.addOutput(coord.getOutput("value"));
inverseKinematicsStudy.addComponent(coordinateReporter);
// Output model marker locations from IK
for (const auto& marker : mode.getMarkers())
modelMarkerReporter.addOutputs(marker.getOutput("location"));
inverseKinematicsStudy.addComponent(modelMarkerReporter);
State& state = inverseKinematicsStudy.initSystem();
// March through time to solve for the state's coordinates
for (double t : markers.getTimes()) {
state.setTime(t);
ik.track(state);
inverseKinematicsStudy.realizeReport(state);
}
// write results to file
FileAdapter fileAdapter;
fileAdapter.write("s01_tr2_IK.mot", coordinateReporter.getReport());
fileAdapter.write("s01_tr2_markers.trc", modelMarkerReporter.getReport());
}
| |
Add C++11 solution for Nov. 2013 Bronze Problem 2 | #include <fstream>
#include <map>
using namespace std;
int main() {
ifstream cin("milktemp.in");
ofstream cout("milktemp.out");
int num_cows, cold, comfortable, hot;
cin >> num_cows >> cold >> comfortable >> hot;
int cold_change = comfortable - cold;
int hot_change = hot - comfortable;
map<int, int> changes;
for (int i = 0; i < num_cows; i++) {
int cold_thresh, hot_thresh;
cin >> cold_thresh >> hot_thresh;
changes[cold_thresh] += cold_change;
changes[hot_thresh + 1] += hot_change;
}
int current = num_cows * cold;
int max = current;
for (const auto &change : changes) {
current += change.second;
if (current > max)
max = current;
}
cout << max << endl;
return 0;
}
| |
Test case for my last patch. | // RUN: clang-cc -fsyntax-only -verify %s
class Base { // expected-error {{cannot define the implicit default assignment operator for 'class Base'}} \
// expected-note {{synthesized method is first required here}}
int &ref; // expected-note {{declared at}}
};
class X : Base { // // expected-error {{cannot define the implicit default assignment operator for 'class X'}}
public:
X();
const int cint; // expected-note {{declared at}}
};
struct Y : X {
Y();
Y& operator=(const Y&);
Y& operator=(volatile Y&);
Y& operator=(const volatile Y&);
Y& operator=(Y&);
};
class Z : Y {};
Z z1;
Z z2;
// Test1
void f(X x, const X cx) {
x = cx; // expected-note {{synthesized method is first required here}}
x = cx;
z1 = z2;
}
// Test2
class T {};
T t1;
T t2;
void g()
{
t1 = t2;
}
// Test3
class V {
public:
V();
V &operator = (V &b);
};
class W : V {};
W w1, w2;
void h()
{
w1 = w2;
}
// Test4
class B1 {
public:
B1();
B1 &operator = (B1 b);
};
class D1 : B1 {};
D1 d1, d2;
void i()
{
d1 = d2;
}
| |
Fix bug found by test. | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>
// Library/third-party includes
// - none
// Standard includes
#include <sstream>
namespace osvr {
namespace routing {
const char *getTypeName(PathNode const &node) {
return elements::getTypeName(node.value());
}
static inline void buildPathRecursively(PathNode const &node,
std::ostream &os) {
auto parent = node.getParent();
if (parent) {
buildPathRecursively(*parent, os);
}
if (!node.isRoot()) {
os << getPathSeparator() << node.getName();
}
}
std::string getFullPath(PathNode const &node) {
std::ostringstream os;
buildPathRecursively(node, os);
return os.str();
}
} // namespace routing
} // namespace osvr | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>
// Library/third-party includes
// - none
// Standard includes
#include <sstream>
namespace osvr {
namespace routing {
const char *getTypeName(PathNode const &node) {
return elements::getTypeName(node.value());
}
static inline void buildPathRecursively(PathNode const &node,
std::ostream &os) {
auto parent = node.getParent();
if (parent) {
buildPathRecursively(*parent, os);
}
if (!node.isRoot()) {
os << getPathSeparator() << node.getName();
}
}
std::string getFullPath(PathNode const &node) {
/// Special case the root
if (node.isRoot()) {
return getPathSeparator();
}
std::ostringstream os;
buildPathRecursively(node, os);
return os.str();
}
} // namespace routing
} // namespace osvr |
Define extern char **environ for OSX, which doesn't define it in a header | #include "env_vars.hh"
namespace Kakoune
{
EnvVarMap get_env_vars()
{
EnvVarMap env_vars;
for (char** it = environ; *it; ++it)
{
const char* name = *it;
const char* value = name;
while (*value != 0 and *value != '=')
++value;
env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
}
return env_vars;
}
}
| #include "env_vars.hh"
#if __APPLE__
extern char **environ;
#endif
namespace Kakoune
{
EnvVarMap get_env_vars()
{
EnvVarMap env_vars;
for (char** it = environ; *it; ++it)
{
const char* name = *it;
const char* value = name;
while (*value != 0 and *value != '=')
++value;
env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
}
return env_vars;
}
}
|
Add warning about "nix" being experimental | #include <algorithm>
#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"
namespace nix {
struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
{
mkFlag('h', "help", "show usage information", [=]() {
printHelp(programName, std::cout);
throw Exit();
});
mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
}
};
void mainWrapped(int argc, char * * argv)
{
initNix();
initGC();
string programName = baseNameOf(argv[0]);
{
auto legacy = (*RegisterLegacyCommand::commands)[programName];
if (legacy) return legacy(argc, argv);
}
NixArgs args;
args.parseCmdline(argvToStrings(argc, argv));
assert(args.command);
args.command->prepare();
args.command->run();
}
}
int main(int argc, char * * argv)
{
return nix::handleExceptions(argv[0], [&]() {
nix::mainWrapped(argc, argv);
});
}
| #include <algorithm>
#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"
namespace nix {
struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
{
mkFlag('h', "help", "show usage information", [=]() {
printHelp(programName, std::cout);
std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n";
throw Exit();
});
mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
}
};
void mainWrapped(int argc, char * * argv)
{
initNix();
initGC();
string programName = baseNameOf(argv[0]);
{
auto legacy = (*RegisterLegacyCommand::commands)[programName];
if (legacy) return legacy(argc, argv);
}
NixArgs args;
args.parseCmdline(argvToStrings(argc, argv));
assert(args.command);
args.command->prepare();
args.command->run();
}
}
int main(int argc, char * * argv)
{
return nix::handleExceptions(argv[0], [&]() {
nix::mainWrapped(argc, argv);
});
}
|
Update the ordering relationships example. | #include <iostream>
#include <thread>
#include <atomic>
#include <vector>
std::vector<int> data;
bool data_ready = false;
void reader_thread()
{
int i = 1;
while (!data_ready) // 1
{
std::cout << "Reader loop " << i << std::endl;
++i;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::cout << "Data value: " << data[0] << std::endl; // 2
}
void writer_thread()
{
// Pretend to do some work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
data.push_back(42); // 3
data_ready = true; // 4
}
int main()
{
std::thread reader(reader_thread);
std::thread writer(writer_thread);
writer.join();
reader.join();
std::cout << "Press any key to continue...\n";
std::getchar();
} | #include <iostream>
#include <thread>
#include <atomic>
#include <vector>
std::vector<int> data;
bool data_ready = false;
void reader_thread()
{
int i = 1;
while (!data_ready) // 1
{
std::cout << "Reader loop " << i << std::endl;
++i;
}
std::cout << "Data value: " << data[0] << std::endl; // 2
}
void writer_thread()
{
// Pretend to do some work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
data.push_back(42); // 3
data_ready = true; // 4
}
int main()
{
std::thread reader(reader_thread);
std::thread writer(writer_thread);
writer.join();
reader.join();
std::cout << "Press any key to continue...\n";
std::getchar();
} |
Use range based for loop instead of raw loop | #include "grid.h"
#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"
namespace bejeweled {
Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
for (int i = 0; i < width_; ++i) {
grid_.emplace_back();
for (int j = 0; j < height_; ++j) {
grid_[i].emplace_back();
}
}
InitJewels(renderer);
}
void Grid::Render(graphics::Renderer &renderer) {
for (int i = 0; i < width_; ++i) {
for (int j = 0; j < height_; ++j) {
grid_[i][j].Render(renderer);
}
}
}
void Grid::InitJewels(graphics::Renderer &renderer) {
for (int i = 0; i < width_; ++i) {
for (int j = 0; j < height_; ++j) {
grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
}
}
}
} //namespace bejeweled
| #include "grid.h"
#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"
namespace bejeweled {
Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
for (int i = 0; i < width_; ++i) {
grid_.emplace_back();
for (int j = 0; j < height_; ++j) {
grid_[i].emplace_back();
}
}
InitJewels(renderer);
}
void Grid::Render(graphics::Renderer &renderer) {
for (auto& column : grid_) {
for (auto& cell : column) {
cell.Render(renderer);
}
}
}
void Grid::InitJewels(graphics::Renderer &renderer) {
for (int i = 0; i < width_; ++i) {
for (int j = 0; j < height_; ++j) {
grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
}
}
}
} //namespace bejeweled
|
Test override and override final | class base {
public:
virtual int foo(int a)
{ return 4 + a; }
int bar(int a)
{ return a - 2; }
};
class sub final : public base {
public:
virtual int foo(int a) override
{ return 8 + 2 * a; };
};
class sub2 final : public base {
public:
virtual int foo(int a) override final
{ return 8 + 2 * a; };
};
int main(void)
{
base b;
sub s;
return (b.foo(2) * 2 == s.foo(2)) ? 0 : 1;
}
| class base {
public:
virtual int foo(int a)
{ return 4 + a; }
int bar(int a)
{ return a - 2; }
};
class sub final : public base {
public:
virtual int foo(int a) override
{ return 8 + 2 * a; };
};
class sub2 final : public base {
public:
virtual int foo(int a) override final
{ return 8 + 2 * a; };
};
int main(void)
{
base b;
sub s;
sub2 t;
return (b.foo(2) * 2 == s.foo(2) && b.foo(2) * 2 == t.foo(2) ) ? 0 : 1;
}
|
Change len to proper type in RapidJSON test | #include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>
using namespace std;
using namespace rapidjson;
int main() {
FILE* fp = std::fopen("./1.json", "r");
char buffer[65536];
FileReadStream frs(fp, buffer, sizeof(buffer));
Document jobj;
jobj.ParseStream(frs);
const Value &coordinates = jobj["coordinates"];
int len = coordinates.Size();
double x = 0, y = 0, z = 0;
for (SizeType i = 0; i < len; i++) {
const Value &coord = coordinates[i];
x += coord["x"].GetDouble();
y += coord["y"].GetDouble();
z += coord["z"].GetDouble();
}
std::cout << x / len << std::endl;
std::cout << y / len << std::endl;
std::cout << z / len << std::endl;
fclose(fp);
return 0;
}
| #include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>
using namespace std;
using namespace rapidjson;
int main() {
FILE* fp = std::fopen("./1.json", "r");
char buffer[65536];
FileReadStream frs(fp, buffer, sizeof(buffer));
Document jobj;
jobj.ParseStream(frs);
const Value &coordinates = jobj["coordinates"];
SizeType len = coordinates.Size();
double x = 0, y = 0, z = 0;
for (SizeType i = 0; i < len; i++) {
const Value &coord = coordinates[i];
x += coord["x"].GetDouble();
y += coord["y"].GetDouble();
z += coord["z"].GetDouble();
}
std::cout << x / len << std::endl;
std::cout << y / len << std::endl;
std::cout << z / len << std::endl;
fclose(fp);
return 0;
}
|
Mark test as a long-test | //===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
// <streambuf>
// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;
// void pbump(int n);
#include <sstream>
#include <cassert>
#include "test_macros.h"
struct SB : std::stringbuf
{
SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
const char* pubpbase() const { return pbase(); }
const char* pubpptr() const { return pptr(); }
};
int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
try {
#endif
std::string str(2147483648, 'a');
SB sb;
sb.str(str);
assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
}
catch (const std::bad_alloc &) {}
#endif
}
| //===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
// <streambuf>
// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;
// void pbump(int n);
//
// REQUIRES: long_tests
#include <sstream>
#include <cassert>
#include "test_macros.h"
struct SB : std::stringbuf
{
SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
const char* pubpbase() const { return pbase(); }
const char* pubpptr() const { return pptr(); }
};
int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
try {
#endif
std::string str(2147483648, 'a');
SB sb;
sb.str(str);
assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
}
catch (const std::bad_alloc &) {}
#endif
}
|
Call physics engine with every tick | #include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
World *world = nullptr;
World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
std::cerr << "World has started"<<std::endl;
for (int i=0; i< SDLK_LAST; ++i) {
keyState[i] = false;
}
}
void World::init() {
world = new World();
}
GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
GameObject * object = new GameObject(&physics, behavior, bdef);
objects.emplace_back(object);
return objects.back().get();
}
bool World::isKeyDown(int keyCode) {
return keyState[keyCode];
}
void World::keyEvent(int keyCode, bool pressed) {
if (keyCode < SDLK_LAST) {
keyState[keyCode] = pressed;
}else {
std::cerr << "Key code out of range "<<keyCode<<"\n";
}
}
void World::tick() {
for (auto &obj : objects) {
obj->tick(this);
std::cerr << obj->printPosition()<<std::endl;
}
//for(auto &gameObject:objects){
//
//}
// Gets called every frame
}
}
| #include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
World *world = nullptr;
World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
std::cerr << "World has started"<<std::endl;
for (int i=0; i< SDLK_LAST; ++i) {
keyState[i] = false;
}
}
void World::init() {
world = new World();
}
GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
GameObject * object = new GameObject(&physics, behavior, bdef);
objects.emplace_back(object);
return objects.back().get();
}
bool World::isKeyDown(int keyCode) {
return keyState[keyCode];
}
void World::keyEvent(int keyCode, bool pressed) {
if (keyCode < SDLK_LAST) {
keyState[keyCode] = pressed;
}else {
std::cerr << "Key code out of range "<<keyCode<<"\n";
}
}
void World::tick() {
physics.Step(0.0166666, 1, 1);
for (auto &obj : objects) {
obj->tick(this);
std::cerr << obj->printPosition()<<std::endl;
}
//for(auto &gameObject:objects){
//
//}
// Gets called every frame
}
}
|
Reduce the test to its minimum. | //---------------------------- block_matrix_array_02.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- block_matrix_array_02.cc ---------------------------
// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// the test also didn't link before, due to some functions that were
// either missing or in the wrong place
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code
#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition_block.h>
#include <iostream>
#include <fstream>
int main ()
{
std::ofstream logfile("block_matrix_array_02.output");
deallog.attach(logfile);
deallog.depth_console(0);
BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
deallog << i << std::endl;
// the following did not compile
// right away
PreconditionBlockSSOR<BlockMatrixArray<SparseMatrix<double> > > p;
return 0;
}
| //---------------------------- block_matrix_array_02.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- block_matrix_array_02.cc ---------------------------
// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code
#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <iostream>
#include <fstream>
int main ()
{
std::ofstream logfile("block_matrix_array_02.output");
deallog.attach(logfile);
deallog.depth_console(0);
BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
deallog << i << std::endl;
return 0;
}
|
Use provided message for UnknownError. | // 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 "modules/push_messaging/PushError.h"
#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"
namespace blink {
PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
switch (webError->errorType) {
case WebPushError::ErrorTypeAbort:
return DOMException::create(AbortError, webError->message);
case WebPushError::ErrorTypeNetwork:
return DOMException::create(NetworkError, webError->message);
case WebPushError::ErrorTypeNotFound:
return DOMException::create(NotFoundError, webError->message);
case WebPushError::ErrorTypeUnknown:
return DOMException::create(UnknownError);
}
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
}
void PushError::dispose(WebType* webErrorRaw)
{
delete webErrorRaw;
}
} // 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 "modules/push_messaging/PushError.h"
#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"
namespace blink {
PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
switch (webError->errorType) {
case WebPushError::ErrorTypeAbort:
return DOMException::create(AbortError, webError->message);
case WebPushError::ErrorTypeNetwork:
return DOMException::create(NetworkError, webError->message);
case WebPushError::ErrorTypeNotFound:
return DOMException::create(NotFoundError, webError->message);
case WebPushError::ErrorTypeUnknown:
return DOMException::create(UnknownError, webError->message);
}
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
}
void PushError::dispose(WebType* webErrorRaw)
{
delete webErrorRaw;
}
} // namespace blink
|
Revert "Remove simple to fix warnings" |
#include "MainWindow.h"
#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>
#include <fiblib/Fibonacci.h>
MainWindow::MainWindow()
{
// Create content widget
QWidget * content = new QWidget(this);
setCentralWidget(content);
// Create layout
QBoxLayout * boxLayout = new QVBoxLayout();
content->setLayout(boxLayout);
// Add title
QLabel * title = new QLabel(content);
title->setText("Please enter n:");
boxLayout->addWidget(title);
// Add input field
QSpinBox * editNumber = new QSpinBox(content);
editNumber->setMinimum(0);
boxLayout->addWidget(editNumber);
// Add result
QLabel * result = new QLabel(content);
result->setText("Fib(0) = 0");
boxLayout->addWidget(result);
// When input changes, calculate and output the fibonacci number
connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
{
fiblib::Fibonacci fib;
result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(static_cast<unsigned int>(n))));
});
}
MainWindow::~MainWindow()
{
}
|
#include "MainWindow.h"
#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>
#include <fiblib/Fibonacci.h>
MainWindow::MainWindow()
{
// Create content widget
QWidget * content = new QWidget(this);
setCentralWidget(content);
// Create layout
QBoxLayout * layout = new QVBoxLayout();
content->setLayout(layout);
// Add title
QLabel * title = new QLabel(content);
title->setText("Please enter n:");
layout->addWidget(title);
// Add input field
QSpinBox * editNumber = new QSpinBox(content);
editNumber->setMinimum(0);
layout->addWidget(editNumber);
// Add result
QLabel * result = new QLabel(content);
result->setText("Fib(0) = 0");
layout->addWidget(result);
// When input changes, calculate and output the fibonacci number
connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
{
fiblib::Fibonacci fib;
result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(n)));
});
}
MainWindow::~MainWindow()
{
}
|
Change C header to C++ header | #include <rusql/connection.hpp>
#include <assert.h>
int main(int argc, char *argv[]) {
assert(argc == 5);
try {
rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
} catch(...) {
return 0;
}
return 1;
}
| #include <rusql/connection.hpp>
#include <cassert>
int main(int argc, char *argv[]) {
assert(argc == 5);
try {
rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
} catch(...) {
return 0;
}
return 1;
}
|
Initialize a variable in PrinterBasicInfo. | // 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 "printing/backend/print_backend.h"
namespace printing {
PrinterBasicInfo::PrinterBasicInfo() : printer_status(0) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
} // namespace printing
| // 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 "printing/backend/print_backend.h"
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
} // namespace printing
|
Add support for quit command | #include <QApplication>
#include <QIcon>
#include <QSettings>
#include <QString>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("SheetMusicViewer");
QCoreApplication::setApplicationName("SheetMusicViewer");
QSettings settings;
QString customIconTheme = settings.value("customIconTheme").toString();
if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
{
QIcon::setThemeName(customIconTheme);
}
else
{
settings.setValue("customIconTheme", QString());
}
QString customStyle = settings.value("customStyle").toString();
if (!customStyle.isNull() && !customStyle.isEmpty())
{
QApplication::setStyle(customStyle);
}
else
{
settings.setValue("customStyle", QString());
}
MainWindow w;
w.show();
return a.exec();
}
| #include <QApplication>
#include <QIcon>
#include <QProcess>
#include <QSettings>
#include <QString>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("SheetMusicViewer");
QCoreApplication::setApplicationName("SheetMusicViewer");
QSettings settings;
QString customIconTheme = settings.value("customIconTheme").toString();
if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
{
QIcon::setThemeName(customIconTheme);
}
else
{
settings.setValue("customIconTheme", QString());
}
QString customStyle = settings.value("customStyle").toString();
if (!customStyle.isNull() && !customStyle.isEmpty())
{
QApplication::setStyle(customStyle);
}
else
{
settings.setValue("customStyle", QString());
}
QString quitCommand = settings.value("quitCommand").toString();
if (quitCommand.isNull() || quitCommand.isEmpty())
{
settings.setValue("quitCommand", QString());
}
MainWindow w;
w.show();
int ret = a.exec();
if ((ret == 0) && !quitCommand.isNull() && !quitCommand.isEmpty())
{
QProcess::execute(quitCommand);
}
return ret;
}
|
Use Kalman estimate in LQR-Kalman test | #include "gtest/gtest.h"
#include "test_convergence.h"
// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
public:
void simulate() {
for(unsigned int i = 0; i < m_N; ++i) {
auto u = m_lqr->control_calculate(m_x);
m_x = m_bicycle->x_next(m_x, u);
auto z = m_bicycle->y(m_x);
z(0) += m_r0(m_gen);
z(1) += m_r1(m_gen);
m_kalman->time_update(u);
m_kalman->measurement_update(z);
}
}
};
TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
simulate();
test_state_near(m_kalman->x(), x_true());
}
INSTANTIATE_TEST_CASE_P(
ConvergenceRange_1_9,
LqrKalmanConvergenceTest,
::testing::Range(0.5, 9.5, 0.5));
| #include "gtest/gtest.h"
#include "test_convergence.h"
// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
public:
void simulate() {
for(unsigned int i = 0; i < m_N; ++i) {
auto u = m_lqr->control_calculate(m_kalman->x());
m_x = m_bicycle->x_next(m_x, u);
auto z = m_bicycle->y(m_x);
z(0) += m_r0(m_gen);
z(1) += m_r1(m_gen);
m_kalman->time_update(u);
m_kalman->measurement_update(z);
}
}
};
TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
simulate();
test_state_near(m_kalman->x(), x_true());
}
INSTANTIATE_TEST_CASE_P(
ConvergenceRange_1_9,
LqrKalmanConvergenceTest,
::testing::Range(0.5, 9.5, 0.5));
|
Revert "Vehicle ammo prefix VAMMOTYPE_ to VEQUIPMENTAMMOTYPE_" | #include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"
namespace OpenApoc
{
const UString &VAmmoType::getPrefix()
{
static UString prefix = "VEQUIPMENTAMMOTYPE_";
return prefix;
}
const UString &VAmmoType::getTypeName()
{
static UString name = "VAmmoType";
return name;
}
sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
auto it = state.vehicle_ammo.find(id);
if (it == state.vehicle_ammo.end())
{
LogError("No vammo type matching ID \"%s\"", id);
return nullptr;
}
return it->second;
}
}
| #include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"
namespace OpenApoc
{
const UString &VAmmoType::getPrefix()
{
static UString prefix = "VAMMOTYPE_";
return prefix;
}
const UString &VAmmoType::getTypeName()
{
static UString name = "VAmmoType";
return name;
}
sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
auto it = state.vehicle_ammo.find(id);
if (it == state.vehicle_ammo.end())
{
LogError("No vammo type matching ID \"%s\"", id);
return nullptr;
}
return it->second;
}
}
|
Make buttons look slightly better on N8 | #include "hapticbutton.h"
#include <QPainter>
HapticButton::HapticButton(const QString &label) :
QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
setMinimumSize(100, 100);
}
void HapticButton::mousePressEvent(QMouseEvent *)
{
if (m_checkable) {
m_checked = !m_checked;
emit toggled(m_checked);
} else {
emit clicked();
}
}
void HapticButton::paintEvent(QPaintEvent *)
{
QPainter paint(this);
QRect r(0, 0, width()-1, height()-1);
paint.drawRoundedRect(r, 10, 10);
paint.drawText(r, Qt::AlignCenter, m_label);
}
| #include "hapticbutton.h"
#include <QPainter>
HapticButton::HapticButton(const QString &label) :
QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
setMinimumSize(100, 100);
}
void HapticButton::mousePressEvent(QMouseEvent *)
{
if (m_checkable) {
m_checked = !m_checked;
emit toggled(m_checked);
} else {
emit clicked();
}
}
void HapticButton::paintEvent(QPaintEvent *)
{
QPainter paint(this);
QRect r(1, 1, width()-2, height()-2);
paint.drawRoundedRect(r, 10, 10);
paint.drawText(r, Qt::AlignCenter, m_label);
}
|
Fix path test on windows | #include <configure/utils/path.hpp>
#include <configure/error.hpp>
BOOST_AUTO_TEST_CASE(path)
{
using namespace configure::utils;
BOOST_CHECK_THROW(
relative_path("pif", "/paf"),
configure::error::InvalidPath
);
BOOST_CHECK_THROW(
relative_path("/pif", "paf"),
configure::error::InvalidPath
);
BOOST_CHECK_EQUAL(
relative_path("/pif", "/paf"),
"../pif"
);
BOOST_CHECK_EQUAL(
relative_path("/pif", "/pif"),
"."
);
}
| #include <configure/utils/path.hpp>
#include <configure/error.hpp>
namespace fs = boost::filesystem;
BOOST_AUTO_TEST_CASE(path)
{
# define P1 "pif"
# define P2 "paf"
#ifdef _WIN32
# define ABS_P1 "c:\\pif"
# define ABS_P2 "c:/paf"
#else
# define ABS_P1 "/pif"
# define ABS_P2 "/paf"
#endif
using namespace configure::utils;
BOOST_CHECK_THROW(
relative_path(P1, ABS_P2),
configure::error::InvalidPath
);
BOOST_CHECK_THROW(
relative_path(ABS_P1, P2),
configure::error::InvalidPath
);
BOOST_CHECK_EQUAL(
relative_path(ABS_P1, ABS_P2),
fs::path("..") / P1
);
BOOST_CHECK_EQUAL(
relative_path(ABS_P2, ABS_P1),
fs::path("..") / P2
);
BOOST_CHECK_EQUAL(
relative_path(ABS_P1, ABS_P1),
"."
);
BOOST_CHECK_EQUAL(
relative_path(ABS_P2, ABS_P2),
"."
);
}
|
Move the window to a good location. | #include "wrangleplow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
WranglePlow::MainWindow wrangleplow;
wrangleplow.show();
wrangleplow.resize(1024, 768);
return app.exec();
} | #include "wrangleplow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
WranglePlow::MainWindow wrangleplow;
wrangleplow.show();
wrangleplow.resize(1024, 768);
wrangleplow.move(100, 100);
return app.exec();
} |
Write PersistentConstraintUpdater::updateConstraints timing to log. | #include "./persistent_constraint_updater.h"
#include "./constraint_updater.h"
PersistentConstraintUpdater::PersistentConstraintUpdater(
std::shared_ptr<ConstraintUpdater> constraintUpdater)
: constraintUpdater(constraintUpdater)
{
}
void PersistentConstraintUpdater::updateConstraints(
int labelId, Eigen::Vector2i anchorForBuffer,
Eigen::Vector2i labelSizeForBuffer)
{
constraintUpdater->clear();
for (auto &placedLabelPair : placedLabels)
{
auto &placedLabel = placedLabelPair.second;
constraintUpdater->drawConstraintRegionFor(
anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
placedLabel.labelPosition, placedLabel.size);
}
placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
Eigen::Vector2i(-1, -1) };
}
void PersistentConstraintUpdater::setPosition(int labelId,
Eigen::Vector2i position)
{
placedLabels[labelId].labelPosition = position;
}
void PersistentConstraintUpdater::clear()
{
placedLabels.clear();
}
| #include "./persistent_constraint_updater.h"
#include <chrono>
#include <QLoggingCategory>
#include "./constraint_updater.h"
QLoggingCategory pcuChan("Placement.PersistentConstraintUpdater");
PersistentConstraintUpdater::PersistentConstraintUpdater(
std::shared_ptr<ConstraintUpdater> constraintUpdater)
: constraintUpdater(constraintUpdater)
{
}
void PersistentConstraintUpdater::updateConstraints(
int labelId, Eigen::Vector2i anchorForBuffer,
Eigen::Vector2i labelSizeForBuffer)
{
auto startTime = std::chrono::high_resolution_clock::now();
constraintUpdater->clear();
for (auto &placedLabelPair : placedLabels)
{
auto &placedLabel = placedLabelPair.second;
constraintUpdater->drawConstraintRegionFor(
anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
placedLabel.labelPosition, placedLabel.size);
}
placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
Eigen::Vector2i(-1, -1) };
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, std::milli> diff = endTime - startTime;
qCInfo(pcuChan) << "updateConstraints took" << diff.count() << "ms";
}
void PersistentConstraintUpdater::setPosition(int labelId,
Eigen::Vector2i position)
{
placedLabels[labelId].labelPosition = position;
}
void PersistentConstraintUpdater::clear()
{
placedLabels.clear();
}
|
Add missing UNSUPPORTED for -fno-exception mode | //===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder
// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.
#include <cstdint>
#include <cassert>
#include <unwind.h>
struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
"_Unwind_Exception is incorrectly aligned. This test is expected to fail");
struct MinAligned { };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");
int main() {
for (int i=0; i < 10; ++i) {
try {
throw MinAligned{};
} catch (MinAligned const& ref) {
assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
}
}
}
| //===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: libcxxabi-no-exceptions
// UNSUPPORTED: c++98, c++03
// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder
// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.
#include <cstdint>
#include <cassert>
#include <unwind.h>
struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
"_Unwind_Exception is incorrectly aligned. This test is expected to fail");
struct MinAligned { };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");
int main() {
for (int i=0; i < 10; ++i) {
try {
throw MinAligned{};
} catch (MinAligned const& ref) {
assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
}
}
}
|
Add test case for r193923 | // RUN: %clang_cc1 -fsyntax-only -verify %s
class A { };
class B1 : A { };
class B2 : virtual A { };
class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}}
class C : public B1, private B2 { };
class D; // expected-note {{forward declaration of 'D'}}
class E : public D { }; // expected-error{{base class has incomplete type}}
typedef int I;
class F : public I { }; // expected-error{{base specifier must name a class}}
union U1 : public A { }; // expected-error{{unions cannot have base classes}}
union U2 {};
class G : public U2 { }; // expected-error{{unions cannot be base classes}}
typedef G G_copy;
typedef G G_copy_2;
typedef G_copy G_copy_3;
class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
public G_copy_3 { }; // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
class A { };
class B1 : A { };
class B2 : virtual A { };
class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}}
class C : public B1, private B2 { };
class D; // expected-note {{forward declaration of 'D'}}
class E : public D { }; // expected-error{{base class has incomplete type}}
typedef int I;
class F : public I { }; // expected-error{{base specifier must name a class}}
union U1 : public A { }; // expected-error{{unions cannot have base classes}}
union U2 {};
class G : public U2 { }; // expected-error{{unions cannot be base classes}}
typedef G G_copy;
typedef G G_copy_2;
typedef G_copy G_copy_3;
class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
public G_copy_3 { }; // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
struct J { char c; int i[]; };
struct K : J { }; // expected-error{{base class 'J' has a flexible array member}}
|
Change std::copy to memcpy in critical places. | #include <stingraykit/io/ByteDataConsumer.h>
namespace stingray
{
ByteDataConsumer::ByteDataConsumer(ByteData consumer)
: _consumer(consumer)
{ }
size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
{
const size_t size = data.size();
STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));
std::copy(data.data(), data.data() + size, _consumer.data());
_consumer = ByteData(_consumer, size);
return size;
}
}
| #include <stingraykit/io/ByteDataConsumer.h>
#include <string.h>
namespace stingray
{
ByteDataConsumer::ByteDataConsumer(ByteData consumer)
: _consumer(consumer)
{ }
size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
{
const size_t size = data.size();
STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));
memcpy(_consumer.data(), data.data(), size);
_consumer = ByteData(_consumer, size);
return size;
}
}
|
Use setContextProperty() to make the input helper available | #include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"
#include "qiscp.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QtQuick1ApplicationViewer viewer;
qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");
viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
viewer.showExpanded();
return app.exec();
}
| #include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"
#include "qiscp.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QtQuick1ApplicationViewer viewer;
qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
// qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");
QDeclarativeContext *context = viewer.rootContext();
context->setContextProperty("ISCPInputs", new qiscpInputs());
viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
viewer.showExpanded();
return app.exec();
}
|
Revert "Revert "Adding laser indicator"" | #include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
}
}
#endif
| #include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
claser.send(value);
}
}
#endif
|
Reorganize KB HK processor for new VK hotkeys | #include "KeyboardHotkeyProcessor.h"
#include <string>
#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"
std::unordered_map<std::wstring, unsigned short>
KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();
void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
if (hki.action != HotkeyInfo::MediaKey || hki.args.size() != 1) {
return;
}
std::wstring arg = hki.args[0];
unsigned short vk = mediaKeyMap[arg];
CLOG(L"Simulating media keypress: %s", arg.c_str());
SyntheticKeyboard::SimulateKeypress(vk);
}
std::unordered_map<std::wstring, unsigned short>
KeyboardHotkeyProcessor::CreateKeyMap() {
std::unordered_map<std::wstring, unsigned short> map;
for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
}
return map;
}
| #include "KeyboardHotkeyProcessor.h"
#include <string>
#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"
std::unordered_map<std::wstring, unsigned short>
KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();
void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
/* These hotkeys *require* exactly one argument: */
if (hki.args.size() != 1) {
return;
}
switch (hki.action) {
case HotkeyInfo::MediaKey: {
std::wstring &arg = hki.args[0];
unsigned short vk = mediaKeyMap[arg];
CLOG(L"Media key: %s", arg.c_str());
SyntheticKeyboard::SimulateKeypress(vk);
break;
}
case HotkeyInfo::VirtualKey: {
break;
}
}
}
std::unordered_map<std::wstring, unsigned short>
KeyboardHotkeyProcessor::CreateKeyMap() {
std::unordered_map<std::wstring, unsigned short> map;
for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
}
return map;
}
|
Fix a parsing issue when a vertex has space in its name |
#include "RawTextGraphInput.hh"
/*
name
|V|
[|V| names]
|E|
[|E| lines formatted like start end type distance]
*/
template <typename V>
void RawTextGraphInput<V>::input(string path) {
ifstream ifs(path, ifstream::in);
int v, e;
string title;
// Graph title fetching
ifs >> title;
this->graph_.setName(title);
// Vertices fetching
ifs >> v;
for (int i = 0; i < v; i++) {
ifs >> title;
this->graph_.addVertex(title);
}
// Edges fetching
unsigned int start, end;
string type;
EdgeType t;
V dist;
ifs >> e;
for (int i = 0; i < e; i++) {
ifs >> start >> end >> type >> dist;
if (type == "Train")
t = EdgeType::Train;
else if (type == "Road")
t = EdgeType::Road;
else
t = EdgeType::Plane;
this->graph_.addEdge(t, dist, start, end);
}
}
template class RawTextGraphInput<double>;
|
#include "RawTextGraphInput.hh"
/*
name
|V|
[|V| names]
|E|
[|E| lines formatted like start end type distance]
*/
template <typename V>
void RawTextGraphInput<V>::input(string path) {
ifstream ifs(path, ifstream::in);
int v, e;
string title;
// Graph title fetching
ifs >> title;
this->graph_.setName(title);
// Vertices fetching
ifs >> v;
getline(ifs, title); // wtf
for (int i = 0; i < v; i++) {
getline(ifs, title);
std::cout << "Found " << title << std::endl;
this->graph_.addVertex(title);
}
// Edges fetching
unsigned int start, end;
string type;
EdgeType t;
V dist;
ifs >> e;
for (int i = 0; i < e; i++) {
ifs >> start >> end >> type >> dist;
if (type == "Train")
t = EdgeType::Train;
else if (type == "Road")
t = EdgeType::Road;
else
t = EdgeType::Plane;
this->graph_.addEdge(t, dist, start, end);
}
}
template class RawTextGraphInput<double>;
|
Fix enableRtti test with GCC. | #include <typeinfo>
class A {
virtual void x() { }
};
class B : public A {
void x() override { }
};
int main() {
A a;
B *b = dynamic_cast<B *>(&a);
(void)b;
return 0;
}
| #include <typeinfo>
class I {
public:
virtual ~I() { }
virtual void x() { }
};
class A : public I {
void x() override { }
};
class B : public I {
void x() override { }
};
int main() {
I *a = new A();
B *b = dynamic_cast<B *>(a);
(void)b;
delete a;
return 0;
}
|
Create output folder if does not exist. Suppress debug popups. | #include "Bootil/Bootil.h"
using namespace Bootil;
int main( int argc, char** argv )
{
CommandLine::Set( argc, argv );
BString strInFolder = CommandLine::GetArg( 0, "" );
BString strOutFolder = CommandLine::GetArg( 1, strInFolder );
if (strInFolder == "")
Output::Error("Usage: gluaextract <in> [out]");
String::List files;
String::List folders;
File::Find( &files, &folders, strInFolder + "/*.lua", false );
Output::Msg( "Converting %i files.\n", files.size() );
BOOTIL_FOREACH_CONST(f, files, String::List)
{
AutoBuffer inBuf;
File::Read(strInFolder + "/" + *f, inBuf);
// Extract using LZMA (first 4 bytes are junk)
AutoBuffer outBuf;
Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);
File::Write(strOutFolder + "/" + *f, outBuf);
}
return 0;
}
| #include "Bootil/Bootil.h"
using namespace Bootil;
int main( int argc, char** argv )
{
Debug::SuppressPopups( true );
CommandLine::Set( argc, argv );
Console::FGColorPush( Console::Green );
Output::Msg( "GMod Lua Cache Extractor 1.0\n\n" );
Console::FGColorPop();
BString strInFolder = CommandLine::GetArg( 0, "" );
BString strOutFolder = CommandLine::GetArg( 1, strInFolder );
if (strInFolder == "")
Output::Error("Usage: gluaextract <in> [out]");
String::List files;
String::List folders;
File::Find( &files, &folders, strInFolder + "/*.lua", false );
File::CreateFolder(strOutFolder);
Output::Msg( "Converting %i files.\n", files.size() );
BOOTIL_FOREACH_CONST(f, files, String::List)
{
AutoBuffer inBuf;
File::Read(strInFolder + "/" + *f, inBuf);
// Extract using LZMA (first 4 bytes are junk)
AutoBuffer outBuf;
Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);
File::Write(strOutFolder + "/" + *f, outBuf);
}
return 0;
}
|
Convert NewRunnableMethod() to base::Bind() in base::TestThreadHelper. | // 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 "base/test/thread_test_helper.h"
#include "base/location.h"
namespace base {
ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
: test_result_(false),
target_thread_(target_thread),
done_event_(false, false) {
}
bool ThreadTestHelper::Run() {
if (!target_thread_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ThreadTestHelper::RunInThread))) {
return false;
}
done_event_.Wait();
return test_result_;
}
void ThreadTestHelper::RunTest() { set_test_result(true); }
ThreadTestHelper::~ThreadTestHelper() {}
void ThreadTestHelper::RunInThread() {
RunTest();
done_event_.Signal();
}
} // namespace base
| // 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 "base/test/thread_test_helper.h"
#include "base/bind.h"
#include "base/location.h"
namespace base {
ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
: test_result_(false),
target_thread_(target_thread),
done_event_(false, false) {
}
bool ThreadTestHelper::Run() {
if (!target_thread_->PostTask(
FROM_HERE, base::Bind(&ThreadTestHelper::RunInThread, this))) {
return false;
}
done_event_.Wait();
return test_result_;
}
void ThreadTestHelper::RunTest() { set_test_result(true); }
ThreadTestHelper::~ThreadTestHelper() {}
void ThreadTestHelper::RunInThread() {
RunTest();
done_event_.Signal();
}
} // namespace base
|
Fix incorrect error code handling. | /******************************************************************************/
/*
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
#include "sidnet/sidnet.h"
#include "sidnet/sidserver.h"
static bool s_shouldExit = false;
int main(int argc, const char** argv)
{
// default config
const char *cfgPath = "sidserver.cfg";
int port = 2266;
FILE *pCfgFile = std::fopen(cfgPath, "r");
if (pCfgFile)
{
std::fscanf(pCfgFile, "%d", &port);
}
else if (pCfgFile = std::fopen(cfgPath, "w+"))
{
std::fprintf(pCfgFile, "%d", port);
}
if (pCfgFile)
{
std::fclose(pCfgFile);
}
int err = 0;
err = sidnet::Init();
if (err)
return err;
sidnet::SidServer server;
err = server.Start(port);
if (!err)
return err;
while (!s_shouldExit)
{
}
sidnet::ShutDown();
return 0;
}
| /******************************************************************************/
/*
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
#include "sidnet/sidnet.h"
#include "sidnet/sidserver.h"
static bool s_shouldExit = false;
int main(int argc, const char** argv)
{
// default config
const char *cfgPath = "sidserver.cfg";
int port = 2266;
FILE *pCfgFile = std::fopen(cfgPath, "r");
if (pCfgFile)
{
std::fscanf(pCfgFile, "%d", &port);
}
else if (pCfgFile = std::fopen(cfgPath, "w+"))
{
std::fprintf(pCfgFile, "%d", port);
}
if (pCfgFile)
{
std::fclose(pCfgFile);
}
int err = 0;
err = sidnet::Init();
if (err)
return err;
sidnet::SidServer server;
err = server.Start(port);
if (err)
return err;
while (!s_shouldExit)
{
}
sidnet::ShutDown();
return 0;
}
|
Fix dangling reference error on gcc | #include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
using std::set;
using rules::ISymbol;
using std::vector;
namespace build_tables {
const ParseItemSet item_set_closure(const ParseItem &item,
const PreparedGrammar &grammar) {
ParseItemSet result;
vector<ParseItem> items_to_add = { item };
while (!items_to_add.empty()) {
const ParseItem &item = items_to_add.back();
items_to_add.pop_back();
auto insertion_result = result.insert(item);
if (insertion_result.second) {
for (const auto &pair : follow_sets(item, grammar)) {
const ISymbol &non_terminal = pair.first;
const set<ISymbol> &terminals = pair.second;
for (const auto &terminal : terminals) {
ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
items_to_add.push_back(next_item);
}
}
}
}
return result;
}
}
} | #include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
using std::set;
using rules::ISymbol;
using std::vector;
namespace build_tables {
const ParseItemSet item_set_closure(const ParseItem &item,
const PreparedGrammar &grammar) {
ParseItemSet result;
vector<ParseItem> items_to_add = { item };
while (!items_to_add.empty()) {
ParseItem item = items_to_add.back();
items_to_add.pop_back();
auto insertion_result = result.insert(item);
if (insertion_result.second) {
for (const auto &pair : follow_sets(item, grammar)) {
const ISymbol &non_terminal = pair.first;
const set<ISymbol> &terminals = pair.second;
for (const auto &terminal : terminals) {
ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
items_to_add.push_back(next_item);
}
}
}
}
return result;
}
}
} |
Revert MatteMaterial to its standard form | #include <memory>
#include "film/color.h"
#include "textures/texture.h"
#include "material/lambertian.h"
#include "material/oren_nayer.h"
#include "material/matte_material.h"
#include "material/specular_reflection.h"
#include "material/fresnel.h"
MatteMaterial::MatteMaterial(const Texture *diffuse, float roughness)
: diffuse(diffuse), roughness(roughness)
{}
BSDF MatteMaterial::get_bsdf(const DifferentialGeometry &dg) const {
BSDF bsdf{dg};
Colorf kd = diffuse->sample(dg).normalized();
if (roughness == 0){
bsdf.add(std::make_unique<Lambertian>(kd));
}
else {
bsdf.add(std::make_unique<OrenNayer>(kd, roughness));
bsdf.add(std::make_unique<SpecularReflection>(kd, std::make_unique<FresnelNoOp>()));
}
return bsdf;
}
| #include <memory>
#include "film/color.h"
#include "textures/texture.h"
#include "material/lambertian.h"
#include "material/oren_nayer.h"
#include "material/matte_material.h"
#include "material/specular_reflection.h"
#include "material/fresnel.h"
MatteMaterial::MatteMaterial(const Texture *diffuse, float roughness)
: diffuse(diffuse), roughness(roughness)
{}
BSDF MatteMaterial::get_bsdf(const DifferentialGeometry &dg) const {
BSDF bsdf{dg};
Colorf kd = diffuse->sample(dg).normalized();
if (roughness == 0){
bsdf.add(std::make_unique<Lambertian>(kd));
}
else {
bsdf.add(std::make_unique<OrenNayer>(kd, roughness));
}
return bsdf;
}
|
Fix overflow issue in file scrubber. npos is big | #include "file_scrubber.hpp"
#include <stdio.h>
#include <iostream>
#include "string_utils.hpp"
#include "error.hpp"
using std::ifstream;
namespace mocc {
FileScrubber::FileScrubber(const char* fName, const char* commentFlag):
stream_(fName),
flag_(commentFlag){
if( !stream_.good() ) {
Error("Failed to open file.");
}
}
FileScrubber::~FileScrubber(){}
std::string FileScrubber::getline(){
while(!stream_.eof()){
std::string line;
std::getline(stream_, line);
// Strip the comments
unsigned int commentPos = line.find(flag_, 0);
if(commentPos != std::string::npos){
line.erase(commentPos, std::string::npos);
}
// Remove whitespace
line = trim(line);
// If the result isnt empty, return the line.
if(!line.empty()){
return line;
}
}
return "";
}
}
| #include "file_scrubber.hpp"
#include <stdio.h>
#include <iostream>
#include "string_utils.hpp"
#include "error.hpp"
using std::ifstream;
namespace mocc {
FileScrubber::FileScrubber(const char* fName, const char* commentFlag):
stream_(fName),
flag_(commentFlag){
if( !stream_.good() ) {
Error("Failed to open file.");
}
}
FileScrubber::~FileScrubber(){}
std::string FileScrubber::getline(){
while(!stream_.eof()){
std::string line;
std::getline(stream_, line);
// Strip the comments
size_t commentPos = line.find(flag_, 0);
if(commentPos != std::string::npos){
line.erase(commentPos, std::string::npos);
}
// Remove whitespace
line = trim(line);
// If the result isnt empty, return the line.
if(!line.empty()){
return line;
}
}
return "";
}
}
|
Remove TODO - problem was debug() printing, not enqueing. | #include "listener.h"
#include "log.h"
#include "buffers.h"
void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
int messageSize) {
if(queue_available(queue) < messageSize + 2) {
debug("Dropped incoming CAN message -- send queue (at %p) full\r\n",
queue);
return;
}
for(int i = 0; i < messageSize; i++) {
QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
}
QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}
void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
// TODO the more we enqueue here, the slower it gets - cuts the rate by
// almost half to do it with 2 queues. we could either figure out how to
// share a queue or make the enqueue function faster. right now I believe it
// enqueues byte by byte, which could obviously be improved.
if(listener->usb->configured) {
conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
} else {
conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
}
}
void processListenerQueues(Listener* listener) {
// Must always process USB, because this function usually runs the MCU's USB
// task that handles SETUP and enumeration.
processInputQueue(listener->usb);
if(!listener->usb->configured) {
processInputQueue(listener->serial);
}
}
| #include "listener.h"
#include "log.h"
#include "buffers.h"
void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
int messageSize) {
if(queue_available(queue) < messageSize + 2) {
debug("Dropped incoming CAN message -- send queue (at %p) full\r\n",
queue);
return;
}
for(int i = 0; i < messageSize; i++) {
QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
}
QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}
void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
if(listener->usb->configured) {
conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
} else {
conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
}
}
void processListenerQueues(Listener* listener) {
// Must always process USB, because this function usually runs the MCU's USB
// task that handles SETUP and enumeration.
processInputQueue(listener->usb);
if(!listener->usb->configured) {
processInputQueue(listener->serial);
}
}
|
Add planar parameter to VerticalCleaner registration | #include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"
const AVS_Linkage *AVS_linkage = nullptr;
extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
AVS_linkage = vectors;
env->AddFunction("RemoveGrain", "c[mode]i[modeU]i[modeV]i[planar]b", Create_RemoveGrain, 0);
env->AddFunction("Repair", "cc[mode]i[modeU]i[modeV]i[planar]b", Create_Repair, 0);
env->AddFunction("Clense", "c[previous]c[next]c[grey]b", Create_Clense, 0);
env->AddFunction("ForwardClense", "c[grey]b", Create_ForwardClense, 0);
env->AddFunction("BackwardClense", "c[grey]b", Create_BackwardClense, 0);
env->AddFunction("VerticalCleaner", "c[mode]i[modeU]i[modeV]i", Create_VerticalCleaner, 0);
return "Itai, onii-chan!";
}
| #include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"
const AVS_Linkage *AVS_linkage = nullptr;
extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
AVS_linkage = vectors;
env->AddFunction("RemoveGrain", "c[mode]i[modeU]i[modeV]i[planar]b", Create_RemoveGrain, 0);
env->AddFunction("Repair", "cc[mode]i[modeU]i[modeV]i[planar]b", Create_Repair, 0);
env->AddFunction("Clense", "c[previous]c[next]c[grey]b", Create_Clense, 0);
env->AddFunction("ForwardClense", "c[grey]b", Create_ForwardClense, 0);
env->AddFunction("BackwardClense", "c[grey]b", Create_BackwardClense, 0);
env->AddFunction("VerticalCleaner", "c[mode]i[modeU]i[modeV]i[planar]b", Create_VerticalCleaner, 0);
return "Itai, onii-chan!";
}
|
Make test work on Linux | // RUN: %clangxx_tsan %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not='ThreadSanitizer'
#include <dispatch/dispatch.h>
#import <memory>
#import <stdatomic.h>
_Atomic(long) destructor_counter = 0;
struct MyStruct {
virtual ~MyStruct() {
usleep(10000);
atomic_fetch_add_explicit(&destructor_counter, 1, memory_order_relaxed);
}
};
int main(int argc, const char *argv[]) {
fprintf(stderr, "Hello world.\n");
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t g = dispatch_group_create();
for (int i = 0; i < 100; i++) {
std::shared_ptr<MyStruct> shared(new MyStruct());
dispatch_group_async(g, q, ^{
shared.get(); // just to make sure the object is captured by the block
});
}
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
if (destructor_counter != 100) {
abort();
}
fprintf(stderr, "Done.\n");
}
// CHECK: Hello world.
// CHECK: Done.
| // RUN: %clangxx_tsan %s %link_libcxx_tsan -o %t
// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not='ThreadSanitizer'
#include <dispatch/dispatch.h>
#include <memory>
#include <stdatomic.h>
#include <cstdio>
_Atomic(long) destructor_counter = 0;
struct MyStruct {
virtual ~MyStruct() {
usleep(10000);
atomic_fetch_add_explicit(&destructor_counter, 1, memory_order_relaxed);
}
};
int main(int argc, const char *argv[]) {
fprintf(stderr, "Hello world.\n");
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t g = dispatch_group_create();
for (int i = 0; i < 100; i++) {
std::shared_ptr<MyStruct> shared(new MyStruct());
dispatch_group_async(g, q, ^{
shared.get(); // just to make sure the object is captured by the block
});
}
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
if (destructor_counter != 100) {
abort();
}
fprintf(stderr, "Done.\n");
}
// CHECK: Hello world.
// CHECK: Done.
|
Add corpus info for conllx_ds. | #include <map>
#include <string>
#include <boost/assign/list_of.hpp>
#include <AlpinoCorpus/CorpusInfo.hh>
namespace alpinocorpus {
CorpusInfo const ALPINO_CORPUS_INFO(
boost::assign::list_of("node"),
"node",
"word");
CorpusInfo const TUEBA_DZ_CORPUS_INFO(
boost::assign::list_of("node")("ne")("word"),
"word",
"form");
std::map<std::string, CorpusInfo> const PREDEFINED_CORPORA =
boost::assign::map_list_of
("alpino_ds", ALPINO_CORPUS_INFO)
("tueba_tree", TUEBA_DZ_CORPUS_INFO);
CorpusInfo const FALLBACK_CORPUS_INFO = ALPINO_CORPUS_INFO;
CorpusInfo predefinedCorpusOrFallback(std::string const &type)
{
std::map<std::string, CorpusInfo>::const_iterator iter =
alpinocorpus::PREDEFINED_CORPORA.find(type);
if (iter != alpinocorpus::PREDEFINED_CORPORA.end())
return iter->second;
return alpinocorpus::FALLBACK_CORPUS_INFO;
}
}
| #include <map>
#include <string>
#include <boost/assign/list_of.hpp>
#include <AlpinoCorpus/CorpusInfo.hh>
namespace alpinocorpus {
CorpusInfo const ALPINO_CORPUS_INFO(
boost::assign::list_of("node"),
"node",
"word");
CorpusInfo const TUEBA_DZ_CORPUS_INFO(
boost::assign::list_of("node")("ne")("word"),
"word",
"form");
CorpusInfo const CONLLX_CORPUS_INFO(
boost::assign::list_of("word"),
"word",
"form");
std::map<std::string, CorpusInfo> const PREDEFINED_CORPORA =
boost::assign::map_list_of
("alpino_ds", ALPINO_CORPUS_INFO)
("tueba_tree", TUEBA_DZ_CORPUS_INFO)
("conllx_ds", CONLLX_CORPUS_INFO);
CorpusInfo const FALLBACK_CORPUS_INFO = ALPINO_CORPUS_INFO;
CorpusInfo predefinedCorpusOrFallback(std::string const &type)
{
std::map<std::string, CorpusInfo>::const_iterator iter =
alpinocorpus::PREDEFINED_CORPORA.find(type);
if (iter != alpinocorpus::PREDEFINED_CORPORA.end())
return iter->second;
return alpinocorpus::FALLBACK_CORPUS_INFO;
}
}
|
Destroy window at the end of the test case. | // ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// 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 <QtTest>
#include <DO/Graphics/DerivedQObjects/OpenGLWindow.hpp>
using namespace DO;
class TestOpenGLWindow: public QObject
{
Q_OBJECT
private slots:
void test_OpenGLWindow_construction()
{
int width = 50;
int height = 50;
QString windowName = "painting window";
int x = 200;
int y = 300;
OpenGLWindow *window = new OpenGLWindow(width, height,
windowName,
x, y);
}
};
QTEST_MAIN(TestOpenGLWindow)
#include "test_opengl_window.moc"
| // ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// 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 <QtTest>
#include <DO/Graphics/DerivedQObjects/OpenGLWindow.hpp>
using namespace DO;
class TestOpenGLWindow: public QObject
{
Q_OBJECT
private slots:
void test_OpenGLWindow_construction()
{
int width = 50;
int height = 50;
QString windowName = "painting window";
int x = 200;
int y = 300;
OpenGLWindow *window = new OpenGLWindow(width, height,
windowName,
x, y);
delete window;
}
};
QTEST_MAIN(TestOpenGLWindow)
#include "test_opengl_window.moc"
|
Fix index range for random shop message | #include "../include/Common.h"
#include "../include/StoreGreetings.h"
#include <random>
#include <string>
std::string random_greeting() {
std::random_device rand;
std::default_random_engine rand_eng(rand());
std::uniform_int_distribution<int> uniform_dist(0, STORE_GREETINGS.size());
size_t index = uniform_dist(rand_eng);
return STORE_GREETINGS[index];
}
| #include "../include/Common.h"
#include "../include/StoreGreetings.h"
#include <random>
#include <string>
std::string random_greeting() {
std::random_device rand;
std::default_random_engine rand_eng(rand());
std::uniform_int_distribution<int> uniform_dist(0, STORE_GREETINGS.size()-1);
size_t index = uniform_dist(rand_eng);
return STORE_GREETINGS[index];
}
|
Use more suitable path for unix domain sockets in testcode | #include <mart-netlib/unix.hpp>
#include <mart-common/PrintWrappers.h>
#include <catch2/catch.hpp>
#include <filesystem>
#include <iostream>
TEST_CASE( "unix_domain_socket_simple_member_check1", "[.][net][unix_domain_socket]" )
{
mart::nw::un::Socket sock1;
mart::nw::un::Socket sock2( //
mart::ConstString( "./__tmp__/sock2.local" ), //
mart::ConstString( "./__tmp__/sock2.remote" ) //
);
} | #include <mart-netlib/unix.hpp>
#include <mart-common/PrintWrappers.h>
#include <catch2/catch.hpp>
#include <filesystem>
#include <iostream>
TEST_CASE( "unix_domain_socket_simple_member_check1", "[.][net][unix_domain_socket]" )
{
mart::nw::un::Socket sock1;
mart::nw::un::Socket sock2( //
mart::ConstString( "sock.local" ), //
mart::ConstString( "sock.remote" ) //
);
} |
Add a triple to codegen test. | // RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s
template<typename T> struct A {
A(T = 0);
A(void*);
};
template<typename T> A(T*) -> A<long>;
A() -> A<int>;
// CHECK-LABEL: @_Z1fPi(
void f(int *p) {
// CHECK: @_ZN1AIiEC
A a{};
// CHECK: @_ZN1AIlEC
A b = p;
// CHECK: @_ZN1AIxEC
A c = 123LL;
}
| // RUN: %clang_cc1 -std=c++1z %s -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %s
template<typename T> struct A {
A(T = 0);
A(void*);
};
template<typename T> A(T*) -> A<long>;
A() -> A<int>;
// CHECK-LABEL: @_Z1fPi(
void f(int *p) {
// CHECK: @_ZN1AIiEC
A a{};
// CHECK: @_ZN1AIlEC
A b = p;
// CHECK: @_ZN1AIxEC
A c = 123LL;
}
|
Make sure our interpreter is valid after construction. |
#include "catch.hpp"
#include "Interpreter.hpp"
TEST_CASE("Allocation", "Make sure we can allocate a scheme interpreter")
{
script::Interpreter eval;
}
|
#include "catch.hpp"
#include "Interpreter.hpp"
TEST_CASE("Allocation", "Make sure we can allocate a scheme interpreter")
{
script::Interpreter eval;
REQUIRE(eval.isValid() == true);
}
|
Fix ``loop'' as that refresh entire screen every keypress | #include <map>
#include <ncurses.h>
#include <string>
#include <typeinfo>
#include <vector>
#include "configuration.hh"
#include "file_contents.hh"
#include "key_listeners.hh"
#include "show_message.hh"
#include "hooks.hh"
void loop() {
add_listeners();
add_hook(Hook::REFRESH,hook_show_message);
while(true) {
char ch(getch());
clear_message();
if(!get_contents()->m(ch)) {
show_message((std::string("Didn't recognize key press: ")
+ ch).c_str());
}
}
}
| #include <map>
#include <ncurses.h>
#include <string>
#include <typeinfo>
#include <vector>
#include "configuration.hh"
#include "file_contents.hh"
#include "key_listeners.hh"
#include "show_message.hh"
#include "hooks.hh"
#include "to_str.hh"
void loop() {
add_listeners();
add_hook(Hook::REFRESH,hook_show_message);
while(true) {
char ch = getch();
clear_message();
if(!get_contents()->m(ch)) {
show_message((std::string("Didn't recognize key press: ")
+ ch).c_str());
} else {
show_message((std::string("x,y: (")
+ int_to_str(get_contents()->x) + ','
+ int_to_str(get_contents()->y) + ')').c_str());
}
get_contents()->refreshmaxyx();
print_contents(get_contents());
}
}
|
Fix broken build on ci | #include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
#include "rendering/renderablezindexcomparer.hpp"
#include "__mocks__/rendering/renderablemock.hpp"
using testing::ElementsAre;
TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
ASSERT_TRUE(comparer(&a, &b));
ASSERT_FALSE(comparer(&b, &a));
}
TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
// Arrange
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
RenderableMock c(0);
c.setZIndex(14);
std::vector<qrw::Renderable*> renderables = {&b, &c, &a};
// Act
std::sort(renderables.begin(), renderables.end(), comparer);
// Assert
ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}
| #include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
#include "rendering/renderablezindexcomparer.hpp"
#include "__mocks__/rendering/renderablemock.hpp"
using ::testing::ElementsAre;
TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
ASSERT_TRUE(comparer(&a, &b));
ASSERT_FALSE(comparer(&b, &a));
}
TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
// Arrange
qrw::RenderableZIndexComparer comparer;
RenderableMock a(0);
a.setZIndex(12);
RenderableMock b(0);
b.setZIndex(13);
RenderableMock c(0);
c.setZIndex(14);
std::vector<qrw::Renderable*> renderables = {&b, &c, &a};
// Act
std::sort(renderables.begin(), renderables.end(), comparer);
// Assert
ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}
|
Fix crash: CoinControl "space" bug | #include "coincontroltreewidget.h"
#include "coincontroldialog.h"
CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
QTreeWidget(parent)
{
}
void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
{
event->ignore();
int COLUMN_CHECKBOX = 0;
this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
}
else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
{
event->ignore();
CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
coinControlDialog->done(QDialog::Accepted);
}
else
{
this->QTreeWidget::keyPressEvent(event);
}
} | #include "coincontroltreewidget.h"
#include "coincontroldialog.h"
CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
QTreeWidget(parent)
{
}
void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
{
event->ignore();
int COLUMN_CHECKBOX = 0;
if(this->currentItem())
this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
}
else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
{
event->ignore();
CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
coinControlDialog->done(QDialog::Accepted);
}
else
{
this->QTreeWidget::keyPressEvent(event);
}
}
|
Fix test stub for run_child_proc. | #include <vector>
#include "proc-service.h"
// Stub out run_child_proc function, for testing purposes.
void base_process_service::run_child_proc(const char * const *args, const char *working_dir,
const char *logfile, bool on_console, int wpipefd, int csfd, int socket_fd,
int notify_fd, int forced_notify_fd, const char * notify_var, uid_t uid, gid_t gid,
const std::vector<service_rlimits> &rlimits) noexcept
{
}
| #include <vector>
#include "proc-service.h"
// Stub out run_child_proc function, for testing purposes.
void base_process_service::run_child_proc(run_proc_params params) noexcept
{
}
|
Build native QSWorld and run it for 100 updates; no muts yet. | // This is the main function for the NATIVE version of this project.
#include <iostream>
#include "../QSWorld.h"
int main()
{
std::cout << "Hello World!" << std::endl;
QSWorld world;
}
| // This is the main function for the NATIVE version of this project.
#include <iostream>
#include "../QSWorld.h"
int main()
{
std::cout << "Hello World!" << std::endl;
QSWorld world(20, 20, 5);
for (size_t ud = 0; ud < 100; ud++) {
world.Update();
}
world.Print();
}
|
Test kóði í hætta hnapp | #include "adalgluggi.h"
#include "ui_adalgluggi.h"
#include <QDebug>
adalgluggi::adalgluggi(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::adalgluggi)
{
ui->setupUi(this);
}
adalgluggi::~adalgluggi()
{
delete ui;
}
void adalgluggi::on_velar_clicked()
{
qDebug () << "Vélar hnappur clicked";
}
void adalgluggi::on_folk_clicked()
{
qDebug () << "Folk hnappur clicked";
}
void adalgluggi::on_haetta_clicked()
{
}
| #include "adalgluggi.h"
#include "ui_adalgluggi.h"
#include <QDebug>
adalgluggi::adalgluggi(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::adalgluggi)
{
ui->setupUi(this);
}
adalgluggi::~adalgluggi()
{
delete ui;
}
void adalgluggi::on_velar_clicked()
{
qDebug () << "Vélar hnappur clicked";
}
void adalgluggi::on_folk_clicked()
{
qDebug () << "Folk hnappur clicked";
}
void adalgluggi::on_haetta_clicked()
{
vector<tolvufolk> folk = _fService.getTolvufolk();
qDebug () << folk.size();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.