/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>

#include <vector>

#include "tensorflow/core/platform/platform.h"

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH, string("/usr/local/cuda")};
#else
  return {string("/usr/local/cuda")};
#endif
}

bool PreferPtxasFromPath() { return true; }

}  // namespace tensorflow

/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>

#include <string>
#include <vector>

#include "tensorflow/core/platform/platform.h"

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<std::string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH, std::string("/usr/local/cuda")};
#else
  return {std::string("/usr/local/cuda")};
#endif
}

bool PreferPtxasFromPath() { return true; }

}  // namespace tensorflow

Fix missing qualifier for std::string

Fix missing qualifier for std::string

PiperOrigin-RevId: 471087779


#include <iostream>
#include <bitset>
#include <vector>
using namespace std;

int main() {
    vector<int> ivec = {1, 2, 3, 5, 8, 13, 21};
    unsigned long val = 0UL;
    for(auto i : ivec) {
        val |= 1UL << i;
    }
    cout << val << endl;
    bitset<32> b(val);
    cout << b << endl;

    bitset<32> bb;
    for(auto i : ivec) {
        bb.set(i);
    }
    cout << bb << endl;
    if(b == bb) {
        cout << "b == bb" << endl;
    }
}

Add solution for chapter 17 test 10

Add solution for chapter 17 test 10


/**
g++ pipe_fds.cpp -g -O0 -o pipe_fds

About the limits:
[winlin@dev6 srs]$ ulimit -n
    1024
[winlin@dev6 srs]$ sudo lsof -p 21182
    pipe_fds 21182 winlin    0u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    1u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    2u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    3r  FIFO    0,8      0t0  464543 pipe
    pipe_fds 21182 winlin 1021r  FIFO    0,8      0t0  465052 pipe
    pipe_fds 21182 winlin 1022w  FIFO    0,8      0t0  465052 pipe
So, all fds can be open is <1024, that is, can open 1023 files.
The 0, 1, 2 is opened file, so can open 1023-3=1020files,
Where 1020/2=512, so we can open 512 pipes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(int argc, char** argv)
{
    if (argc <= 1) {
        printf("Usage: %s <nb_pipes>\n"
            "   nb_pipes the pipes to open.\n"
            "For example:\n"
            "   %s 1024\n", argv[0], argv[0]);
        exit(-1);
    }

    int nb_pipes = ::atoi(argv[1]);
    for (int i = 0; i < nb_pipes; i++) {
        int fds[2];
        if (pipe(fds) < 0) {
            printf("failed to create pipe. i=%d, errno=%d(%s)\n",
                i, errno, strerror(errno));
            break;
        }
    }

    printf("Press CTRL+C to quit, use bellow command to show the fds opened:\n");
    printf("    sudo lsof -p %d\n", getpid());
    sleep(-1);
    return 0;
}

Revert "Revert "add test file to show the max open files.""

This reverts commit ea70f29648e6ab431dfc18dddc4a4831d78e7f84.


#include <iostream>

using namespace std;

int main(){
  cout << "Starting Program..." << flush;

  cout << "This is the first line" << endl;

  cout << "-Item 1. " << "-Item 2. " << "-Item 3." << endl;

  cout << "The Program is ending." << endl;

  return 0;
}

Implement Outputting Text Program in C++


// Chapter 25, exercise 7: write out the hexadecimal values from 0 to 400; write
// out the hexadecimal values from -200 to 200

#include<iostream>
#include<iomanip>

using namespace std;

int main()
{
    cout << "0 to 400:\n\n";
    for (int i = 0; i<=400; ++i)
        cout << hex << i << (i%16 ? '\t' : '\n');

    cout << "\n\n-200 to 200:\n\n";
    for (int i = -200; i<=200; ++i)
        cout << hex << i << (i%8 ? '\t' : '\n');
}

Add Chapter 25, exercise 7

Add Chapter 25, exercise 7


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

using namespace std;

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

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

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

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

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

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

Add solution for chapter 16 test 48.

Add solution for chapter 16 test 48.


// Decorator (run-time)

class foo
{
	public:
		virtual void do_work() = 0;
};

class foo_concrete : public foo
{
	public:
		virtual void do_work()
		{ }
};

class foo_decorator : public foo
{
	public:
		foo_decorator(foo& f)
			: f(f)
		{ }

		virtual void do_work() {
			// Do something else here to decorate
			// the do_work function
			f.do_work();
		}

	private:
		foo& f;
};

void bar(foo& f)
{
	f.do_work();
}

int main()
{
	foo_concrete f;
	foo_decorator decorated_f{f};

	bar(decorated_f);
}

// Wrap a class with a decorator to extend its functionality.
//
// On [9-14], we define the class that we wish to decorate,
// `foo_concrete`, which implements the `foo` interface.
//
// The `foo_decorator` class, on [16-31], also implements the
// `foo` interface. This decorator class wraps any other `foo`
// object, which is passed to the constructor by reference[19-21]
// and decorates its member functions. That is, the
// `foo_decorator::do_work` function ([23-27]) simply calls the
// wrapped object's `do_work` function, while doing some extra work.
//
// To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on
// [40-41], and pass it to the `bar` function on [43], which takes a
// reference to any `foo` object and calls `do_work` on it. In this
// case, the call will be decorated by `foo_decorator`.

Add "run-time decorator pattern" sample

Add "run-time decorator pattern" sample


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

// This is the function actually selected during overload resolution, and the
// only one defined.
template <typename T> void f(T*, int) {}

template <typename T> struct S;
template <typename T> struct S_ : S<T> { typedef int type; }; // expected-note{{in instantiation}}
template <typename T> struct S {
  // Force T to have a complete type here so we can observe instantiations with
  // incomplete types.
  T t; // expected-error{{field has incomplete type}}
};

// Provide a bad class and an overload that instantiates templates with it.
class NoDefinition; // expected-note{{forward declaration}}
template <typename T> S_<NoDefinition>::type f(T*, NoDefinition*); // expected-note{{in instantiation}}

void test(int x) {
  f(&x, 0);
}

Add a test for a subtle instantiation pattern that showed up within a Boost
miscompile reduction. Clang already handles this correctly, but let's make sure
it stays that way.

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


#include "Halide.h"
#include <stdio.h>

using namespace Halide;

int main(int argc, char **argv) {
    Func f, g;
    Var x, y;

    f(x) = x;
    f(x) += x;
    g(x) = f(x);

    // f is inlined, so this schedule is bad.
    f.vectorize(x, 4);

    g.realize(10);

    printf("There should have been an error\n");
    return 0;
}

Add error test for inlined stages

Add error test for inlined stages


// RUN: clang-format -output-replacements-xml -sort-includes %s > %t.xml
// RUN: FileCheck -strict-whitespace -input-file=%t.xml %s

// CHECK: <?xml
// CHECK-NEXT: {{<replacements.*incomplete_format='false'}}
// CHECK-NEXT: {{<replacement.*#include
#include <}}
// CHECK-NEXT: {{<replacement.*>
<}}
// CHECK-NEXT: {{<replacement.*> <}}
#include
#include

int a;int*b;

clang-format: Add test for (properly escaped) XML output.

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


#include "types.hpp"
#include "constants.hpp"

#include "sys/sysctl.hpp"

#include <iostream>  /* std::cout, std::cerr */
#include <chrono>    /* std::chrono::steady_clock::now() */
#include <thread>    /* std::this_thread::sleep_until() */

#include <sys/resource.h>  /* CPUSTATES */

namespace {

using namespace types;
using namespace constants;

} /* namespace */

int main(int argc, char * argv[]) {
	sys::ctl::SysctlOnce<coreid_t, 2> const ncpu{0, {CTL_HW, HW_NCPU}};
	sys::ctl::Sysctl<2> const cp_times_ctl = {CP_TIMES};

	auto cp_times = std::unique_ptr<cptime_t[][CPUSTATES]>(
	    new cptime_t[2 * ncpu][CPUSTATES]{});

	auto time = std::chrono::steady_clock::now();
	//auto const start = time;
	size_t sample = 0;
	while (true) {
		std::this_thread::sleep_until(time += ms{50});
		cp_times_ctl.get(cp_times[sample * ncpu],
		                 ncpu * sizeof(cp_times[0]));
		for (size_t i = 0; i < ncpu; ++i) {
			std::cout << "cpu" << i << ':';
			for (size_t q = 0; q < CPUSTATES; ++q) {
				std::cout << ' '
				          << (cp_times[sample * ncpu + i][q] -
				              cp_times[((sample + 1) % 2) * ncpu + i][q]);
			}
			std::cout << '\n';
		}
		sample = (sample + 1) % 2;
	}
}

