/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include <unistd.h>
#include <fcntl.h>

#include "logging.h"

FILE *logfd = NULL;

void
ori_fuse_log(const char *what, ...)
{
    if (logfd == NULL) {
        logfd = fopen("fuse.log", "wb+");
        if (logfd == NULL) {
            perror("fopen");
            exit(1);
        }
    }

    va_list vl;
    va_start(vl, what);
    vfprintf(logfd, what, vl);

    fsync(fileno(logfd));
}

/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include <unistd.h>
#include <fcntl.h>

#include "logging.h"

FILE *logfd = NULL;

void
ori_fuse_log(const char *what, ...)
{
    if (logfd == NULL) {
        logfd = fopen("fuse.log", "wb+");
        if (logfd == NULL) {
            perror("fopen");
            exit(1);
        }
    }

    va_list vl;
    va_start(vl, what);
    vfprintf(logfd, what, vl);

    fflush(logfd);
}

Use fflush to make sure libc buffer is flushed synchronously for debugging purposes.


/******************************************************************************\
 * This example illustrates how to use aout.                                  *
\ ******************************************************************************/

#include <chrono>
#include <cstdlib>
#include <iostream>
#include "caf/all.hpp"

using namespace caf;
using std::endl;

int main() {
  std::srand(static_cast<unsigned>(std::time(0)));
  for (int i = 1; i <= 50; ++i) {
    spawn<blocking_api>([i](blocking_actor* self) {
      aout(self) << "Hi there! This is actor nr. "
                 << i << "!" << endl;
      std::chrono::milliseconds tout{std::rand() % 1000};
      self->delayed_send(self, tout, atom("done"));
      self->receive(others() >> [i, self] {
        aout(self) << "Actor nr. "
                   << i << " says goodbye!" << endl;
      });
    });
  }
  // wait until all other actors we've spawned are done
  await_all_actors_done();
  // done
  shutdown();
  return 0;
}

/******************************************************************************\
 * This example illustrates how to use aout.                                  *
\ ******************************************************************************/

#include <random>
#include <chrono>
#include <cstdlib>
#include <iostream>

#include "caf/all.hpp"

using namespace caf;
using std::endl;

int main() {
  std::srand(static_cast<unsigned>(std::time(0)));
  for (int i = 1; i <= 50; ++i) {
    spawn<blocking_api>([i](blocking_actor* self) {
      aout(self) << "Hi there! This is actor nr. "
                 << i << "!" << endl;
      std::random_device rd;
      std::default_random_engine re(rd());
      std::chrono::milliseconds tout{re() % 10};
      self->delayed_send(self, tout, atom("done"));
      self->receive(others() >> [i, self] {
        aout(self) << "Actor nr. "
                   << i << " says goodbye!" << endl;
      });
    });
  }
  // wait until all other actors we've spawned are done
  await_all_actors_done();
  // done
  shutdown();
  return 0;
}

Use std::random_device instead of rand()


// RxUN: %clang_cc1 -ast-dump %s | FileCheck %s
// RUN: %clang_cc1 -ast-dump %s > /dev/null

template <int X, typename Y, int Z = 5>
struct foo {
  int constant;
  foo() {}
  Y getSum() { return Y(X + Z); }
};

template <int A, typename B>
B bar() {
  return B(A);
}

void baz() {
  int x = bar<5, int>();
  int y = foo<5, int>().getSum();
  double z = foo<2, double, 3>().getSum();
}

// Template instantiation - foo
// CHECK: template <int X = 5, typename Y = int, int Z = 5> struct foo {
// CHECK: template <int X = 2, typename Y = double, int Z = 3> struct foo {

// Template definition - foo
// CHECK: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)

// Template instantiation - bar
// CHECK: template <int A = 5, typename B = int> int bar()

// Template definition - bar
// CHECK: template <int A, typename B> B bar()

// RUN: %clang_cc1 -ast-dump %s > %t
// RUN: FileCheck < %t %s -check-prefix=CHECK1
// RUN: FileCheck < %t %s -check-prefix=CHECK2

template <int X, typename Y, int Z = 5>
struct foo {
  int constant;
  foo() {}
  Y getSum() { return Y(X + Z); }
};

template <int A, typename B>
B bar() {
  return B(A);
}

void baz() {
  int x = bar<5, int>();
  int y = foo<5, int>().getSum();
  double z = foo<2, double, 3>().getSum();
}

// Template instantiation - foo
// Since the order of instantiation may vary during runs, run FileCheck twice
// to make sure each instantiation is in the correct spot.
// CHECK1: template <int X = 5, typename Y = int, int Z = 5> struct foo {
// CHECK2: template <int X = 2, typename Y = double, int Z = 3> struct foo {

// Template definition - foo
// CHECK1: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)
// CHECK2: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)

// Template instantiation - bar
// CHECK1: template <int A = 5, typename B = int> int bar()
// CHECK2: template <int A = 5, typename B = int> int bar()

// Template definition - bar
// CHECK1: template <int A, typename B> B bar()
// CHECK2: template <int A, typename B> B bar()

Fix a test case that was intermittently failing.  The issue was that instantiations are not stored in an order preserving structure, so the print order may be impacted.  Modified test case to do two FileCheck passes to ensure that both instantiations are in the same place.

Test originially commited at r136306 and temporarily silenced at r136348.

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


#include <map>

#include <kms++util/cpuframebuffer.h>

using namespace std;

namespace kms {

CPUFramebuffer::CPUFramebuffer(uint32_t width, uint32_t height, PixelFormat format)
	: m_width(width), m_height(height), m_format(format)
{
	const PixelFormatInfo& format_info = get_pixel_format_info(m_format);

	m_num_planes = format_info.num_planes;

	for (unsigned i = 0; i < format_info.num_planes; ++i) {
		const PixelFormatPlaneInfo& pi = format_info.planes[i];
		FramebufferPlane& plane = m_planes[i];

		plane.stride = width * pi.bitspp / 8;
		plane.size = plane.stride * height/ pi.ysub;
		plane.offset = 0;
		plane.map = new uint8_t[plane.size];
	}
}

CPUFramebuffer::~CPUFramebuffer()
{
	for (unsigned i = 0; i < m_num_planes; ++i) {
		FramebufferPlane& plane = m_planes[i];

		delete plane.map;
	}
}

}

#include <map>

#include <kms++util/cpuframebuffer.h>

using namespace std;

namespace kms {

CPUFramebuffer::CPUFramebuffer(uint32_t width, uint32_t height, PixelFormat format)
	: m_width(width), m_height(height), m_format(format)
{
	const PixelFormatInfo& format_info = get_pixel_format_info(m_format);

	m_num_planes = format_info.num_planes;

	for (unsigned i = 0; i < format_info.num_planes; ++i) {
		const PixelFormatPlaneInfo& pi = format_info.planes[i];
		FramebufferPlane& plane = m_planes[i];

		plane.stride = width * pi.bitspp / 8;
		plane.size = plane.stride * height/ pi.ysub;
		plane.offset = 0;
		plane.map = new uint8_t[plane.size];
	}
}

CPUFramebuffer::~CPUFramebuffer()
{
	for (unsigned i = 0; i < m_num_planes; ++i) {
		FramebufferPlane& plane = m_planes[i];

		delete [] plane.map;
	}
}

}

Use [] operator delete to free CPUFramebuffer buffers


#define TEST_INSITU
#define TEST_PARSE_FLAG kParseInsituFlag
#define TEST_NAME "RapidJSON_Insitu (C++)"
#define TEST_CLASS RapidjsonInsituTest

#include "rapidjsontest.cpp"

#define TEST_INSITU
#define TEST_PARSE_FLAG kParseInsituFlag
#define TEST_NAME "RapidJSON_Insitu (C++)"
#define TEST_CLASS RapidjsonInsituTest
#define RapidjsonParseResult RapidjsonParseInsituResult

#include "rapidjsontest.cpp"

Fix RapidJSON Insitu Test on Windows

Fix RapidJSON Insitu Test on Windows


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

#include "ui/base/ui_base_switches_util.h"

#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"

namespace switches {

bool IsTouchDragDropEnabled() {
#if defined(OS_CHROMEOS)
  return !CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableTouchDragDrop);
#else
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchDragDrop);
#endif
}

bool IsTouchEditingEnabled() {
#if defined(OS_CHROMEOS)
  return !CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableTouchEditing);
#else
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchEditing);
#endif
}

bool IsNewDialogStyleEnabled() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
    return false;
  if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
    return true;
  return true;
}

}  // namespace switches

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

#include "ui/base/ui_base_switches_util.h"

#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"

namespace switches {

bool IsTouchDragDropEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchDragDrop);
}

bool IsTouchEditingEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchEditing);
}

bool IsNewDialogStyleEnabled() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
    return false;
  if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
    return true;
  return true;
}

}  // namespace switches

Revert 205124 "Turn on touch drag and drop and touch editing by ..."

> Turn on touch drag and drop and touch editing by default on chromeos.
>
> BUG=168162
>
> Review URL: https://chromiumcodereview.appspot.com/16268020

TBR=varunjain@chromium.org,sky@chromium.org

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

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


//
//  positions.cc
//  GameEngine
//
//  Created by Jon Sharkey on 2013-02-19.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "gameengine/positions.h"

#include "thirdparty/tinyxml2/tinyxml2.h"

#include "gameengine/asset_reader.h"

double str2double(const char *str) {
  char *end_ptr;
  double value = strtod(str, &end_ptr);
  if (*end_ptr) return 0;
  return value;
}

