//#include "InstructionParser.h"

#include <string>
#include <stdexcept>

#include "gtest/gtest.h"

class InstructionParser
{
public:
  class UnknownInstruction : public std::runtime_error
  {
  public:
    UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
    {}
  };

  void parseInstructions(const std::string& instruction)
  {
    if (instruction != "ld a," && instruction != "out (0),a")
    {
      throw UnknownInstruction{"Unknown instruction" + instruction};
    }
  }

};

TEST(InstructionParser, ParserShouldDeclineUnknownInstruction)
{
  InstructionParser parser;
  EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}

TEST(InstructionParser, ParserShouldAcceptInstuctionLd)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}

TEST(InstructionParser, ParserShouldAcceptInstructionOut)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
}

//#include "InstructionParser.h"

#include <string>
#include <stdexcept>

#include "gtest/gtest.h"

class InstructionParser
{
public:
  class UnknownInstruction : public std::runtime_error
  {
  public:
    UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
    {}
  };

  void parseInstructions(const std::string& instruction)
  {
    const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"};
    if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end())
    {
      throw UnknownInstruction{"Unknown instruction" + instruction};
    }
  }

};

TEST(InstructionParser, ParserShouldDeclineUnknownInstruction)
{
  InstructionParser parser;
  EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}

TEST(InstructionParser, ParserShouldAcceptInstuctionLd)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}

TEST(InstructionParser, ParserShouldAcceptInstructionOut)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
}

Use container to store acceptable instructions


#include "graph_node.h"
#include "gtest\gtest.h"

/*
 This file will includ all the test for the GraphNode class.
*/

/*
 This test will check if neighbors can be added.
*/
TEST(GraphNodeTest, Add) {

	//Initialize a node with some children
	GraphNode<int> root1;
	GraphNode<int> neighbor1;
	GraphNode<int> neighbor2;
	root1.addNeighbor(&neighbor1);
	root1.addNeighbor(&neighbor2);

	EXPECT_EQ(root1.getNeighbors().size(), 2);
}

/*
This test will check if neighbors can be removed.
*/
TEST(GraphNodeTest, Remove) {

	//Initialize a node with some children
	GraphNode<int> root1;
	GraphNode<int> neighbor1;
	GraphNode<int> neighbor2;
	root1.addNeighbor(&neighbor1);
	root1.addNeighbor(&neighbor2);

	EXPECT_EQ(root1.getNeighbors().size(), 2);

	// Remove one neighbor and check it is removed
	root1.removeNeighbor(1);

	EXPECT_EQ(root1.getNeighbors().size(), 1);

	// Remove the last neighbor and check it the neighbors list is empty
	root1.removeNeighbor(0);

	EXPECT_EQ(root1.getNeighbors().size(), 0);

	// Check if removing when there is no neighbors will chrash
	EXPECT_NO_THROW(root1.removeNeighbor(0));
}

/*
This test will check if the value for each node can be set and extracted.
*/
TEST(GraphNodeTest, Value) {

	//Initialize a node with some children
	GraphNode<int> root1;
	root1.setValue(1);

	EXPECT_EQ(root1.getValue(), 1);
}

Add test for the graphnode.

Add test for the graphnode.


// Program to check if given tree is a BST or not.

#include <iostream>
#define MAX 1000
using namespace std;

int A[MAX];
int index = 0;

struct Node{
	int data;
	struct Node *left;
	struct Node *right;
};

struct Node *newNode(int x){
	struct Node *newptr = new Node;
	newptr->data = x;
	newptr->left = NULL;
	newptr->right = NULL;
	return newptr;
}

void printInorder(struct Node *root){
	if(root == NULL)
		return;
	printInorder(root->left);
	cout<<root->data<<" ";
	A[index] = root->data;
	index++;
	printInorder(root->right);
}

struct Node *insertBST(struct Node *root, int x){
	if(root == NULL)
		return newNode(x);
	else{
		if(root->data > x)
			root->left = insertBST(root->left, x);
		else
			root->right = insertBST(root->right, x);
	}
return root;
}

int main(){
	struct Node *root = NULL;
	root = insertBST(root, 10);
	insertBST(root, 20);
	insertBST(root, -9);
	insertBST(root, 100);
	int i, check;
	check = 1;
	printInorder(root);
	for(i=0; i<index-1; i++){
		if(A[i] > A[i+1]){
			check = 0;
			break;
		}
	}
if(check)
	cout<<"BST!\n";
else
	cout<<"Not BST!\n";
return 0;
}

Check if given binary tree is BST or not.


#include <iostream>
#include <cmath>

using namespace std;

class Point3D {
  double x;
  double y;
  double z;

public:

  double getX() {
    return x;
  }

  double getY() {
    return y;
  }

  double getZ() {
    return z;
  }

  void setX(double newX) {
    x = newX;
  }

  void setY(double newY) {
    y = newY;
  }

  void setZ(double newZ) {
    z = newZ;
  }

  void translate(Point3D translationVector) {
    setX(getX() + translationVector.getX());
    setY(getY() + translationVector.getY());
    setZ(getZ() + translationVector.getZ());
  }

  double distanceTo(Point3D other) {
    return sqrt(pow(getX() - other.getX(), 2) +
                pow(getY() - other.getY(), 2) +
                pow(getZ() - other.getZ(), 2));
  }

  void print() {
    cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n';
  }
};

class Triangle {
  Point3D aVertex;
  Point3D bVertex;
  Point3D cVertex;

public:

  double getASide() {
    return bVertex.distanceTo(cVertex);
  }

  double getBSide() {
    return aVertex.distanceTo(cVertex);
  }

  double getCSide() {
    return aVertex.distanceTo(bVertex);
  }

  double perimeter() {
    return getASide() + getBSide() + getCSide();
  }

  double area() {
    double p = perimeter() / 2;

    return sqrt(p * (p - getASide()) * (p - getBSide()) * (p - getCSide()));
  }

  void translate(Point3D translationVector) {
    aVertex.translate(translationVector);
    bVertex.translate(translationVector);
    cVertex.translate(translationVector);
  }
};

int main() {

  return 0;
}

Add solution to the second problem - 'Triangle'


#include <cstdlib>
#include <iostream>

int
main(void)
{
  std::cin.tie(0);
  std::ios::sync_with_stdio(false);

  int n;
  while (std::cin >> n) {
    std::cout << n << std::endl;
  }
  return EXIT_SUCCESS;
}

Add minimum template for programming contest


// Copyright (c) 2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <string>
#include <android/log.h>

void OpenDebugLog()
{
}

int LogPrintStr(const std::string &str)
{
    return __android_log_print(ANDROID_LOG_INFO, "gulden_unity_jni_", "%s", str.c_str());
}

Implement android specific logging calls


#include <iostream>

using namespace std;

class A {
public:
    A() {
        cout << "A()" << endl;
    }
};

class B : public A {
public:
    B() {
        cout << "B()" << endl;
    }
};

class C : public B {
public:
    C() {
        cout << "C()" << endl;
    }
};

class X {
public:
    X() {
        cout << "X()" << endl;
    }
};

class Y {
public:
    Y() {
        cout << "Y()" << endl;
    }
};

class Z : public X, public Y {
public:
    Z() {
        cout << "Z()" << endl;
    }
};

class MI : public C, public Z {
public:
    MI() {
        cout << "MI()" << endl;
    }
};

class D : public X, public C {
public:
    D() {
        cout << "D()" << endl;
    }
};

int main() {
    D* pd = new D;
    X *px = pd;
    A *pa = pd;
    B *pb = pd;
    C *pc = pd;
    delete pc;
    delete pb;
    delete pa;
    delete pd;
    delete px;

}

Add solution for chapter 18, test 23

Add solution for chapter 18, test 23


/**
 * Coverity Scan model
 *
 * Manage false positives by giving coverity some hints.
 *
 * Updates to this file must be manually submitted by an admin to:
 *
 *   https://scan.coverity.com/projects/1222
 *
 */

// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
  if (tag == 1 || tag == 2) {
    __coverity_panic__();
  }
}

Add Coverity Scan model file.

Add Coverity Scan model file.

Model files help eliminate false positives by giving coverity hints about halts
and memory (de)allocation. The only model, for now, helps coverity understand
that INT_FATAL and USR_FATAL abort execution.

r: sungeun

git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@23622 3a8e244f-b0f2-452b-bcba-4c88e055c3ca


// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -gline-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK-LABEL: define void @_ZN7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
//
// CHECK: !llvm.dbg.cu = !{![[CU:[0-9]+]]}
//
// CHECK: ![[CU]] = !MDCompileUnit({{.*}} subprograms: ![[SPs:[0-9]+]]
// CHECK: ![[SPs]] = !{![[SP:[0-9]+]]}
// CHECK: ![[SP]] = !MDSubprogram(name: "VariadicFunction",{{.*}} function: {{[^:]+}} @_ZN7Derived16VariadicFunctionEz
// CHECK: ![[LOC]] = !MDLocation({{.*}}scope: ![[SP]])

CodeGenCXX: Test that linetables work with variadic virtual thunks

Add a frontend test for PR22929, which was fixed by LLVM r232449.
Besides the crash test, check that the `!dbg` attachment is sane since
its presence was the trigger.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@232450 91177308-0d34-0410-b5e6-96231b3b80d8