Add primitive load recorder prototype

Add primitive load recorder prototype


/*
 * Copyright (C) 2015-2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

void generate(std::string prefix, int open, int len) {
    if (len == prefix.size()) {
        std::cout << prefix << std::endl;
    } else {
        if (open < (len - prefix.size())) {
            generate(prefix + '(', open + 1, len);
        }
        if (open > 0 ) {
            generate(prefix + ')', open - 1, len);
        }
    }
}

int main() {
    int n;
    std::cin >> n;
    generate("", 0, n * 2);
    return 0;
}

Add problem about parenthesis sequences

Add problem about parenthesis sequences


#include<iostream>
#include<cstdlib>

using namespace std;

class Node{
        public:
                int data;
                Node *next;

                Node(){}

                Node(int d){
                        data=d;
                        next=NULL;
                }

                Node *insertElement(Node *head,int d){
                        Node *np=new Node(d);
                        Node *tmp=head;

                        if(head==NULL)
                                return np;
                        else
                                while(tmp->next)
                                        tmp=tmp->next;

                        tmp->next=np;

                        return head;
                }

		void deleteList(Node *head){
			while(head->next!=NULL){
				Node *t=head;
				cout<<"Freeing "<<t->data<<".\n";
				head=head->next;
				free(t);
			}
			cout<<"Freeing "<<head->data<<".\n";
			free(head);
			cout<<"The list is empty now.\n";
		}
};

int main()
{
        int n,p;
        Node np;
        Node *head=NULL;

        cout<<"Enter the size of linked list: ";
        cin>>n;

        for(int i=0;i<n;i++){
                        cout<<"\nEnter element "<<i+1<<": ";
                        cin>>p;
                        head=np.insertElement(head,p);
                }
	np.deleteList(head);
}

Add code to delete a Linked List

Add code to delete a Linked List


/*
* (C) 2018 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_X509_CERTIFICATES)

#include <botan/datastor.h>

namespace Botan_Tests {

class Datastore_Tests : public Test
   {
   public:
      std::vector<Test::Result> run() override
         {
         Test::Result result("Data_Store");

         Botan::Data_Store ds1;
         Botan::Data_Store ds2;

         result.confirm("equality", ds1 == ds2);

         result.test_eq("has_value", ds1.has_value("key"), false);
         result.test_eq("get1 with default", ds1.get1("key", "default"), "default");

         result.test_throws("get1", "Data_Store::get1: No values set for missing_key",
                            [&ds1]() { ds1.get1("missing_key"); });

         result.test_eq("search_for", ds1.search_for([](std::string, std::string) { return true; }).size(), 0);

         ds1.add("key", "value");

         result.test_eq("search_for", ds1.search_for([](std::string, std::string) { return true; }).size(), 1);

         result.test_eq("equality", ds1 == ds2, false);

         result.test_eq("has_value", ds1.has_value("key"), true);
         result.test_eq("get1 with default", ds1.get1("key", "default"), "value");
         result.test_eq("get1", ds1.get1("key"), "value");

         result.test_eq("get1_memvec", ds1.get1_memvec("memvec").size(), 0);

         const std::vector<uint8_t> memvec = { 9, 1, 1, 4 };
         ds1.add("memvec", memvec);

         result.test_eq("get1_memvec", ds1.get1_memvec("memvec"), memvec);

         result.test_eq("get1_uint32", ds1.get1_uint32("memvec"), size_t(9010104));

         result.test_eq("get1_uint32", ds1.get1_uint32("missing", 999), size_t(999));

         ds1.add("key", "value2");

         result.test_throws("get1", "Data_Store::get1: More than one value for key",
                            [&ds1]() { ds1.get1("key"); });

         result.test_eq("get multiple", ds1.get("key").size(), 2);

         return {result};
         }
   };

BOTAN_REGISTER_TEST("x509_datastore", Datastore_Tests);

}

#endif

Add some basic tests of Data_Store class

It's deprecated, but still exposed API and still used internally.


#include <iostream>
#include <stack>
#include <utility>

using std::cout;
using std::boolalpha;
using std::stack;
using std::pair;

class ParenthesesPair {
  pair<char, char> parentheses;

public:

  ParenthesesPair(char opening, char closing): parentheses(opening, closing) {}

  char opening() const {
    return parentheses.first;
  }

  char closing() const {
    return parentheses.second;
  }

  bool operator==(const ParenthesesPair& other_parentheses_pair) const {
    return opening() == other_parentheses_pair.opening() &&
           closing() == other_parentheses_pair.closing();
  }
};

ParenthesesPair parentheses_pairs[4] {
  {'(', ')'},
  {'[', ']'},
  {'{', '}'},
  {'<', '>'}
};

bool is_opening_parenthesis(char character) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i].opening() == character) {
      return true;
    }
  }

  return false;
}

bool is_closing_parenthesis(char character) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i].closing() == character) {
      return true;
    }
  }

  return false;
}

bool parentheses_match(const ParenthesesPair& parentheses_pair) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i] == parentheses_pair) {
      return true;
    }
  }

  return false;
}

bool are_parentheses_correct(const char* expression) {
  stack<char> opening_parentheses;

  while (*expression) {
    if (is_opening_parenthesis(*expression)) {
      opening_parentheses.push(*expression);
    } else if (is_closing_parenthesis(*expression)) {
      if (!opening_parentheses.empty() &&
          parentheses_match(ParenthesesPair(opening_parentheses.top(), *expression))) {
        opening_parentheses.pop();
      } else {
        return false;
      }
    }

    ++expression;
  }

  return opening_parentheses.empty();
}

int main() {
  cout << boolalpha << are_parentheses_correct("{(1 + 2) * [(2 + 3) / 2]}") << '\n';
  cout << boolalpha << are_parentheses_correct("(1 + 2) * [(2 + 3] / 2]") << '\n';
  cout << boolalpha << are_parentheses_correct("(1 + 2))( * [(2 + 3) / 2]") << '\n';

  return 0;
}

Add solution to the matching parentheses problem with multiple kinds of parentheses. This solution uses stack data structure


//===------------------------- catch_ptr_02.cpp ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <cassert>

struct  A {};
A a;
const A ca = A();

void test1 ()
{
    try
    {
        throw &a;
        assert(false);
    }
    catch ( const A* )
    {
    }
    catch ( A *)
    {
        assert (false);
    }
}

void test2 ()
{
    try
     {
    	throw &a;
        assert(false);
    }
    catch ( A* )
    {
    }
    catch ( const A *)
    {
         assert (false);
    }
}

void test3 ()
{
    try
    {
        throw &ca;
        assert(false);
    }
    catch ( const A* )
    {
    }
    catch ( A *)
    {
        assert (false);
    }
}

void test4 ()
{
    try
    {
        throw &ca;
        assert(false);
    }
    catch ( A *)
    {
        assert (false);
    }
    catch ( const A* )
    {
    }
}

int main()
{
    test1();
    test2();
    test3();
    test4();
}

Add test for pointer qualification conversion.

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@149541 91177308-0d34-0410-b5e6-96231b3b80d8


#include <iostream>
#include <string>

void findPossiblePlainTexts(const std::string&, int);
char* decrypt(const char*);

int main(int argc, char** argv)
{
  std::cout << "Letter Frequency attack on additive cipher\n";
  std::cout << "Enter the cipher text: ";

  std::string ciphertext;
  std::cin >> ciphertext;

  int num;
  std::cout << "Total possible plaintext sets: ";
  std::cin >> num;

  findPossiblePlainTexts(ciphertext, num);
}

void findPossiblePlainTexts(const std::string& cipherText, int num)
{
  int i = 0;
  const char *array = cipherText.c_str();
  while (i < num) {
    std::cout << i + 1 << decrypt(array) << "\n";
  }
}

char* decrypt(const char *cipherText)
{
  return nullptr;
}

Add basic structure and interface

Add basic structure and interface


/*
    This file is part of KAddressBook.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "kcmkabldapconfig.h"

#include <QtGui/QCheckBox>
#include <QtGui/QVBoxLayout>

#include <kaboutdata.h>
#include <kcomponentdata.h>
#include <kdemacros.h>
#include <kgenericfactory.h>
#include <klocale.h>

#include "ldapoptionswidget.h"

K_PLUGIN_FACTORY(KCMKabLdapConfigFactory, registerPlugin<KCMKabLdapConfig>();)
K_EXPORT_PLUGIN(KCMKabLdapConfigFactory( "kcmkabldapconfig" ))

KCMKabLdapConfig::KCMKabLdapConfig( QWidget *parent, const QVariantList & )
  : KCModule( KCMKabLdapConfigFactory::componentData(), parent )
{
  KGlobal::locale()->insertCatalog( "libkldap" );
  QVBoxLayout *layout = new QVBoxLayout( this );
  mConfigWidget = new LDAPOptionsWidget( this );
  layout->addWidget( mConfigWidget );

  connect( mConfigWidget, SIGNAL( changed( bool ) ), SIGNAL( changed( bool ) ) );

  load();

  KAboutData *about = new KAboutData( I18N_NOOP( "kcmkabldapconfig" ), 0,
                                      ki18n( "KAB LDAP Configure Dialog" ),
                                      0, KLocalizedString(), KAboutData::License_GPL,
                                      ki18n( "(c), 2003 - 2004 Tobias Koenig" ) );

  about->addAuthor( ki18n("Tobias Koenig"), KLocalizedString(), "tokoe@kde.org" );
  setAboutData( about );
}

void KCMKabLdapConfig::load()
{
  mConfigWidget->restoreSettings();
}

void KCMKabLdapConfig::save()
{
  mConfigWidget->saveSettings();
}

void KCMKabLdapConfig::defaults()
{
  mConfigWidget->defaults();
}

#include "kcmkabldapconfig.moc"

Insert libkldap catalog to translate dialogbox when we "add host"

svn path=/trunk/KDE/kdepim/; revision=925535


/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#endif

namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
}  // namespace
}  // namespace tpu
}  // namespace tensorflow

/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#include "tensorflow/core/platform/status.h"
#endif

namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
}  // namespace
}  // namespace tpu
}  // namespace tensorflow

Fix TPU VM tf-nightly build

Fix TPU VM tf-nightly build

PiperOrigin-RevId: 486159337


// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// REQUIRES: clang
// XFAIL: *

// This tests is meant to demonstrate an existing ABI bug between the
// C++03 and C++11 implementations of std::function. It is not a real test.

// RUN: %cxx -c %s -o %t.first.o %flags %compile_flags -std=c++03 -g
// RUN: %cxx -c %s -o %t.second.o -DWITH_MAIN %flags %compile_flags -g -std=c++11
// RUN: %cxx -o %t.exe %t.first.o %t.second.o %flags %link_flags -g
// RUN: %run

#include <functional>
#include <cassert>

typedef std::function<void(int)> Func;

Func CreateFunc();

#ifndef WITH_MAIN
// In C++03, the functions call operator, which is a part of the vtable,
// is defined as 'void operator()(int)', but in C++11 it's
// void operator()(int&&)'. So when the C++03 version is passed to C++11 code
// the value of the integer is interpreted as its address.
void test(int x) {
  assert(x == 42);
}
Func CreateFunc() {
  Func f(&test);
  return f;
}
#else
int main() {
  Func f = CreateFunc();
  f(42);
}
#endif

Check in test that demonstrates ABI break for std::function.

Our C++03 and C++11 implementations of function are not ABI
compatible. I've added a "test" that demonstrates this.

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


// Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node.

#include <iostream>
using namespace std;

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

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

void displayInorder(struct Node *root){
	if(root == NULL)
		return;
	displayInorder(root->left);
	cout<<root->data<<" ";
	displayInorder(root->right);
}

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

void modifyBSTUtil(struct Node *root, int *sum){
	// Base case
	if(root == NULL)
		return;
	// Recur for right subtree
	modifyBSTUtil(root->right, sum);

	// Now *sum has sum of nodes in right subtree, add root->data to sum and update root->data
	*sum = *sum + root->data;
	root->data = *sum;

	// Recur for left subtree
	modifyBSTUtil(root->left, sum);
}

void modifyBST(struct Node *root){
	int sum = 0;
	modifyBSTUtil(root, &sum);
}

int main(){
	struct Node *root = NULL;
	int num, size;
	cout<<"Enter the number of elements in BST\n";
	cin>>size;
	cout<<"Enter the elements of BST\n";
	while(size--){
		cin>>num;
		root = insertNode(root, num);
	}
	cout<<"Inorder traversal of original BST is\n";
	displayInorder(root);

	modifyBST(root);

	cout<<"\nInorder traversal of modified BST is\n";
	displayInorder(root);
return 0;
}

Add all greater nodes to a node in BST.

Add all greater nodes to a node in BST.


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int arr[9] = { 1, 4, 2, 3, 8, 3, 4, 1, 9};		// LIS should be {1, 2, 3, 8, 9}
   	int	f[9] = {}, LIS[9] = {}, max = 1, L = 0;		// f used to record previous location of LIS
    for (int i = 0; i < 9; i++)
    {
        LIS[i] = 1;
        f[i] = i;
    }
    for (int i = 1; i < 9; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            if (arr[j] < arr[i] && LIS[j]+1 > LIS[i])
            {
                LIS[i] = LIS[j] + 1;
                if (LIS[i] > max)
				{
					max = LIS[i];
					L = i;
				}
                f[i] = j;
            }
        }
    }
	int tmp = L;
	while(LIS[L]--)
	{
		cout << arr[tmp] << " ";
		tmp = f[tmp];
	}
    cout << endl;
    return 0;
}

Add longest increasing subsequence in c++


#include <algorithm>

#include <bts/import_bitcoin_wallet.hpp>

#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>

#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>

namespace bts { namespace bitcoin {

std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
  FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }

} } // bts::bitcoin

#include <algorithm>

#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>

#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/filesystem.hpp>

namespace bts { namespace bitcoin {

std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
  FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }

} } // bts::bitcoin

Fix includes for compiling the bitcoin import stub used when berkeley db is not available


#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"

#include <iostream>
using std::cout;
using std::endl;

TensorIdxImporter t_import;
Context ctx;

void test_core_ntoh32(void) {

  uint32_t input = 63;

  uint32_t result = ntoh32(input);

  EXPECT_EQ(result, 1056964608);
}

void test_core_importUchar(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.ubyte_import("/fs/constants/idxImport/uint8_4d_power2.idx");

  double result = sum<unsigned char>(t);
  EXPECT_EQ(result, 4518);
  delete t;
}

void test_core_importShort(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.short_import("/fs/constants/idxImport/int16_4d_power2.idx");

  double result = sum<short>(t);
  EXPECT_EQ(result, 270250);
  delete t;
}

void test_core_importInt(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.int_import("/fs/constants/idxImport/int32_4d_power2.idx");

  double result = sum<int>(t);
  EXPECT_EQ((int)result, 7158278745);
  delete t;
}

void test_core_importFloat(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.float_import("/fs/constants/idxImport/float_4d_power2.idx");

  double result = sum<float>(t);

  DEBUG("***floating point test yielded: %.8e\r\n", (float)result);
  EXPECT_EQ((float)result, -1.0f);
  delete t;
}

// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()

// Second declare tests to run
UTENSOR_TEST(core, ntoh32, "test ntoh32")
UTENSOR_TEST(core, importUchar, "Test unsigned char import")
UTENSOR_TEST(core, importShort, "Test short inport")
UTENSOR_TEST(core, importInt, "Test import Int")
UTENSOR_TEST(core, importFloat, "Test import float")

// Third, run like hell
UTENSOR_TEST_RUN()

Add tests for idx importer

Add tests for idx importer


// 58. Length of Last Word
/**
 * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
 *
 * If the last word does not exist, return 0.
 *
 * Note: A word is defined as a character sequence consists of non-space characters only.
 *
 * For example,
 * Given s = "Hello World",
 * return 5.
 *
 * Tags: String
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n = s.size();
        if (n == 0)
        {
            return 0;
        }

        // remove trailing spaces
        int last = n - 1;
        while (last >= 0 && s[last] == ' ')
        {
            last--;
        }

        // start to count of the last word
        int len = 0;
        while (last >= 0 && s[last] != ' ')
        {
            len++;
            last--;
        }

        return len;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

Add Solution for Problem 058

Add Solution for Problem 058


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014       Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "StereographicProjection.h"
#include "ViewportParams.h"
#include "TestUtils.h"

namespace Marble
{

class StereographicProjectionTest : public QObject
{
    Q_OBJECT

 private slots:
    void screenCoordinatesOfCenter_data();
    void screenCoordinatesOfCenter();
};

void StereographicProjectionTest::screenCoordinatesOfCenter_data()
{
    ViewportParams stereographic;
    stereographic.setProjection( Stereographic );

    QTest::addColumn<QPoint>( "screenCoordinates" );
    QTest::addColumn<GeoDataCoordinates>( "expected" );

    addRow() << QPoint( 5, 15 ) << GeoDataCoordinates( -45, 76.135, 0, GeoDataCoordinates::Degree );
    addRow() << QPoint( 15, 5 ) << GeoDataCoordinates( 135, 76.135, 0, GeoDataCoordinates::Degree );
}

void StereographicProjectionTest::screenCoordinatesOfCenter()
{
    QFETCH( QPoint, screenCoordinates );
    QFETCH( GeoDataCoordinates, expected );

    ViewportParams viewport;
    viewport.setProjection( Stereographic );
    viewport.setRadius( 180 / 4 ); // for easy mapping of lon <-> x
    viewport.setSize( QSize( 20, 20 ) );
    viewport.centerOn( 0 * DEG2RAD, 90 * DEG2RAD );

    {
        qreal lon, lat;
        const bool retval = viewport.geoCoordinates( screenCoordinates.x(), screenCoordinates.y(), lon, lat, GeoDataCoordinates::Degree );

        QVERIFY( retval ); // we want valid coordinates
        QCOMPARE( lon, expected.longitude( GeoDataCoordinates::Degree ) );
        QFUZZYCOMPARE( lat, expected.latitude( GeoDataCoordinates::Degree ), 0.0001 );
    }
}

}

QTEST_MAIN( Marble::StereographicProjectionTest )

#include "StereographicProjectionTest.moc"

Add test for Stereographic projection for real.


// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_resource_dispatcher_host_delegate.h"

#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace atom {

AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}

bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
    const GURL& url,
    int render_process_id,
    int render_view_id,
    bool is_main_frame,
    ui::PageTransition transition,
    bool has_user_gesture) {
  GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(
          base::IgnoreResult(platform_util::OpenExternal), escaped_url, false));
  return true;
}

content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
    net::AuthChallengeInfo* auth_info,
    net::URLRequest* request) {
  return new LoginHandler(auth_info, request);
}

}  // namespace atom

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_resource_dispatcher_host_delegate.h"

#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace atom {

AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}

bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
    const GURL& url,
    int render_process_id,
    int render_view_id,
    bool is_main_frame,
    ui::PageTransition transition,
    bool has_user_gesture) {
  GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(
          base::IgnoreResult(platform_util::OpenExternal), escaped_url, true));
  return true;
}

content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
    net::AuthChallengeInfo* auth_info,
    net::URLRequest* request) {
  return new LoginHandler(auth_info, request);
}

}  // namespace atom

Call OpenExternal with new true default to activate arg


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L0
 *
 * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

Add empty chip::lowLevelInitialization() for STM32L0


/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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

#include <stdio.h>
#include <string.h>
#include "tensorflow/lite/experimental/micro/debug_log.h"

// These are set by openmv py_tf.c code to redirect printing to an error message
// buffer...

static char *py_tf_putchar_buffer = NULL;
static size_t py_tf_putchar_buffer_len = 0;

extern "C" void DebugLog(const char* s) {
  for (size_t i = 0, j = strlen(s); i < j; i++) {
    if (py_tf_putchar_buffer_len) {
      *py_tf_putchar_buffer++ = s[i];
      py_tf_putchar_buffer_len--;
    } else {
      putchar(s[i]);
    }
  }
}

Update debug log to support redirection

Update debug log to support redirection


class Solution {
public:
    string removeDuplicates(string s) {
        int index = 0;

        while (!s.empty() && index < (s.size()-1)) {
            if (s[index] == s[index+1]) {
                if ((index+2) < s.size()) {
                    s = s.substr(0, index) + s.substr(index+2);
                } else {
                    s = s.substr(0, index);
                }
                if (index > 0)
                    --index;
            } else {
                ++index;
            }
        }
        return s;
    }
};

Remove All Adjacent Duplicates In String


#include <OpenSim/OpenSim.h>

main() {
    // A study is the top level component that contains the model and other
    // computational components.
    Study inverseKinematicsStudy;

    Model model("subject_01.osim");
    inverseKinematicsStudy.addComponent(model);

    // A data Source component wraps a TimeSeriesTables and access rows by time
    // Each column is given its own Output by name unless specified otherwise
    Source markers("subject01_trial2.trc");
    // Source markers("subject01_trial2.trc", Vec2(0, 5)); // by range
    // Source markers("subject01_trial2.trc", {"aa, "ai", ac"}); //by name
    inverseKinematicsStudy.addComponent(markers);

    // InverseKinematicsSolver is wrapped by a component (or one itself?)
    // dependency on model, and marker inputs (outputs of a source) wired
    // upon connect
    InverseKinematics ik(model, markers);
    inverseKinematicsStudy.addComponent(ik);

    // Now handle IK Outputs
    // Extract the outputs from the model and the state via a reporter
    // Do not need to know type BUT cannot combine different types
    // Coordinates are doubles and modelMarkers are Vec3's
    OutputReporter coordinateReporter();
    OutputReporter modelMarkerReporter();
    // Output coordinates from IK
    for(const auto& coord: mode.getCoordinates())
        coordinateReporter.addOutput(coord.getOutput("value"));
    inverseKinematicsStudy.addComponent(coordinateReporter);
    // Output model marker locations from IK
    for (const auto& marker : mode.getMarkers())
        modelMarkerReporter.addOutputs(marker.getOutput("location"));
    inverseKinematicsStudy.addComponent(modelMarkerReporter);

    State& state = inverseKinematicsStudy.initSystem();

    // March through time to solve for the state's coordinates
    for (double t : markers.getTimes()) {
        state.setTime(t);
        ik.track(state);
        inverseKinematicsStudy.realizeReport(state);
    }

    // write results to file
    FileAdapter fileAdapter;
    fileAdapter.write("s01_tr2_IK.mot", coordinateReporter.getReport());
    fileAdapter.write("s01_tr2_markers.trc", modelMarkerReporter.getReport());
}

Add pseudo code for performing an Inverse Kinematics analysis. Perform IK without using a Tool or any Analyses.


#include <fstream>
#include <map>

using namespace std;

int main() {
    ifstream cin("milktemp.in");
    ofstream cout("milktemp.out");

    int num_cows, cold, comfortable, hot;
	cin >> num_cows >> cold >> comfortable >> hot;

	int cold_change = comfortable - cold;
	int hot_change = hot - comfortable;

	map<int, int> changes;
	for (int i = 0; i < num_cows; i++) {
		int cold_thresh, hot_thresh;
		cin >> cold_thresh >> hot_thresh;

		changes[cold_thresh] += cold_change;
		changes[hot_thresh + 1] += hot_change;
	}

	int current = num_cows * cold;
	int max = current;
	for (const auto &change : changes) {
		current += change.second;
		if (current > max)
			max = current;
	}

    cout << max << endl;

    return 0;
}

Add C++11 solution for Nov. 2013 Bronze Problem 2


// RUN: clang-cc -fsyntax-only -verify %s

class Base { // expected-error {{cannot define the implicit default assignment operator for 'class Base'}} \
             // expected-note {{synthesized method is first required here}}
  int &ref;  // expected-note {{declared at}}
};

class X  : Base {  // // expected-error {{cannot define the implicit default assignment operator for 'class X'}}
public:
  X();
  const int cint;  // expected-note {{declared at}}
};

struct Y  : X {
  Y();
  Y& operator=(const Y&);
  Y& operator=(volatile Y&);
  Y& operator=(const volatile Y&);
  Y& operator=(Y&);
};

class Z : Y {};

Z z1;
Z z2;

// Test1
void f(X x, const X cx) {
  x = cx;	// expected-note {{synthesized method is first required here}}
  x = cx;
  z1 = z2;
}

// Test2
class T {};
T t1;
T t2;

void g()
{
  t1 = t2;
}

// Test3
class V {
public:
  V();
  V &operator = (V &b);
};

class W : V {};
W w1, w2;

void h()
{
  w1 = w2;
}

// Test4

class B1 {
public:
  B1();
  B1 &operator = (B1 b);
};

class D1 : B1 {};
D1 d1, d2;

void i()
{
	d1 = d2;
}

Test case for my last patch.

Test case  for my last patch.

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


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>

// Library/third-party includes
// - none

// Standard includes
#include <sstream>

namespace osvr {
namespace routing {
    const char *getTypeName(PathNode const &node) {
        return elements::getTypeName(node.value());
    }
    static inline void buildPathRecursively(PathNode const &node,
                                            std::ostream &os) {
        auto parent = node.getParent();
        if (parent) {
            buildPathRecursively(*parent, os);
        }
        if (!node.isRoot()) {
            os << getPathSeparator() << node.getName();
        }
    }
    std::string getFullPath(PathNode const &node) {
        std::ostringstream os;
        buildPathRecursively(node, os);
        return os.str();
    }
} // namespace routing
} // namespace osvr

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>

// Library/third-party includes
// - none

// Standard includes
#include <sstream>

namespace osvr {
namespace routing {
    const char *getTypeName(PathNode const &node) {
        return elements::getTypeName(node.value());
    }
    static inline void buildPathRecursively(PathNode const &node,
                                            std::ostream &os) {
        auto parent = node.getParent();
        if (parent) {
            buildPathRecursively(*parent, os);
        }
        if (!node.isRoot()) {
            os << getPathSeparator() << node.getName();
        }
    }
    std::string getFullPath(PathNode const &node) {
        /// Special case the root
        if (node.isRoot()) {
            return getPathSeparator();
        }
        std::ostringstream os;
        buildPathRecursively(node, os);
        return os.str();
    }
} // namespace routing
} // namespace osvr

Fix bug found by test.

Fix bug found by test.


#include "env_vars.hh"

namespace Kakoune
{

EnvVarMap get_env_vars()
{
    EnvVarMap env_vars;
    for (char** it = environ; *it; ++it)
    {
        const char* name = *it;
        const char* value = name;
        while (*value != 0 and *value != '=')
            ++value;
        env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
    }
    return env_vars;
}

}

#include "env_vars.hh"

#if __APPLE__
extern char **environ;
#endif

namespace Kakoune
{

EnvVarMap get_env_vars()
{
    EnvVarMap env_vars;
    for (char** it = environ; *it; ++it)
    {
        const char* name = *it;
        const char* value = name;
        while (*value != 0 and *value != '=')
            ++value;
        env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
    }
    return env_vars;
}

}

Define extern char **environ for OSX, which doesn't define it in a header


#include <algorithm>

#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"

namespace nix {

struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
    NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
    {
        mkFlag('h', "help", "show usage information", [=]() {
            printHelp(programName, std::cout);
            throw Exit();
        });

        mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
    }
};

void mainWrapped(int argc, char * * argv)
{
    initNix();
    initGC();

    string programName = baseNameOf(argv[0]);

    {
        auto legacy = (*RegisterLegacyCommand::commands)[programName];
        if (legacy) return legacy(argc, argv);
    }

    NixArgs args;

    args.parseCmdline(argvToStrings(argc, argv));

    assert(args.command);

    args.command->prepare();
    args.command->run();
}

}

int main(int argc, char * * argv)
{
    return nix::handleExceptions(argv[0], [&]() {
        nix::mainWrapped(argc, argv);
    });
}

#include <algorithm>

#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"

namespace nix {

struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
    NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
    {
        mkFlag('h', "help", "show usage information", [=]() {
            printHelp(programName, std::cout);
            std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n";
            throw Exit();
        });

        mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
    }
};

void mainWrapped(int argc, char * * argv)
{
    initNix();
    initGC();

    string programName = baseNameOf(argv[0]);

    {
        auto legacy = (*RegisterLegacyCommand::commands)[programName];
        if (legacy) return legacy(argc, argv);
    }

    NixArgs args;

    args.parseCmdline(argvToStrings(argc, argv));

    assert(args.command);

    args.command->prepare();
    args.command->run();
}

}

int main(int argc, char * * argv)
{
    return nix::handleExceptions(argv[0], [&]() {
        nix::mainWrapped(argc, argv);
    });
}

Add warning about "nix" being experimental


#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

std::vector<int> data;
bool data_ready = false;

void reader_thread()
{
    int i = 1;
    while (!data_ready) // 1
    {
        std::cout << "Reader loop " << i << std::endl;
        ++i;
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    std::cout << "Data value: " << data[0] << std::endl; // 2
}

void writer_thread()
{
    // Pretend to do some work
    std::this_thread::sleep_for(std::chrono::milliseconds(10));

    data.push_back(42); // 3
    data_ready = true;  // 4
}

int main()
{
    std::thread reader(reader_thread);
    std::thread writer(writer_thread);

    writer.join();
    reader.join();

    std::cout << "Press any key to continue...\n";
    std::getchar();
}

#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

std::vector<int> data;
bool data_ready = false;

void reader_thread()
{
    int i = 1;
    while (!data_ready) // 1
    {
        std::cout << "Reader loop " << i << std::endl;
        ++i;
    }

    std::cout << "Data value: " << data[0] << std::endl; // 2
}

void writer_thread()
{
    // Pretend to do some work
    std::this_thread::sleep_for(std::chrono::milliseconds(10));

    data.push_back(42); // 3
    data_ready = true;  // 4
}

int main()
{
    std::thread reader(reader_thread);
    std::thread writer(writer_thread);

    writer.join();
    reader.join();

    std::cout << "Press any key to continue...\n";
    std::getchar();
}

Update the ordering relationships example.


#include "grid.h"

#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"

namespace bejeweled {

Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
  for (int i = 0; i < width_; ++i) {
    grid_.emplace_back();
    for (int j = 0; j < height_; ++j) {
      grid_[i].emplace_back();
    }
  }
  InitJewels(renderer);
}

void Grid::Render(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].Render(renderer);
    }
  }
}

void Grid::InitJewels(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
    }
  }
}

} //namespace bejeweled

#include "grid.h"

#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"

namespace bejeweled {

Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
  for (int i = 0; i < width_; ++i) {
    grid_.emplace_back();
    for (int j = 0; j < height_; ++j) {
      grid_[i].emplace_back();
    }
  }
  InitJewels(renderer);
}

void Grid::Render(graphics::Renderer &renderer) {
  for (auto& column : grid_) {
    for (auto& cell : column) {
      cell.Render(renderer);
    }
  }
}

void Grid::InitJewels(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
    }
  }
}

} //namespace bejeweled

Use range based for loop instead of raw loop


class base {
public:
    virtual int foo(int a)
     { return 4 + a; }
    int bar(int a)
     { return a - 2; }
};

class sub final : public base {
public:
    virtual int foo(int a) override
     { return 8 + 2 * a; };
};

class sub2 final : public base {
public:
    virtual int foo(int a) override final
     { return 8 + 2 * a; };
};

int main(void)
{
    base b;
    sub s;

    return (b.foo(2) * 2 == s.foo(2)) ? 0 : 1;
}

class base {
public:
    virtual int foo(int a)
     { return 4 + a; }
    int bar(int a)
     { return a - 2; }
};

class sub final : public base {
public:
    virtual int foo(int a) override
     { return 8 + 2 * a; };
};

class sub2 final : public base {
public:
    virtual int foo(int a) override final
     { return 8 + 2 * a; };
};

int main(void)
{
    base b;
    sub s;
    sub2 t;

    return (b.foo(2) * 2 == s.foo(2) && b.foo(2) * 2 == t.foo(2) ) ? 0 : 1;
}

Test override and override final

Test override and override final


#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>

using namespace std;
using namespace rapidjson;

int main() {
    FILE* fp = std::fopen("./1.json", "r");
    char buffer[65536];
    FileReadStream frs(fp, buffer, sizeof(buffer));
    Document jobj;
    jobj.ParseStream(frs);

    const Value &coordinates = jobj["coordinates"];
    int len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    fclose(fp);

    return 0;
}

#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>

using namespace std;
using namespace rapidjson;

int main() {
    FILE* fp = std::fopen("./1.json", "r");
    char buffer[65536];
    FileReadStream frs(fp, buffer, sizeof(buffer));
    Document jobj;
    jobj.ParseStream(frs);

    const Value &coordinates = jobj["coordinates"];
    SizeType len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    fclose(fp);

    return 0;
}

Change len to proper type in RapidJSON test


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
    	std::string str(2147483648, 'a');
		SB sb;
		sb.str(str);
		assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
	}
	catch (const std::bad_alloc &) {}
#endif
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);
//
// REQUIRES: long_tests

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
    	std::string str(2147483648, 'a');
		SB sb;
		sb.str(str);
		assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
	}
	catch (const std::bad_alloc &) {}
#endif
}

Mark test as a long-test

Mark test as a long-test

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

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


#include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
  World *world = nullptr;

  World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
    std::cerr << "World has started"<<std::endl;
    for (int i=0; i< SDLK_LAST; ++i) {
      keyState[i] = false;
    }
  }
  void World::init() {
      world = new World();
  }
  GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
      GameObject * object = new GameObject(&physics, behavior, bdef);
      objects.emplace_back(object);
      return objects.back().get();
  }
  bool World::isKeyDown(int keyCode) {
    return keyState[keyCode];
  }
  void World::keyEvent(int keyCode, bool pressed) {
    if (keyCode < SDLK_LAST) {
      keyState[keyCode] = pressed;
    }else {
      std::cerr << "Key code out of range "<<keyCode<<"\n";
    }
  }
  void World::tick() {
    for (auto &obj : objects) {
      obj->tick(this);
      std::cerr << obj->printPosition()<<std::endl;
    }
    //for(auto &gameObject:objects){
    //
    //}

    // Gets called every frame
  }
}

#include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
  World *world = nullptr;

  World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
    std::cerr << "World has started"<<std::endl;
    for (int i=0; i< SDLK_LAST; ++i) {
      keyState[i] = false;
    }
  }
  void World::init() {
      world = new World();
  }
  GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
      GameObject * object = new GameObject(&physics, behavior, bdef);
      objects.emplace_back(object);
      return objects.back().get();
  }
  bool World::isKeyDown(int keyCode) {
    return keyState[keyCode];
  }
  void World::keyEvent(int keyCode, bool pressed) {
    if (keyCode < SDLK_LAST) {
      keyState[keyCode] = pressed;
    }else {
      std::cerr << "Key code out of range "<<keyCode<<"\n";
    }
  }
  void World::tick() {
    physics.Step(0.0166666, 1, 1);
    for (auto &obj : objects) {
      obj->tick(this);
      std::cerr << obj->printPosition()<<std::endl;
    }
    //for(auto &gameObject:objects){
    //
    //}

    // Gets called every frame
  }
}

Call physics engine with every tick

Call physics engine with every tick


//----------------------------  block_matrix_array_02.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  block_matrix_array_02.cc  ---------------------------

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// the test also didn't link before, due to some functions that were
// either missing or in the wrong place
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition_block.h>
#include <iostream>
#include <fstream>

int main ()
{
  std::ofstream logfile("block_matrix_array_02.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

				   // the following did not compile
				   // right away
  PreconditionBlockSSOR<BlockMatrixArray<SparseMatrix<double> > > p;

  return 0;
}

//----------------------------  block_matrix_array_02.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  block_matrix_array_02.cc  ---------------------------

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <iostream>
#include <fstream>

int main ()
{
  std::ofstream logfile("block_matrix_array_02.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

  return 0;
}

Reduce the test to its minimum.

Reduce the test to its minimum.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@9994 0785d39b-7218-0410-832d-ea1e28bc413d


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

#include "config.h"
#include "modules/push_messaging/PushError.h"

#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
    OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
    switch (webError->errorType) {
    case WebPushError::ErrorTypeAbort:
        return DOMException::create(AbortError, webError->message);
    case WebPushError::ErrorTypeNetwork:
        return DOMException::create(NetworkError, webError->message);
    case WebPushError::ErrorTypeNotFound:
        return DOMException::create(NotFoundError, webError->message);
    case WebPushError::ErrorTypeUnknown:
        return DOMException::create(UnknownError);
    }
    ASSERT_NOT_REACHED();
    return DOMException::create(UnknownError);
}

void PushError::dispose(WebType* webErrorRaw)
{
    delete webErrorRaw;
}

} // namespace blink

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

#include "config.h"
#include "modules/push_messaging/PushError.h"

#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
    OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
    switch (webError->errorType) {
    case WebPushError::ErrorTypeAbort:
        return DOMException::create(AbortError, webError->message);
    case WebPushError::ErrorTypeNetwork:
        return DOMException::create(NetworkError, webError->message);
    case WebPushError::ErrorTypeNotFound:
        return DOMException::create(NotFoundError, webError->message);
    case WebPushError::ErrorTypeUnknown:
        return DOMException::create(UnknownError, webError->message);
    }
    ASSERT_NOT_REACHED();
    return DOMException::create(UnknownError);
}

void PushError::dispose(WebType* webErrorRaw)
{
    delete webErrorRaw;
}

} // namespace blink

Use provided message for UnknownError.

[Push] Use provided message for UnknownError.

BUG=None

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

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


#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * boxLayout = new QVBoxLayout();
    content->setLayout(boxLayout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    boxLayout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    boxLayout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    boxLayout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(static_cast<unsigned int>(n))));
    });
}

MainWindow::~MainWindow()
{
}

#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * layout = new QVBoxLayout();
    content->setLayout(layout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    layout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    layout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    layout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(n)));
    });
}

MainWindow::~MainWindow()
{
}

Revert "Remove simple to fix warnings"

Revert "Remove simple to fix warnings"

This reverts commit 32f2b519e23e9bb165d981a5f7b5d73dff8c869d.


#include <rusql/connection.hpp>
#include <assert.h>

int main(int argc, char *argv[]) {
	assert(argc == 5);
	try {
		rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
	} catch(...) {
		return 0;
	}
	return 1;
}

#include <rusql/connection.hpp>
#include <cassert>

int main(int argc, char *argv[]) {
	assert(argc == 5);
	try {
		rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
	} catch(...) {
		return 0;
	}
	return 1;
}

Change C header to C++ header

Change C header to C++ header


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

#include "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo() : printer_status(0) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

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

#include "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo()
    : printer_status(0),
      is_default(false) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

Coverity: Initialize a variable in PrinterBasicInfo.

BUG=none
TEST=none
CID=16140

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

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


#include <QApplication>
#include <QIcon>
#include <QSettings>
#include <QString>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QCoreApplication::setOrganizationName("SheetMusicViewer");
    QCoreApplication::setApplicationName("SheetMusicViewer");

    QSettings settings;
    QString customIconTheme = settings.value("customIconTheme").toString();
    if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
    {
        QIcon::setThemeName(customIconTheme);
    }
    else
    {
        settings.setValue("customIconTheme", QString());
    }

    QString customStyle = settings.value("customStyle").toString();
    if (!customStyle.isNull() && !customStyle.isEmpty())
    {
        QApplication::setStyle(customStyle);
    }
    else
    {
        settings.setValue("customStyle", QString());
    }

    MainWindow w;
    w.show();
    return a.exec();
}

#include <QApplication>
#include <QIcon>
#include <QProcess>
#include <QSettings>
#include <QString>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QCoreApplication::setOrganizationName("SheetMusicViewer");
    QCoreApplication::setApplicationName("SheetMusicViewer");

    QSettings settings;
    QString customIconTheme = settings.value("customIconTheme").toString();
    if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
    {
        QIcon::setThemeName(customIconTheme);
    }
    else
    {
        settings.setValue("customIconTheme", QString());
    }

    QString customStyle = settings.value("customStyle").toString();
    if (!customStyle.isNull() && !customStyle.isEmpty())
    {
        QApplication::setStyle(customStyle);
    }
    else
    {
        settings.setValue("customStyle", QString());
    }

    QString quitCommand = settings.value("quitCommand").toString();
    if (quitCommand.isNull() || quitCommand.isEmpty())
    {
        settings.setValue("quitCommand", QString());
    }

    MainWindow w;
    w.show();
    int ret = a.exec();

    if ((ret == 0) && !quitCommand.isNull() && !quitCommand.isEmpty())
    {
        QProcess::execute(quitCommand);
    }

    return ret;
}

Add support for quit command

Add support for quit command

Add optional quitCommand in application config, to specify a custom
command to execute when closing application


#include "gtest/gtest.h"
#include "test_convergence.h"

// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
    public:
        void simulate() {
            for(unsigned int i = 0; i < m_N; ++i) {
                auto u = m_lqr->control_calculate(m_x);
                m_x = m_bicycle->x_next(m_x, u);

                auto z = m_bicycle->y(m_x);
                z(0) += m_r0(m_gen);
                z(1) += m_r1(m_gen);

                m_kalman->time_update(u);
                m_kalman->measurement_update(z);
            }
        }
};

TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
    simulate();
    test_state_near(m_kalman->x(), x_true());
}

INSTANTIATE_TEST_CASE_P(
    ConvergenceRange_1_9,
    LqrKalmanConvergenceTest,
    ::testing::Range(0.5, 9.5, 0.5));

#include "gtest/gtest.h"
#include "test_convergence.h"

// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
    public:
        void simulate() {
            for(unsigned int i = 0; i < m_N; ++i) {
                auto u = m_lqr->control_calculate(m_kalman->x());
                m_x = m_bicycle->x_next(m_x, u);

                auto z = m_bicycle->y(m_x);
                z(0) += m_r0(m_gen);
                z(1) += m_r1(m_gen);

                m_kalman->time_update(u);
                m_kalman->measurement_update(z);
            }
        }
};

TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
    simulate();
    test_state_near(m_kalman->x(), x_true());
}

INSTANTIATE_TEST_CASE_P(
    ConvergenceRange_1_9,
    LqrKalmanConvergenceTest,
    ::testing::Range(0.5, 9.5, 0.5));

Use Kalman estimate in LQR-Kalman test

Use Kalman estimate in LQR-Kalman test

Replace true system state with Kalman estimate.


#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VEQUIPMENTAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

Revert "Vehicle ammo prefix VAMMOTYPE_ to  VEQUIPMENTAMMOTYPE_"

This reverts commit 7cf76fe3066179d7d49ccec2b428c0a142988c19.


#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(0, 0, width()-1, height()-1);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(1, 1, width()-2, height()-2);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

Make buttons look slightly better on N8

Make buttons look slightly better on N8


#include <configure/utils/path.hpp>
#include <configure/error.hpp>

BOOST_AUTO_TEST_CASE(path)
{
	using namespace configure::utils;
	BOOST_CHECK_THROW(
	    relative_path("pif", "/paf"),
	    configure::error::InvalidPath
	);
	BOOST_CHECK_THROW(
	    relative_path("/pif", "paf"),
	    configure::error::InvalidPath
	);

	BOOST_CHECK_EQUAL(
	    relative_path("/pif", "/paf"),
	    "../pif"
	);

	BOOST_CHECK_EQUAL(
	    relative_path("/pif", "/pif"),
	    "."
	);
}

#include <configure/utils/path.hpp>
#include <configure/error.hpp>

namespace fs = boost::filesystem;

BOOST_AUTO_TEST_CASE(path)
{
# define P1 "pif"
# define P2 "paf"
#ifdef _WIN32
# define ABS_P1 "c:\\pif"
# define ABS_P2 "c:/paf"
#else
# define ABS_P1 "/pif"
# define ABS_P2 "/paf"
#endif
	using namespace configure::utils;
	BOOST_CHECK_THROW(
	    relative_path(P1, ABS_P2),
	    configure::error::InvalidPath
	);
	BOOST_CHECK_THROW(
	    relative_path(ABS_P1, P2),
	    configure::error::InvalidPath
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P1, ABS_P2),
	    fs::path("..") / P1
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P2, ABS_P1),
	    fs::path("..") / P2
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P1, ABS_P1),
	    "."
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P2, ABS_P2),
	    "."
	);
}

Fix path test on windows

Fix path test on windows


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

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

  WranglePlow::MainWindow wrangleplow;
  wrangleplow.show();
  wrangleplow.resize(1024, 768);

  return app.exec();
}

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

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

  WranglePlow::MainWindow wrangleplow;
  wrangleplow.show();
  wrangleplow.resize(1024, 768);
  wrangleplow.move(100, 100);

  return app.exec();
}

Move the window to a good location.

Move the window to a good location.


#include "./persistent_constraint_updater.h"
#include "./constraint_updater.h"

PersistentConstraintUpdater::PersistentConstraintUpdater(
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
  : constraintUpdater(constraintUpdater)
{
}

void PersistentConstraintUpdater::updateConstraints(
    int labelId, Eigen::Vector2i anchorForBuffer,
    Eigen::Vector2i labelSizeForBuffer)
{
  constraintUpdater->clear();

  for (auto &placedLabelPair : placedLabels)
  {
    auto &placedLabel = placedLabelPair.second;
    constraintUpdater->drawConstraintRegionFor(
        anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
        placedLabel.labelPosition, placedLabel.size);
  }

  placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
                                           Eigen::Vector2i(-1, -1) };
}

void PersistentConstraintUpdater::setPosition(int labelId,
                                              Eigen::Vector2i position)
{
  placedLabels[labelId].labelPosition = position;
}

void PersistentConstraintUpdater::clear()
{
  placedLabels.clear();
}

#include "./persistent_constraint_updater.h"
#include <chrono>
#include <QLoggingCategory>
#include "./constraint_updater.h"

QLoggingCategory pcuChan("Placement.PersistentConstraintUpdater");

PersistentConstraintUpdater::PersistentConstraintUpdater(
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
  : constraintUpdater(constraintUpdater)
{
}

void PersistentConstraintUpdater::updateConstraints(
    int labelId, Eigen::Vector2i anchorForBuffer,
    Eigen::Vector2i labelSizeForBuffer)
{
  auto startTime = std::chrono::high_resolution_clock::now();
  constraintUpdater->clear();

  for (auto &placedLabelPair : placedLabels)
  {
    auto &placedLabel = placedLabelPair.second;
    constraintUpdater->drawConstraintRegionFor(
        anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
        placedLabel.labelPosition, placedLabel.size);
  }

  placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
                                           Eigen::Vector2i(-1, -1) };

  auto endTime = std::chrono::high_resolution_clock::now();
  std::chrono::duration<float, std::milli> diff = endTime - startTime;

  qCInfo(pcuChan) << "updateConstraints took" << diff.count() << "ms";
}

void PersistentConstraintUpdater::setPosition(int labelId,
                                              Eigen::Vector2i position)
{
  placedLabels[labelId].labelPosition = position;
}

void PersistentConstraintUpdater::clear()
{
  placedLabels.clear();
}

Write PersistentConstraintUpdater::updateConstraints timing to log.


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03

// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder

// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.

#include <cstdint>
#include <cassert>

#include <unwind.h>

struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
  "_Unwind_Exception is incorrectly aligned. This test is expected to fail");

struct MinAligned {  };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");

int main() {
  for (int i=0; i < 10; ++i) {
    try {
      throw MinAligned{};
    } catch (MinAligned const& ref) {
      assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
    }
  }
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcxxabi-no-exceptions
// UNSUPPORTED: c++98, c++03

// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder

// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.

#include <cstdint>
#include <cassert>

#include <unwind.h>

struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
  "_Unwind_Exception is incorrectly aligned. This test is expected to fail");

struct MinAligned {  };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");

int main() {
  for (int i=0; i < 10; ++i) {
    try {
      throw MinAligned{};
    } catch (MinAligned const& ref) {
      assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
    }
  }
}

Add missing UNSUPPORTED for -fno-exception mode

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@296957 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %clang_cc1 -fsyntax-only -verify %s
class A { };

class B1 : A { };

class B2 : virtual A { };

class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}}

class C : public B1, private B2 { };

class D;                // expected-note {{forward declaration of 'D'}}

class E : public D { }; // expected-error{{base class has incomplete type}}

typedef int I;

class F : public I { }; // expected-error{{base specifier must name a class}}

union U1 : public A { }; // expected-error{{unions cannot have base classes}}

union U2 {};

class G : public U2 { }; // expected-error{{unions cannot be base classes}}

typedef G G_copy;
typedef G G_copy_2;
typedef G_copy G_copy_3;

class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
          public G_copy_3 { }; // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}

struct J { char c; int i[]; };
struct K : J { }; // expected-error{{base class 'J' has a flexible array member}}

Add test case for r193923

Add test case for r193923

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


#include <stingraykit/io/ByteDataConsumer.h>

namespace stingray
{

	ByteDataConsumer::ByteDataConsumer(ByteData consumer)
		:	_consumer(consumer)
	{ }

	size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
	{
		const size_t size = data.size();

		STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));

		std::copy(data.data(), data.data() + size, _consumer.data());
		_consumer = ByteData(_consumer, size);

		return size;
	}

}

#include <stingraykit/io/ByteDataConsumer.h>

#include <string.h>

namespace stingray
{

	ByteDataConsumer::ByteDataConsumer(ByteData consumer)
		:	_consumer(consumer)
	{ }

	size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
	{
		const size_t size = data.size();

		STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));

		memcpy(_consumer.data(), data.data(), size);
		_consumer = ByteData(_consumer, size);

		return size;
	}

}

Change std::copy to memcpy in critical places.

Sadly, std::copy(...) on gcc4.6; mstar k5cn is 1.5-2 times slower than memcpy(...).
Probably the answer is in difference between __builtin_memmove(...) and __builtin_memcpy(...)
on a certain MIPS machine, because libstdc++ uses __builtin_memmove(...) for std::copy(...) on
TriviallyCopyable types.


#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"

#include "qiscp.h"

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

    QtQuick1ApplicationViewer viewer;

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
    qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");

    viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"

#include "qiscp.h"

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

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
    // qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");

    QDeclarativeContext *context = viewer.rootContext();
    context->setContextProperty("ISCPInputs", new qiscpInputs());

    viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

Use setContextProperty() to make the input helper available


#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"

Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);

void CalibrationLaser::device_setup(){
    Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
    claser.write(0);
}

void CalibrationLaser::device_loop(Command command){
    if( command.cmp("claser")){
      int value = command.args[1];
      claser.write(value);
    }

}
#endif

#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"

Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);

void CalibrationLaser::device_setup(){
    Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
    claser.write(0);
}

void CalibrationLaser::device_loop(Command command){
    if( command.cmp("claser")){
      int value = command.args[1];
      claser.write(value);
      claser.send(value);
    }

}
#endif

Revert "Revert "Adding laser indicator""

This reverts commit 282ea0b855b20d23abed1a45d7fcfc311a9ef623.


#include "KeyboardHotkeyProcessor.h"

#include <string>

#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"

std::unordered_map<std::wstring, unsigned short>
    KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();

void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
    if (hki.action != HotkeyInfo::MediaKey || hki.args.size() != 1) {
        return;
    }

    std::wstring arg = hki.args[0];
    unsigned short vk = mediaKeyMap[arg];
    CLOG(L"Simulating media keypress: %s", arg.c_str());
    SyntheticKeyboard::SimulateKeypress(vk);
}

std::unordered_map<std::wstring, unsigned short>
        KeyboardHotkeyProcessor::CreateKeyMap() {
    std::unordered_map<std::wstring, unsigned short> map;
    for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
        map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
    }
    return map;
}

#include "KeyboardHotkeyProcessor.h"

#include <string>

#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"

std::unordered_map<std::wstring, unsigned short>
    KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();

void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
    /* These hotkeys *require* exactly one argument: */
    if (hki.args.size() != 1) {
        return;
    }

    switch (hki.action) {
    case HotkeyInfo::MediaKey: {
        std::wstring &arg = hki.args[0];
        unsigned short vk = mediaKeyMap[arg];
        CLOG(L"Media key: %s", arg.c_str());
        SyntheticKeyboard::SimulateKeypress(vk);
        break;
    }

    case HotkeyInfo::VirtualKey: {

        break;
    }
    }
}