void Positions::LoadFile(AssetReader &asset_reader) {
  tinyxml2::XMLDocument doc;

  char *data = new char[asset_reader.Size() + 1];
  asset_reader.Read(data, sizeof(char), asset_reader.Size());
  data[asset_reader.Size()] = '\0';
  bool successful_parse = !doc.Parse(data);
  if (!successful_parse) {
    assert(false);
  }
  delete data;

  tinyxml2::XMLNode *positionsNode = doc.FirstChild();
  assert(!strcmp("positions", positionsNode->ToElement()->Name()));

  tinyxml2::XMLNode *position = positionsNode->FirstChild();
  while (position) {
    const char *name = position->ToElement()->Attribute("name");
    double x = str2double(position->FirstChildElement("x")->GetText());
    double y = str2double(position->FirstChildElement("y")->GetText());
    assert(positions_.find(name) == positions_.end());
    positions_[name] = game_point_make(x, y);

    position = position->NextSibling();
  }
}

//
//  positions.cc
//  GameEngine
//
//  Created by Jon Sharkey on 2013-02-19.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "gameengine/positions.h"

#include "gameengine/asset_reader.h"
#include "gameengine/thirdparty/tinyxml2/tinyxml2.h"

void Positions::LoadFile(AssetReader &asset_reader) {
  tinyxml2::XMLDocument doc;

  char *data = new char[asset_reader.Size() + 1];
  asset_reader.Read(data, sizeof(char), asset_reader.Size());
  data[asset_reader.Size()] = '\0';
  bool successful_parse = !doc.Parse(data);
  if (!successful_parse) {
    assert(false);
  }
  delete data;

  tinyxml2::XMLNode *positionsNode = doc.FirstChild();
  assert(!strcmp("positions", positionsNode->ToElement()->Name()));

  tinyxml2::XMLNode *position = positionsNode->FirstChild();
  while (position) {
    const char *name = position->ToElement()->Attribute("name");
    double x = strtod(position->FirstChildElement("x")->GetText(), NULL);
    double y = strtod(position->FirstChildElement("y")->GetText(), NULL);
    assert(positions_.find(name) == positions_.end());
    positions_[name] = game_point_make(x, y);

    position = position->NextSibling();
  }
}

Fix header. Remove unneeded helper function.


#pragma GCC diagnostic ignored "-Wdeprecated"

#include "remoteclient.hpp"
#include "core/messages/client/clientmsg.hpp"
#include "core/messages/server/servermsg.hpp"
#include "core/serveriface.hpp"

namespace {
  struct ClientLauncher {
    void operator()(RemoteClient* c) {
      c->run();
    }
  };
}

RemoteClient::RemoteClient(ServerIface* srv)
  : m_server(srv) {}

RemoteClient::~RemoteClient() {}

ServerIface* RemoteClient::server() const {
  return m_server;
}

void RemoteClient::pushMessage(ClientMsg* msg) {
  uint32_t type = msg->type();
  m_stream.write((char*)&type, 4);
  msg->write(m_stream);
}

void RemoteClient::spinup() {
  ClientLauncher launcher;
  boost::thread t(launcher, this);
}

void RemoteClient::run() {
  m_server->addClient(this);
  while(m_stream.good()) {
    uint32_t type;
    m_stream.read((char*)&type, 4);
    // check good again, in case read failed due to disconnect
    if(m_stream.good()) {
      ServerMsg *msg = ServerMsg::create(type, this);
      msg->read(m_stream);
      m_server->pushMessage(msg);
    }
  }
  m_server->removeClient(this);
  delete this;
}

#pragma GCC diagnostic ignored "-Wdeprecated"

#include "remoteclient.hpp"
#include "core/messages/client/clientmsg.hpp"
#include "core/messages/server/servermsg.hpp"
#include "core/serveriface.hpp"

namespace {
  struct ClientLauncher {
    void operator()(RemoteClient* c) {
      c->run();
    }
  };
}

RemoteClient::RemoteClient(ServerIface* srv)
  : m_server(srv) {}

RemoteClient::~RemoteClient() {}

ServerIface* RemoteClient::server() const {
  return m_server;
}

void RemoteClient::pushMessage(ClientMsg* msg) {
  uint32_t type = msg->type();
  m_stream.write((char*)&type, 4);
  msg->write(m_stream);
  delete msg;
}

void RemoteClient::spinup() {
  ClientLauncher launcher;
  boost::thread t(launcher, this);
}

void RemoteClient::run() {
  m_server->addClient(this);
  while(m_stream.good()) {
    uint32_t type;
    m_stream.read((char*)&type, 4);
    // check good again, in case read failed due to disconnect
    if(m_stream.good()) {
      ServerMsg *msg = ServerMsg::create(type, this);
      msg->read(m_stream);
      m_server->pushMessage(msg);
    }
  }
  m_server->removeClient(this);
  delete this;
}

Fix memory leak in RemoteClient

Fix memory leak in RemoteClient


// RUN: %clang_cc1 %s -emit-llvm -o -

// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.

template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
  a f[0];
};
struct g {
  static g h(unsigned);
};
struct i {
  void j() const;
  // Current maximum depth of recursive template instantiation is 1024,
  // thus, this \/ threshold value is used here. BasePathSize in CastExpr might
  // not fit it, so we are testing that we do fit it.
  // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
  // elsewhere.
  d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
  const void *k{f.f};
  (void)k;
}

// RUN: %clang_cc1 %s -emit-llvm-only -o -

// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.

template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
  a f[0];
};
struct g {
  static g h(unsigned);
};
struct i {
  void j() const;
  // Current maximum depth of recursive template instantiation is 1024,
  // thus, this \/ threshold value is used here. BasePathSize in CastExpr might
  // not fit it, so we are testing that we do fit it.
  // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
  // elsewhere.
  d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
  const void *k{f.f};
  (void)k;
}

[NFC][CodeGenCXX] Use -emit-llvm-only instead of -emit-llvm and ignoring it.

As pointed out by Richard Smith in post-review of r338489.

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


/** \file
 * File for the string fonts.
 *
 * @author Nathan Samson
*/

#include <sstream>

#include "resources/stringfontresource.h"
#include "resources/fontresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param surface The surface.
	 * @param id The ID of the string fonts.
	*/
	StringFontResource::StringFontResource(SDL_Surface* surface, std::string id)
	                   : SDLSurfaceResource(id, surface) {
	}

	/**
	 * Destructor.
	*/
	StringFontResource::~StringFontResource() {
	}

	/**
	 * ID Generator.
	 *
	 * @param text The text to print
	 * @param font The font the string should be drawn in.
	 * @param c The color of the string.
	*/
	std::string StringFontResource::getID(std::string text, FontResource* font, SDL_Color c) {
		std::stringstream sID;
		sID << text << font->getName() << c.r << "_" << c.g << "_" << c.b;
		std::string id;
		sID >> id;
		return id;
	}

}

/** \file
 * File for the string fonts.
 *
 * @author Nathan Samson
*/

#include <sstream>

#include "resources/stringfontresource.h"
#include "resources/fontresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param surface The surface.
	 * @param id The ID of the string fonts.
	*/
	StringFontResource::StringFontResource(SDL_Surface* surface, std::string id)
	                   : SDLSurfaceResource(id, surface) {
	}

	/**
	 * Destructor.
	*/
	StringFontResource::~StringFontResource() {
	}

	/**
	 * ID Generator.
	 *
	 * @param text The text to print
	 * @param font The font the string should be drawn in.
	 * @param c The color of the string.
	*/
	std::string StringFontResource::getID(std::string text, FontResource* font, SDL_Color c) {
		std::stringstream sID;
		sID << "_" << c.r << "_" << c.g << "_" << c.b;
		std::string rgb;
		sID >> rgb;
		std::string id = text + font->getName() + rgb;
		return id;
	}

}

Fix ID's of strings with spaces

Fix ID's of strings with spaces


//===--- CallInliner.cpp - Transfer function that inlines callee ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the callee inlining transfer function.
//
//===----------------------------------------------------------------------===//

#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/GRState.h"
#include "clang/Checker/Checkers/LocalCheckers.h"

using namespace clang;

namespace {
class CallInliner : public Checker {
public:
  static void *getTag() {
    static int x;
    return &x;
  }

  virtual bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
};
}

void clang::RegisterCallInliner(GRExprEngine &Eng) {
  Eng.registerCheck(new CallInliner());
}

bool CallInliner::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
  const GRState *state = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = state->getSVal(Callee);

  const FunctionDecl *FD = L.getAsFunctionDecl();
  if (!FD)
    return false;

  if (!FD->isThisDeclarationADefinition())
    return false;

  // Now we have the definition of the callee, create a CallEnter node.
  CallEnter Loc(CE, FD, C.getPredecessor()->getLocationContext());
  C.addTransition(state, Loc);

  return true;
}

//===--- CallInliner.cpp - Transfer function that inlines callee ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the callee inlining transfer function.
//
//===----------------------------------------------------------------------===//

#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/GRState.h"
#include "clang/Checker/Checkers/LocalCheckers.h"

using namespace clang;

namespace {
class CallInliner : public Checker {
public:
  static void *getTag() {
    static int x;
    return &x;
  }

  virtual bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
};
}

void clang::RegisterCallInliner(GRExprEngine &Eng) {
  Eng.registerCheck(new CallInliner());
}

bool CallInliner::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
  const GRState *state = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = state->getSVal(Callee);

  const FunctionDecl *FD = L.getAsFunctionDecl();
  if (!FD)
    return false;

  if (!FD->getBody(FD))
    return false;

  // Now we have the definition of the callee, create a CallEnter node.
  CallEnter Loc(CE, FD, C.getPredecessor()->getLocationContext());
  C.addTransition(state, Loc);

  return true;
}

Use getBody() to get the function definition when the decl referenced is not
definition.

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


//===-- StringSaver.cpp ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/StringSaver.h"

using namespace llvm;

StringRef StringSaver::save(StringRef S) {
  char *P = Alloc.Allocate<char>(S.size() + 1);
  memcpy(P, S.data(), S.size());
  P[S.size()] = '\0';
  return StringRef(P, S.size());
}

StringRef UniqueStringSaver::save(StringRef S) {
  auto R = Unique.insert(S);
  if (R.second)                 // cache miss, need to actually save the string
    *R.first = Strings.save(S); // safe replacement with equal value
  return *R.first;
}