// 122. Best Time to Buy and Sell Stock II
/**
 * Say you have an array for which the ith element is the price of a given stock on day i.
 *
 * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times).
 * However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
 *
 * Tags: Array, Greedy
 *
 * Similar Problems: (M) Best Time to Buy and Sell Stock, (H) Best Time to Buy and Sell Stock III,
 *                   (H) Best Time to Buy and Sell Stock IV, (M) Best Time to Buy and Sell Stock with Cooldown
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n < 2)
        {
            return 0;
        }

        int res = 0;
        for (int i = 1; i < n; i++)
        {
            // add to profit if the price is increasing
            if (prices[i] > prices[i - 1])
            {
                res += prices[i] - prices[i - 1];
            }
        }

        return res;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> profit;
    profit.push_back(4);
    profit.push_back(2);
    profit.push_back(3);
    profit.push_back(1);

    Solution mySolution;
    int result = mySolution.maxProfit(profit);
    cout << result << endl;
    system("pause");

    return 0;
}

Add Solution for Problem 122

Add Solution for Problem 122


#include <iostream>
#include <string>
#include <sstream>

using namespace std;

template <typename T>
string debug_rep(const T &t) {
    ostringstream ret;
    ret << t;
    return ret.str();
}

template <typename T>
string debug_rep(T *p) {
    ostringstream ret;
    ret << "pointer: " << p;
    if(p) {
        ret << " content: " << debug_rep(*p);
    } else {
        ret << " null pointer";
    }
    return ret.str();
}

template <>
string debug_rep(char *p) {
    cout << "debug_rep(char*p) ";
    return debug_rep(string(p));
}

template <>
string debug_rep(const char *p) {
    cout << "debug_rep(const char *)  ";
    return debug_rep(string(p));
}

//string debug_rep(const string &s) {
//    return '"' + s + '"' + "no template";
//}

int main() {
    string s("hi");
    cout << debug_rep(s) << endl;//call debug_rep(const T&t), T is string, when the third function is commented
    cout << debug_rep(&s) << endl;//call debug_rep(T*p), T is string

    const string *sp = &s;
    cout << debug_rep(sp) << endl;//call debug_rep(T* p), T is const string, this one is more specialize

    //const char*
    cout << debug_rep("hi world!") << endl;
    //char*
    char* cp = "hello";
    cout << debug_rep(cp) << endl;
}

Add solution for chapter 16 test 65 66 67


#include <iostream>
#include <cstdlib>

/* This is our main function */
int main() {
    // print Hello world!
    std::cout << "HELLO WORLD!" << std::endl;
    return 1;
    /* TESTING
    MULTILINE
    COMMENTS
    YAY */
}

Add additional test case for multiline comments


#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main() {
    try {
        //[z-a]+\\.(cpp|cxx|cc)$   code 4
        //
        string pattern("[[:alnum:]]+\\.cpp|cxx|cc)$", regex::icase);
        regex r(pattern);
        smatch results;
    } catch(regex_error e) {
        cout << e.what() << "\ncode: " << e.code() << endl;
    }

    return 0;
}

Add solution for chapter 17 test 14

Add solution for chapter 17 test 14


#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main() {
    string pattern("(\\d{5})(\\d{4})");
    regex r(pattern);
    smatch m;
    string s;
    string fmt = "$1-$2";
    while(getline(cin, s)) {
        cout << regex_replace(s, r, fmt) << endl;
    }

    return 0;
}

Add solution for chapter 17 test 27

Add solution for chapter 17 test 27


/*
  Print elements of a linked list in reverse order as standard output
  head pointer could be NULL as well for empty list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/

void ReversePrint(Node *head)
{
    if (head != NULL) {
        ReversePrint(head->next);
        cout << head->data << endl;
    }
}

Print linked list in reverse

Print linked list in reverse


/*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
 *
 *                     The LLVM Compiler Infrastructure
 *
 * This file is dual licensed under the MIT and the University of Illinois Open
 * Source Licenses. See LICENSE.TXT for details.
 *
 * ===----------------------------------------------------------------------===
 *
 * This file implements __muloti4, and is stolen from the compiler_rt library.
 *
 * FIXME: we steal and re-compile it into filesystem, which uses __int128_t,
 * and requires this builtin when sanitized. See llvm.org/PR30643
 *
 * ===----------------------------------------------------------------------===
 */
#include "__config"
#include "climits"

#ifndef _LIBCPP_HAS_NO_INT128

__attribute__((no_sanitize("undefined"))) extern "C" __int128_t
__muloti4(__int128_t a, __int128_t b, int* overflow) {
  const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
  const __int128_t MIN = (__int128_t)1 << (N - 1);
  const __int128_t MAX = ~MIN;
  *overflow = 0;
  __int128_t result = a * b;
  if (a == MIN) {
    if (b != 0 && b != 1)
      *overflow = 1;
    return result;
  }
  if (b == MIN) {
    if (a != 0 && a != 1)
      *overflow = 1;
    return result;
  }
  __int128_t sa = a >> (N - 1);
  __int128_t abs_a = (a ^ sa) - sa;
  __int128_t sb = b >> (N - 1);
  __int128_t abs_b = (b ^ sb) - sb;
  if (abs_a < 2 || abs_b < 2)
    return result;
  if (sa == sb) {
    if (abs_a > MAX / abs_b)
      *overflow = 1;
  } else {
    if (abs_a > MIN / -abs_b)
      *overflow = 1;
  }
  return result;
}

#endif

[libc++] Add hack to allow ubsan to work w/o compiler-rt (__muloti4 is undefined)

Summary:
Using int128_t with UBSAN causes link errors unless compiler-rt is providing the runtime library.
Specifically ubsan generates calls to __muloti4 but libgcc doesn't provide a definition.

In order to avoid this, and allow users to continue using sanitized versions of libc++, this patch introduces a hack.
It adds a cribbed version of  the compiler-rt builtin to the libc++ filesystem sources.

I don't think this approach will work in the long run, but it seems OK for now.

Also see:

https://bugs.llvm.org/show_bug.cgi?id=30643
https://bugs.llvm.org/show_bug.cgi?id=16404

Reviewers: mclow.lists, ldionne, rsmith, jyknight, echristo

Reviewed By: echristo

Subscribers: dberris, cfe-commits

Differential Revision: https://reviews.llvm.org/D49828

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@337990 91177308-0d34-0410-b5e6-96231b3b80d8


#include <iostream>
#include <string>

#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <llvm/Support/CommandLine.h>

using namespace llvm;
using namespace clang::tooling;
using std::string;

static cl::OptionCategory OptionsCategory("Options");

int main(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, OptionsCategory);
  for(auto s : OptionsParser.getSourcePathList()) {
    std::cout << s << std::endl;
  }
  return 0;
}

#include <iostream>
#include <string>

#include <clang/Tooling/Tooling.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/AST/ASTConsumer.h>
#include <llvm/Support/CommandLine.h>

using namespace llvm;
using namespace clang;
using namespace clang::tooling;
using std::string;

class MyFrontendAction : public ASTFrontendAction {
  public:
    MyFrontendAction() {}

    std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
      std::cout << InFile.str() << std::endl;
      return nullptr;
    }
};

static cl::OptionCategory OptionsCategory("skel options");

int main(int argc, const char **argv) {
  CommonOptionsParser op(argc, argv, OptionsCategory);
  ClangTool Tool(op.getCompilations(), op.getSourcePathList());
  return Tool.run(newFrontendActionFactory<MyFrontendAction>().get());
}

Implement action that prints file names

Implement action that prints file names


#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    if (wast) {
        cout << evm2wasm::evmhex2wast(str) << endl;
    } else {
        cout << evm2wasm::evmhex2wasm(str) << endl;
    }

    return 0;
}

#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <algorithm>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    // clean input of any whitespace (including space and new lines)
    str.erase(remove_if(str.begin(), str.end(), [](unsigned char x){return std::isspace(x);}), str.end());

    if (wast) {
        cout << evm2wasm::evmhex2wast(str) << endl;
    } else {
        cout << evm2wasm::evmhex2wasm(str) << endl;
    }

    return 0;
}

Clean input to evm2wasm CLI from any whitespace


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Pavel Strakhov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  a.setOrganizationName("ToolWindowManagerTest");
  a.setApplicationName("ToolWindowManagerTest");
  MainWindow* w = new MainWindow();
  w->show();

  return a.exec();
}

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Pavel Strakhov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  a.setOrganizationName(QStringLiteral("ToolWindowManagerTest"));
  a.setApplicationName(QStringLiteral("ToolWindowManagerTest"));
  MainWindow* w = new MainWindow();
  w->show();

  return a.exec();
}

Fix string literal compile error that didn't show up before


#include "Moves/En_Passant.h"

#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"

//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
    Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
    is_en_passant_move = true;
}

//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
    return board.is_en_passant_targetable(end());
}

//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
    board.remove_piece({end().file(), start().rank()});
    Pawn_Move::side_effects(board);
}

#include "Moves/En_Passant.h"

#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"

//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
    Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
    is_en_passant_move = true;
}

//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
    return board.is_en_passant_targetable(end());
}