std::unordered_map<std::wstring, unsigned short>
        KeyboardHotkeyProcessor::CreateKeyMap() {
    std::unordered_map<std::wstring, unsigned short> map;
    for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
        map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
    }
    return map;
}

Reorganize KB HK processor for new VK hotkeys


#include "RawTextGraphInput.hh"

/*
  name
  |V|
  [|V| names]
  |E|
  [|E| lines formatted like start end type distance]
 */

template <typename V>
void RawTextGraphInput<V>::input(string path) {

  ifstream ifs(path, ifstream::in);

  int v, e;
  string title;

  // Graph title fetching

  ifs >> title;

  this->graph_.setName(title);

  // Vertices fetching

  ifs >> v;

  for (int i = 0; i < v; i++) {
    ifs >> title;
    this->graph_.addVertex(title);
  }

  // Edges fetching

  unsigned int start, end;
  string type;
  EdgeType t;
  V dist;

  ifs >> e;

  for (int i = 0; i < e; i++) {
    ifs >> start >> end >> type >> dist;
    if (type == "Train")
      t = EdgeType::Train;
    else if (type == "Road")
      t = EdgeType::Road;
    else
      t = EdgeType::Plane;

    this->graph_.addEdge(t, dist, start, end);
  }
}

template class RawTextGraphInput<double>;