//===-- StringSaver.cpp ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/StringSaver.h"

using namespace llvm;

StringRef StringSaver::save(StringRef S) {
  char *P = Alloc.Allocate<char>(S.size() + 1);
  if (!S.empty())
    memcpy(P, S.data(), S.size());
  P[S.size()] = '\0';
  return StringRef(P, S.size());
}

StringRef UniqueStringSaver::save(StringRef S) {
  auto R = Unique.insert(S);
  if (R.second)                 // cache miss, need to actually save the string
    *R.first = Strings.save(S); // safe replacement with equal value
  return *R.first;
}

Fix an undefined behavior when storing an empty StringRef.

Summary: Passing a nullptr to memcpy is UB.

Reviewers: ioeric

Subscribers: llvm-commits, cfe-commits

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

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@340170 91177308-0d34-0410-b5e6-96231b3b80d8


#include "Arduino.h"
#include "Game.h"

Game::Game() {
}

void Game::init() {
  restart(1);
}

int Game::p1Score() { return _p1Score; }
int Game::p2Score() { return _p2Score; }
int Game::server()  { return _server;  }

bool Game::over() {
  return (_p1Score >= 11 || _p2Score >= 11) && abs(_p1Score - _p2Score) >= 2;
}

void Game::updateScore(int p1, int p2) {
  // The loop will constantly update the score, so we only act if it has changed
  if ((p1 != _p1Score) || (p2 != _p2Score)) {
    _p1Score = p1;
    _p2Score = p2;
    _serves++;

    Serial.print("Updating scores ");
    Serial.print(_p1Score);
    Serial.print(" ");
    Serial.print(_p2Score);
    Serial.print("   ");
    Serial.println(over());

    if (_serves == 2) {
      _serves = 0;
      _server = _server == 1 ? 2 : 1;
    }
  }
}

void Game::restart(int serve) {
  _p1Score = 0;
  _p2Score = 0;
  _server = 1;
  _serves = 0;
}

#include "Arduino.h"
#include "Game.h"

Game::Game() {
}

void Game::init() {
  restart(1);
}

int Game::p1Score() { return _p1Score; }
int Game::p2Score() { return _p2Score; }
int Game::server()  { return _server;  }

bool Game::over() {
  return (_p1Score >= 11 || _p2Score >= 11) && abs(_p1Score - _p2Score) >= 2;
}

void Game::updateScore(int p1, int p2) {
  // The loop will constantly update the score, so we only act if it has changed
  if ((p1 != _p1Score) || (p2 != _p2Score)) {
    _p1Score = p1;
    _p2Score = p2;
    _serves++;

    Serial.print("Updating scores ");
    Serial.print(_p1Score);
    Serial.print(" ");
    Serial.print(_p2Score);
    Serial.print("   ");
    Serial.println(over());

    if (_serves == 2) {
      _serves = 0;
      _server = _server == 1 ? 2 : 1;
    }
  }
}

void Game::restart(int serve) {
  _p1Score = 0;
  _p2Score = 0;
  _server = serve;
  _serves = 0;
}

Fix setting server on restart

Fix setting server on restart


#include <iostream>

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

#include "common/CLOpts.h"
#include "common/config.h"
#include "common/file_operations.h"
#include "common/packets.h"

// Shorten the crazy long namespacing to asio tcp
using boost::asio::ip::tcp;

int main(int argc, char **argv) {
  // Parse out command line options
  sc2tm::CLOpts opts;
  if (!opts.parseOpts(argc, argv))
    return 0;

  try {
    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query("localhost", sc2tm::serverPortStr);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    sc2tm::SHAFileMap mapMap;
    sc2tm::SHAFileMap botMap;
    sc2tm::hashMapDirectory(opts.getOpt("maps"), mapMap);
    sc2tm::hashBotDirectory(opts.getOpt("bots"), botMap);

    for (const auto &mapInfo : mapMap)
      std::cout << mapInfo.first.filename() << " SHA256: " << mapInfo.second << "\n";

    for (const auto &botInfo : botMap)
      std::cout << botInfo.first.filename() << " SHA256: " << botInfo.second << "\n";

    // Make a handshake packet from the
    sc2tm::ClientHandshakePacket handshake(botMap, mapMap);

    // Write the packet to the buffer
    boost::asio::streambuf buffer;
    handshake.toBuffer(buffer);

    auto noopFn = [&] (const boost::system::error_code& error, std::size_t bytes_transferred) {
      assert(buffer.size() == 0);
    };
    boost::asio::async_write(socket, buffer, noopFn);
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

#include <iostream>

#include <boost/asio.hpp>

#include "client/Client.h"
#include "common/CLOpts.h"
#include "common/config.h"

// Shorten the crazy long namespacing to asio tcp
using boost::asio::ip::tcp;

int main(int argc, char **argv) {
  // Parse out command line options
  sc2tm::CLOpts opts;
  if (!opts.parseOpts(argc, argv))
    return 0;

  try {
    boost::asio::io_service service;
    sc2tm::Client s(service, "localhost", sc2tm::serverPortStr, opts.getOpt("bots"),
                    opts.getOpt("maps"));
    service.run();
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

Rewrite into async like server.

Rewrite into async like server.


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "descriptors.h"
#include <atomic>

using namespace leap;

descriptor_entry::descriptor_entry(const std::type_info& ti, const descriptor& (*pfnDesc)()) :
  Next(descriptors::Link(*this)),
  ti(ti),
  pfnDesc(pfnDesc)
{}

const descriptor_entry* descriptors::s_pHead = nullptr;

const descriptor_entry* descriptors::Link(descriptor_entry& entry) {
  auto retVal = s_pHead;
  s_pHead = &entry;
  return retVal;
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "descriptors.h"
#include <atomic>

using namespace leap;

descriptor_entry::descriptor_entry(const std::type_info& ti, const descriptor& (*pfnDesc)()) :
  Next(descriptors::Link(*this)),
  ti(ti),
  pfnDesc(pfnDesc)
{}

const descriptor_entry* descriptors::s_pHead = nullptr;

#if _MSC_VER <= 1800
// Used for MSVC2013 because it doesn't have magic statics, so we have to initialize all
// of our cached descriptors to ensure that we don't wind up with initialization races.
static bool global_initializer = [] {
  for (auto& cur : descriptors{})
    cur.pfnDesc();
  return true;
}();
#endif

const descriptor_entry* descriptors::Link(descriptor_entry& entry) {
  auto retVal = s_pHead;
  s_pHead = &entry;
  return retVal;
}

Fix initialization race in MSVC2013

Fix initialization race in MSVC2013

MSVC2013 before the CTP doesn't have magic statics, so we need to make sure all of our descriptors are initialized on that platform in advance.


/* utils.cc
   Louis Solofrizzo 2019-10-17

   Utilities for pistache
*/

#include <pistache/peer.h>
#include <unistd.h>

ssize_t SSL_sendfile(SSL *out, int in, off_t *offset, size_t count)
{
    unsigned char       buffer[4096] = { 0 };
    ssize_t             ret;
    ssize_t             written;
    size_t              to_read;

    if (in == -1)
        return -1;

    to_read = sizeof(buffer) > count ? count : sizeof(buffer);

    if (offset != NULL)
        ret = pread(in, buffer, to_read, *offset);
    else
        ret = read(in, buffer, to_read);

    if (ret == -1)
        return -1;

    written = SSL_write(out, buffer, ret);
    if (offset != NULL)
        *offset += written;

    return written;
}

/* utils.cc
   Louis Solofrizzo 2019-10-17

   Utilities for pistache
*/

#include <pistache/peer.h>
#include <unistd.h>

#ifdef PISTACHE_USE_SSL

ssize_t SSL_sendfile(SSL *out, int in, off_t *offset, size_t count)
{
    unsigned char       buffer[4096] = { 0 };
    ssize_t             ret;
    ssize_t             written;
    size_t              to_read;

    if (in == -1)
        return -1;

    to_read = sizeof(buffer) > count ? count : sizeof(buffer);

    if (offset != NULL)
        ret = pread(in, buffer, to_read, *offset);
    else
        ret = read(in, buffer, to_read);

    if (ret == -1)
        return -1;

    written = SSL_write(out, buffer, ret);
    if (offset != NULL)
        *offset += written;

    return written;
}

#endif /* PISTACHE_USE_SSL */

Common: Fix broken compilation for trees without the PISTACHE_USE_SSL option

Due to a brain-lag on my end, I've introduced a regression in commit
44e40478d604746963b898efd463a541ebbea824, because a SSL utility function
was compiling whether or not the SSL was enabled. It is now fixed,
apologies.

Pull Request: https://github.com/oktal/pistache/pull/623
Fixes: https://github.com/oktal/pistache/issues/621
Fixes: https://github.com/oktal/pistache/issues/622

Fork: https://git.mobley.ne02ptzero.me/~louis/pistache
Signed-off-by: Louis Solofrizzo <219d34e4f07f54ff278d7ec92ea24ddc58fdffc0@online.net>


// For conditions of distribution and use, see copyright notice in license.txt

#if SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#if HYDRAX_ENABLED
#include "EC_Hydrax.h"
#endif
#include "Framework.h"
#include "SceneAPI.h"
#include "IComponentFactory.h"

extern "C"
{

DLLEXPORT void TundraPluginMain(Framework *fw)
{
    Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
#if SKYX_ENABLED
    fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SkyX>));
#endif
#if HYDRAX_ENABLED
    fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Hydrax>));
#endif
}

} // ~extern "C"

// For conditions of distribution and use, see copyright notice in license.txt

#if SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#if HYDRAX_ENABLED
#include "EC_Hydrax.h"
#endif
#include "Framework.h"
#include "SceneAPI.h"
#include "IComponentFactory.h"
///\todo HydraxConfigFile support
//#include "AssetAPI.h"
//#include "HydraxConfigAsset.h"

extern "C"
{

DLLEXPORT void TundraPluginMain(Framework *fw)
{
    Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
#if SKYX_ENABLED
    fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SkyX>));
#endif
#if HYDRAX_ENABLED
    fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Hydrax>));
    ///\todo HydraxConfigFile support