//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
    board.remove_piece({end().file(), start().rank()});
    Pawn_Capture::side_effects(board);
}

Use immediate base class method

Use immediate base class method


#include <iostream>

int main () {
    std::cout << "Hello word!" << std::endl;
}

#include <iostream>
#include <boost/asio.hpp>

int main () {
    boost::asio::io_service io_dummy;
    boost::asio::deadline_timer t(io_dummy, boost::posix_time::seconds(5));
    t.wait();
    std::cout << "Hello word!" << std::endl;
}

Add a dummy for testing Boost dependencies within CMake


/*
 * Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "App.hpp"
#include "Window.hpp"

SuperFreeCell::SuperFreeCell()
		:
		BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
	Window* win=new Window();
	win->Lock();
	win->Show();
	win->Unlock();
}

SuperFreeCell::~SuperFreeCell()
{

}

void
SuperFreeCell::AboutRequested()
{
	BString aboutText="";
	aboutText << "SuperFreeCell 0.1 \n";
	aboutText << "A freecell clone for Haiku \n";
	aboutText << "\n";
	aboutText << "2014 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
	aboutText << "Licensed under the MIT license\n";

	BAlert* about=new BAlert("About",aboutText,"OK");
	about->Go();
}

int
main(int argc, char** argv)
{
	SuperFreeCell app;
	app.Run();
	return 0;
}

/*
 * Copyright 2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "App.hpp"
#include "Window.hpp"

SuperFreeCell::SuperFreeCell()
		:
		BApplication("application/x-vnd.adrianarroyocalle.SuperFreeCell")
{
	Window* win=new Window();
	win->Lock();
	win->Show();
	win->Unlock();
}

SuperFreeCell::~SuperFreeCell()
{

}

void
SuperFreeCell::AboutRequested()
{
	BString aboutText="";
	aboutText << "SuperFreeCell 0.1 \n";
	aboutText << "A freecell clone for Haiku \n";
	aboutText << "\n";
	aboutText << "2014-2015 Adrián Arroyo Calle <adrian.arroyocalle@gmail.com>\n";
	aboutText << "Licensed under the MIT license\n";

	BAlert* about=new BAlert("About",aboutText,"OK");
	about->Go();
}

int
main(int argc, char** argv)
{
	SuperFreeCell app;
	app.Run();
	return 0;
}

Change year in About Dialog

Change year in About Dialog


#include "mpage.h"

PageItemProxy & PageItemProxy::operator=(const uint8_t & value)
{
    MemoryPage & page = reinterpret_cast<MemoryPage&>(*this);
    page.m_Data[page.m_ProxyIndex] = value;
    page.m_Dirty = true;
    return *this;
}

PageItemProxy::operator uint8_t()
{
    MemoryPage & page = reinterpret_cast<MemoryPage&>(*this);
    return page.m_Data[page.m_ProxyIndex];
}

MemoryPage::MemoryPage() :
    m_Data(nullptr), m_Size(0), m_Start(0), m_Dirty(false)
{
}

int MemoryPage::size() const
{
    return m_Size;
}

uint64_t MemoryPage::start() const
{
    return m_Start;
}

bool MemoryPage::dirty() const
{
    return m_Dirty;
}

void MemoryPage::reset(int start, int size)
{
    m_Start = start;
    m_Size = size;
    m_Dirty = false;
}

uint8_t *& MemoryPage::data()
{
    return m_Data;
}

PageItemProxy & MemoryPage::relative(uint64_t idx)
{
    m_ProxyIndex = idx;
    return reinterpret_cast<PageItemProxy&>(*this);
}

PageItemProxy & MemoryPage::absolute(uint64_t idx)
{
    return relative(idx - m_Start);
}

#include "mpage.h"

PageItemProxy & PageItemProxy::operator=(const uint8_t & value)
{
    MemoryPage & page = reinterpret_cast<MemoryPage&>(*this);
    if (value == page.m_Data[page.m_ProxyIndex]) {
        return *this;
    }

    page.m_Data[page.m_ProxyIndex] = value;
    page.m_Dirty = true;
    return *this;
}

PageItemProxy::operator uint8_t()
{
    MemoryPage & page = reinterpret_cast<MemoryPage&>(*this);
    return page.m_Data[page.m_ProxyIndex];
}

MemoryPage::MemoryPage() :
    m_Data(nullptr), m_Size(0), m_Start(0), m_Dirty(false)
{
}

int MemoryPage::size() const
{
    return m_Size;
}

uint64_t MemoryPage::start() const
{
    return m_Start;
}

bool MemoryPage::dirty() const
{
    return m_Dirty;
}

void MemoryPage::reset(int start, int size)
{
    m_Start = start;
    m_Size = size;
    m_Dirty = false;
}

uint8_t *& MemoryPage::data()
{
    return m_Data;
}

PageItemProxy & MemoryPage::relative(uint64_t idx)
{
    m_ProxyIndex = idx;
    return reinterpret_cast<PageItemProxy&>(*this);
}

PageItemProxy & MemoryPage::absolute(uint64_t idx)
{
    return relative(idx - m_Start);
}

Add potential optimization check in proxy


/******************************************************************************

  This source file is part of the Avogadro project.

  Copyright 2012 Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "scene.h"

#include "geometryvisitor.h"

#include <Eigen/Geometry>

namespace Avogadro {
namespace Rendering {

Scene::Scene() : m_center(Vector3f::Zero()), m_radius(4.0f)
{
}

Scene::~Scene()
{
}

Vector3f Scene::center()
{
  GeometryVisitor visitor;
  m_rootNode.accept(visitor);

  // For an empty scene ensure that a minimum radius of 4.0 (gives space).
  m_center = visitor.center();
  m_radius = std::max(4.0f, visitor.radius());

  return m_center;
}

float Scene::radius()
{
  // We need to know where the center is to get the radius
  center();
  return m_radius;
}

void Scene::clear()
{
  m_rootNode.clear();
}

} // End Rendering namespace
} // End Avogadro namespace

/******************************************************************************

  This source file is part of the Avogadro project.

  Copyright 2012 Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "scene.h"

#include "geometryvisitor.h"

#include <Eigen/Geometry>

namespace Avogadro {
namespace Rendering {

Scene::Scene() : m_center(Vector3f::Zero()), m_radius(4.0f)
{
}

Scene::~Scene()
{
}

Vector3f Scene::center()
{
  GeometryVisitor visitor;
  m_rootNode.accept(visitor);

  // For an empty scene ensure that a minimum radius of 4.0 (gives space).
  m_center = visitor.center();
  m_radius = std::max(4.0f, visitor.radius()) + 2.0f;

  return m_center;
}

float Scene::radius()
{
  // We need to know where the center is to get the radius
  center();
  return m_radius;
}

void Scene::clear()
{
  m_rootNode.clear();
}

} // End Rendering namespace
} // End Avogadro namespace

Add a little padding to the radius

Add a little padding to the radius

There is no need to use exact radius, pad a little for clipping.

Change-Id: I68945036be9c2c01427b14d97a149fbd10009df1


#include "main_window.hpp"

#include <QApplication>
#include <iostream>

using namespace std;
using namespace datavis;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    auto main_win = new MainWindow;

    auto args = app.arguments();

    if (args.size() > 1)
    {
        auto file_path = args[1];
        if (file_path.endsWith(".h5"))
        {
            cout << "Opening data file: " << file_path.toStdString() << endl;
            main_win->openDataFile(file_path);
        }
        else if (file_path.endsWith(".datavis"))
        {
            cout << "Opening project file: " << file_path.toStdString() << endl;
            main_win->openProjectFile(file_path);
        }
        else
        {
            cout << "Unknown file type: " << file_path.toStdString() << endl;
            return 1;
        }
    }

    main_win->resize(400,500);
    main_win->move(50,50);
    main_win->show();

    return app.exec();
}

#include "main_window.hpp"

#include <QApplication>
#include <iostream>

using namespace std;
using namespace datavis;

namespace datavis {

enum File_Type
{
    Unknown_File_Type,
    Data_File_Type,
    Project_File_Type
};

}
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    auto args = app.arguments();

    QString file_path;
    File_Type file_type = Unknown_File_Type;

    if (args.size() > 1)
    {
        file_path = args[1];
        if (file_path.endsWith(".h5"))
        {
            file_type = Data_File_Type;
        }
        else if (file_path.endsWith(".datavis"))
        {
            file_type = Project_File_Type;
        }
        else
        {
            cout << "Unknown file type: " << file_path.toStdString() << endl;
            return 1;
        }
    }

    auto main_win = new MainWindow;

    if (!file_path.isEmpty())
    {
        switch(file_type)
        {
        case Data_File_Type:
        {
            cout << "Opening data file: " << file_path.toStdString() << endl;
            main_win->openDataFile(file_path);
            break;
        }
        case Project_File_Type:
        {
            cout << "Opening project file: " << file_path.toStdString() << endl;
            main_win->openProjectFile(file_path);
            break;
        }
        default:
        {
            cerr << "Error: Unexpected file type " << file_type << " for file: " << file_path.toStdString() << endl;
        }
        }
    }

    main_win->resize(400,500);
    main_win->move(50,50);
    main_win->show();

    int status = app.exec();

    delete main_win;

    return status;
}

Main: Fix memory leak; Improve command-line argument handling


#include "mem/Compiler.hpp"

int main (int argc, char** argv)
{
   opt::Options opts;
   opts.addStrOpt("--dump-ast-xml", "",
      "Dump the Abstract Syntax Tree as XML");
   opts.addStrOpt("--emit-llvm-bc", "",
      "Emit LLVM bytecode");
   opts.addStrOpt("--log-formatter", "",
      "Set the log formatter");
   opts.addIntEnumOpt("--log-level", "",
      "Set the minimum log level")
      ->bind("unknown", log::UNKNOWN)
      ->bind("debug", log::DEBUG)
      ->bind("info", log::INFO)
      ->bind("warning", log::WARNING)
      ->bind("error", log::ERROR)
      ->bind("fatal-error", log::FATAL_ERROR);
   opts.addBoolOpt("--help", "",
      "Show help");
   opts.addStrOpt("--output", "",
      "Path to the output file");
   opts.addBoolOpt("--version", "",
      "Show version");
   opts.addStrOpt("--dump-st-xml", "",
      "Dump the Symbol Table as XML");
   opts.parse(argc, argv);

   Compiler memc;
   memc.setOptions(&opts);
   memc.run();

   return 0;
}

#include "mem/Compiler.hpp"

int main (int argc, char** argv)
{
   opt::Options opts;
   opts.addStrOpt("--dump-ast-xml", "",
      "Dump the Abstract Syntax Tree as XML");
   opts.addStrOpt("--emit-llvm-bc", "",
      "Emit LLVM bytecode");
   opts.addStrOpt("--log-formatter", "",
      "Set the log formatter");
   opts.addIntEnumOpt("--log-level", "",
      "Set the minimum log level")
      ->bind("unknown", log::UNKNOWN)
      ->bind("debug", log::DEBUG)
      ->bind("info", log::INFO)
      ->bind("warning", log::WARNING)
      ->bind("error", log::ERROR)
      ->bind("fatal-error", log::FATAL_ERROR);
   opts.addBoolOpt("--help", "",
      "Show help");
   opts.addStrOpt("--output", "",
      "Path to the output file");
   opts.addBoolOpt("--version", "",
      "Show version");
   opts.addStrOpt("--dump-st-xml", "",
      "Dump the Symbol Table as XML");
   opts.parse(argc, argv);

   Compiler memc;
   memc.setOptions(&opts);
   memc.run();

   return memc.isBuildSuccessful() ? 0 : 1;
}

Change exit code to 1 if build unsuccessful


// RUN: %clang_cc1 -fsyntax-only -verify %s
template<typename T>
struct X0 {
  typedef T* type;

  void f0(T);
  void f1(type);
};

template<> void X0<char>::f0(char);
template<> void X0<char>::f1(type);

namespace PR6161 {
  template<typename _CharT>
  class numpunct : public locale::facet // expected-error{{use of undeclared identifier 'locale'}} \
              // expected-error{{expected class name}}
  {
    static locale::id id; // expected-error{{use of undeclared identifier}}
  };
  numpunct<char>::~numpunct(); // expected-error{{expected the class name after '~' to name a destructor}}
}

namespace PR12331 {
  template<typename T> struct S {
    struct U { static const int n = 5; };
    enum E { e = U::n }; // expected-note {{implicit instantiation first required here}}
    int arr[e];
  };
  template<> struct S<int>::U { static const int n = sizeof(int); }; // expected-error {{explicit specialization of 'U' after instantiation}}
}

Add regression test for PR12331.

Add regression test for PR12331.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@185453 91177308-0d34-0410-b5e6-96231b3b80d8


#include <cstdio>

long int f[39];
long int r[39];

long int fib(long int n) {
    if (f[n] != -1)
        return f[n];

    if (n <= 1) {
        f[n] = n;
        r[n] = 0;
    } else {
        f[n] = fib(n - 1) + fib(n - 2);
        r[n] = r[n - 1] + r[n - 2] + 2;
    }

    return f[n];
}

int main() {
    int i, j;
    long int n;

    for (j = 0; j <= 39; j++) {
        f[j] = -1;
        r[j] = -1;
    }

    scanf("%d", &i);
    while (i--) {
        scanf("%ld", &n);
        printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
    }

    return 0;
}

#include <cstdio>
#include <cstring>

long int f[39];
long int r[39];

long int fib(long int n) {
    if (f[n] != -1)
        return f[n];

    if (n <= 1) {
        f[n] = n;
        r[n] = 0;
    } else {
        f[n] = fib(n - 1) + fib(n - 2);
        r[n] = r[n - 1] + r[n - 2] + 2;
    }

    return f[n];
}

int main() {
    int i, j;
    long int n;

    memset(f, -1, sizeof(f));
    memset(r, -1, sizeof(r));

    scanf("%d", &i);
    while (i--) {
        scanf("%ld", &n);
        printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
    }

    return 0;
}

Fix undefined behavior for c++17

Fix undefined behavior for c++17


#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
  return true;
}

#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ROS_INFO("Ready. getPostureKey");
  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  ROS_INFO("Get map of patterns parent");
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
    ROS_INFO(std::string("Found posture of ").append(it->second).c_str());
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
  return true;
}

Add status echo to PPG node for debug

Add status echo to PPG node for debug


#include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>

using namespace std;

namespace gazebo
{
  class SetupWorld : public WorldPlugin
  {
    public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
    {
      cout << "Setting up world..." << flush;

      // Create a new transport node
      transport::NodePtr node(new transport::Node());

      // Initialize the node with the world name
      node->Init(_parent->GetName());

      // Create a publisher on the ~/physics topic
      transport::PublisherPtr physicsPub =
        node->Advertise<msgs::Physics>("~/physics");

      msgs::Physics physicsMsg;
      physicsMsg.set_type(msgs::Physics::ODE);

      // Set the step time
      physicsMsg.set_max_step_size(0.001);

      // Set the real time update rate
      physicsMsg.set_real_time_update_rate(0.0);

      // Change gravity
      //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));

      physicsPub->Publish(physicsMsg);

      cout << " done." << endl;
    }
  };

  // Register this plugin with the simulator
  GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}

#include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>

using namespace std;

namespace gazebo
{
  class SetupWorld : public WorldPlugin
  {
    public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
    {
      cout << "Setting up world..." << flush;

      // Create a new transport node
      transport::NodePtr node(new transport::Node());

      // Initialize the node with the world name
      node->Init(_parent->GetName());

      // Create a publisher on the ~/physics topic
      transport::PublisherPtr physicsPub =
        node->Advertise<msgs::Physics>("~/physics");

      msgs::Physics physicsMsg;
      physicsMsg.set_type(msgs::Physics::ODE);

      // Set the step time
      physicsMsg.set_max_step_size(0.001);

      // Set the real time update rate
      physicsMsg.set_real_time_update_rate(1000.0);

      // Change gravity
      //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));

      physicsPub->Publish(physicsMsg);

      cout << " done." << endl;
    }
  };

  // Register this plugin with the simulator
  GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}

Set gazebo to run at real time (if possible) for debugging The previous default was too fast for proper manual control of the robot


#include <stdexcept>
#include <iostream>

int opt_parse(int argc, char** argv) {
    // implement option parsing and call the real main
    // with everything ready to use
    return 0;
}

int main(int argc, char** argv) {
    try {
        return opt_parse(argc, argv);
    } catch (std::exception& e) {
        std::cerr << "Standard exception. What: " << e.what() << "\n";
        return 10;
    } catch (...) {
        std::cerr << "Unknown exception.\n";
        return 11;
    }
}

#include <stdexcept>
#include <iostream>

int opt_parse(int argc, char** argv) {
    // implement option parsing and call the real main
    // with everything ready to use
    return 0;
}

int main(int argc, char** argv) {
    //unless one needs C-style I/O
    std::ios_base::sync_with_stdio(false);
    try {
        return opt_parse(argc, argv);
    } catch (std::exception& e) {
        std::cerr << "Standard exception. What: " << e.what() << "\n";
        return 10;
    } catch (...) {
        std::cerr << "Unknown exception.\n";
        return 11;
    }
}

Add sync_with_stdio(false), tour c++ pg132


/*
 * =========================================================================================
 * Name        : eventLib.cpp
 * Author      : Duc Dung Nguyen
 * Email       : nddung@hcmut.edu.vn
 * Copyright   : Faculty of Computer Science and Engineering - Bach Khoa University
 * Description : library for Assignment 1 - Data structures and Algorithms - Spring 2017
 *               This library contains functions used for event management
 * =========================================================================================
 */