#include "RawTextGraphInput.hh"

/*
  name
  |V|
  [|V| names]
  |E|
  [|E| lines formatted like start end type distance]
 */

template <typename V>
void RawTextGraphInput<V>::input(string path) {

  ifstream ifs(path, ifstream::in);

  int v, e;
  string title;

  // Graph title fetching

  ifs >> title;

  this->graph_.setName(title);

  // Vertices fetching

  ifs >> v;
  getline(ifs, title); // wtf

  for (int i = 0; i < v; i++) {
    getline(ifs, title);
    std::cout << "Found " << title << std::endl;
    this->graph_.addVertex(title);
  }

  // Edges fetching

  unsigned int start, end;
  string type;
  EdgeType t;
  V dist;

  ifs >> e;

  for (int i = 0; i < e; i++) {
    ifs >> start >> end >> type >> dist;
    if (type == "Train")
      t = EdgeType::Train;
    else if (type == "Road")
      t = EdgeType::Road;
    else
      t = EdgeType::Plane;

    this->graph_.addEdge(t, dist, start, end);
  }
}

template class RawTextGraphInput<double>;

Fix a parsing issue when a vertex has space in its name


#include <typeinfo>

class A {
    virtual void x() { }
};

class B : public A {
    void x() override { }
};

int main() {
    A a;
    B *b = dynamic_cast<B *>(&a);
    (void)b;
    return 0;
}