//    fw->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<HydraxConfigAsset>("HydraxConfigFile")));
#endif
}

} // ~extern "C"

Mark down todo for HydraxConfigFile support.


#include "env.hpp"
#include "java_classes.hpp"
#include <atomic>
#include <fmo/benchmark.hpp>
#include <thread>

namespace {
    struct {
        Reference<Callback> callbackRef;
        JavaVM* javaVM;
        JNIEnv* threadEnv;
        std::atomic<bool> stop;
    } global;
}

void Java_cz_fmo_Lib_benchmarkingStart(JNIEnv* env, jclass, jobject cbObj) {
    global.callbackRef = {env, cbObj};
    global.stop = false;
    env->GetJavaVM(&global.javaVM);

    std::thread thread([]() {
        Env threadEnv{global.javaVM, "benchmarking"};
        global.threadEnv = threadEnv.get();
        fmo::Registry::get().runAll([](const char* cStr) {
                                        Callback cb{global.callbackRef.get(global.threadEnv)};
                                        cb.log(cStr);
                                    },
                                    []() {
                                        return bool(global.stop);
                                    });
        global.callbackRef.release(global.threadEnv);
    });

    thread.detach();
}

void Java_cz_fmo_Lib_benchmarkingStop(JNIEnv* env, jclass) {
    global.stop = true;
}

#include "env.hpp"
#include "java_classes.hpp"
#include <atomic>
#include <fmo/benchmark.hpp>
#include <thread>

namespace {
    struct {
        Reference<Callback> callbackRef;
        JavaVM* javaVM;
        JNIEnv* threadEnv;
        std::atomic<bool> stop;
    } global;
}

void Java_cz_fmo_Lib_benchmarkingStart(JNIEnv* env, jclass, jobject cbObj) {
    initJavaClasses(env);
    global.callbackRef = {env, cbObj};
    global.stop = false;
    env->GetJavaVM(&global.javaVM);

    std::thread thread([]() {
        Env threadEnv{global.javaVM, "benchmarking"};
        global.threadEnv = threadEnv.get();
        fmo::Registry::get().runAll([](const char* cStr) {
                                        Callback cb{global.callbackRef.get(global.threadEnv)};
                                        cb.log(cStr);
                                    },
                                    []() {
                                        return bool(global.stop);
                                    });
        global.callbackRef.release(global.threadEnv);
    });

    thread.detach();
}

void Java_cz_fmo_Lib_benchmarkingStop(JNIEnv* env, jclass) {
    global.stop = true;
}

Fix crash when going straight to benchmark


// Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s

struct Foo {
  Foo() {}
  Foo(int) {}
  ~Foo() {}
};

struct Bar : public Foo {
  Bar() {}
  Bar(int x) : Foo(x) {}
  ~Bar();
};

Foo foo;
Foo foo2(1);
Bar bar;

// Profile data for complete constructors and destructors must absent.

// CHECK-NOT: @__profc__ZN3FooC1Ev
// CHECK-NOT: @__profc__ZN3FooC1Ei
// CHECK-NOT: @__profc__ZN3FooD1Ev
// CHECK-NOT: @__profc__ZN3BarC1Ev
// CHECK-NOT: @__profc__ZN3BarD1Ev
// CHECK-NOT: @__profc__ZN3FooD1Ev

int main() {
}

// Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o %t -emit-llvm -fprofile-instrument=clang
// RUN: FileCheck %s -input-file=%t -check-prefix=INSTR
// RUN: FileCheck %s -input-file=%t -check-prefix=NOINSTR

struct Foo {
  Foo() {}
  Foo(int) {}
  ~Foo() {}
};

struct Bar : public Foo {
  Bar() {}
  Bar(int x) : Foo(x) {}
  ~Bar();
};

Foo foo;
Foo foo2(1);
Bar bar;

// Profile data for complete constructors and destructors must absent.

// INSTR: @__profc_main =
// INSTR: @__profc__ZN3FooC2Ev =
// INSTR: @__profc__ZN3FooD2Ev =
// INSTR: @__profc__ZN3FooC2Ei =
// INSTR: @__profc__ZN3BarC2Ev =

// NOINSTR-NOT: @__profc__ZN3FooC1Ev
// NOINSTR-NOT: @__profc__ZN3FooC1Ei
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
// NOINSTR-NOT: @__profc__ZN3BarC1Ev
// NOINSTR-NOT: @__profc__ZN3BarD1Ev
// NOINSTR-NOT: @__profc__ZN3FooD1Ev

int main() {
}

Make a test more explicit. NFC.

[profiling] Make a test more explicit. NFC.

The cxx-structors.cpp test checks that some instrumentation doesn't
appear, but it should be more explicit about which instrumentation it
actually expects to appear.

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


// RUN: %clangxx -O0 -g %s -o %t -lcrypt && %run %t

// crypt() is missing from Android and -lcrypt from darwin.
// UNSUPPORTED: android, darwin

#include <assert.h>
#include <unistd.h>
#include <cstring>

int
main (int argc, char** argv)
{
  {
    char *p = crypt("abcdef", "xz");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$1$");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$5$");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$6$");
    volatile size_t z = strlen(p);
  }
}

// RUN: %clangxx -O0 -g %s -o %t -lcrypt && %run %t

// crypt() is missing from Android and -lcrypt from darwin.
// UNSUPPORTED: android, darwin

#include <assert.h>
#include <unistd.h>
#include <cstring>
#include <crypt.h>

int
main (int argc, char** argv)
{
  {
    char *p = crypt("abcdef", "xz");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$1$");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$5$");
    volatile size_t z = strlen(p);
  }
  {
    char *p = crypt("abcdef", "$6$");
    volatile size_t z = strlen(p);
  }
}

Add a missing include in test.

Add a missing include in test.

A fix for r373993.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@374448 91177308-0d34-0410-b5e6-96231b3b80d8


#include <test/unit/math/test_ad.hpp>
#include <limits>

TEST(mathMixScalFun, std_normal_cdf_derivatives) {
  auto f = [](const auto& y) { return stan::math::std_normal_cdf(y); };

  stan::test::expect_ad(f, -50.0);
  // stan::test::expect_ad(f, -20.0 * stan::math::SQRT_TWO);
  // stan::test::expect_ad(f, -10.0);
  stan::test::expect_ad(f, -5.5);
  stan::test::expect_ad(f, 0.0);
  stan::test::expect_ad(f, 0.15);
  stan::test::expect_ad(f, 1.14);
  stan::test::expect_ad(f, 3.00);
  stan::test::expect_ad(f, 10.00);
}

#include <test/unit/math/test_ad.hpp>
#include <limits>

TEST(mathMixScalFun, std_normal_cdf_derivatives) {
  auto f = [](const auto& y) { return stan::math::std_normal_cdf(y); };

  stan::test::expect_ad(f, -50.0);
  // the following fails because AD returns -nan in the Hessian
  // stan::test::expect_ad(f, -20.0 * stan::math::SQRT_TWO);
  // the following fails because AD returns inf in the Hessian
  // stan::test::expect_ad(f, -20.0);
  stan::test::expect_ad(f, -19);
  stan::test::expect_ad(f, -5.5);
  stan::test::expect_ad(f, 0.0);
  stan::test::expect_ad(f, 0.15);
  stan::test::expect_ad(f, 1.14);
  stan::test::expect_ad(f, 3.00);
  stan::test::expect_ad(f, 10.00);
}

Clarify reason for failing tests

Clarify reason for failing tests


// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Slider.h"

void Slider::Buddy(Control *buddy, bool bottomOrRight) {
    _buddyWnd = buddy->Handle();
    SendMessage(_hWnd, TBM_SETBUDDY,
        (WPARAM) bottomOrRight ? FALSE : TRUE, (LPARAM) _buddyWnd);
}

int Slider::Position() {
    return (int) SendMessage(_hWnd, TBM_GETPOS, 0, 0);
}

void Slider::Position(int position) {
    SendMessage(_hWnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) position);
}

void Slider::Range(int lo, int hi) {
    SendMessage(_hWnd, TBM_SETRANGE, (WPARAM) TRUE, MAKELPARAM(lo, hi));
}

BOOL Slider::Notification(NMHDR *nHdr) {
    switch (nHdr->code) {
    case TRBN_THUMBPOSCHANGING:
        if (OnSlide) {
            NMTRBTHUMBPOSCHANGING *pc
                = reinterpret_cast<NMTRBTHUMBPOSCHANGING *>(nHdr);
            OnSlide(pc);
        }
    }

    return FALSE;
}

// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Slider.h"

void Slider::Buddy(Control *buddy, bool bottomOrRight) {
    _buddyWnd = buddy->Handle();
    SendMessage(_hWnd, TBM_SETBUDDY,
        (WPARAM) bottomOrRight ? FALSE : TRUE, (LPARAM) _buddyWnd);
}

int Slider::Position() {
    return (int) SendMessage(_hWnd, TBM_GETPOS, 0, 0);
}

void Slider::Position(int position) {
    SendMessage(_hWnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) position);
    if (OnSlide) {
        OnSlide();
    }
}

void Slider::Range(int lo, int hi) {
    SendMessage(_hWnd, TBM_SETRANGE, (WPARAM) TRUE, MAKELPARAM(lo, hi));
}

BOOL Slider::Notification(NMHDR *nHdr) {
    switch (nHdr->code) {
    case TRBN_THUMBPOSCHANGING:
        if (OnSlide) {
            NMTRBTHUMBPOSCHANGING *pc
                = reinterpret_cast<NMTRBTHUMBPOSCHANGING *>(nHdr);
            OnSlide(pc);
        }
    }

    return FALSE;
}

Call OnSlide when the slider position changes programmatically


#include "qlazerdriveplayer.h"