#include "eventLib.h"

/// NOTE: each event will be separated by spaces, or endline character
void loadEvents(char* fName, L1List<busEvent_t> &eList) {
    ifstream inFile(fName);

    if (inFile) {
        string line;
        while (getline(inFile , line)) {
            istringstream iss(line);
            while (iss) {
                string sub;
                iss >> sub;
                busEvent_t __e(sub);
                eList.insertHead(__e);
            }
        }
        eList.reverse();
        inFile.close();
    }
    else {
        cout << "The file is not found!";
    }
}

/*
 * =========================================================================================
 * Name        : eventLib.cpp
 * Author      : Duc Dung Nguyen
 * Email       : nddung@hcmut.edu.vn
 * Copyright   : Faculty of Computer Science and Engineering - Bach Khoa University
 * Description : library for Assignment 1 - Data structures and Algorithms - Spring 2017
 *               This library contains functions used for event management
 * =========================================================================================
 */

#include "eventLib.h"

/// NOTE: each event will be separated by spaces, or endline character
void loadEvents(char* fName, L1List<busEvent_t> &eList) {
    ifstream inFile(fName);

    if (inFile) {
        string line;
        while (getline(inFile , line)) {
            /// On Windows, lines on file ends with \r\n. So you have to remove \r
            if (line[line.length() - 1] == '\r')
                line.erase(line.length() - 1);

            istringstream iss(line);
            while (iss) {
                string sub;
                iss >> sub;
                busEvent_t __e(sub);
                eList.insertHead(__e);
            }
        }
        eList.reverse();
        inFile.close();
    }
    else {
        cout << "The file is not found!";
    }
}