#include <typeinfo>

class I {
public:
    virtual ~I() { }
    virtual void x() { }
};

class A : public I {
    void x() override { }
};

class B : public I {
    void x() override { }
};

int main() {
    I *a = new A();
    B *b = dynamic_cast<B *>(a);
    (void)b;
    delete a;
    return 0;
}

Fix enableRtti test with GCC.

Fix enableRtti test with GCC.

GCC is stricter than Clang/MSVC and fails to compile certain provably
meaningless constructs like dynamic_casts that will never succeed.

Change-Id: I5e1a5c965395f218c4dd6340b761c308fe41282f
Reviewed-by: Christian Kandeler <3aa99dcdd3f0cac61fb81c2a11771c0cc2497607@theqtcompany.com>


#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	CommandLine::Set( argc, argv );

	BString strInFolder = CommandLine::GetArg( 0, "" );
	BString strOutFolder = CommandLine::GetArg( 1, strInFolder );

	if (strInFolder == "")
		Output::Error("Usage: gluaextract <in> [out]");

	String::List files;
	String::List folders;
	File::Find( &files, &folders, strInFolder + "/*.lua", false );

	Output::Msg( "Converting %i files.\n", files.size() );

	BOOTIL_FOREACH_CONST(f, files, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}

#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	Debug::SuppressPopups( true );
	CommandLine::Set( argc, argv );

	Console::FGColorPush( Console::Green );
    Output::Msg( "GMod Lua Cache Extractor 1.0\n\n" );
    Console::FGColorPop();

	BString strInFolder = CommandLine::GetArg( 0, "" );
	BString strOutFolder = CommandLine::GetArg( 1, strInFolder );

	if (strInFolder == "")
		Output::Error("Usage: gluaextract <in> [out]");

	String::List files;
	String::List folders;
	File::Find( &files, &folders, strInFolder + "/*.lua", false );
	File::CreateFolder(strOutFolder);

	Output::Msg( "Converting %i files.\n", files.size() );

	BOOTIL_FOREACH_CONST(f, files, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}