QLazerDrivePlayer::QLazerDrivePlayer(const uint &id, const QString &name, const uint &r, const uint &g, const uint &b, const uint &score)
{
    m_id = id;
    m_name = name;
    m_r = r;
    m_g = g;
    m_b = b;
    m_score = score;
}

uint QLazerDrivePlayer::r() const
{
    return m_r;
}

void QLazerDrivePlayer::setR(const uint &r)
{
    m_r = r;
}

uint QLazerDrivePlayer::g() const
{
    return m_g;
}

void QLazerDrivePlayer::setG(const uint &g)
{
    m_g = g;
}

uint QLazerDrivePlayer::b() const
{
    return m_b;
}

void QLazerDrivePlayer::setB(const uint &b)
{
    m_b = b;
}

#include "qlazerdriveplayer.h"

QLazerDrivePlayer::QLazerDrivePlayer(const uint &id, const QString &name, const uint &r, const uint &g, const uint &b, const uint &score)
{
    m_id = id;
    m_name = name;
    m_r = r;
    m_g = g;
    m_b = b;
    m_score = score;
}

uint QLazerDrivePlayer::id() const
{
    return m_id;
}

void QLazerDrivePlayer::setId(const uint &id)
{
    m_id = id;
}

uint QLazerDrivePlayer::score() const
{
    return m_score;
}

void QLazerDrivePlayer::setScore(const uint &score)
{
    m_score = score;
}

QString QLazerDrivePlayer::name() const
{
    return m_name;
}

void QLazerDrivePlayer::setName(const QString &name)
{
    m_name = name;
}

uint QLazerDrivePlayer::r() const
{
    return m_r;
}

void QLazerDrivePlayer::setR(const uint &r)
{
    m_r = r;
}

uint QLazerDrivePlayer::g() const
{
    return m_g;
}

void QLazerDrivePlayer::setG(const uint &g)
{
    m_g = g;
}

uint QLazerDrivePlayer::b() const
{
    return m_b;
}

void QLazerDrivePlayer::setB(const uint &b)
{
    m_b = b;
}

Add missing getters / setters

Add missing getters / setters


#include "..\include\Game.h"

//
// TO-DO:
// - add more enemies
// - implement arena
// - implement custom moves (e.g. specific moves to each class, custom Attack(); stuff)
// - add advanced AI (when taking a risk attack and miss, heal)
// - store and sell (buy with coins, sell arrows/bombs/etc for money or experience)
// - use items in between matches (whetstone, potion)

/// Continue commenting code at Player.GenericAttack().

int main(){
    Game _Game;
    // Goes to main menu. Nice.
    _Game.MainMenu();
	return 0;
}

#include "..\include\Game.h"

//
// TO-DO:
// - add more enemies
// - implement arena
// - implement custom moves (e.g. specific moves to each class, custom Attack(); stuff)
// - add advanced AI (when taking a risk attack and miss, heal)
// - store and sell (buy with coins, sell arrows/bombs/etc for money or experience)
// - use items in between matches (whetstone, potion)
// - save data in file

/// Continue commenting code at Player.GenericAttack().

int main(){
    Game _Game;
    // Goes to main menu. Nice.
    _Game.MainMenu();
	return 0;
}

Revert "Moved comments into right places"

This reverts commit a3f3210f73e017b304eebcc9614c03bd033a80bc.


/*
 * qca_systemstore_flatfile.cpp - Qt Cryptographic Architecture
 * Copyright (C) 2004,2005  Justin Karneges
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "qca_systemstore.h"

#include <QtCore>

namespace QCA {

bool qca_have_systemstore()
{
	QFile f(QCA_SYSTEMSTORE_PATH);
	return f.open(QFile::ReadOnly);
}

CertificateCollection qca_get_systemstore(const QString &provider)
{
	return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
}

}

/*
 * qca_systemstore_flatfile.cpp - Qt Cryptographic Architecture
 * Copyright (C) 2004,2005  Justin Karneges
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "qca_systemstore.h"

#include <QtCore>

namespace QCA {

bool qca_have_systemstore()
{
#ifdef QCA_NO_SYSTEMSTORE
	return false;
#else
	QFile f(QCA_SYSTEMSTORE_PATH);
	return f.open(QFile::ReadOnly);
#endif
}

CertificateCollection qca_get_systemstore(const QString &provider)
{
#ifdef QCA_NO_SYSTEMSTORE
	Q_UNUSED(provider);
	return CertificateCollection();
#else
	return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
#endif
}

}

Add in support for when there is no system store support.

svn path=/trunk/kdesupport/qca/; revision=407460


//The injector source file for the Consume hook module.
#include "consume.h"
#include <hook_tools.h>

namespace {

void __declspec(naked) consumeHitWrapper() {
	CUnit *target, *caster;

	__asm {
		PUSHAD
		MOV caster, ESI
		MOV target, EAX
	}

  hooks::consumeHitHook(target, caster);

	__asm {
	  POPAD
	  RETN
	}
}

} //Unnamed namespace

namespace hooks {

void injectConsumeHooks() {
  callPatch(consumeHitWrapper, 0x0048BB27);
}

} //hooks

//The injector source file for the Consume hook module.
#include "consume.h"
#include <hook_tools.h>

namespace {

void __declspec(naked) consumeHitWrapper() {
	static CUnit *target, *caster;

	__asm {
		PUSHAD
		MOV caster, ESI
		MOV target, EAX
	}

  hooks::consumeHitHook(target, caster);

	__asm {
	  POPAD
	  RETN
	}
}

} //Unnamed namespace

namespace hooks {

void injectConsumeHooks() {
  callPatch(consumeHitWrapper, 0x0048BB27);
}

} //hooks

GPTP: Fix a stack corruption bug in Consume hook module.


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by WRLD";
                std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by WRLD";
                std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://wrld3d.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Update watermark 'Find out more' url.

Update watermark 'Find out more' url.


// RUN: rm -rf %t
// RUN: mkdir -p %t/Src
// RUN: cp "%s" "%t/Src/test.cpp"
// RUN: mkdir -p %t/Include
// RUN: cp "%S/Inputs/fixed-header.h" "%t/Include/"
// -I flag is relative to %t (where compile_flags is), not Src/.
// RUN: echo '-IInclude/' >> %t/compile_flags.txt
// RUN: echo "-Dklazz=class" >> %t/compile_flags.txt
// RUN: echo '-std=c++11' >> %t/compile_flags.txt
// RUN: clang-check "%t/Src/test.cpp" 2>&1
// RUN: not clang-check "%s" 2>&1 | FileCheck "%s" -check-prefix=NODB

// NODB: unknown type name 'klazz'
klazz F{};

// NODB: 'fixed-header.h' file not found
#include "fixed-header.h"
static_assert(SECRET_SYMBOL == 1, "");

// RUN: rm -rf %t
// RUN: mkdir -p %t/Src
// RUN: cp "%s" "%t/Src/test.cpp"
// RUN: mkdir -p %t/Include
// RUN: cp "%S/Inputs/fixed-header.h" "%t/Include/"
// -I flag is relative to %t (where compile_flags is), not Src/.
// RUN: echo '-IInclude/' >> %t/compile_flags.txt
// RUN: echo "-Dklazz=class" >> %t/compile_flags.txt
// RUN: echo '-std=c++11' >> %t/compile_flags.txt
// RUN: clang-check "%t/Src/test.cpp" 2>&1
// RUN: echo > %t/compile_flags.txt
// RUN: not clang-check "%t/Src/test.cpp" 2>&1 | FileCheck "%s" -check-prefix=NODB

// NODB: unknown type name 'klazz'
klazz F{};

// NODB: 'fixed-header.h' file not found
#include "fixed-header.h"
static_assert(SECRET_SYMBOL == 1, "");

[tooling] Make compile_flags.txt negative test more hermetic

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


Use the local variable instead of a global accessor.


#include "character/classes/class.h"

namespace d20 {
	bool Class::operator==(const Class &other) const {
		this->get_name() == other.get_name();
	}

	float Class::bab_progression() const {
		throw("called bab_progression on class base!");
	}

	std::string Class::get_name() const {
		throw("called get_name on class base!");
	}
}

#include "character/classes/class.h"

namespace d20 {
	bool Class::operator==(const Class &other) const {
		return this->get_name() == other.get_name();
	}

	float Class::bab_progression() const {
		throw("called bab_progression on class base!");
	}

	std::string Class::get_name() const {
		throw("called get_name on class base!");
	}
}

Fix warning missing return statement

Fix warning missing return statement


// Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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

  return 0;
}

Fix an OSS build error.

Fix an OSS build error.

* cc_binary requires a main function.

PiperOrigin-RevId: 450640612


//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Timer.h"
#include "llvm/Support/Thread.h"
#include "gtest/gtest.h"
#include <chrono>

using namespace llvm;

namespace {

TEST(Timer, Additivity) {
  Timer T1("T1");

  EXPECT_TRUE(T1.isInitialized());

  T1.startTimer();
  T1.stopTimer();
  auto TR1 = T1.getTotalTime();

  T1.startTimer();
  std::this_thread::sleep_for(std::chrono::milliseconds(1));
  T1.stopTimer();
  auto TR2 = T1.getTotalTime();

  EXPECT_TRUE(TR1 < TR2);
}

TEST(Timer, CheckIfTriggered) {
  Timer T1("T1");

  EXPECT_FALSE(T1.hasTriggered());
  T1.startTimer();
  EXPECT_TRUE(T1.hasTriggered());
  T1.stopTimer();
  EXPECT_TRUE(T1.hasTriggered());

  T1.clear();
  EXPECT_FALSE(T1.hasTriggered());
}

} // end anon namespace

//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Timer.h"
#include "llvm/Support/thread.h"
#include "gtest/gtest.h"
#include <chrono>

using namespace llvm;

namespace {

TEST(Timer, Additivity) {
  Timer T1("T1");

  EXPECT_TRUE(T1.isInitialized());

  T1.startTimer();
  T1.stopTimer();
  auto TR1 = T1.getTotalTime();

  T1.startTimer();
  std::this_thread::sleep_for(std::chrono::milliseconds(1));
  T1.stopTimer();
  auto TR2 = T1.getTotalTime();

  EXPECT_TRUE(TR1 < TR2);
}

TEST(Timer, CheckIfTriggered) {
  Timer T1("T1");

  EXPECT_FALSE(T1.hasTriggered());
  T1.startTimer();
  EXPECT_TRUE(T1.hasTriggered());
  T1.stopTimer();
  EXPECT_TRUE(T1.hasTriggered());

  T1.clear();
  EXPECT_FALSE(T1.hasTriggered());
}

} // end anon namespace

[unittest] Use Support/thread.h instead of <thread> (second try)

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@256292 91177308-0d34-0410-b5e6-96231b3b80d8


#include<math.h>

bool isPrimeBruteForce(int x) {
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) {
		if (x%i==0)
			return false;
	}
	return true;
}

#include<math.h>

bool isPrimeBruteForce(int x) {
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

Add comment to sqrt calculation

Add comment to sqrt calculation


//===--- RewriteTest.cpp - Rewriter playground ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a testbed.
//
//===----------------------------------------------------------------------===//

#include "clang.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/TokenRewriter.h"
#include <iostream>

void clang::DoRewriteTest(Preprocessor &PP, const std::string &InFileName,
                          const std::string &OutFileName) {
  SourceManager &SM = PP.getSourceManager();
  const LangOptions &LangOpts = PP.getLangOptions();

  TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);

  // Throw <i> </i> tags around comments.
  for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
       E = Rewriter.token_end(); I != E; ++I) {
    if (I->isNot(tok::comment)) continue;

    Rewriter.AddTokenBefore(I, "<i>");
    Rewriter.AddTokenAfter(I, "</i>");
  }

  // Print out the output.
  for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
       E = Rewriter.token_end(); I != E; ++I)
    std::cout << PP.getSpelling(*I);
}

Add newline at the end of file, to silence compiler warning.

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


#include "geometry/vertex.h"

namespace aten
{
	std::vector<int> VertexManager::s_indices;
	std::vector<vertex> VertexManager::s_vertices;
	GeomVertexBuffer VertexManager::s_vb;

	void VertexManager::build()
	{
		s_vb.init(
			sizeof(vertex),
			s_vertices.size(),
			0,
			&s_vertices[0]);
	}
}

#include "geometry/vertex.h"

namespace aten
{
	std::vector<int> VertexManager::s_indices;
	std::vector<vertex> VertexManager::s_vertices;
	GeomVertexBuffer VertexManager::s_vb;

	void VertexManager::build()
	{
		if (!s_vertices.empty()
			&& !s_vb.isInitialized())
		{
			s_vb.init(
				sizeof(vertex),
				s_vertices.size(),
				0,
				&s_vertices[0]);
		}
	}
}

Modify to initialize one time.

Modify to initialize one time.


#include <TimerMessage.h>
#include <QDebug>

TimerMessage::TimerMessage(QObject *parent) :
    QObject(parent),
    m_pTimer(new QTimer(this)),
    m_counter(0)
{
    connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );

    m_pTimer->setInterval(1000);
    m_pTimer->start();
}

void TimerMessage::printCounter()
{
    print(QString("Message counter # %1").arg(m_counter++));
    if(m_counter >= 1024)
        m_counter = 0;
}

void TimerMessage::print(const QString &msg)
{
    qDebug() << qPrintable(msg);
}

#include <TimerMessage.h>
#include <QDebug>

TimerMessage::TimerMessage(QObject *parent) :
    QObject(parent),
    m_pTimer(new QTimer(this)),
    m_counter(0)
{
    connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );

    m_pTimer->setInterval(750);
    m_pTimer->start();
}

void TimerMessage::printCounter()
{
    print(QString("Message counter # %1").arg(m_counter++));
    if(m_counter >= 1024)
        m_counter = 0;
}

void TimerMessage::print(const QString &msg)
{
    qDebug() << qPrintable(msg);
}

Test them all. Fix interval

Test them all. Fix interval


#include "../quick.hpp"
#include "../swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    int size = end - start + 1;

    if(start >= end) return; /* Base case */

    /* Conquer */
    int pivot = partition(data, start, end);

    /* Divide */
    quick(data, start, pe - 1);
    quick(data, pe + 1, end);
}