Fix endline character problem on Windows


// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/network_change_notifier_win.h"

#include <iphlpapi.h>
#include <winsock2.h>

#pragma comment(lib, "iphlpapi.lib")

namespace net {

NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
  memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
  addr_overlapped_.hEvent = WSACreateEvent();
}

NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
  CancelIPChangeNotify(&addr_overlapped_);
  addr_watcher_.StopWatching();
  WSACloseEvent(addr_overlapped_.hEvent);
}

void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
  NotifyObserversOfIPAddressChange();

  // Start watching for the next address change.
  WatchForAddressChange();
}

void NetworkChangeNotifierWin::WatchForAddressChange() {
  HANDLE handle = NULL;
  DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
  CHECK(ret == ERROR_IO_PENDING);
  addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}

}  // namespace net

// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/network_change_notifier_win.h"

#include <iphlpapi.h>
#include <winsock2.h>

#pragma comment(lib, "iphlpapi.lib")

namespace net {

NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
  memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
  addr_overlapped_.hEvent = WSACreateEvent();
  WatchForAddressChange();
}

NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
  CancelIPChangeNotify(&addr_overlapped_);
  addr_watcher_.StopWatching();
  WSACloseEvent(addr_overlapped_.hEvent);
}

void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
  NotifyObserversOfIPAddressChange();

  // Start watching for the next address change.
  WatchForAddressChange();
}

void NetworkChangeNotifierWin::WatchForAddressChange() {
  HANDLE handle = NULL;
  DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
  CHECK(ret == ERROR_IO_PENDING);
  addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}

}  // namespace net

Fix regression where we didn't ever start watching for network address changes on Windows.

BUG=48204
TEST=NetworkChangeNotifier works on Windows
Review URL: http://codereview.chromium.org/2807036

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51574 0039d316-1c4b-4281-b951-d872f2087c98


#include <bulk.hpp>
#include <iostream>

int main() {
    bulk::spawn(bulk::available_processors(), [](int s, int p) {
        for (int t = 0; t < p; ++t) {
            bulk::send<int, int>(t, s, s);
        }

        bulk::sync();

        if (s == 0) {
            for (auto message : bulk::messages<int, int>()) {
                std::cout << message.tag << ", " << message.content << std::endl;
            }
        }
    });

    return 0;
}

#include <bulk.hpp>
#include <iostream>

int main() {
    auto center = bulk::center();
    center.spawn(center.available_processors(), [&center](int s, int p) {
        for (int t = 0; t < p; ++t) {
            center.send<int, int>(t, s, s);
        }

        center.sync();

        if (s == 0) {
            for (auto message : center.messages<int, int>()) {
                std::cout << message.tag << ", " << message.content << std::endl;
            }
        }
    });

    return 0;
}

Update syntax for message passing example


// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/script_prologue.h"

namespace bindings {

// NOTE: Line breaks will be removed from these scripts before their execution in the
//       JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
//       as that will cause the first line of the user script to be ignored.

// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
  enumerable: true,
  configurable: false,
  writable: false,
  value: (() => {
    let _script_cache = {};
    let _script_mappings = {};

    /** require(script) **/
    let _function = (script) => {
      if (_script_mappings.hasOwnProperty(script))
        script = _script_mappings[script];
      if (!_script_cache.hasOwnProperty(script))
        _script_cache[script] = requireImpl(script);
      return _script_cache[script];
    };

    /** require.map(source, destination) **/
    _function.map = (script, destination) =>
      _script_mappings[script] = destination;
    return _function;
  })()
});
)";

const char kModulePrologue[] = R"(
(function() {
  let exports = {};
  let module = {};

  return (function(require, exports, module, global) {
)";

const char kModuleEpilogue[] = R"(
    ; return exports;
  })(require, exports, module, self);
})();
)";

}  // namespace bindings

// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/script_prologue.h"

namespace bindings {

// NOTE: Line breaks will be removed from these scripts before their execution in the
//       JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
//       as that will cause the first line of the user script to be ignored.

// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
  enumerable: true,
  configurable: false,
  writable: false,
  value: (() => {
    let _script_cache = {};

    /** require(script) **/
    let _function = (script) => {
      if (!_script_cache.hasOwnProperty(script))
        _script_cache[script] = requireImpl(script);
      return _script_cache[script];
    }

    return _function;
  })()
});
)";

const char kModulePrologue[] = R"(
(function() {
  let exports = {};
  let module = {};

  return (function(require, exports, module, global) {
)";

const char kModuleEpilogue[] = R"(
    ; return exports;
  })(require, exports, module, self);
})();
)";

}  // namespace bindings

Remove require.map() from the script prologue


// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.02.25

// Options.cpp

#include "Options.hpp"

Options::Options(int argc, char **argv)
#ifdef PROJECT_NAME
	#define HELPER4QUOTE(N) #N
	: cxxopts::Options(HELPER4QUOTE(PROJECT_NAME), "Description of program (?)")
	#undef HELPER4QUOTE
#else
	#error "PROJECT_NAME undefined"
#endif
{
	_configFile = "etc/config.conf";
}

Options::~Options()
{
}

const std::string& Options::getConfig() const
{
	return _configFile;
}

// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.02.25

// Options.cpp

#include "Options.hpp"

Options::Options(int argc, char **argv)
#ifdef PROJECT_NAME
	#define HELPER4QUOTE(N) #N
	: cxxopts::Options(HELPER4QUOTE(PROJECT_NAME), "Description of program (?)")
	#undef HELPER4QUOTE
#else
	#error "PROJECT_NAME undefined"
#endif
{
	add_options()
	("c,config", "Path to config file", cxxopts::value<std::string>(_configFile), "[config] helper (?)")
	;

	parse(argc, argv);
}

Options::~Options()
{
}

const std::string& Options::getConfig() const
{
	return _configFile;
}

Implement getting of path to config file by argument


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

Delete Node in a Linked List

Delete Node in a Linked List


//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "OuterWallInsetBeadingStrategy.h"

#include <algorithm>

namespace cura
{
    BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
    {
        Beading ret = parent->compute(thickness, bead_count);

        // Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signalling' walls.
        bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; });

        // Early out when the only walls are outer.
        if (bead_count < 3)
        {
            return ret;
        }

        // Actually move the outer wall inside.
        ret.toolpath_locations[0] = ret.toolpath_locations[0] + outer_wall_offset;

        return ret;
    }

} // namespace cura

//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "OuterWallInsetBeadingStrategy.h"

#include <algorithm>

namespace cura
{
    BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
    {
        Beading ret = parent->compute(thickness, bead_count);

        // Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signalling' walls.
        bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; });

        // Early out when the only walls are outer.
        if (bead_count < 2)
        {
            return ret;
        }

        // Actually move the outer wall inside. Ensure that the outer wall never goes beyond the middle line.
        ret.toolpath_locations[0] = std::min(ret.toolpath_locations[0] + outer_wall_offset, thickness / 2);
        return ret;
    }

} // namespace cura

Fix outerwall inset for thin parts

Fix outerwall inset for thin parts

CURA-7830


#include "frames.h"

frameGPUi::frameGPUi (int w, int h, bool full) {
	glGenTextures (1, &plane);
	glBindTexture (GL_TEXTURE_2D, plane);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB10_A2, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, NULL);
	timecode = 0;
}

frameGPUi::~frameGPUi () {
	glDeleteTextures (1, &plane);
}

#include "frames.h"

frameGPUi::frameGPUi (int w, int h, bool full) {
	glGenTextures (1, &plane);
	glBindTexture (GL_TEXTURE_2D, plane);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D (GL_TEXTURE_2D, 0, full ? GL_RGBA32F : GL_RGBA16F, w, h, 0, GL_RGBA, full ? GL_FLOAT : GL_HALF_FLOAT, NULL);

	timecode = 0;
}

frameGPUi::~frameGPUi () {
	glDeleteTextures (1, &plane);
}

Revert "10-bit normalased internal frames"

This reverts commit cd31198a032cbbcd1cc52e4bdcc8795ae3b1d802.


/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/HttpCode.hpp"