Create output folder if does not exist. Suppress debug popups.


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

#include "base/test/thread_test_helper.h"

#include "base/location.h"

namespace base {

ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
    : test_result_(false),
      target_thread_(target_thread),
      done_event_(false, false) {
}

bool ThreadTestHelper::Run() {
  if (!target_thread_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &ThreadTestHelper::RunInThread))) {
    return false;
  }
  done_event_.Wait();
  return test_result_;
}

void ThreadTestHelper::RunTest() { set_test_result(true); }

ThreadTestHelper::~ThreadTestHelper() {}

void ThreadTestHelper::RunInThread() {
  RunTest();
  done_event_.Signal();
}

}  // namespace base

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

#include "base/test/thread_test_helper.h"

#include "base/bind.h"
#include "base/location.h"

namespace base {

ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
    : test_result_(false),
      target_thread_(target_thread),
      done_event_(false, false) {
}

bool ThreadTestHelper::Run() {
  if (!target_thread_->PostTask(
          FROM_HERE, base::Bind(&ThreadTestHelper::RunInThread, this))) {
    return false;
  }
  done_event_.Wait();
  return test_result_;
}

void ThreadTestHelper::RunTest() { set_test_result(true); }

ThreadTestHelper::~ThreadTestHelper() {}

void ThreadTestHelper::RunInThread() {
  RunTest();
  done_event_.Signal();
}

}  // namespace base

Convert NewRunnableMethod() to base::Bind() in base::TestThreadHelper.

BUG=none
TEST=trybot compile

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

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