int partition(int *data, const int start, const int end)
{
    int pivot = end; /* Set pivot */

    int ps = start, pe = end - 1;
    while(ps < pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pe] > data[pivot])
        swap(data[pe], data[pivot]);
    else if(pe == end - 1)
        ++pe;

    return pe;
}

#include "../quick.hpp"
#include "../swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    int size = end - start + 1;

    if(start >= end) return; /* Base case */

    /* Conquer */
    int pivot = partition(data, start, end);

    /* Divide */
    quick(data, start, pivot - 1);
    quick(data, pivot + 1, end);
}

int partition(int *data, const int start, const int end)
{
    int pivot = end; /* Set pivot */

    int ps = start, pe = end - 1;
    while(ps < pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pe] > data[pivot])
        swap(data[pe], data[pivot]);
    else if(pe == end - 1)
        ++pe;

    return pe;
}

Fix bug which variable name is not match


#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int length, count = 0;
    cin >> length;

    vector<string> vector(length);

    for (int i = 0; i < length; i++)
    {
        cin >> vector[i];
    }

    //sort logic

    cout << vector[0];
    for (int i = 1; i < length; i++)
    {
        cout << ' '<< vector[i];
    }
    cout << endl << count << endl;
}

#include <iostream>
#include <vector>

using namespace std;

class Card
{
private:
    string name_;
    int value_;

public:
    Card(string card)
    {
        name_ = card;
        value_ = stoi(card.substr(1, 1));
    };

    string name(){return name_;};
    int value(){return value_;};
};

void bubbleSort(vector<Card *> &cards);

void shellSort(vector<Card *> &cards);

int main()
{
    int length, count = 0;
    cin >> length;

    vector<Card*> cards(length);

    for (int i = 0; i < length; i++)
    {
        string card;
        cin >> card;
        cards[i] = new Card(card);
    }

    bubbleSort(cards);
    shellSort(cards);
}

void bubbleSort(vector<Card *> &cards)
{
    for(int i = 0; i < cards.size(); i++)
    {
        for(int j = cards.size() - 1; j > i; j--)
        {
            if(cards[j-1]->value() > cards[j]->value())
            {
                Card* temp = cards[j-1];
                cards[j-1] = cards[j];
                cards[j] = temp;
            }
        }
    }
    cout << cards[0]->name();
    for(int i = 1; i < cards.size(); i++)
    {
        cout << ' ' << cards[i]->name();
    }
    cout << endl << "Stable" << endl;
}

void shellSort(vector<Card *> &cards)
{

}

Add bubbleSort() to stable sort.

Add bubbleSort() to stable sort.


#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

 PyObject* PyInit_pyQuantuccia(void){
     return NULL;
 }

Add a stub function to init the module.

Add a stub function to init the module.


#include <orz/types.h>
#include "hw3d_opengl_common.h"

namespace Hw3D
{
	GLint GetGlInternalFormat(Format fmt)
	{
		return GL_RGBA;
	}

	GLenum GetGlFormat(Format)
	{
		return GL_RGBA;
	}

	GLenum GetGlDataType(Format)
	{
		return GL_UNSIGNED_BYTE;
	}

	::std::string GetGlErrorString(GLenum error)
	{
		switch (error)
		{
			case GL_NO_ERROR:
				return "No error";
			case GL_INVALID_ENUM:
				return "Invalid enum";
			case GL_INVALID_VALUE:
				return "Invalid value";
			case GL_INVALID_OPERATION:
				return "Invalid operation";
			case GL_INVALID_FRAMEBUFFER_OPERATION:
				return "Invalid framebuffer operation";
			case GL_OUT_OF_MEMORY:
				return "Out of memory";
			case GL_STACK_UNDERFLOW:
				return "Stack underflow";
			case GL_STACK_OVERFLOW:
				return "Stack overflow";
			default:
				return "Unknown error code:" + ToAString(error);
		}
	}
}

#include <orz/types.h>
#include "hw3d_opengl_common.h"

namespace Hw3D
{
	GLint GetGlInternalFormat(Format fmt)
	{
		return GL_RGBA;
	}

	GLenum GetGlFormat(Format)
	{
		return GL_BGRA;
	}

	GLenum GetGlDataType(Format)
	{
		return GL_UNSIGNED_BYTE;
	}

	::std::string GetGlErrorString(GLenum error)
	{
		switch (error)
		{
			case GL_NO_ERROR:
				return "No error";
			case GL_INVALID_ENUM:
				return "Invalid enum";
			case GL_INVALID_VALUE:
				return "Invalid value";
			case GL_INVALID_OPERATION:
				return "Invalid operation";
			case GL_INVALID_FRAMEBUFFER_OPERATION:
				return "Invalid framebuffer operation";
			case GL_OUT_OF_MEMORY:
				return "Out of memory";
			case GL_STACK_UNDERFLOW:
				return "Stack underflow";
			case GL_STACK_OVERFLOW:
				return "Stack overflow";
			default:
				return "Unknown error code:" + ToAString(error);
		}
	}
}

Make test images look better

Make test images look better


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

#include "chrome/browser/safe_browsing/safe_browsing_service.h"

#include <stddef.h>

#include "chrome/browser/safe_browsing/ui_manager.h"

namespace safe_browsing {

const scoped_refptr<SafeBrowsingUIManager>&
SafeBrowsingService::ui_manager() const {
  return nullptr;
}

void SafeBrowsingService::DisableQuicOnIOThread() {}

}  // namespace safe_browsing

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

#include "chrome/browser/safe_browsing/safe_browsing_service.h"

#include <stddef.h>