std::string HTTPP::HTTP::getDefaultMessage(HttpCode code)
{
    switch (code)
    {

    case HttpCode::Continue:
        return "Continue";

    case HttpCode::Ok:
        return "Ok";
    case HttpCode::Created:
        return "Created";
    case HttpCode::Accepted:
        return "Accepted";
    case HttpCode::NoContent:
        return "NoContent";

    case HttpCode::MultipleChoice:
        return "MultipleChoice";
    case HttpCode::MovedPermentaly:
        return "MovedPermentaly";
    case HttpCode::MovedTemporarily:
        return "MovedTemporarily";
    case HttpCode::NotModified:
        return "NotModified";

    case HttpCode::BadRequest:
        return "BadRequest";
    case HttpCode::Unauthorized:
        return "Unauthorized";
    case HttpCode::Forbidden:
        return "Forbidden";
    case HttpCode::NotFound:
        return "NotFound";

    case HttpCode::InternalServerError:
        return "InternalServerError";
    case HttpCode::NotImplemented:
        return "NotImplemented";
    case HttpCode::BadGateway:
        return "BadGateway";
    case HttpCode::ServiceUnavailable:
        return "ServiceUnavailable";
    case HttpCode::HttpVersionNotSupported:
        return "HttpVersionNotSupported";
    }
}

/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/HttpCode.hpp"

std::string HTTPP::HTTP::getDefaultMessage(HttpCode code)
{
    switch (code)
    {

    default:
        return "Unknown";

    case HttpCode::Continue:
        return "Continue";

    case HttpCode::Ok:
        return "Ok";
    case HttpCode::Created:
        return "Created";
    case HttpCode::Accepted:
        return "Accepted";
    case HttpCode::NoContent:
        return "NoContent";

    case HttpCode::MultipleChoice:
        return "MultipleChoice";
    case HttpCode::MovedPermentaly:
        return "MovedPermentaly";
    case HttpCode::MovedTemporarily:
        return "MovedTemporarily";
    case HttpCode::NotModified:
        return "NotModified";

    case HttpCode::BadRequest:
        return "BadRequest";
    case HttpCode::Unauthorized:
        return "Unauthorized";
    case HttpCode::Forbidden:
        return "Forbidden";
    case HttpCode::NotFound:
        return "NotFound";

    case HttpCode::InternalServerError:
        return "InternalServerError";
    case HttpCode::NotImplemented:
        return "NotImplemented";
    case HttpCode::BadGateway:
        return "BadGateway";
    case HttpCode::ServiceUnavailable:
        return "ServiceUnavailable";
    case HttpCode::HttpVersionNotSupported:
        return "HttpVersionNotSupported";
    }
}

Add default clause to switch

Add default clause to switch


#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include <string>

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  explicit KrsServoNode(ros::NodeHandle& nh, const char* path);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  std::string path;
  nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");

  KrsServoNode ksn(nh, path.c_str());

  ros::spin();
  return 0;
}

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
  : krs(path)
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include <string>

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  KrsServoNode(ros::NodeHandle& nh, const char* path);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  std::string path;
  nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");

  KrsServoNode ksn(nh, path.c_str());

  ros::spin();
  return 0;
}

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
  : krs(path)
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

Remove explicit by constructor has too many args.


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/animation/css/CSSTransitionData.h"

#include "core/animation/Timing.h"

namespace blink {

CSSTransitionData::CSSTransitionData()
{
    m_propertyList.append(initialProperty());
}

CSSTransitionData::CSSTransitionData(const CSSTransitionData& other)
    : CSSTimingData(other)
    , m_propertyList(other.m_propertyList)
{
}

bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const
{
    return m_propertyList == other.m_propertyList;
}

Timing CSSTransitionData::convertToTiming(size_t index) const
{
    ASSERT(index < m_propertyList.size());
    // Note that the backwards fill part is required for delay to work.
    Timing timing = CSSTimingData::convertToTiming(index);
    timing.fillMode = Timing::FillModeBoth;
    return timing;
}

} // namespace blink

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/animation/css/CSSTransitionData.h"

#include "core/animation/Timing.h"

namespace blink {

CSSTransitionData::CSSTransitionData()
{
    m_propertyList.append(initialProperty());
}

CSSTransitionData::CSSTransitionData(const CSSTransitionData& other)
    : CSSTimingData(other)
    , m_propertyList(other.m_propertyList)
{
}

bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const
{
    return m_propertyList == other.m_propertyList;
}

Timing CSSTransitionData::convertToTiming(size_t index) const
{
    ASSERT(index < m_propertyList.size());
    // Note that the backwards fill part is required for delay to work.
    Timing timing = CSSTimingData::convertToTiming(index);
    timing.fillMode = Timing::FillModeBackwards;
    return timing;
}

} // namespace blink

Animations: Change fill mode of transitions to backwards not both

This change allows CSS transitions to be replayed via the AnimationPlayer
API and not prevent new transitions from being triggered.

BUG=437102

Review URL: https://codereview.chromium.org/761033002

git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@186083 bbb929c8-8fbe-4397-9dbb-9b2b20218538


#include <iostream>

using namespace std;

int main()
{
	cout << "TODO" << endl;

	return -1;
}

#include <iostream>
#include <string>
#include <fstream>
#include <array>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include "IndexHelper.hpp"

using namespace std;

const array<pair<int, string>, 3> INDEXWEIGHTS {{
	{16, "titleindex"},
	{4, "webindex"},
	{1, "pageindex"}
}};

string getQueryString()
{
	ifstream input("query.txt");
	string query;
	getline(input, query);

	return query;
}

map<string, int> getWeightedResults(const string& query)
{
	map<string, int> results;
	IndexHelper helper;

	// Add the base score from the index
	for (const auto index : INDEXWEIGHTS) {
		for (auto link : helper.getLinksFromIndex(query, index.second)) {
			results[link] += index.first;
		}
	}

	// TODO: Add the link score

	return results;
}

vector<string> getResults(string query)
{
	vector<pair<int, string>> orderedResults;
	for (auto entry : getWeightedResults(query)) {
		orderedResults.emplace_back(entry.second, entry.first);
	}

	sort(orderedResults.begin(), orderedResults.end(), greater<pair<int, string>>());

	vector<string> results;
	for (auto result : orderedResults) {
		results.emplace_back(result.second);
	}

	return results;

}

int main()
{
	string query = "liacs";
	for (auto result : getResults(query)) {
		cout << result << endl;
	}
	return 0;
}

Implement ranking system based on web, title, and pageindex.


// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])

// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP_I:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC_I:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
// CHECK: ![[SP_I]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC_I]] = !DILocation({{.*}}scope: ![[SP_I]])

Update testcase for upstream LLVM changes (r302469).

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@302577 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit b6c02e8e5ac5de00590d22161a0eac44cb9a4a8a)


#include <iostream>

int main()
{
	std::cout << "Hello, world!" << std::endl;
}

#include <iostream>

int main()
{
	std::cout << "Hello, world! \n";
}

Change space 8 to 4

Change space 8 to 4


// RUN: %clang_cc1 %s -fsyntax-only -verify

// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}

template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}

template <__int128_t T> class Type3 {};
template <__int128_t T> void Function3(Type3<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type3<-42>' to 'Type3<-42i128> &' for 1st argument;}}

template <__uint128_t T> class Type4 {};
template <__uint128_t T> void Function4(Type4<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type4<42>' to 'Type4<42Ui128> &' for 1st argument;}}

void Function() {
  Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
  Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
  Function3(Type3<-42>()); // expected-error{{no matching function for call to 'Function3'}}
  Function4(Type4<42>()); // expected-error{{no matching function for call to 'Function4'}}
}

// RUN: %clang_cc1 %s -fsyntax-only -verify

// PR11179
template <short T> class Type1 {};
template <short T> void Function1(Type1<T>& x) {} // expected-note{{candidate function [with T = -42] not viable: no known conversion from 'Type1<-42>' to 'Type1<-42> &' for 1st argument;}}

template <unsigned short T> class Type2 {};
template <unsigned short T> void Function2(Type2<T>& x) {} // expected-note{{candidate function [with T = 42] not viable: no known conversion from 'Type2<42>' to 'Type2<42> &' for 1st argument;}}

void Function() {
  Function1(Type1<-42>()); // expected-error{{no matching function for call to 'Function1'}}
  Function2(Type2<42>()); // expected-error{{no matching function for call to 'Function2'}}
}

Remove test with int128 printing since it breaks on some platforms.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@143997 91177308-0d34-0410-b5e6-96231b3b80d8


// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	run_tests();

	return 0;
}

// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	//test change
	run_tests();

	return 0;
}

Test change to test both branch functionality and approval process

.


Remove unnecessary output redirection in a test.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@158424 91177308-0d34-0410-b5e6-96231b3b80d8


#if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"

using namespace std;

int main(int argc, char *argv[])
{
   EApplication application(""
                            ,"kinc"
                            ,MAJOR_VERSION
                            ,MINOR_VERSION
                            ,REVISION
                            ,unique_ptr<DataFactory>(new DataFactory)
                            ,unique_ptr<AnalyticFactory>(new AnalyticFactory)
                            ,argc
                            ,argv);
   return application.exec();
}

#if(GUI == 0)
#include <ace/console/eapplication.h>
#else
#include <ace/gui/eapplication.h>
#endif
#include "core/analyticfactory.h"
#include "core/datafactory.h"

using namespace std;

int main(int argc, char *argv[])
{
   EApplication application("SystemsGenetics"
                            ,"kinc"
                            ,MAJOR_VERSION
                            ,MINOR_VERSION
                            ,REVISION
                            ,unique_ptr<DataFactory>(new DataFactory)
                            ,unique_ptr<AnalyticFactory>(new AnalyticFactory)
                            ,argc
                            ,argv);
   return application.exec();
}

Set organization name to SystemsGenetics


#include <ncurses.h>

#include <string>

#include "game.h"

using namespace std;

int main(int argc, char **argv) {

    int initStatus = init();
    if (initStatus == 0) run();

    close();

    printf("GAME OVER\n");

    return 0;
}

#include <ncurses.h>

#include <string>

#include "game.h"

using namespace std;

int main(int argc, char **argv) {

    if (init() == 0) run();

    close();

    printf("GAME OVER\n");

    return 0;
}

Remove unnecessary variable assignment (is implicit return, imho)


#include "HumbugWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }
    w.show();

    return a.exec();
}

#include "HumbugWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setApplicationName("Humbug Desktop");
    a.setApplicationVersion("0.1");

    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }

    w.show();

    return a.exec();
}

Declare an application name and version.


#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, stackAllocate) {
	[[gnu::unused]] Page p;
}

TEST(TestPage, mapOnePage) {
	Span<Page> pages{nullptr, 1};
	auto result = Page::map(pages);
	EXPECT_TRUE(result);
	EXPECT_NE(result(), nullptr);
	pages.value(result());
	EXPECT_EQ(Page::unmap(pages), 0);
}

TEST(TestPage, setPermissions) {
	Span<Page> pages{nullptr, 1};
}

TEST(TestPage, setPermissionsOnUnmappedPage) {
	Span<Page> pages{nullptr, 1};

	// Get a fresh page.
	{
		auto r = Page::map(pages);
		ASSERT_TRUE(r);
		pages.value(r());
	}

	// Explicitly unmap it.
	{
		auto e = Page::unmap(pages);
		ASSERT_EQ(e, 0);
	}

	// Fail to set permissions on unmapped page.
	{
		auto e = Page::setPermissions(pages, Page::Permissions::READ);
		ASSERT_NE(e, 0);
	}
}

#if 0
TEST(PageSpan, mapAndUnmap) {
	PageSpan pages{nullptr, 1};
	auto map = pages.map();
	map.unmap();
}
#endif  // 0

#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, pageSize) {
	Process::init();
	EXPECT_NE(Page::size(), std::size_t{0});
	Process::kill();
}

TEST(TestPage, mapOnePage) {
	Process::init();
	auto size = Page::size();
	auto addr = Page::map(size);
	Page::unmap(addr, size);
	Process::kill();
}

Update the page tests to work with the new API

Signed-off-by: Robert Young <42c59959a3f4413d6a1b4d7b4f99db457d199e49@gmail.com>


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskLoaderTest
#include <boost/test/unit_test.hpp>

#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( my_test1 )
{
  BOOST_REQUIRE(1==0);
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskLoaderTest
#include <boost/test/unit_test.hpp>

#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(defaultConstrutocTest)
{
    /*JPetOptions::Options options = {
      {"inputFile", "data_files/cosm_barrel.hld.root"},
      {"inputFileType", "hld"},
      {"outputFile", "data_files/cosm_barrel.tslot.raw.out.root"},
      {"outputFileType", "tslot.raw"},
      {"firstEvent", "1"},
      {"lastEvent", "10"},
      {"progressBar", "false"}
    };

    JPetTaskLoader taskLoader;
    taskLoader.init(options);*/
}

BOOST_AUTO_TEST_SUITE_END()

Change unit test for JPetTaskLoader.

Change unit test for JPetTaskLoader.

Former-commit-id: 1cbaa59c1010a96926acec93a2e313f482e62943


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  CrcGenerateTable();
  uint32 crc = 0xffffffffL;
  crc = ~CrcCalc(buffer, size);
  return crc;
}

}  // namespace

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "courgette/crc.h"

#ifdef COURGETTE_USE_CRC_LIB
#  include "zlib.h"
#else
extern "C" {
#  include "third_party/lzma_sdk/7zCrc.h"
}
#endif

#include "base/basictypes.h"

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  uint32 crc;

#ifdef COURGETTE_USE_CRC_LIB
  // Calculate Crc by calling CRC method in zlib
  crc = crc32(0, buffer, size);
#else
  // Calculate Crc by calling CRC method in LZMA SDK
  CrcGenerateTable();
  crc = CrcCalc(buffer, size);
#endif

  return ~crc;
}

}  // namespace

Use a different define to decide which CRC library to use.

Change 8569018 used a #ifdef to conditionally decide which external
library to use for Crc calculation. It used OS_CHROMIUMOS to tell
if the build was targetted at Chromium OS.

However, it broke Chromium OS builds of the full Chromium tree in
some cases (heapcheck bots), and was reverted.

Since I really only want to change the library when building from
inside a custom ebuild in the Chromium OS build, it makes sense
to use a #define custom to that ebuild.

So, this change is the same as 8569018, except that is uses
COURGETTE_USE_CRC_LIB instead of OS_CHROMIUMOS.

BUG=8569018

Review URL: http://codereview.chromium.org/8763014

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@112565 0039d316-1c4b-4281-b951-d872f2087c98


// coding: utf-8
#include "hardware.hpp"

// system tick timer
ISR(TIMER2_COMPA_vect)
{
	xpcc::Clock::increment();
}

// main function \o/
int
main(void)
{
	// set the led pins
	initializeLeds();
	RedLedPin::setOutput();
	GreenLedPin::setOutput();
	BlueLedPin::setOutput();

	LightSensorPin::setInput();

	// set up the oversampling of the photosensitive diode
	AdcInterrupt::initialize(AdcInterrupt::Reference::ExternalARef, AdcInterrupt::Prescaler::Div32);
	lightSensor::initialize(adcMap, &lightSensorData);

	GpioD0::connect(Uart::Rx);
	GpioD1::connect(Uart::Tx);
	Uart::initialize<Uart::B115200>();

	xpcc::atmega::enableInterrupts();
	XPCC_LOG_INFO << "\n\nRESTART\n\n";

	while(1)
	{
		dreamer.run();
	}

	return 0;
}

// coding: utf-8
#include "hardware.hpp"

// system tick timer
ISR(TIMER2_COMPA_vect)
{
	xpcc::Clock::increment();
}

// main function \o/
int
main(void)
{
	// set the led pins
	initializeLeds();
	RedLedPin::setOutput();
	GreenLedPin::setOutput();
	BlueLedPin::setOutput();

	LightSensorPin::setInput();

	// set up the oversampling of the photosensitive diode
	AdcInterrupt::initialize(AdcInterrupt::Reference::ExternalARef, AdcInterrupt::Prescaler::Div32);
	lightSensor::initialize(adcMap, &lightSensorData);

	GpioD0::connect(Uart::Rx);
	GpioD1::connect(Uart::Tx);
	Uart::initialize<Uart::B38400>();

	xpcc::atmega::enableInterrupts();
	XPCC_LOG_INFO << "\n\nRESTART\n\n";

	while(1)
	{
		dreamer.run();
	}

	return 0;
}

Set Uart Baudrate to 38.4kBaud, for minimal error.


// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

Disable the right RUN line

Disable the right RUN line

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@231098 91177308-0d34-0410-b5e6-96231b3b80d8


#include <iostream>
#include <unistd.h>

int age = 23;

int main()
{
	sleep(2);
	std::cout << "I am Adrian.\n" << "Age: " << age << "\n";
	return 0;
}

Add newline at the end of the file

Add newline at the end of the file


/*
 * SOPMQ - Scalable optionally persistent message queue
 * Copyright 2014 InWorldz, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "gtest/gtest.h"

#include "util.h"

#include <string>

using sopmq::shared::util;

TEST(UtilTest, HexEncoderWorks)
{
    std::string testStr("abcde");

    std::string result = util::hex_encode((const unsigned char*)testStr.c_str(), testStr.size());

    ASSERT_EQ("6162636465", result);
}

TEST(UtilTest, RandomBytes)
{
    std::string bytes = util::random_bytes(1024);
    ASSERT_EQ(1024, bytes.length());
}

Add additional test for the random bytes utility


// Copyright (C) 2015 Jack Maloney. All Rights Reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

#include "voltz-internal.h"

double StartupTime;

int main(int argc, const char** argv) {

    clock_t begin, end;
    begin = clock();

    vz_bootstrap_runtime(argc, argv);

    end = clock();

    StartupTime = (end - begin) / CLOCKS_PER_SEC;

#ifdef VOLTZ_DEBUG
    printf("Took %f seconds to startup.\n", StartupTime);
#endif

    vz_linker_entry(nil, nil);

}

// Copyright (C) 2015 Jack Maloney. All Rights Reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

#include "voltz-internal.h"
#include <ctime>
#include <cstdio>

double StartupTime;

int main(int argc, const char** argv) {

    clock_t begin, end;
    begin = clock();

    vz_bootstrap_runtime(argc, argv);

    end = clock();

    StartupTime = (end - begin) / CLOCKS_PER_SEC;

#ifdef VOLTZ_DEBUG
    printf("Took %f seconds to startup.\n", StartupTime);
#endif

    vz_linker_entry(nil, nil);

}

Add needed header for travis-ci build

Add needed header for travis-ci build


#include<iostream>

int main()
{
     int value1 = 0, value2 = 0;
     std::cin >> value1 >> value2;
     std::cout << "The product of " << value1 << " and " << value2 << " equals " << value1 + value2 << std::endl;
     return 0;
}

#include<iostream>

int main()
{
     int value1 = 0, value2 = 0;
     std::cin >> value1 >> value2;
     std::cout << "The product of " << value1 << " and " << value2 << " equals " << value1 * value2 << std::endl;
     return 0;
}

Fix * instead of +

Fix * instead of +


/*
* Copyright (c) 2003-2016 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/

/**
 * \file Windows-specific implementation of logit.h
 */