#include "chrome/browser/safe_browsing/ui_manager.h"

namespace safe_browsing {

const scoped_refptr<SafeBrowsingUIManager>&
SafeBrowsingService::ui_manager() const {
  static scoped_refptr<SafeBrowsingUIManager> empty;
  return empty;
}

void SafeBrowsingService::DisableQuicOnIOThread() {}

}  // namespace safe_browsing

Fix "warning: returning reference to local temporary object"


#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test in a compiler compatible format.
    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, std::cout);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}

#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test results to a file
	std::ofstream ofile("OgreTestResults.log");

    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, ofile);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}

Write test results to a file for easier examination


#include "country_decl.hpp"

string storage::CountryInfo::FileName2FullName(string fName)
{
  size_t const i = fName.find('_');
  if (i != string::npos)
  {
    // replace '_' with ", "
    fName[i] = ',';
    fName.insert(i+1, " ");
  }
  return fName;
}

void storage::CountryInfo::FullName2GroupAndMap(string const & fName, string & group, string & map)
{
  size_t pos = fName.find(",");
  if (pos == string::npos)
  {
    map = fName;
  }
  else
  {
    map = fName.substr(pos + 2);
    group = fName.substr(0, pos);
  }
}

#include "country_decl.hpp"

string storage::CountryInfo::FileName2FullName(string fName)
{
  size_t const i = fName.find('_');
  if (i != string::npos)
  {
    // replace '_' with ", "
    fName[i] = ',';
    fName.insert(i+1, " ");
  }
  return fName;
}

void storage::CountryInfo::FullName2GroupAndMap(string const & fName, string & group, string & map)
{
  size_t pos = fName.find(",");
  if (pos == string::npos)
  {
    map = fName;
    group.clear();
  }
  else
  {
    map = fName.substr(pos + 2);
    group = fName.substr(0, pos);
  }
}

Fix bug with country group name.

Fix bug with country group name.


#include "Output.h"
#include "Parameters.h"
#include "Parser.h"
#include "PerformanceTracker.h"
#include "Simulation.h"

#include <iostream>
#include <map>
#include <string>

using namespace pica;
using namespace std;

int realMain(int argc, char* argv[]);

int main(int argc, char* argv[])
{
    try {
        return realMain(argc, argv);
    }
    catch (...) {
        cout << "ERROR: Unhandled exception, benchmark terminated\n";
        return EXIT_FAILURE;
    }
}

int realMain(int argc, char* argv[])
{
    printHeader();
    Parameters parameters = readParameters(argc, argv);
    printParameters(parameters);
    PerformanceTracker tracker;
    runSimulation(parameters, tracker);
    printPerformance(tracker);
    return 0;
}

#include "Output.h"
#include "Parameters.h"
#include "Parser.h"
#include "PerformanceTracker.h"
#include "Simulation.h"

#include <iostream>
#include <map>
#include <stdexcept>
#include <string>

using namespace pica;
using namespace std;

int realMain(int argc, char* argv[]);

int main(int argc, char* argv[])
{
    try {
        return realMain(argc, argv);
    }
    catch (std::exception& e) {
        cout << "ERROR: Unhandled exception with message '" << e.what()
            << "', benchmark terminated\n";
        return EXIT_FAILURE;
    }
    catch (...) {
        cout << "ERROR: Unhandled exception, benchmark terminated\n";
        return EXIT_FAILURE;
    }
}

int realMain(int argc, char* argv[])
{
    printHeader();
    Parameters parameters = readParameters(argc, argv);
    printParameters(parameters);
    PerformanceTracker tracker;
    runSimulation(parameters, tracker);
    printPerformance(tracker);
    return 0;
}

Improve output of standard exceptions.

Improve output of standard exceptions.


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

void f1() {
  struct X {
    struct Y;
  };

  struct X::Y {
    void f() {}
  };
}

void f2() {
  struct X {
    struct Y;

    struct Y {
      void f() {}
    };
  };
}

// A class nested within a local class is a local class.
void f3(int a) { // expected-note{{'a' declared here}}
  struct X {
    struct Y {
      int f() {
        return a; // expected-error{{reference to local variable 'a' declared in enclosed function 'f3'}}
        return 1;
      }
    };
  };
}

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

void f1() {
  struct X {
    struct Y;
  };

  struct X::Y {
    void f() {}
  };
}

void f2() {
  struct X {
    struct Y;

    struct Y {
      void f() {}
    };
  };
}

// A class nested within a local class is a local class.
void f3(int a) { // expected-note{{'a' declared here}}
  struct X {
    struct Y {
      int f() { return a; } // expected-error{{reference to local variable 'a' declared in enclosed function 'f3'}}
    };
  };
}

Revert this, we have a better way to do this.

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


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

#include "gtest/gtest.h"

#include "util.h"

#include <string>

using sopmq::shared::util;

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

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

    ASSERT_EQ("6162636465", result);
}

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

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

#include "gtest/gtest.h"

#include "util.h"

#include <string>

using sopmq::shared::util;

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

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

    ASSERT_EQ("61626364654F", result);
}

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

Improve hex encoder unit test

Improve hex encoder unit test


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 31
// Coin sums

namespace problem_31 {

constexpr long n_denoms = 8;
constexpr long denom_values[n_denoms] = {
	1, 2, 5, 10, 20, 50, 100, 200
};

long n_coin_sums(const long sum, const long index) {
	if (sum < 0 || index < 0) {
		return 0;
	}
	if (sum == 0) {
		return 1;
	}
	const long value = denom_values[index];
	const long with = n_coin_sums(sum - value, index);
	const long without = n_coin_sums(sum, index - 1);
	return with + without;
}

long solve() {
	return n_coin_sums(200, n_denoms);
}

} // namespace problem_31

// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 31
// Coin sums

namespace problem_31 {

constexpr long n_denoms = 8;
constexpr long denom_values[n_denoms] = {
	1, 2, 5, 10, 20, 50, 100, 200
};

long n_coin_sums(const long sum, const long index) {
	if (sum < 0 || index < 0) {
		return 0;
	}
	if (sum == 0) {
		return 1;
	}
	const long value = denom_values[index];
	const long with = n_coin_sums(sum - value, index);
	const long without = n_coin_sums(sum, index - 1);
	return with + without;
}

long solve() {
	return n_coin_sums(200, n_denoms - 1);
}

} // namespace problem_31

Fix solution to problem 31

Fix solution to problem 31


#include "ReQL-test.hpp"

#include "catch.h"

#include <limits>

using namespace ReQL;

TEST_CASE("Connection", "[c++][connect]") {
  Connection conn = connect();

  REQUIRE(conn.isOpen());
}

TEST_CASE("Expr", "[c][expr]") {
  SECTION("number") {
    _ReQL_Op_t num;

    const double val = 42.0;

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("number edges") {
    _ReQL_Op_t num;

    const double val = std::numeric_limits<std::double_t>::max();

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("string") {
    _ReQL_Op_t string;

    const uint32_t size = 12;

    uint8_t buf[size] = "Hello World";

    std::string orig = std::string((char *)buf, size);

    _reql_string_init(&string, buf, size, size);

    CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
    CHECK(size == _reql_string_size(&string));
  }
}

#include "ReQL-test.hpp"

#include "catch.h"

#include <limits>

using namespace ReQL;

TEST_CASE("Connection", "[c++][connect]") {
  Connection conn = connect();

  REQUIRE(conn.isOpen());
}

TEST_CASE("Expr", "[c][expr]") {
  SECTION("null") {
    _ReQL_Op_t null;

    _reql_null_init(&null);

    CHECK(_reql_datum_type(&null) == _REQL_R_NULL);
  }
  SECTION("number") {
    _ReQL_Op_t num;

    const double val = 42.0;

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("number edges") {
    _ReQL_Op_t num;

    const double val = std::numeric_limits<std::double_t>::max();

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("string") {
    _ReQL_Op_t string;

    const uint32_t size = 12;

    uint8_t buf[size] = "Hello World";

    std::string orig = std::string((char *)buf, size);

    _reql_string_init(&string, buf, size, size);

    CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
    CHECK(size == _reql_string_size(&string));
  }
}

Add null c constructor test.

Add null c constructor test.


#include <QtGui/QApplication>
#include "mainwindow.h"
#include "fvupdater.h"

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

	// Prerequisite for the Fervor updater
	QApplication::setOrganizationName("pypt");
	QApplication::setOrganizationDomain("pypt.lt");

	// Set feed URL before doing anything else
	FvUpdater::sharedUpdater()->SetFeedURL("http://pypt.github.com/fervor/Appcast.xml");

	// Check for updates automatically
	FvUpdater::sharedUpdater()->CheckForUpdatesSilent();

	// Show main window
	MainWindow w;
	w.show();

	return a.exec();
}

#include <QApplication>
#include "mainwindow.h"
#include "fvupdater.h"

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

	// Prerequisite for the Fervor updater
	QApplication::setOrganizationName("pypt");
	QApplication::setOrganizationDomain("pypt.lt");

	// Set feed URL before doing anything else
	FvUpdater::sharedUpdater()->SetFeedURL("http://pypt.github.com/fervor/Appcast.xml");

	// Check for updates automatically
	FvUpdater::sharedUpdater()->CheckForUpdatesSilent();

	// Show main window
	MainWindow w;
	w.show();

	return a.exec();
}

Fix compile issue on Qt5

Fix compile issue on Qt5


#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

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

    ros::NodeHandle node;
    ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);

    ros::Duration(1).sleep();

    geometry_msgs::Twist cmd;

    cmd.linear.z = 5;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    cmd.linear.z = 0.0;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    return 0;
}

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

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

    ros::NodeHandle node;
    ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);

    ros::Duration(1).sleep();

    geometry_msgs::Twist cmd;

    cmd.linear.z = 1;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    cmd.linear.z = 0.0;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    return 0;
}

Fix parameter of the Twist

Fix parameter of the Twist