#include "../logit.h"
#include "../../core/PWSLog.h"

#include <wtypes.h>

void pws_os::Logit(LPCTSTR lpszFormat, ...)
{
  va_list args;
  va_start(args, lpszFormat);

  TCHAR szBuffer[1024];
  int nBuf = _vsntprintf_s(szBuffer, sizeof(szBuffer) / sizeof(TCHAR), _TRUNCATE,
                           lpszFormat, args);
#ifdef DEBUG
  ASSERT(nBuf > 0);
#else
  UNREFERENCED_PARAMETER(nBuf); // In Release build only otherwise MS Compiler warning
#endif
  PWSLog::GetLog()->Add(stringT(szBuffer));
  va_end(args);
}

/*
* Copyright (c) 2003-2016 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/

/**
 * \file Windows-specific implementation of logit.h
 */

#include "../logit.h"
#include "../../core/PWSLog.h"

#include <wtypes.h>

// Following disables Microsoft's telemetry code
// added in VS2015
// See https://www.reddit.com/r/cpp/comments/4ibauu/visual_studio_adding_telemetry_function_calls_to/
extern "C"
{
        void _cdecl __vcrt_initialize_telemetry_provider() {}
        void _cdecl __telemetry_main_invoke_trigger() {}
        void _cdecl __telemetry_main_return_trigger() {}
        void _cdecl __vcrt_uninitialize_telemetry_provider() {}
};

void pws_os::Logit(LPCTSTR lpszFormat, ...)
{
  va_list args;
  va_start(args, lpszFormat);

  TCHAR szBuffer[1024];
  int nBuf = _vsntprintf_s(szBuffer, sizeof(szBuffer) / sizeof(TCHAR), _TRUNCATE,
                           lpszFormat, args);
#ifdef DEBUG
  ASSERT(nBuf > 0);
#else
  UNREFERENCED_PARAMETER(nBuf); // In Release build only otherwise MS Compiler warning
#endif
  PWSLog::GetLog()->Add(stringT(szBuffer));
  va_end(args);
}

Disable telemetry installed by Microsoft in VS2015

 See https://www.reddit.com/r/cpp/comments/4ibauu/visual_studio_adding_telemetry_function_calls_to/

Thanks to pm_kan for pointing this out.


#include "output.h"

Output output;

float a = 123.0;
int b = 79;
unsigned int c = 24;

int main()
{
	float d = b;
	float e = c;

	output << (int) a;			// CHECK: 0x0000007b
	output << (unsigned int) a;	// CHECK: 0x0000007b
	output << (int) d;			// CHECK: 0x0000004f
//	output << (int) e;			// XXX should be 0x18, but is 0x17 for some reason
}

#include "output.h"

Output output;

float a = 123.0;
int b = 79;
unsigned int c = 24;
unsigned int f = 0x81234000;

int main()
{
	float d = b;
	float e = c;
	float g = f;

	output << (int) a;			// CHECK: 0x0000007b
	output << (unsigned int) a;	// CHECK: 0x0000007b
	output << (int) d;			// CHECK: 0x0000004f
	output << (int) e;			// CHECK: 0x00000018
	output << (unsigned int) g;	// CHECK: 0x81234000
}

Add test cases for unsigned int to floating point


// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clang_cc1 %s -o - -emit-llvm -fprofile-instrument=clang -mllvm -enable-value-profiling -fexceptions -fcxx-exceptions -triple %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

Fix another use of the driver.

[profile] Fix another use of the driver.

Follow-on to r267262.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@267263 91177308-0d34-0410-b5e6-96231b3b80d8


//------------------------------------------------------------------------------
//  HTTPFileSystemTest.cc
//  Test HTTP file system functionality.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "HTTP/HTTPFileSystem.h"
#include "IO/IO.h"

using namespace Oryol;

#if !ORYOL_EMSCRIPTEN
TEST(HTTPFileSystemTest) {
    Core::Setup();

    // setup an IO facade, and associate http: with the HTTPFileSystem
    IOSetup ioSetup;
    ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
    IO::Setup(ioSetup);

    // asynchronously load the index.html file
    Ptr<IORead> req = IO::LoadFile("http://www.flohofwoe.net/index.html");

    // trigger the runloop until the request has been handled
    while (!req->Handled) {
        Core::PreRunLoop()->Run();
    }

    // check what we got
    CHECK(req->Status == IOStatus::OK);
    CHECK(!req->Data.Empty());
    CHECK(req->Data.Size() > 0);
    if (req->Data.Size() > 0) {
        String content((const char*)req->Data.Data(), 0, req->Data.Size());
        Log::Info("%s\n", content.AsCStr());
    }
    req = 0;

    IO::Discard();
    Core::Discard();
}
#endif

//------------------------------------------------------------------------------
//  HTTPFileSystemTest.cc
//  Test HTTP file system functionality.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "HTTP/HTTPFileSystem.h"
#include "IO/IO.h"

using namespace Oryol;

#if !ORYOL_EMSCRIPTEN && !ORYOL_UNITTESTS_HEADLESS
TEST(HTTPFileSystemTest) {
    Core::Setup();

    // setup an IO facade, and associate http: with the HTTPFileSystem
    IOSetup ioSetup;
    ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
    IO::Setup(ioSetup);

    // asynchronously load the index.html file
    Ptr<IORead> req = IO::LoadFile("http://www.flohofwoe.net/index.html");

    // trigger the runloop until the request has been handled
    while (!req->Handled) {
        Core::PreRunLoop()->Run();
    }

    // check what we got
    CHECK(req->Status == IOStatus::OK);
    CHECK(!req->Data.Empty());
    CHECK(req->Data.Size() > 0);
    if (req->Data.Size() > 0) {
        String content((const char*)req->Data.Data(), 0, req->Data.Size());
        Log::Info("%s\n", content.AsCStr());
    }
    req = 0;

    IO::Discard();
    Core::Discard();
}
#endif

Disable HTTPTest if 'headless', seems to hang travis-ci now


#include <Halide.h>
#include <sys/time.h>

using namespace Halide;

double currentTime() {
    timeval t;
    gettimeofday(&t, NULL);
    return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}

int main(int argc, char **argv) {

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

#include <Halide.h>
using namespace Halide;

int main(int argc, char **argv) {

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

Clear spurious timing code from bounds_interence


#include "fish_detector/common/species_dialog.h"
#include "ui_species_dialog.h"

namespace fish_detector {

SpeciesDialog::SpeciesDialog(QWidget *parent)
  : QDialog(parent)
  , ui_(new Ui::SpeciesDialog) {
  ui_->setupUi(this);
}

void SpeciesDialog::on_ok_clicked() {
}

void SpeciesDialog::on_cancel_clicked() {
}

void SpeciesDialog::on_removeSubspecies_clicked() {
}

void SpeciesDialog::on_addSubspecies_clicked() {
}

Species SpeciesDialog::getSpecies() {
  Species species;
  return species;
}

#include "../../include/fish_detector/common/moc_species_dialog.cpp"

} // namespace fish_detector

#include "fish_detector/common/species_dialog.h"
#include "ui_species_dialog.h"

namespace fish_detector {

SpeciesDialog::SpeciesDialog(QWidget *parent)
  : QDialog(parent)
  , ui_(new Ui::SpeciesDialog) {
  ui_->setupUi(this);
}

void SpeciesDialog::on_ok_clicked() {
  accept();
}

void SpeciesDialog::on_cancel_clicked() {
  reject();
}

void SpeciesDialog::on_removeSubspecies_clicked() {
  QListWidgetItem *current = ui_->subspeciesList->currentItem();
  if(current != nullptr) {
    delete current;
  }
}

void SpeciesDialog::on_addSubspecies_clicked() {
  QListWidgetItem *item = new QListWidgetItem("New subspecies");
  item->setFlags(item->flags() | Qt::ItemIsEditable);
  ui_->subspeciesList->addItem(item);
  ui_->subspeciesList->editItem(item);
}

Species SpeciesDialog::getSpecies() {
  Species species;
  return species;
}

#include "../../include/fish_detector/common/moc_species_dialog.cpp"

} // namespace fish_detector

Add implementation for adding/removing subspecies functions