#include<iostream>
#include<stdlib.h>
#include"filecopy.h"

int main(int argc, char *argv[])
{
     if(argc != 3)
     {
          std::cout << "USAGE: " << argv[0] << " <filesource> <filedestination>" << std::endl;
          return 1;
     }
     else
     {
          filecopy target1(argv[2], argv[1]);
          std::cout << "TARGET ASSIGNED" << std::endl;
          std::cout << "EXECUTE FILEWORKER" << std::endl;
     }
     return 0;
}

#include<iostream>
#include<stdlib.h>
#include"filecopy.h"

int main(int argc, char *argv[])
{
     if(argc != 3)
     {
          std::cout << "USAGE: " << argv[0] << " <filesource> <filedestination>" << std::endl;
          return 1;
     }
     else
     {
          filecopy target1(argv[2], argv[1]);
          std::cout << "TARGET ASSIGNED" << std::endl;
          target1.filecopy_worker();
          std::cout << "EXECUTE FILEWORKER" << std::endl;
     }
     return 0;
}

Fix client for not executing fileworker

Fix client for not executing fileworker


#include <ccspec/matchers/be_something.h>

namespace ccspec {
namespace matchers {

const BeSomething& be = BeSomething::instance();

const BeSomething& BeSomething::instance() {
    static BeSomething instance;
    return instance;
}

BeSomething::BeSomething() {}

} // namespace matchers
} // namespace ccspec

#include <ccspec/matchers/be_something.h>

namespace ccspec {
namespace matchers {

const BeSomething& be = BeSomething::instance();

// Public methods.

const BeSomething& BeSomething::instance() {
    static BeSomething instance;
    return instance;
}

// Private methods.

BeSomething::BeSomething() {}

} // namespace matchers
} // namespace ccspec

Add comments for public and private sections


#include "ofApp.h"

void ofApp::setup() {
  ofBackground(0);

  // Add our CustomSource to list of fbo sources of the piMapper
  // FBO sources should be added before piMapper.setup() so the
  // piMapper is able to load the source if it is assigned to
  // a surface in XML settings.
  piMapper.addFboSource(customSource);
  piMapper.setup();

  // The info layer is hidden by default, press <i> to toggle
  piMapper.showInfo();
}

void ofApp::draw() {
  piMapper.draw();
}

#include "ofApp.h"

void ofApp::setup() {
  ofBackground(0);

  // Add our CustomSource to list of fbo sources of the piMapper
  // FBO sources should be added before piMapper.setup() so the
  // piMapper is able to load the source if it is assigned to
  // a surface in XML settings.
  piMapper.addFboSource(customSource);
  piMapper.setup();

  // The info layer is hidden by default, press <i> to toggle
  // piMapper.showInfo();
}

void ofApp::draw() {
  piMapper.draw();
}

Hide info on startup, but leave commented code


#include <iostream>
#include <string>
#include "hash_table.cpp"
#include <time.h>

void randstr(const int length, std::string &out);

int main(void)
{
    srand(time(NULL));

    hash_set<std::string> hs_str(10, 0.8,
        [] (const std::string entry) -> unsigned int
        {
            unsigned int hash = 0;
            for(char c : entry) hash = c + (13 * hash);
            return hash;
        }
    );

    const int s_count = 30;
    std::string arr[s_count];
    for(int i = 0; i < s_count; ++i)
    {
        randstr(10, arr[i]);
        std::cout << arr[i] << std::endl;
    }

    for(std::string s : arr)
    {
        hs_str.add(s);

        hs_str.print();
        std::cout << std::endl
                    << "count: " << hs_str.size() << std::endl
                    << "capacity: " << hs_str.get_capacity() << std::endl;
    }
}

void randstr(const int length, std::string &out)
{
    char range[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
    for (int n = 0; n < length; ++n)
        out.push_back(range[rand() % sizeof(range - 1)]);

    out.push_back('\0');
}

#include <iostream>
#include <string>
#include "hash_table.hpp"
#include <time.h>

void randstr(const int length, std::string &out);

int main(void)
{
    srand(time(NULL));

    hash_set<std::string> hs_str(10, 0.8,
        [] (const std::string entry) -> unsigned int
        {
            unsigned int hash = 0;
            for(char c : entry) hash = c + (13 * hash);
            return hash;
        }
    );

    const int s_count = 30;
    std::string arr[s_count];
    for(int i = 0; i < s_count; ++i)
    {
        randstr(10, arr[i]);
        std::cout << arr[i] << std::endl;
    }

    for(std::string s : arr)
    {
        hs_str.add(s);

        hs_str.print();
        std::cout << std::endl
                    << "count: " << hs_str.size() << std::endl
                    << "capacity: " << hs_str.get_capacity() << std::endl;
    }
}

void randstr(const int length, std::string &out)
{
    char range[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
    for (int n = 0; n < length; ++n)
        out.push_back(range[rand() % sizeof(range - 1)]);

    out.push_back('\0');
}

Fix the path of header file

Fix the path of header file

Due to commit 6c418384573acb3a4842352948c9f489043c8d51


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

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/common/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  base::RemoveChars(name, base::kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s",
      name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(
    int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
      resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(
      resource_id);
}

}  // namespace brightray

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

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "content/public/common/user_agent.h"
#include "ui/base/resource/resource_bundle.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  base::RemoveChars(name, base::kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s",
      name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return content::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(
    int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
      resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(
      resource_id);
}

}  // namespace brightray

Update for move of BuildUserAgentFromProduct in Chrome 35

See https://codereview.chromium.org/186883002


#include <QInputDialog>

#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"

QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
    QWidget(parent),
    link(link),
    ui(new Ui::QGCTCPLinkConfiguration)
{
    ui->setupUi(this);
    uint16_t port = link->getPort();
    ui->portSpinBox->setValue(port);
    QString addr = link->getHostAddress().toString();
    ui->hostAddressLineEdit->setText(addr);
    connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
    connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setAddress(const QString &)));
}

QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
    delete ui;
}

void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

#include <QInputDialog>

#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"
#include <stdint.h>

QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
    QWidget(parent),
    link(link),
    ui(new Ui::QGCTCPLinkConfiguration)
{
    ui->setupUi(this);
    uint16_t port = link->getPort();
    ui->portSpinBox->setValue(port);
    QString addr = link->getHostAddress().toString();
    ui->hostAddressLineEdit->setText(addr);
    connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
    connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setAddress(const QString &)));
}

QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
    delete ui;
}

void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

Add in a missing stdint.h include

Add in a missing stdint.h include


#include <mart-common/experimental/ranges.h>

#include <catch2/catch.hpp>

TEST_CASE( "experimental_frange_compiles", "[experimental][ranges]" )
{
	auto r = mart::experimental::frange( 0.1, 0.3 ).step( 0.1 );
	(void)r;
}

TEST_CASE( "experimental_vrange_compiles", "[experimental][ranges]" )
{
	auto r = mart::experimental::vrange<float>( 0.1, 0.3 ).step( 0.1 );
	(void)r;
}

#include <mart-common/experimental/ranges.h>

#include <catch2/catch.hpp>

TEST_CASE( "experimental_frange_compiles", "[experimental][ranges]" )
{
	auto r = mart::experimental::frange( 0.1, 0.3 ).step( 0.1 );
	(void)r;
}

TEST_CASE( "experimental_vrange_compiles", "[experimental][ranges]" )
{
	auto r = mart::experimental::vrange<float>( 0.1f, 0.3f ).step( 0.1f );
	(void)r;
}

Fix conversion warning in range tests

[Tests] Fix conversion warning in range tests


#include "fly/logger/log.h"

#include "fly/logger/logger_config.h"

namespace fly {

//==============================================================================
Log::Log() :
    m_level(NUM_LEVELS),
    m_time(-1.0),
    m_gameId(-1),
    m_line(-1),
    m_message()
{
    ::memset(m_file, 0, sizeof(m_file));
    ::memset(m_function, 0, sizeof(m_file));
}

//==============================================================================
Log::Log(const LoggerConfigPtr &spConfig, const std::string &message) :
    m_level(NUM_LEVELS),
    m_time(-1.0),
    m_gameId(-1),
    m_line(-1),
    m_message(message, 0, spConfig->MaxMessageSize())
{
    ::memset(m_file, 0, sizeof(m_file));
    ::memset(m_function, 0, sizeof(m_file));
}

//==============================================================================
std::ostream &operator << (std::ostream &stream, const Log &log)
{
    stream << log.m_level << "\t";
    stream << log.m_time << "\t";
    stream << log.m_gameId << "\t";
    stream << log.m_file << "\t";
    stream << log.m_function << "\t";
    stream << log.m_line << "\t";
    stream << log.m_message << "\n";

    return stream;
}

}

#include "fly/logger/log.h"

#include <cstring>

#include "fly/logger/logger_config.h"

namespace fly {

//==============================================================================
Log::Log() :
    m_level(NUM_LEVELS),
    m_time(-1.0),
    m_gameId(-1),
    m_line(-1),
    m_message()
{
    ::memset(m_file, 0, sizeof(m_file));
    ::memset(m_function, 0, sizeof(m_file));
}

//==============================================================================
Log::Log(const LoggerConfigPtr &spConfig, const std::string &message) :
    m_level(NUM_LEVELS),
    m_time(-1.0),
    m_gameId(-1),
    m_line(-1),
    m_message(message, 0, spConfig->MaxMessageSize())
{
    ::memset(m_file, 0, sizeof(m_file));
    ::memset(m_function, 0, sizeof(m_file));
}

//==============================================================================
std::ostream &operator << (std::ostream &stream, const Log &log)
{
    stream << log.m_level << "\t";
    stream << log.m_time << "\t";
    stream << log.m_gameId << "\t";
    stream << log.m_file << "\t";
    stream << log.m_function << "\t";
    stream << log.m_line << "\t";
    stream << log.m_message << "\n";

    return stream;
}

}

Add missing include for linux build

Add missing include for linux build